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,583 @@
|
|
|
1
|
+
"""子代理定义:内置三份,其余从全局目录与项目目录的 Markdown 文件读取。
|
|
2
|
+
|
|
3
|
+
文件形状是 YAML frontmatter + 正文:
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
---
|
|
7
|
+
name: explore
|
|
8
|
+
description: 只读探索
|
|
9
|
+
tools: [read, grep, find, ls]
|
|
10
|
+
permissionMode: read-only
|
|
11
|
+
maxTurns: 16
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
你是一名只读探索子代理。……
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
frontmatter 用 :mod:`yaml` 解析,正文原样作为 ``system_prompt``。技能定义目前同时
|
|
18
|
+
接受 YAML 与 TOML 两种 frontmatter,子代理定义沿用同一条兼容规则:``---`` 按 YAML
|
|
19
|
+
解析,``+++`` 按 TOML 解析。字段名以 YAML 的 camelCase 为准,TOML 里的 snake_case
|
|
20
|
+
作为旧写法继续接受。
|
|
21
|
+
|
|
22
|
+
覆盖顺序:内置 → 全局 ``~/.braid/agents/`` → 项目 ``.braid/agents/``。
|
|
23
|
+
后加载的同名定义整体替换先加载的。
|
|
24
|
+
|
|
25
|
+
读取采用容错策略:不支持的字段与非法取值会被忽略并记入诊断,文件仍然生效;
|
|
26
|
+
名字缺失时使用文件名,描述缺失时使用正文首行。只有缺少 frontmatter、frontmatter
|
|
27
|
+
无法解析、正文为空这类无法构成一份可用定义的文件才会被跳过。启动流程不会因为
|
|
28
|
+
某一份定义文件而中止,诊断经 ``/agents`` 与启动提示展示。
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import re
|
|
34
|
+
import tomllib
|
|
35
|
+
from collections.abc import Mapping, Sequence
|
|
36
|
+
from dataclasses import dataclass, replace
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import Literal, cast
|
|
39
|
+
|
|
40
|
+
import yaml
|
|
41
|
+
|
|
42
|
+
from braid_ai.types import JsonValue
|
|
43
|
+
from braid_coding_agent.config import PROJECT_CONFIG_DIR
|
|
44
|
+
from braid_coding_agent.permissions.engine import PERMISSION_MODES
|
|
45
|
+
from braid_coding_agent.permissions.model import PermissionMode
|
|
46
|
+
from braid_coding_agent.subagents.settings import (
|
|
47
|
+
DEFAULT_MAX_TURNS,
|
|
48
|
+
IsolationMode,
|
|
49
|
+
MemoryScope,
|
|
50
|
+
SubagentSpec,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
AGENTS_DIR_NAME = "agents"
|
|
54
|
+
YAML_DELIMITER = "---"
|
|
55
|
+
TOML_DELIMITER = "+++"
|
|
56
|
+
_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_-]*$")
|
|
57
|
+
|
|
58
|
+
type DiagnosticKind = Literal["ignored", "skipped"]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(slots=True, frozen=True)
|
|
62
|
+
class DefinitionDiagnostic:
|
|
63
|
+
"""发现阶段的一条非致命问题:被忽略的字段、被回退的取值、被跳过的文件。"""
|
|
64
|
+
|
|
65
|
+
kind: DiagnosticKind
|
|
66
|
+
message: str
|
|
67
|
+
path: str
|
|
68
|
+
|
|
69
|
+
def wire(self) -> dict[str, JsonValue]:
|
|
70
|
+
return {"kind": self.kind, "message": self.message, "path": self.path}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(slots=True, frozen=True)
|
|
74
|
+
class DefinitionScan:
|
|
75
|
+
"""一次目录扫描的结果:可用的定义与全部诊断。"""
|
|
76
|
+
|
|
77
|
+
specs: tuple[SubagentSpec, ...]
|
|
78
|
+
diagnostics: tuple[DefinitionDiagnostic, ...]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
#: 规范字段名(YAML 写法)与旧 TOML 写法的别名。
|
|
82
|
+
_FIELD_ALIASES: dict[str, str] = {
|
|
83
|
+
"tools": "tools",
|
|
84
|
+
"disallowedTools": "disallowedTools",
|
|
85
|
+
"disallowed_tools": "disallowedTools",
|
|
86
|
+
"permissionMode": "permissionMode",
|
|
87
|
+
"permission_mode": "permissionMode",
|
|
88
|
+
"maxTurns": "maxTurns",
|
|
89
|
+
"max_turns": "maxTurns",
|
|
90
|
+
"mcpServers": "mcpServers",
|
|
91
|
+
"mcp_servers": "mcpServers",
|
|
92
|
+
}
|
|
93
|
+
_ALLOWED_KEYS = frozenset(
|
|
94
|
+
{
|
|
95
|
+
"name",
|
|
96
|
+
"description",
|
|
97
|
+
"model",
|
|
98
|
+
"skills",
|
|
99
|
+
"memory",
|
|
100
|
+
"isolation",
|
|
101
|
+
"hooks",
|
|
102
|
+
*_FIELD_ALIASES,
|
|
103
|
+
}
|
|
104
|
+
)
|
|
105
|
+
_MEMORY_SCOPES: tuple[MemoryScope, ...] = ("none", "user", "project", "session")
|
|
106
|
+
_ISOLATION_MODES: tuple[IsolationMode, ...] = ("inherit", "none", "worktree")
|
|
107
|
+
|
|
108
|
+
#: ``/agents create`` 生成的定义模板。``hooks`` 在 ``format`` 里要写成双花括号。
|
|
109
|
+
AGENT_TEMPLATE = """\
|
|
110
|
+
---
|
|
111
|
+
name: {name}
|
|
112
|
+
description: 一句话说明什么时候该派这个子代理
|
|
113
|
+
# tools: [read, grep, find, ls] # 省略时继承父会话的全部工具;[] 表示不给任何工具
|
|
114
|
+
# disallowedTools: [bash] # 从继承结果或白名单里排除的工具
|
|
115
|
+
# model: provider/model-id # 省略时用主会话的模型
|
|
116
|
+
# permissionMode: inherit # inherit | read-only | plan | accept-edits | full
|
|
117
|
+
# maxTurns: 20
|
|
118
|
+
# skills: [] # 预加载正文的技能名
|
|
119
|
+
# mcpServers: [] # 指定 MCP Server(当前只保留接口)
|
|
120
|
+
# memory: none # none | user | project | session(当前只保留接口)
|
|
121
|
+
# isolation: inherit # inherit | none | worktree
|
|
122
|
+
# hooks: {{}} # 专属生命周期 Hook(当前只保留接口)
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
在这里写这个子代理的系统提示词。它看不到父会话的转录,所以要把职责边界、
|
|
126
|
+
需要遵守的约束和最终回答的形状写清楚。
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class DefinitionError(Exception):
|
|
131
|
+
"""一份代理定义无法构成可用定义。目录扫描把它记成 ``skipped`` 诊断并跳过。"""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
BUILTIN_SPECS: tuple[SubagentSpec, ...] = (
|
|
135
|
+
SubagentSpec(
|
|
136
|
+
name="explore",
|
|
137
|
+
description="只读探索:定位代码、读文件、给出结论与关键路径,不改动文件",
|
|
138
|
+
system_prompt=(
|
|
139
|
+
"你是一名只读探索子代理。你的任务是读文件、搜索代码、定位实现,"
|
|
140
|
+
"然后把结论、涉及的关键文件路径写成一段简短的中文回答。\n"
|
|
141
|
+
"不要修改任何文件,不要运行会改动工作区的命令,不要派生子代理。\n"
|
|
142
|
+
"父会话看不到你的对话过程,所以最终回答必须自包含:写清楚你查了什么、"
|
|
143
|
+
"结论是什么、关键文件在哪里。"
|
|
144
|
+
),
|
|
145
|
+
tools=("read", "grep", "find", "ls"),
|
|
146
|
+
permission_mode="read-only",
|
|
147
|
+
max_turns=16,
|
|
148
|
+
source="builtin",
|
|
149
|
+
),
|
|
150
|
+
SubagentSpec(
|
|
151
|
+
name="general",
|
|
152
|
+
description="通用执行:读写文件、运行命令,在独立会话里完成一个明确子任务",
|
|
153
|
+
system_prompt=(
|
|
154
|
+
"你是一名通用执行子代理。你在一个独立的会话里完成父代理交办的单个任务,"
|
|
155
|
+
"可以使用声明给你的全部工具。\n"
|
|
156
|
+
"动手前先看清任务边界,完成后用一段简短的中文回答写清改了哪些文件、"
|
|
157
|
+
"跑了什么验证、还有什么没做。\n"
|
|
158
|
+
"父会话看不到你的对话过程,最终回答必须自包含。不要派生子代理,"
|
|
159
|
+
"除非系统明确给了你 task 工具。"
|
|
160
|
+
),
|
|
161
|
+
tools=("read", "write", "edit", "bash", "grep", "find", "ls"),
|
|
162
|
+
permission_mode="full",
|
|
163
|
+
max_turns=24,
|
|
164
|
+
source="builtin",
|
|
165
|
+
),
|
|
166
|
+
SubagentSpec(
|
|
167
|
+
name="background",
|
|
168
|
+
description="后台会话:承接当前会话的完整上下文,在后台继续完成一项独立任务",
|
|
169
|
+
system_prompt=(
|
|
170
|
+
"你是从主会话分离出来的后台代理。你拥有主会话此前的完整转录,"
|
|
171
|
+
"现在要独立完成用户指定的后续任务。\n"
|
|
172
|
+
"不要向用户提问,也不要假设用户会立刻回答;遇到不确定的地方选择最保守的"
|
|
173
|
+
"可验证做法,并在最终回答里说明你的假设。\n"
|
|
174
|
+
"完成后用一段简短的中文回答写清做了什么、改了哪些文件、跑了什么验证、"
|
|
175
|
+
"还有哪些未完成事项。"
|
|
176
|
+
),
|
|
177
|
+
tools=None,
|
|
178
|
+
permission_mode=None,
|
|
179
|
+
max_turns=32,
|
|
180
|
+
isolation="none",
|
|
181
|
+
source="builtin",
|
|
182
|
+
),
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def builtin_specs() -> tuple[SubagentSpec, ...]:
|
|
187
|
+
return BUILTIN_SPECS
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def is_valid_agent_name(name: str) -> bool:
|
|
191
|
+
return _NAME_PATTERN.fullmatch(name) is not None
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def agent_template(name: str) -> str:
|
|
195
|
+
"""生成一份可编辑的定义模板。调用方先校验名字。"""
|
|
196
|
+
return AGENT_TEMPLATE.format(name=name)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def definition_by_name(specs: Sequence[SubagentSpec], name: str) -> SubagentSpec | None:
|
|
200
|
+
for spec in specs:
|
|
201
|
+
if spec.name == name:
|
|
202
|
+
return spec
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def parse_definition(
|
|
207
|
+
text: str,
|
|
208
|
+
*,
|
|
209
|
+
where: str,
|
|
210
|
+
known_tools: Sequence[str],
|
|
211
|
+
diagnostics: list[DefinitionDiagnostic] | None = None,
|
|
212
|
+
) -> SubagentSpec:
|
|
213
|
+
"""解析一份定义;不支持的字段与取值被忽略并写入 ``diagnostics``。
|
|
214
|
+
|
|
215
|
+
只有无法构成一份可用定义的问题才会抛出 :class:`DefinitionError`:frontmatter
|
|
216
|
+
缺失或无法解析、名字无法确定、description 缺失、正文为空。
|
|
217
|
+
"""
|
|
218
|
+
reported = diagnostics if diagnostics is not None else []
|
|
219
|
+
frontmatter, body, error = _extract_frontmatter(text)
|
|
220
|
+
if error is not None:
|
|
221
|
+
raise DefinitionError(f"{where}: {error}")
|
|
222
|
+
if frontmatter is None:
|
|
223
|
+
raise DefinitionError(f"{where}: 缺少 frontmatter,文件第一行应为 --- 或 +++")
|
|
224
|
+
|
|
225
|
+
raw = _normalize_keys(frontmatter, where=where, diagnostics=reported)
|
|
226
|
+
unknown = sorted((key for key in raw if key not in _ALLOWED_KEYS), key=str)
|
|
227
|
+
for key in unknown:
|
|
228
|
+
del raw[key]
|
|
229
|
+
if unknown:
|
|
230
|
+
_report(reported, where, f"忽略不支持的字段 {', '.join(str(key) for key in unknown)}")
|
|
231
|
+
|
|
232
|
+
name = _name(raw, where, reported)
|
|
233
|
+
system_prompt = body.strip()
|
|
234
|
+
if not system_prompt:
|
|
235
|
+
raise DefinitionError(
|
|
236
|
+
f"{where}: 系统提示词不能为空(frontmatter 之后的正文就是系统提示词)"
|
|
237
|
+
)
|
|
238
|
+
description = _description(raw, system_prompt, where, reported)
|
|
239
|
+
|
|
240
|
+
tools = _optional_tools(raw, "tools", where, known_tools, reported)
|
|
241
|
+
disallowed = _optional_tools(raw, "disallowedTools", where, known_tools, reported) or ()
|
|
242
|
+
if tools is not None:
|
|
243
|
+
conflict = sorted(set(tools) & set(disallowed))
|
|
244
|
+
if conflict:
|
|
245
|
+
_report(
|
|
246
|
+
reported,
|
|
247
|
+
where,
|
|
248
|
+
f"tools 与 disallowedTools 同时声明了 {', '.join(conflict)},已从 tools 移除",
|
|
249
|
+
)
|
|
250
|
+
tools = tuple(item for item in tools if item not in conflict)
|
|
251
|
+
|
|
252
|
+
permission_mode = _permission_mode(raw, where, reported)
|
|
253
|
+
model = _model(raw, where, reported)
|
|
254
|
+
max_turns = _max_turns(raw, where, reported)
|
|
255
|
+
skills = _string_list(raw, "skills", where, reported)
|
|
256
|
+
mcp_servers = _string_list(raw, "mcpServers", where, reported)
|
|
257
|
+
memory = _memory(raw, where, reported)
|
|
258
|
+
isolation = _isolation(raw, where, reported)
|
|
259
|
+
hooks = _hooks(raw, where, reported)
|
|
260
|
+
|
|
261
|
+
return SubagentSpec(
|
|
262
|
+
name=name,
|
|
263
|
+
description=description,
|
|
264
|
+
system_prompt=system_prompt,
|
|
265
|
+
tools=tools,
|
|
266
|
+
disallowed_tools=disallowed,
|
|
267
|
+
permission_mode=permission_mode,
|
|
268
|
+
model=model,
|
|
269
|
+
max_turns=max_turns,
|
|
270
|
+
skills=skills,
|
|
271
|
+
mcp_servers=mcp_servers,
|
|
272
|
+
memory=memory,
|
|
273
|
+
isolation=isolation,
|
|
274
|
+
hooks=hooks,
|
|
275
|
+
source=where,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _extract_frontmatter(
|
|
280
|
+
text: str,
|
|
281
|
+
) -> tuple[Mapping[str, JsonValue] | None, str, str | None]:
|
|
282
|
+
"""返回 ``(frontmatter, body, error)``。无 frontmatter 时 frontmatter 为 ``None``。"""
|
|
283
|
+
normalized = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
284
|
+
if normalized.startswith("\ufeff"):
|
|
285
|
+
normalized = normalized[1:]
|
|
286
|
+
lines = normalized.split("\n")
|
|
287
|
+
if not lines or lines[0].strip() not in (YAML_DELIMITER, TOML_DELIMITER):
|
|
288
|
+
return None, normalized, None
|
|
289
|
+
delimiter = lines[0].strip()
|
|
290
|
+
end = next((index for index in range(1, len(lines)) if lines[index].strip() == delimiter), None)
|
|
291
|
+
if end is None:
|
|
292
|
+
return None, normalized, f"frontmatter 缺少结束的 {delimiter}"
|
|
293
|
+
raw = "\n".join(lines[1:end])
|
|
294
|
+
body = "\n".join(lines[end + 1 :])
|
|
295
|
+
try:
|
|
296
|
+
loaded: object = yaml.safe_load(raw) if delimiter == YAML_DELIMITER else tomllib.loads(raw)
|
|
297
|
+
except (yaml.YAMLError, tomllib.TOMLDecodeError) as exc:
|
|
298
|
+
return None, body, f"frontmatter 解析失败:{exc}"
|
|
299
|
+
if loaded is None:
|
|
300
|
+
return cast("Mapping[str, JsonValue]", {}), body, None
|
|
301
|
+
if not isinstance(loaded, dict):
|
|
302
|
+
return None, body, "frontmatter 必须是一个映射"
|
|
303
|
+
return cast("Mapping[str, JsonValue]", loaded), body, None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _report(
|
|
307
|
+
diagnostics: list[DefinitionDiagnostic],
|
|
308
|
+
path: str,
|
|
309
|
+
message: str,
|
|
310
|
+
*,
|
|
311
|
+
kind: DiagnosticKind = "ignored",
|
|
312
|
+
) -> None:
|
|
313
|
+
diagnostics.append(DefinitionDiagnostic(kind=kind, message=message, path=path))
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _detail(exc: DefinitionError, where: str) -> str:
|
|
317
|
+
prefix = f"{where}: "
|
|
318
|
+
text = str(exc)
|
|
319
|
+
detail = text[len(prefix) :] if text.startswith(prefix) else text
|
|
320
|
+
return " ".join(detail.split())
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _normalize_keys(
|
|
324
|
+
raw: Mapping[str, JsonValue], *, where: str, diagnostics: list[DefinitionDiagnostic]
|
|
325
|
+
) -> dict[str, JsonValue]:
|
|
326
|
+
"""把旧 TOML 字段名折成规范字段名;非字符串的键转成字符串后当作未知字段。"""
|
|
327
|
+
normalized: dict[str, JsonValue] = {}
|
|
328
|
+
for key, value in cast("Mapping[object, JsonValue]", raw).items():
|
|
329
|
+
canonical = _FIELD_ALIASES.get(key, key) if isinstance(key, str) else str(key)
|
|
330
|
+
if canonical in normalized:
|
|
331
|
+
_report(diagnostics, where, f"字段 {canonical} 重复声明,保留第一次的值")
|
|
332
|
+
continue
|
|
333
|
+
normalized[canonical] = value
|
|
334
|
+
return normalized
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _name(raw: Mapping[str, JsonValue], where: str, diagnostics: list[DefinitionDiagnostic]) -> str:
|
|
338
|
+
"""名字缺失或不合法时退回文件名;文件名也不能用才算这份定义不可用。"""
|
|
339
|
+
value = raw.get("name")
|
|
340
|
+
if isinstance(value, str) and _NAME_PATTERN.fullmatch(value.strip()):
|
|
341
|
+
return value.strip()
|
|
342
|
+
stem = Path(where).stem
|
|
343
|
+
if _NAME_PATTERN.fullmatch(stem):
|
|
344
|
+
_report(diagnostics, where, f"name 缺失或不合法,按文件名使用 {stem!r}")
|
|
345
|
+
return stem
|
|
346
|
+
raise DefinitionError(f"{where}: name 缺失或不合法,文件名也无法作为名字")
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _description(
|
|
350
|
+
raw: Mapping[str, JsonValue], body: str, where: str, diagnostics: list[DefinitionDiagnostic]
|
|
351
|
+
) -> str:
|
|
352
|
+
"""description 缺失或写坏时退回正文第一行,这份定义仍然可以被派发。"""
|
|
353
|
+
value = raw.get("description")
|
|
354
|
+
if isinstance(value, str) and value.strip():
|
|
355
|
+
return value.strip()
|
|
356
|
+
line = next((line.strip() for line in body.splitlines() if line.strip()), "")
|
|
357
|
+
fallback = line.lstrip("#").strip()[:120] or f"{Path(where).stem} 子代理"
|
|
358
|
+
_report(diagnostics, where, f"description 缺失或不合法,暂用 {fallback!r}")
|
|
359
|
+
return fallback
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _optional_tools(
|
|
363
|
+
raw: Mapping[str, JsonValue],
|
|
364
|
+
key: str,
|
|
365
|
+
where: str,
|
|
366
|
+
known_tools: Sequence[str],
|
|
367
|
+
diagnostics: list[DefinitionDiagnostic],
|
|
368
|
+
) -> tuple[str, ...] | None:
|
|
369
|
+
value = raw.get(key)
|
|
370
|
+
if value is None:
|
|
371
|
+
return None
|
|
372
|
+
if not isinstance(value, list):
|
|
373
|
+
_report(diagnostics, where, f"{key} 必须是字符串数组,已忽略该字段")
|
|
374
|
+
return None
|
|
375
|
+
tools: list[str] = []
|
|
376
|
+
dropped: list[str] = []
|
|
377
|
+
for item in value:
|
|
378
|
+
if not isinstance(item, str) or item not in known_tools:
|
|
379
|
+
dropped.append(repr(item))
|
|
380
|
+
continue
|
|
381
|
+
if item not in tools:
|
|
382
|
+
tools.append(item)
|
|
383
|
+
if dropped:
|
|
384
|
+
_report(diagnostics, where, f"{key} 里的 {', '.join(dropped)} 不是可用工具,已忽略")
|
|
385
|
+
return tuple(tools)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _string_list(
|
|
389
|
+
raw: Mapping[str, JsonValue],
|
|
390
|
+
key: str,
|
|
391
|
+
where: str,
|
|
392
|
+
diagnostics: list[DefinitionDiagnostic],
|
|
393
|
+
) -> tuple[str, ...]:
|
|
394
|
+
value = raw.get(key)
|
|
395
|
+
if value is None:
|
|
396
|
+
return ()
|
|
397
|
+
if not isinstance(value, list):
|
|
398
|
+
_report(diagnostics, where, f"{key} 必须是字符串数组,已忽略该字段")
|
|
399
|
+
return ()
|
|
400
|
+
items: list[str] = []
|
|
401
|
+
for item in value:
|
|
402
|
+
if not isinstance(item, str) or not item.strip():
|
|
403
|
+
_report(diagnostics, where, f"{key} 里的 {item!r} 不是非空字符串,已忽略")
|
|
404
|
+
continue
|
|
405
|
+
if item not in items:
|
|
406
|
+
items.append(item)
|
|
407
|
+
return tuple(items)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _permission_mode(
|
|
411
|
+
raw: Mapping[str, JsonValue], where: str, diagnostics: list[DefinitionDiagnostic]
|
|
412
|
+
) -> PermissionMode | None:
|
|
413
|
+
value = raw.get("permissionMode")
|
|
414
|
+
if value is None:
|
|
415
|
+
return None
|
|
416
|
+
if isinstance(value, str) and value == "inherit":
|
|
417
|
+
return None
|
|
418
|
+
if isinstance(value, str) and value in PERMISSION_MODES:
|
|
419
|
+
return value
|
|
420
|
+
_report(
|
|
421
|
+
diagnostics,
|
|
422
|
+
where,
|
|
423
|
+
f"permissionMode 只支持 inherit, {', '.join(PERMISSION_MODES)},"
|
|
424
|
+
f"收到 {value!r},已按 inherit 处理",
|
|
425
|
+
)
|
|
426
|
+
return None
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _model(
|
|
430
|
+
raw: Mapping[str, JsonValue], where: str, diagnostics: list[DefinitionDiagnostic]
|
|
431
|
+
) -> str | None:
|
|
432
|
+
value = raw.get("model")
|
|
433
|
+
if value is None:
|
|
434
|
+
return None
|
|
435
|
+
if isinstance(value, str):
|
|
436
|
+
provider_id, _, model_id = value.partition("/")
|
|
437
|
+
if provider_id.strip() and model_id.strip():
|
|
438
|
+
return value
|
|
439
|
+
_report(diagnostics, where, f"model 要写成 provider/模型 id,收到 {value!r},已忽略")
|
|
440
|
+
return None
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _max_turns(
|
|
444
|
+
raw: Mapping[str, JsonValue], where: str, diagnostics: list[DefinitionDiagnostic]
|
|
445
|
+
) -> int:
|
|
446
|
+
value = raw.get("maxTurns")
|
|
447
|
+
if value is None:
|
|
448
|
+
return DEFAULT_MAX_TURNS
|
|
449
|
+
if isinstance(value, int) and not isinstance(value, bool) and value > 0:
|
|
450
|
+
return value
|
|
451
|
+
_report(
|
|
452
|
+
diagnostics,
|
|
453
|
+
where,
|
|
454
|
+
f"maxTurns 必须是正整数,收到 {value!r},已按 {DEFAULT_MAX_TURNS} 处理",
|
|
455
|
+
)
|
|
456
|
+
return DEFAULT_MAX_TURNS
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _memory(
|
|
460
|
+
raw: Mapping[str, JsonValue], where: str, diagnostics: list[DefinitionDiagnostic]
|
|
461
|
+
) -> MemoryScope:
|
|
462
|
+
value = raw.get("memory", "none")
|
|
463
|
+
if isinstance(value, str) and value in _MEMORY_SCOPES:
|
|
464
|
+
return value
|
|
465
|
+
_report(
|
|
466
|
+
diagnostics,
|
|
467
|
+
where,
|
|
468
|
+
f"memory 只支持 {', '.join(_MEMORY_SCOPES)},收到 {value!r},已按 none 处理",
|
|
469
|
+
)
|
|
470
|
+
return "none"
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _isolation(
|
|
474
|
+
raw: Mapping[str, JsonValue], where: str, diagnostics: list[DefinitionDiagnostic]
|
|
475
|
+
) -> IsolationMode:
|
|
476
|
+
value = raw.get("isolation", "inherit")
|
|
477
|
+
if isinstance(value, str) and value in _ISOLATION_MODES:
|
|
478
|
+
return value
|
|
479
|
+
_report(
|
|
480
|
+
diagnostics,
|
|
481
|
+
where,
|
|
482
|
+
f"isolation 只支持 {', '.join(_ISOLATION_MODES)},收到 {value!r},已按 inherit 处理",
|
|
483
|
+
)
|
|
484
|
+
return "inherit"
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _hooks(
|
|
488
|
+
raw: Mapping[str, JsonValue], where: str, diagnostics: list[DefinitionDiagnostic]
|
|
489
|
+
) -> dict[str, JsonValue]:
|
|
490
|
+
value = raw.get("hooks")
|
|
491
|
+
if value is None:
|
|
492
|
+
return {}
|
|
493
|
+
if not isinstance(value, dict):
|
|
494
|
+
_report(diagnostics, where, "hooks 必须是一个映射,已忽略该字段")
|
|
495
|
+
return {}
|
|
496
|
+
hooks: dict[str, JsonValue] = {}
|
|
497
|
+
for key, item in cast("dict[object, JsonValue]", value).items():
|
|
498
|
+
if not isinstance(key, str) or not key.strip():
|
|
499
|
+
_report(diagnostics, where, f"hooks 的键必须是字符串,已忽略 {key!r}")
|
|
500
|
+
continue
|
|
501
|
+
if isinstance(item, str):
|
|
502
|
+
if not item.strip():
|
|
503
|
+
_report(diagnostics, where, f"hooks.{key} 的字符串不能为空,已忽略该条目")
|
|
504
|
+
continue
|
|
505
|
+
elif isinstance(item, list):
|
|
506
|
+
if not all(isinstance(entry, str) and entry.strip() for entry in item):
|
|
507
|
+
_report(diagnostics, where, f"hooks.{key} 只能包含非空字符串,已忽略该条目")
|
|
508
|
+
continue
|
|
509
|
+
else:
|
|
510
|
+
_report(diagnostics, where, f"hooks.{key} 必须是字符串或字符串数组,已忽略该条目")
|
|
511
|
+
continue
|
|
512
|
+
hooks[key] = item
|
|
513
|
+
return hooks
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def load_definitions(*, agent_dir: Path, cwd: str, known_tools: Sequence[str]) -> DefinitionScan:
|
|
517
|
+
"""读三个来源,返回按名称去重后的定义与全部诊断。
|
|
518
|
+
|
|
519
|
+
顺序是内置、全局新增、项目新增。单份文件的问题不会中止扫描:无法解析的文件
|
|
520
|
+
记一条 ``skipped`` 诊断后跳过,其余内容照常加载。
|
|
521
|
+
"""
|
|
522
|
+
specs: dict[str, SubagentSpec] = {spec.name: spec for spec in BUILTIN_SPECS}
|
|
523
|
+
diagnostics: list[DefinitionDiagnostic] = []
|
|
524
|
+
for directory in (
|
|
525
|
+
agent_dir / AGENTS_DIR_NAME,
|
|
526
|
+
Path(cwd) / PROJECT_CONFIG_DIR / AGENTS_DIR_NAME,
|
|
527
|
+
):
|
|
528
|
+
if not directory.exists():
|
|
529
|
+
continue
|
|
530
|
+
if not directory.is_dir():
|
|
531
|
+
_report(
|
|
532
|
+
diagnostics,
|
|
533
|
+
str(directory),
|
|
534
|
+
"子代理目录应当是一个目录,已跳过",
|
|
535
|
+
kind="skipped",
|
|
536
|
+
)
|
|
537
|
+
continue
|
|
538
|
+
for path in sorted(directory.glob("*.md")):
|
|
539
|
+
try:
|
|
540
|
+
text = path.read_text(encoding="utf-8")
|
|
541
|
+
spec = parse_definition(
|
|
542
|
+
text,
|
|
543
|
+
where=str(path),
|
|
544
|
+
known_tools=known_tools,
|
|
545
|
+
diagnostics=diagnostics,
|
|
546
|
+
)
|
|
547
|
+
except DefinitionError as exc:
|
|
548
|
+
_report(
|
|
549
|
+
diagnostics,
|
|
550
|
+
str(path),
|
|
551
|
+
_detail(exc, str(path)),
|
|
552
|
+
kind="skipped",
|
|
553
|
+
)
|
|
554
|
+
continue
|
|
555
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
556
|
+
_report(
|
|
557
|
+
diagnostics,
|
|
558
|
+
str(path),
|
|
559
|
+
f"无法读取文件:{exc}",
|
|
560
|
+
kind="skipped",
|
|
561
|
+
)
|
|
562
|
+
continue
|
|
563
|
+
specs[spec.name] = replace(spec, source=str(path))
|
|
564
|
+
return DefinitionScan(tuple(specs.values()), tuple(diagnostics))
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
__all__ = [
|
|
568
|
+
"AGENTS_DIR_NAME",
|
|
569
|
+
"AGENT_TEMPLATE",
|
|
570
|
+
"BUILTIN_SPECS",
|
|
571
|
+
"TOML_DELIMITER",
|
|
572
|
+
"YAML_DELIMITER",
|
|
573
|
+
"DefinitionDiagnostic",
|
|
574
|
+
"DefinitionError",
|
|
575
|
+
"DefinitionScan",
|
|
576
|
+
"DiagnosticKind",
|
|
577
|
+
"agent_template",
|
|
578
|
+
"builtin_specs",
|
|
579
|
+
"definition_by_name",
|
|
580
|
+
"is_valid_agent_name",
|
|
581
|
+
"load_definitions",
|
|
582
|
+
"parse_definition",
|
|
583
|
+
]
|