braid-coding-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""上下文明细:把一次请求的提示词与消息拆成互不重叠的分项。
|
|
2
|
+
|
|
3
|
+
``ContextStatus.tokens`` 回答"占了多少",这里回答"占在哪里"。分项全部来自
|
|
4
|
+
会话投影里模型真正能看到的内容:系统提示词按分节拆开,工具声明按 ``mcp__``
|
|
5
|
+
前缀与 ``task`` 工具归到各自的来源,压缩摘要单独成项。分项估算与总量之间的
|
|
6
|
+
差额记在 ``residual_tokens``:服务端的 prompt 模板、消息封包等开销在客户端
|
|
7
|
+
看不到,解释成"服务端未归因"比硬塞进某一项更诚实。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Sequence
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from math import ceil
|
|
16
|
+
from typing import Final
|
|
17
|
+
|
|
18
|
+
from braid_ai.types import SystemMessage, Tool
|
|
19
|
+
from braid_ai.wire import content_text
|
|
20
|
+
from braid_coding_agent.compaction.tokens import estimate_tokens
|
|
21
|
+
from braid_coding_agent.session.entries import (
|
|
22
|
+
BranchSummaryMessage,
|
|
23
|
+
CompactionSummaryMessage,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"ContextBreakdown",
|
|
28
|
+
"ContextPart",
|
|
29
|
+
"build_context_breakdown",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
_PART_LABELS: Final[dict[str, str]] = {
|
|
33
|
+
"system": "系统提示词",
|
|
34
|
+
"project": "项目规则",
|
|
35
|
+
"tools": "工具声明",
|
|
36
|
+
"skills": "技能清单",
|
|
37
|
+
"mcp": "MCP 工具",
|
|
38
|
+
"subagents": "子代理",
|
|
39
|
+
"summary": "压缩摘要",
|
|
40
|
+
"conversation": "对话消息",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_PART_ORDER: Final[tuple[str, ...]] = (
|
|
44
|
+
"system",
|
|
45
|
+
"project",
|
|
46
|
+
"tools",
|
|
47
|
+
"skills",
|
|
48
|
+
"mcp",
|
|
49
|
+
"subagents",
|
|
50
|
+
"summary",
|
|
51
|
+
"conversation",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
_MCP_TOOL_PREFIX: Final[str] = "mcp__"
|
|
55
|
+
_TASK_TOOL_NAME: Final[str] = "task"
|
|
56
|
+
_TOOL_LINE = re.compile(r"^- (?P<name>[A-Za-z0-9_.-]+): ")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(slots=True, frozen=True)
|
|
60
|
+
class ContextPart:
|
|
61
|
+
"""一个分项:键名、显示标签、token 估算与一句出处说明。"""
|
|
62
|
+
|
|
63
|
+
key: str
|
|
64
|
+
label: str
|
|
65
|
+
tokens: int
|
|
66
|
+
detail: str = ""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(slots=True, frozen=True)
|
|
70
|
+
class ContextBreakdown:
|
|
71
|
+
"""一次上下文明细。
|
|
72
|
+
|
|
73
|
+
``parts`` 只包含当前确实存在的来源;``estimated_tokens`` 是分项之和,
|
|
74
|
+
``total_tokens`` 是 :meth:`AgentSession.context_status` 的同一个总量。
|
|
75
|
+
``context_window`` 是当前模型的窗口大小,用来把分项换算成百分比。
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
parts: tuple[ContextPart, ...]
|
|
79
|
+
total_tokens: int
|
|
80
|
+
estimated_tokens: int
|
|
81
|
+
residual_tokens: int
|
|
82
|
+
context_window: int = 0
|
|
83
|
+
|
|
84
|
+
def part(self, key: str) -> ContextPart | None:
|
|
85
|
+
"""按分项键名取一项;不存在时返回 ``None``。"""
|
|
86
|
+
for part in self.parts:
|
|
87
|
+
if part.key == key:
|
|
88
|
+
return part
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
def percent_of_window(self, tokens: int) -> float:
|
|
92
|
+
"""一段 token 占模型上下文窗口的百分比;窗口未知时返回 ``0.0``。"""
|
|
93
|
+
return tokens / self.context_window * 100.0 if self.context_window > 0 else 0.0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def build_context_breakdown(
|
|
97
|
+
*,
|
|
98
|
+
system: SystemMessage | None,
|
|
99
|
+
messages: Sequence[object],
|
|
100
|
+
total_tokens: int,
|
|
101
|
+
context_window: int = 0,
|
|
102
|
+
subagent_names: Sequence[str] = (),
|
|
103
|
+
skill_names: Sequence[str] = (),
|
|
104
|
+
mcp_servers: Sequence[str] = (),
|
|
105
|
+
) -> ContextBreakdown:
|
|
106
|
+
"""把提示词与投影消息拆成互不重叠的分项。
|
|
107
|
+
|
|
108
|
+
:param system: 重放后的当前系统消息;``None`` 表示这次请求还没有提示词。
|
|
109
|
+
:param messages: 会话投影里的全部消息,包含系统消息与压缩摘要。
|
|
110
|
+
:param total_tokens: 服务端用量或字符估算得到的总量;``0`` 时改用分项之和。
|
|
111
|
+
:param context_window: 当前模型的上下文窗口大小,用来计算分项占比。
|
|
112
|
+
:param subagent_names: 已注册子代理名,写在 ``subagents`` 的说明里。
|
|
113
|
+
:param skill_names: 已发现技能名,写在 ``skills`` 的说明里。
|
|
114
|
+
:param mcp_servers: 已连接的 MCP 服务器名,写在 ``mcp`` 的说明里。
|
|
115
|
+
"""
|
|
116
|
+
buckets: dict[str, int] = {}
|
|
117
|
+
details: dict[str, str] = {}
|
|
118
|
+
|
|
119
|
+
if system is not None:
|
|
120
|
+
sections = {
|
|
121
|
+
name: text for name, text in (system.sections or {}).items() if text is not None
|
|
122
|
+
}
|
|
123
|
+
base_names = [
|
|
124
|
+
name for name in sections if name not in ("tools", "project_context", "skills")
|
|
125
|
+
]
|
|
126
|
+
base_chars = len(content_text(system.content)) + sum(
|
|
127
|
+
len(sections[name]) for name in base_names
|
|
128
|
+
)
|
|
129
|
+
base_tokens = _chars_to_tokens(base_chars)
|
|
130
|
+
if base_tokens:
|
|
131
|
+
buckets["system"] = base_tokens
|
|
132
|
+
details["system"] = "、".join(base_names)
|
|
133
|
+
|
|
134
|
+
project = sections.get("project_context")
|
|
135
|
+
if project:
|
|
136
|
+
buckets["project"] = _chars_to_tokens(len(project))
|
|
137
|
+
details["project"] = f"{len(project)} 个字符"
|
|
138
|
+
|
|
139
|
+
skills_section = sections.get("skills")
|
|
140
|
+
skill_tokens = _chars_to_tokens(len(skills_section)) if skills_section else 0
|
|
141
|
+
if skill_tokens:
|
|
142
|
+
buckets["skills"] = skill_tokens
|
|
143
|
+
details["skills"] = _name_detail(skill_names, "个技能")
|
|
144
|
+
|
|
145
|
+
tools_section = sections.get("tools")
|
|
146
|
+
section_chars = {"tools": 0, "mcp": 0, "subagents": 0}
|
|
147
|
+
listed: dict[str, list[str]] = {"tools": [], "mcp": [], "subagents": []}
|
|
148
|
+
if tools_section:
|
|
149
|
+
for line in tools_section.splitlines(keepends=True):
|
|
150
|
+
name = _listed_tool_name(line)
|
|
151
|
+
key = _tool_bucket(name) if name is not None else "tools"
|
|
152
|
+
section_chars[key] += len(line)
|
|
153
|
+
if name is not None:
|
|
154
|
+
listed[key].append(name)
|
|
155
|
+
tool_tokens = _chars_to_tokens(section_chars["tools"])
|
|
156
|
+
plain_tools: list[str] = []
|
|
157
|
+
mcp_tools: list[Tool] = []
|
|
158
|
+
subagent_tools: list[Tool] = []
|
|
159
|
+
for tool in system.tools_added or ():
|
|
160
|
+
match _tool_bucket(tool.name):
|
|
161
|
+
case "mcp":
|
|
162
|
+
mcp_tools.append(tool)
|
|
163
|
+
case "subagents":
|
|
164
|
+
subagent_tools.append(tool)
|
|
165
|
+
case _:
|
|
166
|
+
plain_tools.append(tool.name)
|
|
167
|
+
tool_tokens += _tool_tokens(tool)
|
|
168
|
+
tool_names = [*listed["tools"], *plain_tools]
|
|
169
|
+
if tool_tokens or tool_names:
|
|
170
|
+
buckets["tools"] = tool_tokens
|
|
171
|
+
details["tools"] = _name_detail(tool_names, "个工具")
|
|
172
|
+
|
|
173
|
+
mcp_tokens = _chars_to_tokens(section_chars["mcp"]) + sum(
|
|
174
|
+
_tool_tokens(tool) for tool in mcp_tools
|
|
175
|
+
)
|
|
176
|
+
server_names = {server for server in mcp_servers if server} | {
|
|
177
|
+
name for name in (_mcp_server_name(tool.name) for tool in mcp_tools) if name is not None
|
|
178
|
+
}
|
|
179
|
+
server_names |= {
|
|
180
|
+
name
|
|
181
|
+
for name in (_mcp_server_name(tool_name) for tool_name in listed["mcp"])
|
|
182
|
+
if name is not None
|
|
183
|
+
}
|
|
184
|
+
if mcp_tokens:
|
|
185
|
+
buckets["mcp"] = mcp_tokens
|
|
186
|
+
tool_count = len(mcp_tools) or len(listed["mcp"])
|
|
187
|
+
details["mcp"] = _server_detail(server_names, tool_count)
|
|
188
|
+
|
|
189
|
+
subagent_tokens = _chars_to_tokens(section_chars["subagents"]) + sum(
|
|
190
|
+
_tool_tokens(tool) for tool in subagent_tools
|
|
191
|
+
)
|
|
192
|
+
if subagent_tokens:
|
|
193
|
+
buckets["subagents"] = subagent_tokens
|
|
194
|
+
details["subagents"] = _subagent_detail(subagent_names, bool(subagent_tools))
|
|
195
|
+
|
|
196
|
+
summary_tokens = 0
|
|
197
|
+
summary_kinds: list[str] = []
|
|
198
|
+
conversation_tokens = 0
|
|
199
|
+
conversation_count = 0
|
|
200
|
+
for message in messages:
|
|
201
|
+
if isinstance(message, SystemMessage):
|
|
202
|
+
continue
|
|
203
|
+
if isinstance(message, CompactionSummaryMessage):
|
|
204
|
+
summary_tokens += estimate_tokens(message)
|
|
205
|
+
summary_kinds.append("压缩摘要")
|
|
206
|
+
continue
|
|
207
|
+
if isinstance(message, BranchSummaryMessage):
|
|
208
|
+
summary_tokens += estimate_tokens(message)
|
|
209
|
+
summary_kinds.append("分支摘要")
|
|
210
|
+
continue
|
|
211
|
+
conversation_tokens += estimate_tokens(message)
|
|
212
|
+
conversation_count += 1
|
|
213
|
+
|
|
214
|
+
if summary_tokens:
|
|
215
|
+
buckets["summary"] = summary_tokens
|
|
216
|
+
details["summary"] = "、".join(dict.fromkeys(summary_kinds))
|
|
217
|
+
if conversation_tokens or conversation_count:
|
|
218
|
+
buckets["conversation"] = conversation_tokens
|
|
219
|
+
details["conversation"] = f"{conversation_count} 条消息"
|
|
220
|
+
|
|
221
|
+
parts = tuple(
|
|
222
|
+
ContextPart(
|
|
223
|
+
key=key,
|
|
224
|
+
label=_PART_LABELS[key],
|
|
225
|
+
tokens=buckets[key],
|
|
226
|
+
detail=details.get(key, ""),
|
|
227
|
+
)
|
|
228
|
+
for key in _PART_ORDER
|
|
229
|
+
if key in buckets
|
|
230
|
+
)
|
|
231
|
+
estimated = sum(part.tokens for part in parts)
|
|
232
|
+
total = total_tokens if total_tokens > 0 else estimated
|
|
233
|
+
return ContextBreakdown(
|
|
234
|
+
parts=parts,
|
|
235
|
+
total_tokens=total,
|
|
236
|
+
estimated_tokens=estimated,
|
|
237
|
+
residual_tokens=total - estimated,
|
|
238
|
+
context_window=context_window,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _chars_to_tokens(chars: int) -> int:
|
|
243
|
+
"""字符数按 4 字符一个 token 向上取整,与压缩模块的口径一致。"""
|
|
244
|
+
return ceil(chars / 4) if chars > 0 else 0
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _tool_tokens(tool: Tool) -> int:
|
|
248
|
+
"""一条工具声明的估算体积:名字、描述与参数 JSON 都算进去。"""
|
|
249
|
+
return estimate_tokens(SystemMessage(timestamp=0, content="", tools_added=[tool]))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _listed_tool_name(line: str) -> str | None:
|
|
253
|
+
"""工具清单里 ``- name: 介绍`` 一行的工具名;其他行返回 ``None``。"""
|
|
254
|
+
matched = _TOOL_LINE.match(line)
|
|
255
|
+
return matched.group("name") if matched is not None else None
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _tool_bucket(name: str) -> str:
|
|
259
|
+
"""工具名归到哪个分项:MCP、子代理或普通工具。"""
|
|
260
|
+
if name.startswith(_MCP_TOOL_PREFIX):
|
|
261
|
+
return "mcp"
|
|
262
|
+
if name == _TASK_TOOL_NAME:
|
|
263
|
+
return "subagents"
|
|
264
|
+
return "tools"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _mcp_server_name(tool_name: str) -> str | None:
|
|
268
|
+
"""``mcp__<server>__<tool>`` 里的服务器名;形状不符时返回 ``None``。"""
|
|
269
|
+
parts = tool_name.split("__")
|
|
270
|
+
if len(parts) < 3 or parts[0] != "mcp":
|
|
271
|
+
return None
|
|
272
|
+
return parts[1] or None
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _name_detail(names: Sequence[str], suffix: str) -> str:
|
|
276
|
+
unique = [name for name in dict.fromkeys(names) if name]
|
|
277
|
+
if not unique:
|
|
278
|
+
return ""
|
|
279
|
+
shown = "、".join(unique[:4])
|
|
280
|
+
if len(unique) > 4:
|
|
281
|
+
shown += f" 等 {len(unique)} {suffix}"
|
|
282
|
+
return shown
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _server_detail(names: set[str], tool_count: int) -> str:
|
|
286
|
+
unique = sorted(name for name in names if name)
|
|
287
|
+
shown = "、".join(unique) if unique else "工具声明"
|
|
288
|
+
if tool_count:
|
|
289
|
+
return f"{shown} · {tool_count} 个工具"
|
|
290
|
+
return shown
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _subagent_detail(names: Sequence[str], has_tool: bool) -> str:
|
|
294
|
+
unique = [name for name in dict.fromkeys(names) if name]
|
|
295
|
+
shown = "、".join(unique[:6])
|
|
296
|
+
if len(unique) > 6:
|
|
297
|
+
shown += f" 等 {len(unique)} 个"
|
|
298
|
+
if shown and has_tool:
|
|
299
|
+
return f"{shown} · task 工具声明"
|
|
300
|
+
if shown:
|
|
301
|
+
return shown
|
|
302
|
+
return "task 工具声明"
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""会话发现:把会话目录读成一份可以续接的清单。
|
|
2
|
+
|
|
3
|
+
会话文件是追加式 JSONL,续接需要三样东西:**哪个文件、什么时候动过、里面在聊什么**。
|
|
4
|
+
后两样只有读内容才知道,所以这里读整份文件,而不是只看文件名或 mtime:
|
|
5
|
+
|
|
6
|
+
- 文件名里的时间戳是会话创建时间,不是最后一次活动时间;
|
|
7
|
+
- mtime 会被备份、``git checkout``、复制工具改写;
|
|
8
|
+
- 显示名(``session_info``)与首条用户消息可能落在文件任意位置,压缩之后尤其如此。
|
|
9
|
+
|
|
10
|
+
排序用**最后一条条目的时间戳**,它是会话自己的事实。代价与文件总字节数成正比,
|
|
11
|
+
因此 :func:`list_sessions` 先读完全部再截断,并如实报告总数。
|
|
12
|
+
|
|
13
|
+
坏文件不静默丢弃:解析失败进 :class:`SkippedSession`,由调用方打印。一条损坏的
|
|
14
|
+
会话不该让整个列表报错,也不该被悄悄藏起来——用户会以为那份会话丢了。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Final
|
|
25
|
+
|
|
26
|
+
from braid_ai.types import JsonValue, UserMessage
|
|
27
|
+
from braid_ai.wire import content_text
|
|
28
|
+
from braid_coding_agent.session.entries import (
|
|
29
|
+
SessionFormatError,
|
|
30
|
+
SessionHeader,
|
|
31
|
+
SessionInfoEntry,
|
|
32
|
+
SessionMessageEntry,
|
|
33
|
+
entry_from_wire,
|
|
34
|
+
ms_from_iso,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
#: 清单里标题最多保留多少个字符。再长就没有区分度,只是把行撑爆。
|
|
38
|
+
TITLE_LIMIT: Final[int] = 60
|
|
39
|
+
#: 默认返回多少条。
|
|
40
|
+
DEFAULT_LIST_LIMIT: Final[int] = 20
|
|
41
|
+
#: 会话文件后缀。会话目录里还有快照子目录与锁文件,只认这个后缀。
|
|
42
|
+
SESSION_SUFFIX: Final[str] = ".jsonl"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class SessionSummary:
|
|
47
|
+
"""一份会话文件的摘要。字段全部来自文件内容,没有一个来自文件名。"""
|
|
48
|
+
|
|
49
|
+
path: str
|
|
50
|
+
session_id: str
|
|
51
|
+
cwd: str
|
|
52
|
+
created_at: str
|
|
53
|
+
updated_at: str
|
|
54
|
+
name: str | None
|
|
55
|
+
parent_session: str | None
|
|
56
|
+
first_user_message: str | None
|
|
57
|
+
messages: int
|
|
58
|
+
version: int | None
|
|
59
|
+
|
|
60
|
+
def title(self) -> str:
|
|
61
|
+
"""给人看的名字:显示名 → 首条用户消息 → 会话 id。"""
|
|
62
|
+
if self.name:
|
|
63
|
+
return self.name
|
|
64
|
+
if self.first_user_message:
|
|
65
|
+
return self.first_user_message
|
|
66
|
+
return self.session_id
|
|
67
|
+
|
|
68
|
+
def describe(self) -> str:
|
|
69
|
+
"""一行摘要:最后活动时间(本地)· 标题 · 消息数。"""
|
|
70
|
+
return f"{_local_minute(self.updated_at)} · {self.title()} · {self.messages} 条消息"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class SkippedSession:
|
|
75
|
+
"""读不出来的会话文件与原因。"""
|
|
76
|
+
|
|
77
|
+
path: str
|
|
78
|
+
reason: str
|
|
79
|
+
|
|
80
|
+
def describe(self) -> str:
|
|
81
|
+
return f"{self.path}:{self.reason}"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True, slots=True)
|
|
85
|
+
class SessionListing:
|
|
86
|
+
"""一次目录扫描的结果。``sessions`` 已按最后活动时间倒序并截断。"""
|
|
87
|
+
|
|
88
|
+
sessions: tuple[SessionSummary, ...]
|
|
89
|
+
skipped: tuple[SkippedSession, ...]
|
|
90
|
+
#: 目录里的会话文件总数(含读取失败的),用来告诉用户"还有多少没显示"。
|
|
91
|
+
total: int
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def list_sessions(session_dir: str, *, limit: int = DEFAULT_LIST_LIMIT) -> SessionListing:
|
|
95
|
+
"""列出 ``session_dir`` 下的会话,最近活动的在前。
|
|
96
|
+
|
|
97
|
+
:param limit: 最多返回多少条(排序之后截断)。
|
|
98
|
+
:raises ValueError: ``limit`` 不为正。
|
|
99
|
+
"""
|
|
100
|
+
if limit <= 0:
|
|
101
|
+
raise ValueError(f"limit 必须为正整数,收到 {limit}")
|
|
102
|
+
if not os.path.isdir(session_dir):
|
|
103
|
+
return SessionListing(sessions=(), skipped=(), total=0)
|
|
104
|
+
|
|
105
|
+
summaries: list[SessionSummary] = []
|
|
106
|
+
skipped: list[SkippedSession] = []
|
|
107
|
+
for name in sorted(os.listdir(session_dir)):
|
|
108
|
+
if not name.endswith(SESSION_SUFFIX):
|
|
109
|
+
continue
|
|
110
|
+
path = os.path.join(session_dir, name)
|
|
111
|
+
try:
|
|
112
|
+
summaries.append(read_session_summary(path))
|
|
113
|
+
except (SessionFormatError, OSError, UnicodeDecodeError) as error:
|
|
114
|
+
skipped.append(SkippedSession(path=path, reason=str(error)))
|
|
115
|
+
|
|
116
|
+
summaries.sort(key=lambda item: ms_from_iso(item.updated_at), reverse=True)
|
|
117
|
+
return SessionListing(
|
|
118
|
+
sessions=tuple(summaries[:limit]),
|
|
119
|
+
skipped=tuple(skipped),
|
|
120
|
+
total=len(summaries) + len(skipped),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def read_session_summary(path: str) -> SessionSummary:
|
|
125
|
+
"""读一份会话文件,得到摘要。
|
|
126
|
+
|
|
127
|
+
最后一行不完整(写入中途崩溃)时忽略它;中间出现坏行则整份文件判为损坏——
|
|
128
|
+
已经写了换行说明不是截断,是真实损坏,继续读下去只会得到一份错的摘要。
|
|
129
|
+
|
|
130
|
+
:raises SessionFormatError: 不是会话文件,或内容损坏。
|
|
131
|
+
:raises OSError: 文件读不出来。
|
|
132
|
+
"""
|
|
133
|
+
text = Path(path).read_text(encoding="utf-8")
|
|
134
|
+
raw_entries = _read_entries(text, path)
|
|
135
|
+
header_entry = entry_from_wire(raw_entries[0])
|
|
136
|
+
if not isinstance(header_entry, SessionHeader):
|
|
137
|
+
raise SessionFormatError(f"{path} 不是会话文件:首条记录不是 session 头")
|
|
138
|
+
|
|
139
|
+
updated_at = header_entry.timestamp
|
|
140
|
+
name: str | None = None
|
|
141
|
+
first_user_message: str | None = None
|
|
142
|
+
messages = 0
|
|
143
|
+
for raw in raw_entries[1:]:
|
|
144
|
+
entry = entry_from_wire(raw)
|
|
145
|
+
if ms_from_iso(entry.timestamp) > ms_from_iso(updated_at):
|
|
146
|
+
updated_at = entry.timestamp
|
|
147
|
+
if isinstance(entry, SessionInfoEntry):
|
|
148
|
+
# 空名字是显式清除,与 Manager.get_session_name 保持同一条规则。
|
|
149
|
+
name = entry.name.strip() if entry.name and entry.name.strip() else None
|
|
150
|
+
continue
|
|
151
|
+
if isinstance(entry, SessionMessageEntry):
|
|
152
|
+
messages += 1
|
|
153
|
+
if first_user_message is None and isinstance(entry.message, UserMessage):
|
|
154
|
+
first_user_message = _clip(content_text(entry.message.content))
|
|
155
|
+
return SessionSummary(
|
|
156
|
+
path=os.path.abspath(path),
|
|
157
|
+
session_id=header_entry.id,
|
|
158
|
+
cwd=header_entry.cwd,
|
|
159
|
+
created_at=header_entry.timestamp,
|
|
160
|
+
updated_at=updated_at,
|
|
161
|
+
name=name,
|
|
162
|
+
parent_session=header_entry.parent_session,
|
|
163
|
+
first_user_message=first_user_message,
|
|
164
|
+
messages=messages,
|
|
165
|
+
version=header_entry.version,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _read_entries(text: str, path: str) -> list[dict[str, JsonValue]]:
|
|
170
|
+
"""逐行解析成 raw 条目,只容忍末行的截断。"""
|
|
171
|
+
lines = text.split("\n")
|
|
172
|
+
entries: list[dict[str, JsonValue]] = []
|
|
173
|
+
for index, line in enumerate(lines):
|
|
174
|
+
if not line.strip():
|
|
175
|
+
continue
|
|
176
|
+
try:
|
|
177
|
+
parsed: JsonValue = json.loads(line)
|
|
178
|
+
except json.JSONDecodeError:
|
|
179
|
+
if index == len(lines) - 1:
|
|
180
|
+
break
|
|
181
|
+
raise SessionFormatError(f"{path} 第 {index + 1} 行不是合法 JSON") from None
|
|
182
|
+
if not isinstance(parsed, dict):
|
|
183
|
+
raise SessionFormatError(f"{path} 第 {index + 1} 行不是 JSON 对象")
|
|
184
|
+
entries.append(parsed)
|
|
185
|
+
if not entries:
|
|
186
|
+
raise SessionFormatError(f"{path} 是空文件")
|
|
187
|
+
return entries
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _clip(text: str) -> str:
|
|
191
|
+
"""压成一行并截断。标题要能放进一行终端,换行会把列表排版打散。"""
|
|
192
|
+
flat = " ".join(text.split())
|
|
193
|
+
if len(flat) <= TITLE_LIMIT:
|
|
194
|
+
return flat
|
|
195
|
+
return flat[: TITLE_LIMIT - 1] + "…"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _local_minute(timestamp: str) -> str:
|
|
199
|
+
"""ISO 时间戳 → 本地时区的 ``月-日 时:分``。"""
|
|
200
|
+
return datetime.fromisoformat(timestamp).astimezone().strftime("%m-%d %H:%M")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = [
|
|
204
|
+
"DEFAULT_LIST_LIMIT",
|
|
205
|
+
"SESSION_SUFFIX",
|
|
206
|
+
"TITLE_LIMIT",
|
|
207
|
+
"SessionListing",
|
|
208
|
+
"SessionSummary",
|
|
209
|
+
"SkippedSession",
|
|
210
|
+
"list_sessions",
|
|
211
|
+
"read_session_summary",
|
|
212
|
+
]
|