braid-coding-agent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,681 @@
1
+ """技能发现与解析:从三类目录找出 ``SKILL.md``,解析 frontmatter,裁决同名冲突。
2
+
3
+ 目录按优先级从低到高扫描,后加载的同名技能整体覆盖先加载的:
4
+
5
+ 1. 全局 ``<agent_dir>/skills/<name>/SKILL.md``(默认 ``~/.braid/skills``)
6
+ 2. Claude 兼容 ``<cwd>/.claude/skills/<name>/SKILL.md``
7
+ 3. 项目 ``<cwd>/.braid/skills/<name>/SKILL.md``
8
+
9
+ 全局用户级技能只有配置根下这一处,与全局 ``AGENTS.md``、``settings.json`` 同级;
10
+ 它和项目的 ``.braid/skills`` 形状相同,只是作用域不同。
11
+
12
+ 「项目技能优先」与上游把 user 放在最前、采用先发现者胜的顺序相反。这里选项目优先,
13
+ 因为项目技能随仓库分发、可评审,全局技能只影响个人;同名时个人配置不该盖掉团队约定。
14
+ 冲突不静默:每次覆盖都写一条 ``collision`` 诊断(含赢家与输家路径)。
15
+
16
+ frontmatter 同时接受 YAML(``---``,Agent Skills 标准)与 TOML(``+++``,本项目
17
+ 子代理定义沿用的写法)。解析用标准库 :mod:`tomllib` 与 :mod:`yaml`:两者都是成熟
18
+ 库,不为这点格式再写解析器。缺 description 或 frontmatter 语法错误的技能被丢弃,
19
+ 并附一条诊断——一个坏技能不该让整次启动失败,但也不该无声无息地消失。
20
+
21
+ 正文加载由 :func:`create_skill_tool` 承担;加载前 :func:`check_skill_access` 用权限
22
+ 引擎的纯规则判定检查技能声明的工具与最低模式。声明了需求却没有权限引擎时拒绝加载
23
+ (失败关闭),否则「只读模式里加载一个需要写工具的技能」会绕过权限系统。
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import re
31
+ import tomllib
32
+ from collections.abc import Mapping, Sequence
33
+ from dataclasses import dataclass, replace
34
+ from pathlib import Path
35
+ from typing import Literal, cast
36
+
37
+ import yaml
38
+
39
+ from braid_agent.tools import AgentTool, AgentToolResult
40
+ from braid_ai.cancel import CancelToken
41
+ from braid_ai.types import JsonValue, TextContent
42
+ from braid_coding_agent.permissions.engine import (
43
+ PERMISSION_MODES,
44
+ PermissionEngine,
45
+ PermissionMode,
46
+ PermissionSettings,
47
+ build_request,
48
+ evaluate_rules,
49
+ )
50
+ from braid_coding_agent.prompt import Skill
51
+ from braid_coding_agent.startup.cache import JsonCacheFile, file_fingerprint
52
+ from braid_coding_agent.startup.monitor import StartupMonitor
53
+ from braid_coding_agent.subagents.settings import as_permission_mode, clamp_permission_mode
54
+ from braid_coding_agent.tools.args import string_arg
55
+ from braid_coding_agent.tools.truncate import DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncate_head
56
+
57
+ PROJECT_SKILLS_DIRNAME = ".braid/skills"
58
+ USER_SKILLS_DIRNAME = "skills"
59
+ CLAUDE_SKILLS_DIRNAME = ".claude/skills"
60
+ SKILL_FILENAME = "SKILL.md"
61
+
62
+ _NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_-]*$")
63
+ _YAML_DELIMITER = "---"
64
+ _TOML_DELIMITER = "+++"
65
+
66
+ SkillSource = Literal["user", "claude", "project"]
67
+ DiagnosticKind = Literal["collision", "warning"]
68
+
69
+
70
+ @dataclass(slots=True, frozen=True)
71
+ class SkillDiagnostic:
72
+ """发现过程中的一条非致命问题:冲突、坏 frontmatter、缺字段。"""
73
+
74
+ kind: DiagnosticKind
75
+ message: str
76
+ path: str
77
+ winner_path: str | None = None
78
+
79
+
80
+ @dataclass(slots=True, frozen=True)
81
+ class SkillDocument:
82
+ """一份解析成功的技能:元数据给清单用,正文按需加载。
83
+
84
+ ``user_invocable`` 与 ``disable_model_invocation`` 是两个方向的开关:前者关掉
85
+ 用户侧的 ``/名字`` 与 ``/skill``,后者关掉模型侧的 ``skill`` 工具。两个都关掉
86
+ 的技能没有入口,解析阶段直接丢弃并附诊断。
87
+ """
88
+
89
+ name: str
90
+ description: str
91
+ file_path: str
92
+ base_dir: str
93
+ source: SkillSource
94
+ disable_model_invocation: bool
95
+ allowed_tools: tuple[str, ...]
96
+ permission: PermissionMode | None
97
+ body: str
98
+ user_invocable: bool = True
99
+ argument_hint: str | None = None
100
+ #: 文件修改时间、大小与工具上下文的指纹;缓存与刷新比较都读它。
101
+ fingerprint: str = ""
102
+
103
+ def to_prompt_skill(self) -> Skill:
104
+ """折成系统提示词里的一条清单项。"""
105
+ return Skill(
106
+ name=self.name,
107
+ description=self.description,
108
+ file_path=self.file_path,
109
+ disable_model_invocation=self.disable_model_invocation,
110
+ )
111
+
112
+
113
+ @dataclass(slots=True, frozen=True)
114
+ class SkillAccess:
115
+ """加载前的权限预检结论。``denied_tools`` 给模型可定位的原因。"""
116
+
117
+ allowed: bool
118
+ reason: str
119
+ denied_tools: tuple[str, ...] = ()
120
+
121
+
122
+ def _extract_frontmatter(
123
+ text: str,
124
+ ) -> tuple[Mapping[str, JsonValue] | None, str, str | None]:
125
+ """返回 ``(frontmatter, body, error)``。无 frontmatter 时 frontmatter 为 ``None``。"""
126
+ normalized = text.replace("\r\n", "\n").replace("\r", "\n")
127
+ lines = normalized.split("\n")
128
+ if not lines or lines[0].strip() not in (_YAML_DELIMITER, _TOML_DELIMITER):
129
+ return None, normalized, None
130
+ delimiter = lines[0].strip()
131
+ end = next((index for index in range(1, len(lines)) if lines[index].strip() == delimiter), None)
132
+ if end is None:
133
+ return None, normalized, f"frontmatter 缺少结束的 {delimiter}"
134
+ raw = "\n".join(lines[1:end])
135
+ body = "\n".join(lines[end + 1 :]).strip()
136
+ try:
137
+ if delimiter == _TOML_DELIMITER:
138
+ loaded: object = tomllib.loads(raw)
139
+ else:
140
+ loaded = yaml.safe_load(raw)
141
+ except (tomllib.TOMLDecodeError, yaml.YAMLError) as exc:
142
+ return None, body, f"frontmatter 解析失败:{exc}"
143
+ if loaded is None:
144
+ return cast("Mapping[str, JsonValue]", {}), body, None
145
+ if not isinstance(loaded, dict):
146
+ return None, body, "frontmatter 必须是一个映射"
147
+ parsed = cast("dict[str, JsonValue]", loaded)
148
+ return parsed, body, None
149
+
150
+
151
+ def parse_skill_document(
152
+ text: str,
153
+ *,
154
+ source: SkillSource,
155
+ path: str,
156
+ known_tools: Sequence[str] | None = None,
157
+ ) -> tuple[SkillDocument | None, tuple[SkillDiagnostic, ...]]:
158
+ """解析一份 SKILL.md:坏文件返回 ``(None, 诊断)``,不抛异常到调用方。"""
159
+ frontmatter, body, error = _extract_frontmatter(text)
160
+ if error is not None:
161
+ return None, (SkillDiagnostic("warning", error, path),)
162
+ if frontmatter is None:
163
+ return None, ()
164
+
165
+ raw_description = frontmatter.get("description")
166
+ if not isinstance(raw_description, str) or not raw_description.strip():
167
+ return None, (SkillDiagnostic("warning", "缺少非空的 description", path),)
168
+ description = raw_description.strip()
169
+
170
+ raw_name = frontmatter.get("name")
171
+ if raw_name is not None and not isinstance(raw_name, str):
172
+ return None, (SkillDiagnostic("warning", "name 必须是字符串", path),)
173
+ name = (raw_name or Path(path).parent.name).strip()
174
+ if not _NAME_PATTERN.fullmatch(name):
175
+ return None, (
176
+ SkillDiagnostic(
177
+ "warning", f"name 只能是小写字母、数字、下划线与连字符:{name!r}", path
178
+ ),
179
+ )
180
+
181
+ raw_disabled = frontmatter.get("disable-model-invocation", False)
182
+ if not isinstance(raw_disabled, bool):
183
+ return None, (SkillDiagnostic("warning", "disable-model-invocation 必须是布尔值", path),)
184
+
185
+ raw_user_invocable = frontmatter.get("user-invocable", True)
186
+ if not isinstance(raw_user_invocable, bool):
187
+ return None, (SkillDiagnostic("warning", "user-invocable 必须是布尔值", path),)
188
+ if raw_disabled and not raw_user_invocable:
189
+ return None, (
190
+ SkillDiagnostic(
191
+ "warning",
192
+ "disable-model-invocation 与 user-invocable: false 同时生效,"
193
+ "模型与用户都无法调用这份技能",
194
+ path,
195
+ ),
196
+ )
197
+
198
+ # ``argument-hint: [pr-number]`` 在 YAML 里是一个列表,作者的本意是显示方括号提示;
199
+ # 两种写法都接受,列表按原样拼回 ``[a, b]``。
200
+ raw_hint = frontmatter.get("argument-hint")
201
+ argument_hint: str | None = None
202
+ if isinstance(raw_hint, str):
203
+ argument_hint = raw_hint.strip() or None
204
+ elif isinstance(raw_hint, list):
205
+ hint_items = [item for item in raw_hint if isinstance(item, str)]
206
+ if len(hint_items) != len(raw_hint):
207
+ return None, (
208
+ SkillDiagnostic("warning", "argument-hint 必须是字符串或字符串数组", path),
209
+ )
210
+ cleaned = [item.strip() for item in hint_items if item.strip()]
211
+ argument_hint = f"[{', '.join(cleaned)}]" if cleaned else None
212
+ elif raw_hint is not None:
213
+ return None, (SkillDiagnostic("warning", "argument-hint 必须是字符串或字符串数组", path),)
214
+
215
+ raw_tools: JsonValue | None = frontmatter.get("allowed-tools")
216
+ tool_names: list[str] = []
217
+ if isinstance(raw_tools, str):
218
+ tool_names = [item.strip() for item in raw_tools.split(",") if item.strip()]
219
+ elif isinstance(raw_tools, list):
220
+ if not all(isinstance(item, str) and item.strip() for item in raw_tools):
221
+ return None, (SkillDiagnostic("warning", "allowed-tools 必须是工具名字符串数组", path),)
222
+ tool_names = [item.strip() for item in raw_tools if isinstance(item, str)]
223
+ elif raw_tools is not None:
224
+ return None, (SkillDiagnostic("warning", "allowed-tools 必须是工具名字符串数组", path),)
225
+ allowed_tools = tuple(dict.fromkeys(tool_names))
226
+ if known_tools is not None:
227
+ unknown = [tool for tool in allowed_tools if tool not in known_tools]
228
+ if unknown:
229
+ return None, (
230
+ SkillDiagnostic("warning", f"声明了未知工具:{', '.join(unknown)}", path),
231
+ )
232
+
233
+ permission: PermissionMode | None = None
234
+ raw_permission = frontmatter.get("permission")
235
+ if raw_permission is not None:
236
+ if not isinstance(raw_permission, str) or raw_permission not in PERMISSION_MODES:
237
+ return None, (
238
+ SkillDiagnostic(
239
+ "warning",
240
+ f"permission 只支持 {', '.join(PERMISSION_MODES)}",
241
+ path,
242
+ ),
243
+ )
244
+ permission = as_permission_mode(raw_permission, where=path)
245
+
246
+ doc = SkillDocument(
247
+ name=name,
248
+ description=description,
249
+ file_path=str(Path(path).resolve()),
250
+ base_dir=str(Path(path).parent.resolve()),
251
+ source=source,
252
+ disable_model_invocation=raw_disabled,
253
+ allowed_tools=allowed_tools,
254
+ permission=permission,
255
+ body=body,
256
+ user_invocable=raw_user_invocable,
257
+ argument_hint=argument_hint,
258
+ )
259
+ return doc, ()
260
+
261
+
262
+ def _digest(entries: Sequence[SkillDocument]) -> str:
263
+ """按路径、正文与影响清单的元数据算哈希。
264
+
265
+ 两个调用方向开关与参数提示都会改变用户看到的清单或补全,因此必须进哈希:
266
+ 只改 ``disable-model-invocation`` 而不改正文,清单内容同样变了。
267
+ """
268
+ payload = [
269
+ [
270
+ doc.file_path,
271
+ doc.fingerprint,
272
+ doc.description,
273
+ doc.source,
274
+ doc.name,
275
+ doc.disable_model_invocation,
276
+ doc.user_invocable,
277
+ doc.argument_hint,
278
+ list(doc.allowed_tools),
279
+ doc.permission,
280
+ ]
281
+ for doc in sorted(entries, key=lambda item: item.file_path)
282
+ ]
283
+ blob = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
284
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()
285
+
286
+
287
+ class SkillMetadataCache:
288
+ """按绝对路径保存技能元信息,读写都经过同一份 JSON 文件。"""
289
+
290
+ def __init__(self, path: Path) -> None:
291
+ self._file = JsonCacheFile(path)
292
+ self._entries = self._file.load()
293
+ self._dirty = False
294
+ self.hits = 0
295
+ self.misses = 0
296
+
297
+ def get(self, path: Path, fingerprint: str) -> SkillDocument | None:
298
+ raw = self._entries.get(str(path))
299
+ if raw is None or raw.get("fingerprint") != fingerprint:
300
+ self.misses += 1
301
+ return None
302
+ document = _document_from_payload(raw.get("document"), fingerprint)
303
+ if document is None:
304
+ self.misses += 1
305
+ return None
306
+ self.hits += 1
307
+ return document
308
+
309
+ def put(self, path: Path, fingerprint: str, document: SkillDocument) -> None:
310
+ self._entries[str(path)] = {
311
+ "fingerprint": fingerprint,
312
+ "document": _document_to_payload(document),
313
+ }
314
+ self._dirty = True
315
+
316
+ def save(self) -> None:
317
+ if self._dirty:
318
+ self._file.save(self._entries)
319
+ self._dirty = False
320
+
321
+
322
+ class SkillsLoader:
323
+ """一份可刷新的技能快照。构造时扫一次,每次 ``refresh`` 再扫并比较哈希。"""
324
+
325
+ def __init__(
326
+ self,
327
+ *,
328
+ cwd: str | Path,
329
+ agent_dir: str | Path,
330
+ known_tools: Sequence[str] | None = None,
331
+ cache_enabled: bool = True,
332
+ monitor: StartupMonitor | None = None,
333
+ ) -> None:
334
+ self._cwd = Path(cwd).expanduser().resolve()
335
+ self._agent_dir = Path(agent_dir).expanduser().resolve()
336
+ self._known_tools = None if known_tools is None else tuple(known_tools)
337
+ self._cache = (
338
+ SkillMetadataCache(self._agent_dir / "skill_cache.json") if cache_enabled else None
339
+ )
340
+ self._monitor = monitor
341
+ raw = self._load()
342
+ self._docs = raw[0]
343
+ self._diagnostics = raw[1]
344
+ self._digest = raw[2]
345
+
346
+ def _load(self) -> tuple[tuple[SkillDocument, ...], tuple[SkillDiagnostic, ...], str]:
347
+ # 全局用户级技能只在配置根下这一处(默认 ~/.braid/skills)。
348
+ ordered: tuple[tuple[Path, SkillSource], ...] = (
349
+ (self._agent_dir / USER_SKILLS_DIRNAME, "user"),
350
+ (self._cwd / CLAUDE_SKILLS_DIRNAME, "claude"),
351
+ (self._cwd / PROJECT_SKILLS_DIRNAME, "project"),
352
+ )
353
+ all_diagnostics: list[SkillDiagnostic] = []
354
+ by_name: dict[str, SkillDocument] = {}
355
+ collisions: list[SkillDiagnostic] = []
356
+ for directory, source in ordered:
357
+ for path, doc in _scan_dir_with_diagnostics(
358
+ directory,
359
+ source,
360
+ self._known_tools,
361
+ all_diagnostics,
362
+ self._cache,
363
+ ):
364
+ if doc.name in by_name:
365
+ loser = by_name[doc.name]
366
+ collisions.append(
367
+ SkillDiagnostic(
368
+ "collision",
369
+ f"技能名 {doc.name!r} 冲突:{source} 覆盖 {loser.source}",
370
+ path=str(path),
371
+ winner_path=doc.file_path,
372
+ )
373
+ )
374
+ by_name[doc.name] = doc
375
+ documents = tuple(by_name[name] for name in sorted(by_name))
376
+ if self._cache is not None:
377
+ self._cache.save()
378
+ total = self._cache.hits + self._cache.misses
379
+ if self._monitor is not None:
380
+ self._monitor.increment("skill_cache_hit", self._cache.hits)
381
+ self._monitor.increment("skill_cache_miss", self._cache.misses)
382
+ if total:
383
+ self._monitor.metric("skill_cache_hit_rate", self._cache.hits / total)
384
+ return (
385
+ documents,
386
+ tuple([*all_diagnostics, *collisions]),
387
+ _digest(documents),
388
+ )
389
+
390
+ def refresh(self) -> bool:
391
+ """重读磁盘;快照变化时更新并返回 ``True``。"""
392
+ documents, diagnostics, digest = self._load()
393
+ if digest == self._digest:
394
+ return False
395
+ self._docs = documents
396
+ self._diagnostics = diagnostics
397
+ self._digest = digest
398
+ return True
399
+
400
+ @property
401
+ def documents(self) -> tuple[SkillDocument, ...]:
402
+ return self._docs
403
+
404
+ @property
405
+ def diagnostics(self) -> tuple[SkillDiagnostic, ...]:
406
+ return self._diagnostics
407
+
408
+ @property
409
+ def digest(self) -> str:
410
+ return self._digest
411
+
412
+ def prompt_skills(self) -> tuple[Skill, ...]:
413
+ """模型可见的清单项:``disable-model-invocation`` 的只在 ``documents`` 里。"""
414
+ return tuple(
415
+ doc.to_prompt_skill() for doc in self._docs if not doc.disable_model_invocation
416
+ )
417
+
418
+ def find(self, name: str) -> SkillDocument | None:
419
+ for index, doc in enumerate(self._docs):
420
+ if doc.name == name:
421
+ if doc.body:
422
+ return doc
423
+ hydrated = self._read_body(doc)
424
+ self._docs = (*self._docs[:index], hydrated, *self._docs[index + 1 :])
425
+ return hydrated
426
+ return None
427
+
428
+ def _read_body(self, document: SkillDocument) -> SkillDocument:
429
+ """按名字取正文时再读文件,元信息阶段不做这件事。"""
430
+ path = Path(document.file_path)
431
+ text = path.read_text(encoding="utf-8", errors="replace")
432
+ parsed, _ = parse_skill_document(
433
+ text,
434
+ source=document.source,
435
+ path=document.file_path,
436
+ known_tools=self._known_tools,
437
+ )
438
+ if parsed is None:
439
+ raise RuntimeError(f"技能文件 {document.file_path} 在读取正文时解析失败")
440
+ return replace(parsed, fingerprint=document.fingerprint)
441
+
442
+
443
+ def _scan_dir_with_diagnostics(
444
+ directory: Path,
445
+ source: SkillSource,
446
+ known_tools: Sequence[str] | None,
447
+ diagnostics: list[SkillDiagnostic],
448
+ cache: SkillMetadataCache | None,
449
+ ) -> list[tuple[Path, SkillDocument]]:
450
+ found: list[tuple[Path, SkillDocument]] = []
451
+ if not directory.is_dir():
452
+ return found
453
+ context = "" if known_tools is None else "\0".join(known_tools)
454
+ for path in sorted(directory.glob(f"*/{SKILL_FILENAME}")):
455
+ if not path.is_file():
456
+ continue
457
+ fingerprint = file_fingerprint(path, extra=context)
458
+ if cache is not None:
459
+ cached = cache.get(path, fingerprint)
460
+ if cached is not None:
461
+ found.append((path, cached))
462
+ continue
463
+ text = path.read_text(encoding="utf-8", errors="replace")
464
+ doc, issues = parse_skill_document(
465
+ text, source=source, path=str(path), known_tools=known_tools
466
+ )
467
+ diagnostics.extend(issues)
468
+ if doc is not None:
469
+ metadata = replace(doc, body="", fingerprint=fingerprint)
470
+ if cache is not None:
471
+ cache.put(path, fingerprint, metadata)
472
+ found.append((path, metadata))
473
+ return found
474
+
475
+
476
+ def _document_to_payload(document: SkillDocument) -> dict[str, JsonValue]:
477
+ return {
478
+ "name": document.name,
479
+ "description": document.description,
480
+ "file_path": document.file_path,
481
+ "base_dir": document.base_dir,
482
+ "source": document.source,
483
+ "disable_model_invocation": document.disable_model_invocation,
484
+ "allowed_tools": list(document.allowed_tools),
485
+ "permission": document.permission,
486
+ "user_invocable": document.user_invocable,
487
+ "argument_hint": document.argument_hint,
488
+ }
489
+
490
+
491
+ def _document_from_payload(raw: JsonValue, fingerprint: str) -> SkillDocument | None:
492
+ if not isinstance(raw, dict):
493
+ return None
494
+ name = raw.get("name")
495
+ description = raw.get("description")
496
+ file_path = raw.get("file_path")
497
+ base_dir = raw.get("base_dir")
498
+ source = raw.get("source")
499
+ allowed_tools = raw.get("allowed_tools")
500
+ if (
501
+ not isinstance(name, str)
502
+ or not isinstance(description, str)
503
+ or not isinstance(file_path, str)
504
+ or not isinstance(base_dir, str)
505
+ or source not in ("user", "claude", "project")
506
+ or not isinstance(allowed_tools, list)
507
+ ):
508
+ return None
509
+ permission = raw.get("permission")
510
+ argument_hint = raw.get("argument_hint")
511
+ if permission is not None and (
512
+ not isinstance(permission, str) or permission not in PERMISSION_MODES
513
+ ):
514
+ return None
515
+ return SkillDocument(
516
+ name=name,
517
+ description=description,
518
+ file_path=file_path,
519
+ base_dir=base_dir,
520
+ source=source,
521
+ disable_model_invocation=raw.get("disable_model_invocation") is True,
522
+ allowed_tools=tuple(str(item) for item in allowed_tools),
523
+ permission=(
524
+ as_permission_mode(permission, where=file_path) if permission is not None else None
525
+ ),
526
+ body="",
527
+ user_invocable=raw.get("user_invocable") is not False,
528
+ argument_hint=argument_hint if isinstance(argument_hint, str) else None,
529
+ fingerprint=fingerprint,
530
+ )
531
+
532
+
533
+ def check_skill_access(
534
+ doc: SkillDocument,
535
+ engine: PermissionEngine | None,
536
+ *,
537
+ cwd: str,
538
+ ) -> SkillAccess:
539
+ """加载前的权限预检:用规则的纯判定,不发起交互批准。"""
540
+ if not doc.allowed_tools and doc.permission is None:
541
+ return SkillAccess(allowed=True, reason="技能未声明工具或权限要求")
542
+
543
+ if engine is None:
544
+ return SkillAccess(
545
+ allowed=False,
546
+ reason="技能声明了工具或权限要求,但本次运行没有装配权限引擎",
547
+ denied_tools=doc.allowed_tools,
548
+ )
549
+
550
+ settings: PermissionSettings = engine.settings
551
+ if (
552
+ doc.permission is not None
553
+ and clamp_permission_mode(settings.mode, doc.permission) != doc.permission
554
+ ):
555
+ return SkillAccess(
556
+ allowed=False,
557
+ reason=f"技能要求 {doc.permission} 模式,当前为 {settings.mode}",
558
+ denied_tools=doc.allowed_tools,
559
+ )
560
+
561
+ denied: list[str] = []
562
+ for tool in doc.allowed_tools:
563
+ request = build_request(tool, f"skill:{doc.name}", {}, cwd)
564
+ verdict = evaluate_rules(settings, request)
565
+ if verdict.action == "deny":
566
+ denied.append(tool)
567
+ if denied:
568
+ return SkillAccess(
569
+ allowed=False,
570
+ reason=f"技能声明的工具被当前规则拒绝:{', '.join(denied)}",
571
+ denied_tools=tuple(denied),
572
+ )
573
+ return SkillAccess(allowed=True, reason="技能声明的工具与权限均已满足")
574
+
575
+
576
+ SKILL_PARAMETERS: dict[str, JsonValue] = {
577
+ "type": "object",
578
+ "properties": {
579
+ "name": {
580
+ "type": "string",
581
+ "description": "Name of the skill whose full instructions to load",
582
+ }
583
+ },
584
+ "required": ["name"],
585
+ "additionalProperties": False,
586
+ }
587
+
588
+
589
+ def create_skill_tool(
590
+ loader: SkillsLoader,
591
+ engine: PermissionEngine | None,
592
+ *,
593
+ cwd: str,
594
+ ) -> AgentTool:
595
+ """按名字加载技能正文的工具。正文进上下文,元数据不重复渲染。"""
596
+
597
+ async def execute(
598
+ tool_call_id: str,
599
+ args: dict[str, JsonValue],
600
+ signal: CancelToken | None,
601
+ on_update: object,
602
+ ) -> AgentToolResult:
603
+ del tool_call_id, on_update
604
+ name = string_arg(args, "name")
605
+ if signal is not None and signal.cancelled:
606
+ return AgentToolResult(content=[TextContent(text="Operation aborted")], is_error=True)
607
+ doc = loader.find(name)
608
+ if doc is None:
609
+ return AgentToolResult(
610
+ content=[TextContent(text=f"Skill {name!r} not found. Use /skills to list them.")],
611
+ details={"name": name},
612
+ is_error=True,
613
+ )
614
+ if doc.disable_model_invocation:
615
+ return AgentToolResult(
616
+ content=[
617
+ TextContent(
618
+ text=(
619
+ f"Skill {name!r} is marked disable-model-invocation and can only be "
620
+ "loaded explicitly by the user with /skill."
621
+ )
622
+ )
623
+ ],
624
+ details={"name": name},
625
+ is_error=True,
626
+ )
627
+ access = check_skill_access(doc, engine, cwd=cwd)
628
+ if not access.allowed:
629
+ return AgentToolResult(
630
+ content=[TextContent(text=f"Skill {name!r} refused: {access.reason}")],
631
+ details={"name": name, "denied_tools": list(access.denied_tools)},
632
+ is_error=True,
633
+ )
634
+ truncation = truncate_head(
635
+ doc.body, max_lines=DEFAULT_MAX_LINES, max_bytes=DEFAULT_MAX_BYTES
636
+ )
637
+ # 技能目录必须进结果正文:正文里的相对路径要以它为基准,details 只有界面看得到。
638
+ header = (
639
+ f"Skill: {doc.name}\n"
640
+ f"Base directory: {doc.base_dir}\n"
641
+ "Relative paths in this skill resolve against that directory; read the files a "
642
+ "step tells you to read when you reach it.\n\n"
643
+ )
644
+ text = header + truncation.content
645
+ if truncation.truncated:
646
+ text += f"\n\n[Skill body truncated; read {doc.file_path} for the full text.]"
647
+ return AgentToolResult(
648
+ content=[TextContent(text=text)],
649
+ details={
650
+ "name": name,
651
+ "path": doc.file_path,
652
+ "base_dir": doc.base_dir,
653
+ "allowed_tools": list(doc.allowed_tools),
654
+ },
655
+ )
656
+
657
+ return AgentTool(
658
+ name="skill",
659
+ label="skill",
660
+ description=(
661
+ "Load the full instructions of a named skill into context, together with the "
662
+ "skill's base directory so its bundled files can be read on demand. Use "
663
+ "/skills to see which skills are available and when each applies."
664
+ ),
665
+ parameters=SKILL_PARAMETERS,
666
+ execute=execute,
667
+ )
668
+
669
+
670
+ __all__ = [
671
+ "CLAUDE_SKILLS_DIRNAME",
672
+ "PROJECT_SKILLS_DIRNAME",
673
+ "USER_SKILLS_DIRNAME",
674
+ "SkillAccess",
675
+ "SkillDiagnostic",
676
+ "SkillDocument",
677
+ "SkillsLoader",
678
+ "check_skill_access",
679
+ "create_skill_tool",
680
+ "parse_skill_document",
681
+ ]