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,553 @@
|
|
|
1
|
+
"""扩展分发:按加载顺序调用处理器,把异常收成 ``extension_error``,绝不让它穿透。
|
|
2
|
+
|
|
3
|
+
## 三条规则,每条都对应一种会在真实使用中咬人的情况
|
|
4
|
+
|
|
5
|
+
**① 顺序 = 加载顺序。** 同一事件上多个处理器按扩展加载顺序、扩展内注册顺序调用。
|
|
6
|
+
"谁生效"因此是数据可查的:不依赖字典遍历顺序,也不依赖某个注册中心的权重字段。
|
|
7
|
+
|
|
8
|
+
**② 异常被收成数据。** 处理器抛异常不会中断分发:收成 :class:`ExtensionError`,
|
|
9
|
+
交给错误监听方,然后继续下一个。唯一的例外是 ``before_tool_call``——它**失败即阻断**
|
|
10
|
+
(fail closed):权限钩子算不出结论时放行,等于把最需要拦的调用放过去。
|
|
11
|
+
|
|
12
|
+
**③ 返回值是"建议",不是"副作用"。** 处理器拿到的消息列表、工具结果都是副本;
|
|
13
|
+
它们要改什么,得在返回值里说清楚,由内核合并。这样"这次请求为什么长这样"始终
|
|
14
|
+
能追到一条钩子返回值。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import importlib.util
|
|
20
|
+
import inspect
|
|
21
|
+
import logging
|
|
22
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
23
|
+
from dataclasses import dataclass, replace
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import cast
|
|
26
|
+
|
|
27
|
+
from braid_agent.tools import AgentTool
|
|
28
|
+
from braid_agent.types import (
|
|
29
|
+
AfterToolCallContext,
|
|
30
|
+
AfterToolCallResult,
|
|
31
|
+
AgentEndEvent,
|
|
32
|
+
AgentMessage,
|
|
33
|
+
BeforeToolCallContext,
|
|
34
|
+
BeforeToolCallResult,
|
|
35
|
+
)
|
|
36
|
+
from braid_ai.transcript import get_current_system_message
|
|
37
|
+
from braid_ai.types import ImageContent, Message, SystemMessage, TextContent
|
|
38
|
+
from braid_ai.wire import system_message_text
|
|
39
|
+
from braid_coding_agent.extensions.api import (
|
|
40
|
+
AppendEntryAction,
|
|
41
|
+
BeforeAgentStartEvent,
|
|
42
|
+
BeforeAgentStartPatch,
|
|
43
|
+
BeforeAgentStartResult,
|
|
44
|
+
ContextEvent,
|
|
45
|
+
ContextResult,
|
|
46
|
+
Extension,
|
|
47
|
+
ExtensionAPI,
|
|
48
|
+
ExtensionError,
|
|
49
|
+
ExtensionErrorListener,
|
|
50
|
+
ExtensionHandler,
|
|
51
|
+
ExtensionRuntime,
|
|
52
|
+
RegisteredCommand,
|
|
53
|
+
SessionBeforeCompactEvent,
|
|
54
|
+
SessionBeforeCompactResult,
|
|
55
|
+
SessionShutdownEvent,
|
|
56
|
+
ToolCallEvent,
|
|
57
|
+
ToolResultEvent,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
logger = logging.getLogger(__name__)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ExtensionLoadError(Exception):
|
|
64
|
+
"""扩展装载失败:模块导入不了、没有 ``activate``、或激活时抛了异常。
|
|
65
|
+
|
|
66
|
+
它与运行期失败是两件事:这里**就地失败**,因为"配置里有一个跑不起来的扩展"
|
|
67
|
+
没有合理的降级形态——带着半个扩展运行会让用户以为能力已经生效。
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(slots=True)
|
|
72
|
+
class LoadedExtension:
|
|
73
|
+
"""一个已装载扩展的记录:名字、来源、以及它自己的注册表。"""
|
|
74
|
+
|
|
75
|
+
name: str
|
|
76
|
+
api: ExtensionAPI
|
|
77
|
+
source: str = "<inline>"
|
|
78
|
+
|
|
79
|
+
def tools(self) -> list[AgentTool]:
|
|
80
|
+
"""该扩展注册的工具。"""
|
|
81
|
+
return self.api.tools()
|
|
82
|
+
|
|
83
|
+
def commands(self) -> list[RegisteredCommand]:
|
|
84
|
+
"""该扩展注册的命令。"""
|
|
85
|
+
return self.api.commands()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ExtensionRunner:
|
|
89
|
+
"""全部扩展的容器与分发器。
|
|
90
|
+
|
|
91
|
+
它只做三件事:装载/卸载、按顺序分发、把异常变成事件。它不知道 Agent、会话树、
|
|
92
|
+
模型目录的存在——那些是 :class:`~braid_coding_agent.session.agent_session.AgentSession`
|
|
93
|
+
的责任:会话把钩子挂到内核上,再转交给这里。
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(self) -> None:
|
|
97
|
+
self._extensions: list[LoadedExtension] = []
|
|
98
|
+
self._runtime = ExtensionRuntime()
|
|
99
|
+
self._error_listeners: list[ExtensionErrorListener] = []
|
|
100
|
+
self._module_seq = 0
|
|
101
|
+
|
|
102
|
+
# ------------------------------------------------------------ 装载/卸载
|
|
103
|
+
|
|
104
|
+
async def load(self, extension: Extension, *, source: str = "<inline>") -> LoadedExtension:
|
|
105
|
+
"""激活一个扩展并记录它。
|
|
106
|
+
|
|
107
|
+
:raises ExtensionLoadError: 名字为空/重复,或 ``activate`` 抛了异常。
|
|
108
|
+
"""
|
|
109
|
+
name = extension.name
|
|
110
|
+
if not name:
|
|
111
|
+
raise ValueError("扩展必须有非空名字")
|
|
112
|
+
if self.get(name) is not None:
|
|
113
|
+
raise ExtensionLoadError(f"扩展 {name} 已装载")
|
|
114
|
+
api = ExtensionAPI(name, self._runtime)
|
|
115
|
+
try:
|
|
116
|
+
outcome = extension.activate(api)
|
|
117
|
+
if inspect.isawaitable(outcome):
|
|
118
|
+
await outcome
|
|
119
|
+
except Exception as exc:
|
|
120
|
+
raise ExtensionLoadError(f"扩展 {name} 激活失败: {exc}") from exc
|
|
121
|
+
loaded = LoadedExtension(name=name, api=api, source=source)
|
|
122
|
+
self._extensions.append(loaded)
|
|
123
|
+
await self._report_registration_conflicts(loaded)
|
|
124
|
+
return loaded
|
|
125
|
+
|
|
126
|
+
async def load_module(self, path: str | Path, *, name: str | None = None) -> LoadedExtension:
|
|
127
|
+
"""从 Python 文件装载扩展:模块里必须有一个 ``activate(api)`` 函数。
|
|
128
|
+
|
|
129
|
+
按文件路径导入而不是 ``import`` 包名:扩展是用户放在任意目录下的脚本,
|
|
130
|
+
不要求它可导入。模块名带序号,同一个文件被装载两次也不会共用模块对象。
|
|
131
|
+
|
|
132
|
+
:raises ExtensionLoadError: 文件不存在、导入失败、没有 ``activate``。
|
|
133
|
+
"""
|
|
134
|
+
module_path = Path(path).expanduser()
|
|
135
|
+
if not module_path.is_file():
|
|
136
|
+
raise ExtensionLoadError(f"扩展文件不存在: {path}")
|
|
137
|
+
self._module_seq += 1
|
|
138
|
+
spec = importlib.util.spec_from_file_location(
|
|
139
|
+
f"pi_extension_{module_path.stem}_{self._module_seq}", module_path
|
|
140
|
+
)
|
|
141
|
+
if spec is None or spec.loader is None:
|
|
142
|
+
raise ExtensionLoadError(f"无法从文件装载扩展: {path}")
|
|
143
|
+
module = importlib.util.module_from_spec(spec)
|
|
144
|
+
try:
|
|
145
|
+
spec.loader.exec_module(module)
|
|
146
|
+
except Exception as exc:
|
|
147
|
+
raise ExtensionLoadError(f"扩展 {path} 导入失败: {exc}") from exc
|
|
148
|
+
activate = getattr(module, "activate", None)
|
|
149
|
+
if not callable(activate):
|
|
150
|
+
raise ExtensionLoadError(f"扩展 {path} 没有定义 activate(api) 函数")
|
|
151
|
+
return await self.load(
|
|
152
|
+
_ModuleExtension(
|
|
153
|
+
name or module_path.stem,
|
|
154
|
+
cast("Callable[[ExtensionAPI], Awaitable[None] | None]", activate),
|
|
155
|
+
),
|
|
156
|
+
source=str(module_path),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def unload(self, name: str) -> bool:
|
|
160
|
+
"""卸载一个扩展:它的工具、命令、处理器一起失效。
|
|
161
|
+
|
|
162
|
+
已经产生的消息留在转录里(历史不因为卸载而改写),但下一回合的请求不再
|
|
163
|
+
声明它的工具——工具声明差异由循环在请求前算出来。
|
|
164
|
+
"""
|
|
165
|
+
for index, loaded in enumerate(self._extensions):
|
|
166
|
+
if loaded.name == name:
|
|
167
|
+
del self._extensions[index]
|
|
168
|
+
return True
|
|
169
|
+
return False
|
|
170
|
+
|
|
171
|
+
def get(self, name: str) -> LoadedExtension | None:
|
|
172
|
+
"""按名字取一个已装载扩展。"""
|
|
173
|
+
for loaded in self._extensions:
|
|
174
|
+
if loaded.name == name:
|
|
175
|
+
return loaded
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def extensions(self) -> list[LoadedExtension]:
|
|
180
|
+
"""已装载扩展,按加载顺序。"""
|
|
181
|
+
return list(self._extensions)
|
|
182
|
+
|
|
183
|
+
@property
|
|
184
|
+
def names(self) -> list[str]:
|
|
185
|
+
"""已装载扩展的名字,按加载顺序。"""
|
|
186
|
+
return [loaded.name for loaded in self._extensions]
|
|
187
|
+
|
|
188
|
+
def bind_append_entry(self, action: AppendEntryAction) -> None:
|
|
189
|
+
"""绑定"追加自定义条目"动作。由会话在构造时调用一次。"""
|
|
190
|
+
self._runtime.append_entry = action
|
|
191
|
+
|
|
192
|
+
# ------------------------------------------------------------ 注册表读取
|
|
193
|
+
|
|
194
|
+
def tools(self) -> list[AgentTool]:
|
|
195
|
+
"""全部扩展注册的工具,按加载顺序;同名先到先得。"""
|
|
196
|
+
tools: dict[str, AgentTool] = {}
|
|
197
|
+
for loaded in self._extensions:
|
|
198
|
+
for tool in loaded.tools():
|
|
199
|
+
tools.setdefault(tool.name, tool)
|
|
200
|
+
return list(tools.values())
|
|
201
|
+
|
|
202
|
+
def commands(self) -> dict[str, RegisteredCommand]:
|
|
203
|
+
"""全部扩展注册的命令,按键名;同名先到先得。"""
|
|
204
|
+
commands: dict[str, RegisteredCommand] = {}
|
|
205
|
+
for loaded in self._extensions:
|
|
206
|
+
for command in loaded.commands():
|
|
207
|
+
commands.setdefault(command.name, command)
|
|
208
|
+
return commands
|
|
209
|
+
|
|
210
|
+
def has_handlers(self, event: str) -> bool:
|
|
211
|
+
"""某个事件上是否还有处理器。没有处理器时调用方可以跳过整个分发。"""
|
|
212
|
+
return any(loaded.api.handlers(event) for loaded in self._extensions)
|
|
213
|
+
|
|
214
|
+
# ---------------------------------------------------------------- 错误
|
|
215
|
+
|
|
216
|
+
def on_error(self, listener: ExtensionErrorListener) -> Callable[[], None]:
|
|
217
|
+
"""注册错误监听方,返回取消注册的函数。"""
|
|
218
|
+
self._error_listeners.append(listener)
|
|
219
|
+
|
|
220
|
+
def unsubscribe() -> None:
|
|
221
|
+
if listener in self._error_listeners:
|
|
222
|
+
self._error_listeners.remove(listener)
|
|
223
|
+
|
|
224
|
+
return unsubscribe
|
|
225
|
+
|
|
226
|
+
async def _report(self, extension: str, event: str, error: BaseException | str) -> None:
|
|
227
|
+
"""把一个扩展失败变成 :class:`ExtensionError` 并广播。
|
|
228
|
+
|
|
229
|
+
日志与事件都要发:事件给用户看,日志给排查用。只发事件的话,非交互模式下
|
|
230
|
+
一次失败会随着进程退出而彻底消失。
|
|
231
|
+
"""
|
|
232
|
+
detail = error if isinstance(error, str) else _describe(error)
|
|
233
|
+
record = ExtensionError(extension=extension, event=event, error=detail)
|
|
234
|
+
logger.warning("扩展 %s 在 %s 上失败: %s", extension, event, detail)
|
|
235
|
+
for listener in list(self._error_listeners):
|
|
236
|
+
outcome = listener(record)
|
|
237
|
+
if inspect.isawaitable(outcome):
|
|
238
|
+
await outcome
|
|
239
|
+
|
|
240
|
+
async def _report_registration_conflicts(self, loaded: LoadedExtension) -> None:
|
|
241
|
+
"""把重名工具/命令记一条错误。先注册者生效,后来者可见但不静默。"""
|
|
242
|
+
others = [other for other in self._extensions if other is not loaded]
|
|
243
|
+
known_tools = {tool.name for other in others for tool in other.tools()}
|
|
244
|
+
for tool in loaded.tools():
|
|
245
|
+
if tool.name in known_tools:
|
|
246
|
+
await self._report(
|
|
247
|
+
loaded.name, "register_tool", f"工具 {tool.name} 已被更早装载的扩展注册"
|
|
248
|
+
)
|
|
249
|
+
known_commands = {command.name for other in others for command in other.commands()}
|
|
250
|
+
for command in loaded.commands():
|
|
251
|
+
if command.name in known_commands:
|
|
252
|
+
await self._report(
|
|
253
|
+
loaded.name,
|
|
254
|
+
"register_command",
|
|
255
|
+
f"命令 /{command.name} 已被更早装载的扩展注册",
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
# ---------------------------------------------------------------- 分发
|
|
259
|
+
|
|
260
|
+
async def emit(self, event: AgentEndEvent | SessionShutdownEvent) -> None:
|
|
261
|
+
"""观察型事件:分发完就结束,返回值忽略。
|
|
262
|
+
|
|
263
|
+
处理器慢会拖慢 run(``agent_end`` 的订阅者是 run 的一部分)。所以观察型处理器
|
|
264
|
+
只应做通知类的工作,长任务要先排队。
|
|
265
|
+
"""
|
|
266
|
+
for loaded, handler in self._handlers(event.type):
|
|
267
|
+
try:
|
|
268
|
+
outcome = handler(event)
|
|
269
|
+
if inspect.isawaitable(outcome):
|
|
270
|
+
await outcome
|
|
271
|
+
except Exception as exc:
|
|
272
|
+
await self._report(loaded.name, event.type, exc)
|
|
273
|
+
|
|
274
|
+
async def emit_before_agent_start(self, event: BeforeAgentStartEvent) -> BeforeAgentStartResult:
|
|
275
|
+
"""``before_agent_start``:逐节合并提示词改动,收集要追加的消息。
|
|
276
|
+
|
|
277
|
+
每个处理器看到的分节都是**前面处理器改过之后**的版本,所以同节冲突由
|
|
278
|
+
加载顺序决定——最后改的那次生效。
|
|
279
|
+
"""
|
|
280
|
+
sections: dict[str, str] = dict(event.sections)
|
|
281
|
+
messages: list[AgentMessage] = []
|
|
282
|
+
for loaded, handler in self._handlers("before_agent_start"):
|
|
283
|
+
current = replace(
|
|
284
|
+
event, sections=dict(sections), system_prompt=render_prompt_sections(sections)
|
|
285
|
+
)
|
|
286
|
+
try:
|
|
287
|
+
outcome = handler(current)
|
|
288
|
+
if inspect.isawaitable(outcome):
|
|
289
|
+
outcome = await outcome
|
|
290
|
+
except Exception as exc:
|
|
291
|
+
await self._report(loaded.name, "before_agent_start", exc)
|
|
292
|
+
continue
|
|
293
|
+
if outcome is None:
|
|
294
|
+
continue
|
|
295
|
+
if not isinstance(outcome, BeforeAgentStartPatch):
|
|
296
|
+
await self._report(
|
|
297
|
+
loaded.name,
|
|
298
|
+
"before_agent_start",
|
|
299
|
+
f"处理器必须返回 BeforeAgentStartPatch 或 None,收到 {type(outcome).__name__}",
|
|
300
|
+
)
|
|
301
|
+
continue
|
|
302
|
+
if outcome.sections:
|
|
303
|
+
for name, text in outcome.sections.items():
|
|
304
|
+
if text is None:
|
|
305
|
+
sections.pop(name, None)
|
|
306
|
+
else:
|
|
307
|
+
sections[name] = text
|
|
308
|
+
if outcome.message is not None:
|
|
309
|
+
# ``CustomMessage.role`` 是 ``ClassVar``,结构上不满足 ``CustomAgentMessage``
|
|
310
|
+
# 对可变属性的要求(原因见 :mod:`braid_agent.types` 的注解)。循环只读
|
|
311
|
+
# ``role``,``convert_to_llm`` 按类型分派,所以这里收窄是安全的。
|
|
312
|
+
messages.append(cast("AgentMessage", outcome.message))
|
|
313
|
+
return BeforeAgentStartResult(sections=sections, messages=messages)
|
|
314
|
+
|
|
315
|
+
async def emit_context(self, messages: Sequence[AgentMessage]) -> list[AgentMessage]:
|
|
316
|
+
"""``context``:逐个处理器改写对话,返回最终要发给模型的那份。
|
|
317
|
+
|
|
318
|
+
每个处理器只看得到**对话**(系统消息被摘掉);返回之后内核把系统消息放回去。
|
|
319
|
+
没改就原样返回同一个列表,这样"没动过"与"动成了空列表"不会混淆。
|
|
320
|
+
"""
|
|
321
|
+
current: list[AgentMessage] = list(messages)
|
|
322
|
+
for loaded, handler in self._handlers("context"):
|
|
323
|
+
visible: list[AgentMessage] = [
|
|
324
|
+
message for message in current if message.role != "system"
|
|
325
|
+
]
|
|
326
|
+
snapshot = list(visible)
|
|
327
|
+
try:
|
|
328
|
+
outcome = handler(ContextEvent(messages=visible))
|
|
329
|
+
if inspect.isawaitable(outcome):
|
|
330
|
+
outcome = await outcome
|
|
331
|
+
except Exception as exc:
|
|
332
|
+
await self._report(loaded.name, "context", exc)
|
|
333
|
+
continue
|
|
334
|
+
if outcome is None:
|
|
335
|
+
# 处理器可能原地改过 event.messages;没改就跳过。
|
|
336
|
+
if _same_messages(visible, snapshot):
|
|
337
|
+
continue
|
|
338
|
+
current = _restore_system_messages(current, snapshot, visible)
|
|
339
|
+
continue
|
|
340
|
+
if not isinstance(outcome, ContextResult):
|
|
341
|
+
await self._report(
|
|
342
|
+
loaded.name,
|
|
343
|
+
"context",
|
|
344
|
+
f"处理器必须返回 ContextResult 或 None,收到 {type(outcome).__name__}",
|
|
345
|
+
)
|
|
346
|
+
continue
|
|
347
|
+
if outcome.messages is None:
|
|
348
|
+
continue
|
|
349
|
+
current = _restore_system_messages(current, snapshot, outcome.messages)
|
|
350
|
+
return current
|
|
351
|
+
|
|
352
|
+
async def emit_before_tool_call(
|
|
353
|
+
self, context: BeforeToolCallContext
|
|
354
|
+
) -> BeforeToolCallResult | None:
|
|
355
|
+
"""``before_tool_call``:任一处理器阻断即阻断;处理器抛异常按阻断处理。
|
|
356
|
+
|
|
357
|
+
失败即阻断(fail closed)不是保守,是唯一说得通的选择:权限钩子的异常通常
|
|
358
|
+
意味着"我把策略读错了",这时放行等于放过去一个本该被拦的调用。
|
|
359
|
+
"""
|
|
360
|
+
event = ToolCallEvent(
|
|
361
|
+
tool_name=context.tool_call.name,
|
|
362
|
+
tool_call_id=context.tool_call.id,
|
|
363
|
+
args=dict(context.args),
|
|
364
|
+
)
|
|
365
|
+
result: BeforeToolCallResult | None = None
|
|
366
|
+
for loaded, handler in self._handlers("before_tool_call"):
|
|
367
|
+
try:
|
|
368
|
+
outcome = handler(event)
|
|
369
|
+
if inspect.isawaitable(outcome):
|
|
370
|
+
outcome = await outcome
|
|
371
|
+
except Exception as exc:
|
|
372
|
+
await self._report(loaded.name, "before_tool_call", exc)
|
|
373
|
+
return BeforeToolCallResult(
|
|
374
|
+
block=True, reason=f"扩展 {loaded.name} 出错,调用被阻断: {_describe(exc)}"
|
|
375
|
+
)
|
|
376
|
+
if outcome is None:
|
|
377
|
+
continue
|
|
378
|
+
if not isinstance(outcome, BeforeToolCallResult):
|
|
379
|
+
await self._report(
|
|
380
|
+
loaded.name,
|
|
381
|
+
"before_tool_call",
|
|
382
|
+
f"处理器必须返回 BeforeToolCallResult 或 None,收到 {type(outcome).__name__}",
|
|
383
|
+
)
|
|
384
|
+
continue
|
|
385
|
+
if outcome.block:
|
|
386
|
+
return outcome
|
|
387
|
+
result = outcome
|
|
388
|
+
return result
|
|
389
|
+
|
|
390
|
+
async def emit_after_tool_call(
|
|
391
|
+
self, context: AfterToolCallContext
|
|
392
|
+
) -> AfterToolCallResult | None:
|
|
393
|
+
"""``after_tool_call``:字段级合并多个处理器的覆盖。
|
|
394
|
+
|
|
395
|
+
每个处理器看到的是**前面改过之后**的结果。覆盖了 ``content`` 却没给
|
|
396
|
+
``structured_content`` 时,结构化结果一并作废——两份内容不一致比没有更糟。
|
|
397
|
+
"""
|
|
398
|
+
content: list[TextContent | ImageContent] = list(context.result.content)
|
|
399
|
+
details = context.result.details
|
|
400
|
+
structured = context.result.structured_content
|
|
401
|
+
is_error = context.is_error
|
|
402
|
+
usage = context.result.usage
|
|
403
|
+
modified = False
|
|
404
|
+
for loaded, handler in self._handlers("after_tool_call"):
|
|
405
|
+
event = ToolResultEvent(
|
|
406
|
+
tool_name=context.tool_call.name,
|
|
407
|
+
tool_call_id=context.tool_call.id,
|
|
408
|
+
args=dict(context.args),
|
|
409
|
+
content=list(content),
|
|
410
|
+
details=details,
|
|
411
|
+
structured_content=structured,
|
|
412
|
+
is_error=is_error,
|
|
413
|
+
usage=usage,
|
|
414
|
+
)
|
|
415
|
+
try:
|
|
416
|
+
outcome = handler(event)
|
|
417
|
+
if inspect.isawaitable(outcome):
|
|
418
|
+
outcome = await outcome
|
|
419
|
+
except Exception as exc:
|
|
420
|
+
await self._report(loaded.name, "after_tool_call", exc)
|
|
421
|
+
continue
|
|
422
|
+
if outcome is None:
|
|
423
|
+
continue
|
|
424
|
+
if not isinstance(outcome, AfterToolCallResult):
|
|
425
|
+
await self._report(
|
|
426
|
+
loaded.name,
|
|
427
|
+
"after_tool_call",
|
|
428
|
+
f"处理器必须返回 AfterToolCallResult 或 None,收到 {type(outcome).__name__}",
|
|
429
|
+
)
|
|
430
|
+
continue
|
|
431
|
+
if outcome.content is not None:
|
|
432
|
+
content = list(outcome.content)
|
|
433
|
+
if outcome.structured_content is None:
|
|
434
|
+
structured = None
|
|
435
|
+
modified = True
|
|
436
|
+
if outcome.details is not None:
|
|
437
|
+
details = outcome.details
|
|
438
|
+
modified = True
|
|
439
|
+
if outcome.structured_content is not None:
|
|
440
|
+
structured = outcome.structured_content
|
|
441
|
+
modified = True
|
|
442
|
+
if outcome.is_error is not None:
|
|
443
|
+
is_error = outcome.is_error
|
|
444
|
+
modified = True
|
|
445
|
+
if outcome.usage is not None:
|
|
446
|
+
usage = outcome.usage
|
|
447
|
+
modified = True
|
|
448
|
+
if not modified:
|
|
449
|
+
return None
|
|
450
|
+
return AfterToolCallResult(
|
|
451
|
+
content=list(content),
|
|
452
|
+
details=details,
|
|
453
|
+
structured_content=structured,
|
|
454
|
+
is_error=is_error,
|
|
455
|
+
usage=usage,
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
async def emit_session_before_compact(
|
|
459
|
+
self, event: SessionBeforeCompactEvent
|
|
460
|
+
) -> SessionBeforeCompactResult | None:
|
|
461
|
+
"""``session_before_compact``:取消优先,否则用最后一个给出的摘要。"""
|
|
462
|
+
result: SessionBeforeCompactResult | None = None
|
|
463
|
+
for loaded, handler in self._handlers("session_before_compact"):
|
|
464
|
+
try:
|
|
465
|
+
outcome = handler(event)
|
|
466
|
+
if inspect.isawaitable(outcome):
|
|
467
|
+
outcome = await outcome
|
|
468
|
+
except Exception as exc:
|
|
469
|
+
await self._report(loaded.name, "session_before_compact", exc)
|
|
470
|
+
continue
|
|
471
|
+
if outcome is None:
|
|
472
|
+
continue
|
|
473
|
+
if not isinstance(outcome, SessionBeforeCompactResult):
|
|
474
|
+
await self._report(
|
|
475
|
+
loaded.name,
|
|
476
|
+
"session_before_compact",
|
|
477
|
+
f"处理器必须返回 SessionBeforeCompactResult 或 None,"
|
|
478
|
+
f"收到 {type(outcome).__name__}",
|
|
479
|
+
)
|
|
480
|
+
continue
|
|
481
|
+
if outcome.cancel:
|
|
482
|
+
return outcome
|
|
483
|
+
result = outcome
|
|
484
|
+
return result
|
|
485
|
+
|
|
486
|
+
def _handlers(self, event: str) -> list[tuple[LoadedExtension, ExtensionHandler]]:
|
|
487
|
+
"""``(扩展, 处理器)`` 列表,按加载顺序与注册顺序。
|
|
488
|
+
|
|
489
|
+
先取快照再迭代:处理器在分发过程中取消订阅或装载新扩展,都不影响这一轮。
|
|
490
|
+
"""
|
|
491
|
+
pairs: list[tuple[LoadedExtension, ExtensionHandler]] = []
|
|
492
|
+
for loaded in self._extensions:
|
|
493
|
+
for handler in loaded.api.handlers(event):
|
|
494
|
+
pairs.append((loaded, handler))
|
|
495
|
+
return pairs
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
@dataclass(slots=True)
|
|
499
|
+
class _ModuleExtension:
|
|
500
|
+
"""模块文件装载出来的扩展:模块里的 ``activate`` 就是激活函数。"""
|
|
501
|
+
|
|
502
|
+
name: str
|
|
503
|
+
activate_fn: Callable[[ExtensionAPI], Awaitable[None] | None]
|
|
504
|
+
|
|
505
|
+
def activate(self, api: ExtensionAPI) -> Awaitable[None] | None:
|
|
506
|
+
return self.activate_fn(api)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def render_prompt_sections(sections: dict[str, str]) -> str:
|
|
510
|
+
"""把分节渲染成一段提示词文本,与转录重放的结果一致。"""
|
|
511
|
+
return system_message_text(
|
|
512
|
+
SystemMessage(
|
|
513
|
+
timestamp=0, content="", sections={name: text for name, text in sections.items()}
|
|
514
|
+
)
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _same_messages(left: Sequence[AgentMessage], right: Sequence[AgentMessage]) -> bool:
|
|
519
|
+
"""逐条按**身份**比较。消息是值相等的 dataclass,用 ``==`` 会把"换成一条内容
|
|
520
|
+
相同的消息"误判成"没改"。"""
|
|
521
|
+
return len(left) == len(right) and all(a is b for a, b in zip(left, right, strict=True))
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _restore_system_messages(
|
|
525
|
+
current: Sequence[AgentMessage],
|
|
526
|
+
visible_snapshot: Sequence[AgentMessage],
|
|
527
|
+
returned: Sequence[AgentMessage],
|
|
528
|
+
) -> list[AgentMessage]:
|
|
529
|
+
"""把系统消息放回一份被改写过的对话。
|
|
530
|
+
|
|
531
|
+
对话没变时返回**原来的列表**:多轮之间保持同一份系统消息,模型的缓存前缀才
|
|
532
|
+
不会因为一次无关的 ``context`` 处理器而失效。对话变了则只保留重放出来的那一条
|
|
533
|
+
提示词,放在最前面——剪枝、切片、从摘要重建都不能把提示词丢掉。
|
|
534
|
+
"""
|
|
535
|
+
if _same_messages(returned, visible_snapshot):
|
|
536
|
+
return list(current)
|
|
537
|
+
head = get_current_system_message(cast("list[Message]", list(current)))
|
|
538
|
+
if head is None:
|
|
539
|
+
return list(returned)
|
|
540
|
+
return [head, *returned]
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _describe(error: BaseException) -> str:
|
|
544
|
+
"""异常 → 一行文本。空消息的异常只留类名。"""
|
|
545
|
+
return str(error) or type(error).__name__
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
__all__ = [
|
|
549
|
+
"ExtensionLoadError",
|
|
550
|
+
"ExtensionRunner",
|
|
551
|
+
"LoadedExtension",
|
|
552
|
+
"render_prompt_sections",
|
|
553
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""格式化:按扩展名跑项目自己的格式化命令。
|
|
2
|
+
|
|
3
|
+
- :mod:`.settings` —— ``format`` 的形状与占位符替换(纯数据);
|
|
4
|
+
- :mod:`.tool` —— 模型看到的 ``format`` 工具。
|
|
5
|
+
|
|
6
|
+
导入包本身不执行任何命令。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from braid_coding_agent.formatting.settings import (
|
|
16
|
+
DEFAULT_FORMAT_TIMEOUT_SECONDS,
|
|
17
|
+
PATH_PLACEHOLDER,
|
|
18
|
+
FormatSettings,
|
|
19
|
+
build_argv,
|
|
20
|
+
build_shell_command,
|
|
21
|
+
)
|
|
22
|
+
from braid_coding_agent.formatting.tool import (
|
|
23
|
+
FORMAT_PARAMETERS,
|
|
24
|
+
PROMPT_GUIDELINES,
|
|
25
|
+
PROMPT_SNIPPET,
|
|
26
|
+
create_format_tool,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
_LAZY_EXPORTS: dict[str, str] = {
|
|
30
|
+
"DEFAULT_FORMAT_TIMEOUT_SECONDS": "braid_coding_agent.formatting.settings",
|
|
31
|
+
"PATH_PLACEHOLDER": "braid_coding_agent.formatting.settings",
|
|
32
|
+
"FormatSettings": "braid_coding_agent.formatting.settings",
|
|
33
|
+
"build_argv": "braid_coding_agent.formatting.settings",
|
|
34
|
+
"build_shell_command": "braid_coding_agent.formatting.settings",
|
|
35
|
+
"FORMAT_PARAMETERS": "braid_coding_agent.formatting.tool",
|
|
36
|
+
"PROMPT_GUIDELINES": "braid_coding_agent.formatting.tool",
|
|
37
|
+
"PROMPT_SNIPPET": "braid_coding_agent.formatting.tool",
|
|
38
|
+
"create_format_tool": "braid_coding_agent.formatting.tool",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def __getattr__(name: str) -> object:
|
|
43
|
+
"""按需导入导出名。配置层只需要 ``format`` 的形状。"""
|
|
44
|
+
module_name = _LAZY_EXPORTS.get(name)
|
|
45
|
+
if module_name is None:
|
|
46
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
47
|
+
value = getattr(importlib.import_module(module_name), name)
|
|
48
|
+
globals()[name] = value
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"DEFAULT_FORMAT_TIMEOUT_SECONDS",
|
|
54
|
+
"FORMAT_PARAMETERS",
|
|
55
|
+
"PATH_PLACEHOLDER",
|
|
56
|
+
"PROMPT_GUIDELINES",
|
|
57
|
+
"PROMPT_SNIPPET",
|
|
58
|
+
"FormatSettings",
|
|
59
|
+
"build_argv",
|
|
60
|
+
"build_shell_command",
|
|
61
|
+
"create_format_tool",
|
|
62
|
+
]
|