@hfyjq/crannia 1.0.0 → 1.1.0

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 (221) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +45 -45
  3. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  4. package/THIRD-PARTY-PYTHON.md +162 -153
  5. package/THIRD-PARTY.md +316 -316
  6. package/apps/desktop/quotes.txt +56 -56
  7. package/bus/core.py +671 -671
  8. package/bus/loaders/channel_loader.py +64 -64
  9. package/bus/loaders/skill_md.py +676 -676
  10. package/bus/skill_state.py +124 -124
  11. package/channels/cli_channel/manifest.yaml +5 -5
  12. package/channels/dingtalk_channel/manifest.yaml +12 -12
  13. package/channels/feishu_channel/manifest.yaml +12 -12
  14. package/channels/qq_bot_channel/__init__.py +1 -1
  15. package/channels/qq_bot_channel/handler.py +881 -881
  16. package/channels/qq_bot_channel/manifest.yaml +4 -4
  17. package/channels/telegram_channel/__init__.py +1 -1
  18. package/channels/telegram_channel/handler.py +813 -813
  19. package/channels/telegram_channel/manifest.yaml +4 -4
  20. package/channels/telegram_channel/media.py +231 -231
  21. package/channels/textfmt.py +58 -58
  22. package/channels/wechat_channel/__init__.py +1 -1
  23. package/channels/wechat_channel/auth.py +23 -5
  24. package/channels/wechat_channel/manifest.yaml +5 -5
  25. package/channels/wechat_channel/media.py +178 -178
  26. package/config.yaml +2 -2
  27. package/core/activity.py +3 -0
  28. package/core/agent_loop.py +390 -55
  29. package/core/approval.py +17 -6
  30. package/core/artifacts.py +7 -0
  31. package/core/auto_review.py +23 -5
  32. package/core/channel_configs.py +34 -2
  33. package/core/channel_turns.py +759 -759
  34. package/core/child_approval.py +150 -0
  35. package/core/config_requirements.py +205 -0
  36. package/core/cron/runner.py +118 -6
  37. package/core/cron/store.py +14 -5
  38. package/core/cron/tools.py +17 -5
  39. package/core/endpoint.py +141 -0
  40. package/core/events.py +23 -0
  41. package/core/i18n.py +329 -329
  42. package/core/ice/store.py +191 -191
  43. package/core/inbound.py +193 -193
  44. package/core/jobs.py +19 -3
  45. package/core/last_good.py +150 -150
  46. package/core/llm_errors.py +227 -227
  47. package/core/llm_retry.py +230 -230
  48. package/core/memory/compressor.py +1214 -1214
  49. package/core/memory/manager.py +14 -0
  50. package/core/model_configs.py +80 -0
  51. package/core/pipeline/scheduler.py +2 -2
  52. package/core/pipeline/stages/agent_loop.py +24 -4
  53. package/core/pipeline/stages/pre_process.py +58 -7
  54. package/core/prompt_assembler.py +680 -680
  55. package/core/rg.py +255 -255
  56. package/core/security.py +1544 -1544
  57. package/core/settings_baseline.py +70 -1
  58. package/core/shell.py +5 -17
  59. package/core/skill_settings.py +7 -2
  60. package/core/state_registry.py +19 -0
  61. package/core/subagent.py +64 -3
  62. package/core/task_tool.py +1 -1
  63. package/core/tasks_notify.py +69 -4
  64. package/core/tiers.py +9 -3
  65. package/core/tool_outcome.py +108 -0
  66. package/core/update_tui.py +158 -0
  67. package/core/version.py +2 -2
  68. package/core/web_cache.py +152 -0
  69. package/crannia_tray.py +278 -278
  70. package/creators/models.json +4 -4
  71. package/data/settings.example.json +67 -0
  72. package/licenses/GPL-3.0.txt +619 -619
  73. package/licenses/LGPL-2.1.txt +502 -502
  74. package/licenses/LGPL-3.0.txt +165 -165
  75. package/licenses/MIT-chat-on-wechat.txt +18 -18
  76. package/licenses/MIT-deepseek-harness.txt +21 -21
  77. package/licenses/Molio-LICENSE.txt +44 -44
  78. package/locales/en.json +9 -4
  79. package/main.py +154 -154
  80. package/mcpx/manager.py +522 -522
  81. package/mcpx/servers/__init__.py +22 -22
  82. package/mcpx/servers/web_search.py +321 -33
  83. package/package.json +14 -9
  84. package/providers/anthropic/client.py +772 -772
  85. package/providers/cost_table.json +3779 -3779
  86. package/providers/deepseek/client.py +20 -20
  87. package/providers/deepseek/manifest.yaml +2 -2
  88. package/providers/factory.py +136 -136
  89. package/providers/lmstudio/client.py +2 -2
  90. package/providers/metadata.py +80 -80
  91. package/providers/model_capabilities.json +6665 -6665
  92. package/providers/moonshot/client.py +12 -12
  93. package/providers/ollama/client.py +2 -2
  94. package/providers/openai/client.py +13 -13
  95. package/providers/openrouter/client.py +2 -2
  96. package/providers/qwen/__init__.py +1 -1
  97. package/providers/qwen/client.py +2 -2
  98. package/providers/qwen/manifest.yaml +16 -16
  99. package/providers/rate_limiter.py +144 -144
  100. package/providers/siliconflow/client.py +2 -2
  101. package/providers/validation.py +171 -171
  102. package/providers/window_table.json +8909 -8909
  103. package/sbom.json +4413 -4296
  104. package/skills/entertainment/SKILL.md +35 -35
  105. package/skills/entertainment/__init__.py +1 -1
  106. package/skills/entertainment/handler.py +91 -91
  107. package/skills/entertainment/manifest.yaml +26 -26
  108. package/skills/file_parser/GUIDANCE.md +10 -10
  109. package/skills/file_parser/handler.py +177 -4
  110. package/skills/file_parser/manifest.yaml +22 -1
  111. package/skills/github/SKILL.md +32 -32
  112. package/skills/github/__init__.py +1 -1
  113. package/skills/github/manifest.yaml +5 -0
  114. package/skills/mail_parser/SKILL.md +68 -68
  115. package/skills/mail_parser/__init__.py +1 -1
  116. package/skills/mail_parser/handler.py +806 -806
  117. package/skills/mail_parser/manifest.yaml +5 -0
  118. package/skills/media_gen/GUIDANCE.md +19 -19
  119. package/skills/media_gen/SKILL.md +43 -43
  120. package/skills/media_gen/__init__.py +1 -1
  121. package/skills/media_gen/handler.py +430 -430
  122. package/skills/media_gen/manifest.yaml +93 -88
  123. package/skills/office_parser/cell_validation.py +127 -127
  124. package/skills/office_parser/excel_transform.py +936 -936
  125. package/skills/office_parser/layout_spec.py +243 -243
  126. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  127. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  128. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  129. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  130. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  131. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  133. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  134. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  135. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  136. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  137. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  143. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  151. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  152. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  153. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  154. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  155. package/skills/office_parser/references/layout_library.md +816 -816
  156. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  157. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  158. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  159. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  160. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  161. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  162. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  181. package/skills/office_parser/references/spec_lock.md +235 -235
  182. package/skills/office_parser/soffice.py +68 -68
  183. package/skills/office_parser/word_tools.py +2909 -2909
  184. package/tui/crannia.cmd +134 -0
  185. package/tui/crannia_tui/__init__.py +1 -0
  186. package/tui/crannia_tui/__main__.py +223 -0
  187. package/tui/crannia_tui/app.py +1318 -0
  188. package/tui/crannia_tui/app.tcss +153 -0
  189. package/tui/crannia_tui/approval.py +85 -0
  190. package/tui/crannia_tui/backend.py +279 -0
  191. package/tui/crannia_tui/channel.py +472 -0
  192. package/tui/crannia_tui/client.py +125 -0
  193. package/tui/crannia_tui/clipboard.py +62 -0
  194. package/tui/crannia_tui/commands.py +65 -0
  195. package/tui/crannia_tui/doctor.py +304 -0
  196. package/tui/crannia_tui/events.py +84 -0
  197. package/tui/crannia_tui/headless.py +152 -0
  198. package/tui/crannia_tui/i18n.py +164 -0
  199. package/tui/crannia_tui/locales/en.json +263 -0
  200. package/tui/crannia_tui/outcome.py +62 -0
  201. package/tui/crannia_tui/paths.py +181 -0
  202. package/tui/crannia_tui/probe.py +53 -0
  203. package/tui/crannia_tui/profile.py +169 -0
  204. package/tui/crannia_tui/render.py +209 -0
  205. package/tui/crannia_tui/settings.py +134 -0
  206. package/tui/crannia_tui/setup.py +380 -0
  207. package/tui/crannia_tui/term.py +116 -0
  208. package/tui/crannia_tui/ui.py +1236 -0
  209. package/tui/crannia_tui/update.py +389 -0
  210. package/vendor/ripgrep/COPYING.txt +3 -3
  211. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  212. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  213. package/vendor/ripgrep/README.md +51 -51
  214. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  215. package/vendor/ripgrep/package-source.json +19 -19
  216. package/web/__main__.py +15 -0
  217. package/web/server.py +168 -19
  218. package/web/static/img/channel-telegram.svg +1 -1
  219. package/web/static/img/channel-wechat.svg +1 -1
  220. package/web/templates/logs.html +49 -49
  221. package/web/templates/models.html +46 -46
@@ -1,676 +1,676 @@
1
- """指令型 skill(只有 `SKILL.md`、没有 `manifest.yaml` 的那种)—— 发现 + 解析。
2
-
3
- ## 它治的是什么
4
-
5
- 用户往 `skills/` 里放一个只有 `SKILL.md` 的目录,会被静默忽略:
6
- `bus/core.py:326` 与 `bus/loaders/skill_loader.py:611` 都是"没有 `manifest.yaml` 就跳过"。
7
- `reload_skills` 的结果里连 `failed` 都不进,用户看到的是「什么都没发生」。
8
-
9
- ## 判据 = 有没有 `manifest.yaml` —— 不是"像不像"
10
-
11
- 有 `manifest.yaml`,工具提供者(走工具装载那条,一个字不改)
12
- 没有、但有 `SKILL.md`,指令型 skill(本模块)
13
- 两个都没有,跳过(它本来就不是 skill 目录)
14
-
15
- 判据是一个文件的存在性,可机械核,且不会随内容漂。
16
-
17
- ## 这不是"两种 skill",是两层
18
-
19
- 能注册工具的 skill 不是 skill 的一种:`manifest.yaml` + `handler.py`
20
- 在机制上对应的是插件 / MCP;而 skill 层就是纯指令正文。本模块是另一层。
21
-
22
- ## 为什么是纯函数、没有模块级表
23
-
24
- 1. 可测 —— 喂一个临时目录就行,不用启动框架。
25
- 2. 模块级的可变表会被 census 当场抓住
26
- (它扫 `core/` + `bus/` 里"import 之后被写过"的名字)。而这里不需要是状态:
27
- 谁要就在那一刻扫一遍。少一格要登记的、要 purge 的东西。
28
- """
29
-
30
- from __future__ import annotations
31
-
32
- import json
33
- import re
34
- from dataclasses import dataclass, field
35
- from pathlib import Path
36
- from typing import Optional
37
-
38
- import yaml
39
-
40
- from bus.loaders.skill_loader import _parse_skill_md
41
- from core import skill_sources as _sources
42
- from core.content_sanitizer import sanitize_text
43
- from core.tool_names import normalise_tools as _normalise
44
-
45
- #: 跳过前导带这些字符的目录 —— 与 `skill_loader.reload_skills` 同一条规则。
46
- #: `_wip_` 那一类是 `create_skill` 的临时目录:必须跳过,
47
- #: 否则一个"还没体检完"的包会被当成装好的。
48
- _SKIP_PREFIXES = (".", "_", "$")
49
-
50
- #: 目录名长得像版本号(`1.0.0` / `5.6.2-wb.…`)。
51
- #: 插件缓存里 `SKILL.md` 直接躺在版本目录下,那种目录名不能当技能名。
52
- _VERSION_DIR_RE = re.compile(r"^\d+\.\d+")
53
-
54
-
55
- def _skill_name_from_dir(entry: Path) -> str:
56
- """技能名 = 目录名;目录名是版本号时取上一层的插件名。
57
-
58
- 判据没变(只有目录名能 import / 当命令,frontmatter 的 `name` 可以撒谎),
59
- 但插件缓存是一种新形状:`<市场>/<插件>/<版本>/SKILL.md` ——
60
- 那一层的目录名是版本号,直接用它会让所有技能叫 `1.0.0`。
61
- 只认"以数字开头带点"这一种形状,不做通用猜测。
62
- """
63
- if _VERSION_DIR_RE.match(entry.name):
64
- parent = entry.parent.name
65
- if parent:
66
- return parent
67
- return entry.name
68
-
69
- _MANIFEST = "manifest.yaml"
70
- _SKILL_MD = "SKILL.md"
71
-
72
- #: 共享根里 `SKILL.md` 解析问题的汇总口径(短标签 → 那句话,见
73
- #: `skill_loader._parse_skill_md` 的 `on_problem`)。分两组:
74
- #: · 致命 —— 这个 skill 收不进来(并进 `skipped` 那一行);
75
- #: · 提示 —— 收进来了,只是某个字段不合规范(不影响使用,名字取目录名)。
76
- _PARSE_FATAL = {
77
- "no-frontmatter": "SKILL.md 没有 frontmatter",
78
- "yaml": "SKILL.md 的 YAML 读不出",
79
- "not-dict": "SKILL.md 的 frontmatter 不是字典",
80
- "missing-name": "SKILL.md 缺 name",
81
- "missing-description": "SKILL.md 缺 description",
82
- }
83
- _PARSE_ADVISORY = {
84
- "bad-name": "name 不符合 agentskills.io 规范",
85
- }
86
-
87
-
88
- @dataclass(frozen=True)
89
- class InstructionSkill:
90
- """一个指令型 skill。字段全是"发现那一刻"的事实,没有运行时状态。"""
91
-
92
- #: 命令名 = 目录名。
93
- #: 理由:目录名是唯一无歧义的;frontmatter 的 `name` 可以撒谎或重复。
94
- #: (现成的例子:我们自己的 `skills/file_parser/` 里 `name:` 写的是 `file-parser`
95
- #: —— 同一个东西两个名字,而只有目录名能 `import`。)
96
- #: 别人源码的 `文件:行号` 不写在这里 —— 源码来源棘轮
97
- #: 只许降地钉着(它是发布前要清的东西)。
98
- name: str
99
-
100
- #: 绝对路径。 `Base directory for this skill:` 那行就是它 ——
101
- #: 模型靠它把正文里的相对路径(`assets/…` / `references/…`)解析成真文件。
102
- directory: Path
103
-
104
- description: str
105
-
106
- #: 正文(frontmatter 之后的部分)。发现阶段它没有读者 —— 留着是为了渲染,
107
- #: 也是为了"解析真的成功了"这件事可断言(空正文与解析失败长得像)。
108
- body: str
109
-
110
- #: 来源。`"repo"` 或 `"external"`(两值,`skill_sources.source_of` 推)。
111
- source: str = "repo"
112
-
113
- #: 更细的来源(给界面分类用):`repo` / `agents` / `claude` /
114
- #: `codex` / `workbuddy` / `explicit`。由根规格给,不由内容推。
115
- origin: str = "explicit"
116
-
117
- #: frontmatter 里的 `arguments:`(具名参数)。
118
- #: 纯数字名在替换时会被跳过 —— 否则 `$0` 有两个意思。
119
- named_args: dict = field(default_factory=dict)
120
-
121
- #: 四态。发现时不判它(`discover_instruction_skills` 是纯发现);
122
- #: 过滤在 `instruction_command_map` 里,因为那里才拿得到设置。
123
- state: str = "on"
124
-
125
- #: `allowed-tools`:这条命令/技能允许调用的工具。None = 不限制。
126
- #: 名称已归一为框架工具名(`core/tool_names.py`)。
127
- allowed_tools: object = None
128
-
129
-
130
- def _as_specs(root) -> list[_sources.SkillRoot]:
131
- """把 *root* 归一成根规格清单(带深度与来源)。
132
-
133
- · `None`,全部根(`skill_sources.skill_root_specs()` = 仓内 + 共享)
134
- · 单个 `str` / `Path`,或一个序列,就那几个;深度 1、
135
- 来源按已知根反查(查不到记 `explicit`)
136
-
137
- 反查而不是"调用方必须传规格" —— 现有的调用点传的是
138
- `skill_roots()`(一个路径列表),那条路要继续能用,而且要拿到正确的
139
- 来源与深度(否则插件缓存那种根会被按 1 层扫,一个都发现不了)。
140
- """
141
- if root is None:
142
- return _sources.skill_root_specs()
143
- if isinstance(root, (str, Path)):
144
- paths = [Path(root)]
145
- else:
146
- items = list(root)
147
- # 已经是 `SkillRoot` 的原样收(`instruction_command_map` 就是这么传的)。
148
- if items and all(isinstance(x, _sources.SkillRoot) for x in items):
149
- return items
150
- paths = [Path(r) for r in items]
151
- known: dict[str, _sources.SkillRoot] = {}
152
- try:
153
- for s in _sources.skill_root_specs(shared=True):
154
- try:
155
- known[str(s.path.resolve())] = s
156
- except OSError:
157
- continue
158
- except Exception: # noqa: BLE001
159
- known = {}
160
- out: list[_sources.SkillRoot] = []
161
- for p in paths:
162
- try:
163
- k = str(p.resolve())
164
- except OSError:
165
- k = str(p)
166
- out.append(known.get(k)
167
- or _sources.SkillRoot(p, 1, "explicit", "explicit"))
168
- return out
169
-
170
-
171
- #: 命令文件:`<插件>/commands/<名>.md` —— 文件名就是命令名。
172
- #: frontmatter 可以只有 `description`(甚至没有),正文就是提示词。
173
- _COMMAND_NAME = "commands"
174
- _FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?(.*)", re.DOTALL)
175
-
176
-
177
- def _walk_command_dirs(base: Path, depth: int) -> list[Path]:
178
- """在 *base* 下最多走 *depth* 层,返回名为 `commands` 的目录。"""
179
- out: list[Path] = []
180
- if depth <= 0:
181
- return out
182
- try:
183
- entries = sorted(base.iterdir(), key=lambda p: p.name)
184
- except OSError:
185
- return out
186
- for entry in entries:
187
- if entry.name.startswith(_SKIP_PREFIXES):
188
- continue
189
- try:
190
- if not entry.is_dir():
191
- continue
192
- except OSError:
193
- continue
194
- if entry.name == _COMMAND_NAME:
195
- out.append(entry)
196
- continue
197
- out.extend(_walk_command_dirs(entry, depth - 1))
198
- return out
199
-
200
-
201
- def _parse_command_md(path: Path) -> Optional[dict]:
202
- """读一个命令文件。没有 frontmatter 也是合法的(整篇就是提示词)。"""
203
- try:
204
- text = path.read_text(encoding="utf-8")
205
- except OSError:
206
- return None
207
- m = _FRONTMATTER_RE.match(text)
208
- if not m:
209
- return {"description": "", "body": text.strip()}
210
- try:
211
- meta = yaml.safe_load(m.group(1))
212
- except yaml.YAMLError:
213
- return None
214
- if not isinstance(meta, dict):
215
- meta = {}
216
- return {"description": str(meta.get("description") or "").strip(),
217
- "body": m.group(2).strip(),
218
- "allowed_tools": meta.get("allowed-tools")}
219
-
220
-
221
- def discover_plugin_commands(root=None) -> list[InstructionSkill]:
222
- """扫插件里的 `commands/<名>.md`,文件名就是命令名。
223
-
224
- 这是另一层:命令是"一段提示词模板",不是技能正文 ——
225
- 所以 `origin` 记 `"command"`(不进模型面,只进 `/` 命令面)。
226
- 与技能同一个判据来源(`_as_specs` 的根 + 深度),不另建一套根。
227
- """
228
- out: list[InstructionSkill] = []
229
- seen: set[str] = set()
230
- for spec in _as_specs(root):
231
- base = spec.path
232
- if not base.is_dir():
233
- continue
234
- for cmd_dir in _walk_command_dirs(base, spec.depth):
235
- try:
236
- files = sorted(cmd_dir.glob("*.md"), key=lambda p: p.name)
237
- except OSError:
238
- continue
239
- for f in files:
240
- try:
241
- real = str(f.resolve())
242
- except OSError:
243
- real = str(f)
244
- if real in seen:
245
- continue
246
- seen.add(real)
247
- meta = _parse_command_md(f)
248
- if meta is None:
249
- print("[skill] 跳过命令文件(读不出 frontmatter):%s" % f)
250
- continue
251
- out.append(InstructionSkill(
252
- name=f.stem,
253
- directory=f.parent,
254
- description=meta["description"],
255
- body=meta["body"],
256
- source=_sources.source_of(base),
257
- origin="command",
258
- allowed_tools=_normalise(meta.get("allowed_tools")),
259
- ))
260
- return out
261
-
262
-
263
- def _walk_skill_dirs(base: Path, depth: int,
264
- skipped: dict[str, int]) -> list[Path]:
265
- """在 *base* 下最多走 *depth* 层,返回含 `SKILL.md` 的目录(找到就停)。
266
-
267
- 找到就停:一个插件要么根上有 `SKILL.md`、要么在 `skills/<名>/` 下,
268
- 两种不会同时是"技能";继续深入只会把同一份技能再收一次
269
- (然后撞重名拒)。
270
-
271
- 序是确定的(每层按名字排)—— 顺序漂了,缓存前缀就跟着漂。
272
- """
273
- out: list[Path] = []
274
- if depth <= 0:
275
- return out
276
- try:
277
- entries = sorted(base.iterdir(), key=lambda p: p.name)
278
- except OSError as exc:
279
- skipped["读不到(%s)" % type(exc).__name__] = \
280
- skipped.get("读不到(%s)" % type(exc).__name__, 0) + 1
281
- return out
282
- for entry in entries:
283
- if entry.name.startswith(_SKIP_PREFIXES):
284
- continue
285
- why = _sources.skip_reason(entry, base)
286
- if why:
287
- skipped[why] = skipped.get(why, 0) + 1
288
- continue
289
- try:
290
- if not entry.is_dir():
291
- continue
292
- except OSError:
293
- continue
294
- if (entry / _SKILL_MD).is_file():
295
- out.append(entry)
296
- continue
297
- out.extend(_walk_skill_dirs(entry, depth - 1, skipped))
298
- return out
299
-
300
-
301
- def discover_instruction_skills(root=None) -> list[InstructionSkill]:
302
- """扫 *root*,返回指令型 skill,按目录名排序。*root* 三态见 `_as_specs`
303
- (`None` = 仓内 + 共享;给了具体路径就只扫那一个)。
304
-
305
- 序是确定的:顺序漂了,缓存前缀就跟着漂。
306
-
307
- 两条降权在这里生效(共享目录的包):
308
- ① 目录本身是符号链接,跳(`skill_sources.skip_reason`)
309
- ② `SKILL.md` > 128 KB,跳(`skill_sources.skill_md_skipped`;仓内不限)
310
- 两条都出声(`print`)—— 「静默跳过」是反模式。
311
- ①在本机会命中:`~/.claude/skills/*` 那 27 项全是指向
312
- `~/.agents/skills/*` 的符号链接(见 `core/skill_sources` 的 docstring)。
313
-
314
- 共享根里的解析问题也按根汇总 ——
315
- 那里会出现非法 YAML(`description_en:` 里一个裸冒号)与中文 `name:`;
316
- 逐条打全路径会把启动日志刷爆,而这些不是我们能修的。
317
- · 致命(拿不到 frontmatter / YAML 坏 / 不是字典 / 缺字段),并进 `skipped`;
318
- · 提示(`name` 不符合 agentskills.io),单列,并说清不影响使用
319
- (命令名取目录名,那个字段我们根本不读)。
320
- 仓内那一个根仍然逐条打 —— 那里坏了是我们的 bug,需要精确的路径。
321
-
322
- 它一个字节都不写(不注册、不落盘、不缓存)。调用方拿到的是那一刻的事实;
323
- 要长期持有就自己存,并去 `core/state_registry.py` 登记一行。
324
- """
325
- out: list[InstructionSkill] = []
326
- seen_dirs: set[str] = set()
327
- for spec in _as_specs(root):
328
- base = spec.path
329
- if not base.is_dir():
330
- continue
331
-
332
- #: 跳过的按原因计数,末尾汇总成一行打出。
333
- #: [!] 逐条 `print` 会把控制台刷爆(本机 `~/.claude/skills` 那 27 条 junction
334
- #: 逐条一行、而这一段每次重建索引都跑)—— 但不许静默
335
- #: (静默跳过是反模式),所以是汇总而不是删掉。
336
- skipped: dict[str, int] = {}
337
- #: 解析问题(同一条判据):致命的并进 `skipped`,提示性的单列。
338
- _problems: dict[str, int] = {}
339
- _external = _sources.is_external(base)
340
-
341
- def _note(key: str) -> None:
342
- _problems[key] = _problems.get(key, 0) + 1
343
-
344
- # 同一个插件在缓存里可能留着多个版本(`<插件>/<版本>/SKILL.md`)
345
- #同一根内先按技能名去重,只留 mtime 最新的那个,并出声。
346
- # 只在本根内去重:跨根同名是真的冲突,交给
347
- # `instruction_command_map` 拒(那条判据不许在这里提前吞掉)。
348
- _found = _walk_skill_dirs(base, spec.depth, skipped)
349
- if _found:
350
- _by_name: dict[str, Path] = {}
351
- _old = 0
352
- for e in _found:
353
- n = _skill_name_from_dir(e)
354
- cur = _by_name.get(n)
355
- if cur is None:
356
- _by_name[n] = e
357
- continue
358
- _old += 1
359
- try:
360
- if e.stat().st_mtime > cur.stat().st_mtime:
361
- _by_name[n] = e
362
- except OSError:
363
- continue
364
- if _old:
365
- skipped["同一插件的旧版本(只留最新)"] = _old
366
- _found = [_by_name[k] for k in sorted(_by_name)]
367
-
368
- for entry in _found:
369
- if (entry / _MANIFEST).is_file():
370
- continue # 工具型 —— 不归这里,它走 `skill_loader` 那条
371
- md = entry / _SKILL_MD
372
- if not md.is_file():
373
- continue # 两个都没有:它本来就不是 skill 目录,静默跳过是对的
374
- if _sources.skill_md_skipped(md, base):
375
- why = "SKILL.md 超过 %d KB(§5.2 共享目录的上限)" % (
376
- _sources.MAX_EXTERNAL_SKILL_MD_BYTES // 1024)
377
- skipped[why] = skipped.get(why, 0) + 1
378
- continue
379
-
380
- # 跨根去重按真实路径 —— 同一个包经两个根解析到同一个目录算一份
381
- # (名字相同而真实路径不同,才是 `instruction_command_map` 要拒的那种)。
382
- try:
383
- real = str(entry.resolve())
384
- except OSError:
385
- real = str(entry)
386
- if real in seen_dirs:
387
- continue
388
- seen_dirs.add(real)
389
-
390
- # 复用已有的那个解析器(别写第二个)。
391
- # 共享根:把问题交给下面的汇总(逐条打会刷屏,且那些文件不归我们修);
392
- # 仓内:照旧逐条出声 —— 那里坏了是我们自己的 bug,路径要精确。
393
- meta = _parse_skill_md(entry, on_problem=None if not _external else _note)
394
- if meta is None:
395
- continue # 致命解析问题:已计入 `_problems`(或已自己出声)
396
-
397
- # 具名参数只认"字典形"的 `arguments:`(`{名: 值}`)。
398
- # 它是列表形(`[name1, name2]` —— 只声明名字不给值)时不填 ——
399
- # 那种形状下「`$name` 的值从哪来」我们没有核实过
400
- # (只记了"`arguments:` frontmatter 声明的",没记值怎么绑)。
401
- #不猜(不许承诺兑现不了的):宁可 `$name` 保持原样,
402
- # 也不要按一个猜的语义去替换。
403
- raw_args = (meta.get("raw_metadata") or {}).get("arguments")
404
- named = dict(raw_args) if isinstance(raw_args, dict) else {}
405
-
406
- out.append(InstructionSkill(
407
- name=_skill_name_from_dir(entry),
408
- directory=entry.resolve(),
409
- description=(meta.get("description") or "").strip(),
410
- body=(meta.get("body") or "").strip(),
411
- # 来源从根推(不硬编码 `"repo"`)。
412
- source=_sources.source_of(base),
413
- origin=spec.origin,
414
- named_args=named,
415
- allowed_tools=_normalise(
416
- (meta.get("raw_metadata") or {}).get("allowed-tools")),
417
- ))
418
-
419
- # 解析问题并进同一套汇总(判据见 `_parse_skill_md` 的 `on_problem`)。
420
- advisory: dict[str, int] = {}
421
- for _key, _n in _problems.items():
422
- _label = _PARSE_FATAL.get(_key)
423
- if _label is None:
424
- advisory[_PARSE_ADVISORY.get(_key, _key)] = _n
425
- else:
426
- skipped[_label] = skipped.get(_label, 0) + _n
427
-
428
- for why, n in sorted(skipped.items()):
429
- print("[skill] 跳过 %d 个(%s)—— 根:%s" % (n, why, base))
430
- for why, n in sorted(advisory.items()):
431
- # 点破"不影响使用":命令名取目录名,frontmatter 那个 `name`
432
- # 我们根本不读 —— 不说的话,用户会以为这个技能坏了。
433
- print("[skill] %d 个 %s(不影响使用:命令名取目录名)—— 根:%s"
434
- % (n, why, base))
435
- return out
436
-
437
-
438
- # 参数替换 · 四态 · 命令表
439
-
440
- #: 四态:
441
- #:
442
- #: on 模型看得见 + `/名字` 能用(默认)
443
- #: name-only 列出来但不带描述(省钱)
444
- #: user-invocable-only 模型看不见,但 `/名字` 还在
445
- #: off 两边都藏
446
- #:
447
- #: 判据:按 skill 名覆盖;缺席 = on。
448
- #:读不到不是错误,是默认(同一句判据也适用于坏掉的设置文件)。
449
- SKILL_STATES = ("on", "name-only", "user-invocable-only", "off")
450
-
451
- #: 内联 shell 关闭。
452
- #:
453
- #: 是换成占位符,不是删掉 —— 删掉会让正文读起来断片
454
- #: (模型看到前后不接,会自己去猜那里原本是什么)。
455
- #: 判据:外来 skill 的正文是「别人写的提示词进你的 agent」,
456
- #: 只让它说话,不让它动手。
457
- SHELL_DISABLED_PLACEHOLDER = "[shell command execution disabled by policy]"
458
-
459
- #: 内联 shell 的形状:`` !`cmd` ``。
460
- _INLINE_SHELL_RE = re.compile(r"!`[^`]*`")
461
-
462
- _SETTINGS_PATH = Path("data/settings.json")
463
-
464
-
465
- def _skill_states() -> dict:
466
- """`{skill 名: 四态}`。读不到 / 坏 JSON,`{}`(= 全默认 `on`)。
467
-
468
- 不抛:一个坏掉的设置文件不该让所有 skill 一起消失
469
- (同 `core/mail_config` 那条:读不到,`{}`)。
470
- 未知的态,当 `on`(读到了但读不懂时,默认方向是"照常",
471
- 因为这一根是呈现轴不是安全轴)。
472
- """
473
- try:
474
- raw = json.loads(_SETTINGS_PATH.read_text(encoding="utf-8"))
475
- except (OSError, ValueError):
476
- return {}
477
- cfg = (raw or {}).get("skill_configs") or {}
478
- out = {}
479
- for name, entry in cfg.items():
480
- if isinstance(entry, dict):
481
- st = entry.get("state")
482
- if isinstance(st, str) and st.strip():
483
- out[name] = st.strip()
484
- return out
485
-
486
-
487
- def substitute_args(text: str, args: str, named=None) -> str:
488
- """参数替换。
489
-
490
- | 写法 | 换成 |
491
- |---|---|
492
- | `$ARGUMENTS` | 全部参数 |
493
- | `$ARGUMENTS[n]` / `$n` | 第 n 个(0 基) |
494
- | `$name` | `arguments:` frontmatter 里声明的具名参数(纯数字名不算 —— 否则和 `$0` 撞) |
495
- | 一个占位符都没有、但有参数 | 尾部追加 `\\n\\nARGUMENTS: <全部>` |
496
- | 没传参 | 全部占位符换成空串 |
497
-
498
- 具名参数先替换:`$ARGUMENTS` 是 `$A…` 形的,若先做 `$0..$n` 那一轮
499
- 不会有问题,但先替换具名能让"名字恰好是 `ARGUMENTS`"这种边角也落对。
500
- """
501
- named = named or {}
502
- parts = args.split() if args else []
503
- # 必须在替换之前判 —— 替换之后占位符都被吃掉了,那时再判就是恒假
504
- # (否则"没占位符"那条路永远走,尾注每次都追加)。
505
- had_placeholder = bool(_HAS_PLACEHOLDER.search(text))
506
-
507
- def _pos(i):
508
- return parts[i] if 0 <= i < len(parts) else ""
509
-
510
- # ① 具名(纯数字名不算 —— 那是 `$0` 的写法)
511
- for k, v in named.items():
512
- key = str(k)
513
- if key.isdigit():
514
- continue
515
- text = text.replace("${%s}" % key, str(v)).replace("$%s" % key, str(v))
516
-
517
- # ② `$ARGUMENTS[n]` 与 `$ARGUMENTS`
518
- text = re.sub(r"\$ARGUMENTS\[(\d+)\]", lambda m: _pos(int(m.group(1))), text)
519
- text = text.replace("$ARGUMENTS", args)
520
-
521
- # ③ `$0` `$1` …(只认 0-9:单位数)
522
- text = re.sub(r"\$([0-9])", lambda m: _pos(int(m.group(1))), text)
523
-
524
- # ④ 一个占位符都没有过、但用户给了参数,尾部追加
525
- if args and not had_placeholder:
526
- text = text.rstrip() + "\n\nARGUMENTS: " + args
527
- return text
528
-
529
-
530
- #: `substitute_args` 第 ④ 步的判据。它问的是「原始正文里有没有过占位符」,
531
- #: 所以必须在替换之前查(替换之后一律为假 —— 见上面那行注释)。
532
- _HAS_PLACEHOLDER = re.compile(r"\$ARGUMENTS|\$[0-9]|\$\{[A-Za-z_]")
533
-
534
-
535
- def render_skill_content(skill, args: str = "") -> str:
536
- """把正文包成那个壳(外壳逐字固定)。
537
-
538
- ```
539
- <skill_content name="…">
540
- <skill_resources>
541
- Base directory for this skill: <绝对路径>
542
- Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.
543
- </skill_resources>
544
- <skill_instructions>
545
- …正文(过参数替换 + 内联 shell 关掉)…
546
- </skill_instructions>
547
- </skill_content>
548
- ```
549
-
550
- 外壳形状与那两句英文与 dsh 的 `renderSkillContent` 相同(MIT,见
551
- `THIRD-PARTY.md` 第 17 节)。
552
-
553
- `Base directory for this skill:` 那两句逐字固定 ——
554
- 这是「别人的 skill 拿过来就能用」的关键:正文里的相对路径
555
- (`assets/template.html` / `references/themes.md`)模型靠这一句才解析得对。
556
- `references/` / `scripts/` 不枚举,正文自己点名,模型用自己的工具读。
557
- 不做资源加载器。
558
-
559
- 正文过 `sanitize_text`:
560
- 与「框架拼进 prompt 的块」同一条不变量。
561
- 包裹照发、只打码内容(打码只打内容这条不变量)。
562
- 这是我们的加强,可推翻。
563
- """
564
- body = substitute_args(skill.body, args, getattr(skill, "named_args", None))
565
- # 内联 shell 关闭:换成占位符,不是删掉。
566
- body = _INLINE_SHELL_RE.sub(SHELL_DISABLED_PLACEHOLDER, body)
567
- body = sanitize_text(body)
568
- return (
569
- '<skill_content name="%s">\n'
570
- "<skill_resources>\n"
571
- "Base directory for this skill: %s\n"
572
- "Resolve relative paths mentioned by this skill against the base directory "
573
- "before using them. Load referenced resources only as needed.\n"
574
- "</skill_resources>\n"
575
- "<skill_instructions>\n"
576
- "%s\n"
577
- "</skill_instructions>\n"
578
- "</skill_content>"
579
- ) % (skill.name, skill.directory.as_posix(), body)
580
-
581
-
582
- #: 进程级缓存。
583
- #:
584
- #: 为什么必须有它:扫一遍 `skills/` 要读每一个 `SKILL.md`
585
- #: (真实的 skill 那个 `SKILL.md` 有 36 KB),每条消息扫一次是不可接受的 ——
586
- #: 而 `_is_framework_command` 正是每条消息都会走的那条路。
587
- #:
588
- #: 它必须能被失效 —— 否则「用户放一个 skill 进去就能用」这句话就是假的。
589
- #: 失效点只有一处:`skill_loader.reload_skills`
590
- #: (生效要人按一下,缓存跟着那一下走)。
591
- #:
592
- #: 它是进程级,登记在 `core/state_registry.py` 的 `PROCESS_SHARED`,
593
- #: 并明说 `/clear` 不清它 —— 清了不是错,只是白扫一遍(与 `_sibling_cache` 同族)。
594
- #: 显式传 `states` 时不走缓存(测试与一次性诊断要的是"此刻的事实")。
595
- _map_cache: dict = {}
596
-
597
-
598
- def invalidate_command_map() -> None:
599
- """清掉 `instruction_command_map` 的缓存。 `/skill reload` 调它(唯一失效点)。"""
600
- _map_cache.clear()
601
-
602
-
603
- def instruction_command_map(root=None, reserved=(), states=None):
604
- """`{命令名: InstructionSkill}`,外加被拒的。
605
-
606
- Returns:
607
- `(visible, rejected)`:
608
- · *visible* —— 可以当 `/命令` 用的(含 `user-invocable-only`:
609
- 它只是不进模型面,`/` 照样敲得到)
610
- · *rejected* —— `[(名字, 原因)]`。出声用,绝不静默 ——
611
- 判据:在有权限含义的地方必须拒,
612
- 不采用「静默跳过 + 后者覆盖」那种做法。
613
-
614
- ## 两条拒法
615
-
616
- 1. 与内置命令撞(`/clear` 之类)—— `reserved` 由调用方注入
617
- (`core/` 与 `bus/` 的叶子规矩:这里不 import `pre_process`)。
618
- 2. 两个 skill 同目录名 —— 同一目录里不可能,但多 root 时可能
619
- (`~/.agents/skills` 等),判据写在这儿,到时不用改。
620
-
621
- ## 四态
622
-
623
- `off`,不进 / 列表(也不进模型面);其余三态都进来。
624
- `off` 不算"被拒" —— 那是用户的选择,不是冲突(两者不许同形:
625
- 一个是"你得处理",一个是"就这样")。
626
- """
627
- cacheable = states is None
628
- #: 缓存键必须是根清单(不是那个可能为 `None` 的入参)—— 两串不同的根
629
- #: 解析出同一份清单时,键也该相同;而 `None` 每次现算 cwd/home(`skill_sources` 那条)。
630
- specs = _as_specs(root)
631
- #: 缓存键要含深度与来源 —— 只拿路径当键的话,
632
- #: 同一个根换个深度扫出来的清单会串(后一次静默拿到前一次的结果)。
633
- ck = (tuple((str(s.path), s.depth, s.origin) for s in specs),
634
- tuple(sorted(str(r) for r in reserved)))
635
- if cacheable and ck in _map_cache:
636
- return _map_cache[ck]
637
-
638
- st = _skill_states() if states is None else states
639
- reserved = {r.lower() for r in reserved}
640
- visible, rejected, seen = {}, [], set()
641
-
642
- for s in list(discover_instruction_skills(specs)) + list(
643
- discover_plugin_commands(specs)):
644
- key = ("/" + s.name).lower()
645
- state = st.get(s.name, "on")
646
- if state not in SKILL_STATES:
647
- state = "on" # 读不懂,照常(呈现轴,见 `_skill_states`)
648
- if state == "off":
649
- continue
650
- if key in reserved:
651
- rejected.append((s.name, "与内置命令 %s 撞名" % key))
652
- continue
653
- if key in seen:
654
- rejected.append((s.name, "与另一个 skill 撞名(%s)" % key))
655
- continue
656
- seen.add(key)
657
- visible[key] = s
658
- if cacheable:
659
- _map_cache[ck] = (visible, rejected)
660
- return visible, rejected
661
-
662
-
663
- def report_line(skills: list) -> str:
664
- """一行汇总(给启动日志 / `/skill` 回执用)。0 个时返回空串。
665
-
666
- 判据:"不再静默" —— 有指令型 skill 时必须
667
- 说得出有几个、分别是谁。
668
-
669
- 0 个时返回空串是有意的:一个每次启动都打的「指令型 skill: 0 个」
670
- 会变成背景噪声,而噪声里的真信号不会被看见
671
- (一个"什么都没发生"的行会让下一条真的"什么都没发生"消失)。
672
- """
673
- if not skills:
674
- return ""
675
- names = ", ".join(s.name for s in skills)
676
- return "instruction-type skills: %d [%s]" % (len(skills), names)
1
+ """指令型 skill(只有 `SKILL.md`、没有 `manifest.yaml` 的那种)—— 发现 + 解析。
2
+
3
+ ## 它治的是什么
4
+
5
+ 用户往 `skills/` 里放一个只有 `SKILL.md` 的目录,会被静默忽略:
6
+ `bus/core.py:326` 与 `bus/loaders/skill_loader.py:611` 都是"没有 `manifest.yaml` 就跳过"。
7
+ `reload_skills` 的结果里连 `failed` 都不进,用户看到的是「什么都没发生」。
8
+
9
+ ## 判据 = 有没有 `manifest.yaml` —— 不是"像不像"
10
+
11
+ 有 `manifest.yaml`,工具提供者(走工具装载那条,一个字不改)
12
+ 没有、但有 `SKILL.md`,指令型 skill(本模块)
13
+ 两个都没有,跳过(它本来就不是 skill 目录)
14
+
15
+ 判据是一个文件的存在性,可机械核,且不会随内容漂。
16
+
17
+ ## 这不是"两种 skill",是两层
18
+
19
+ 能注册工具的 skill 不是 skill 的一种:`manifest.yaml` + `handler.py`
20
+ 在机制上对应的是插件 / MCP;而 skill 层就是纯指令正文。本模块是另一层。
21
+
22
+ ## 为什么是纯函数、没有模块级表
23
+
24
+ 1. 可测 —— 喂一个临时目录就行,不用启动框架。
25
+ 2. 模块级的可变表会被 census 当场抓住
26
+ (它扫 `core/` + `bus/` 里"import 之后被写过"的名字)。而这里不需要是状态:
27
+ 谁要就在那一刻扫一遍。少一格要登记的、要 purge 的东西。
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ import re
34
+ from dataclasses import dataclass, field
35
+ from pathlib import Path
36
+ from typing import Optional
37
+
38
+ import yaml
39
+
40
+ from bus.loaders.skill_loader import _parse_skill_md
41
+ from core import skill_sources as _sources
42
+ from core.content_sanitizer import sanitize_text
43
+ from core.tool_names import normalise_tools as _normalise
44
+
45
+ #: 跳过前导带这些字符的目录 —— 与 `skill_loader.reload_skills` 同一条规则。
46
+ #: `_wip_` 那一类是 `create_skill` 的临时目录:必须跳过,
47
+ #: 否则一个"还没体检完"的包会被当成装好的。
48
+ _SKIP_PREFIXES = (".", "_", "$")
49
+
50
+ #: 目录名长得像版本号(`1.0.0` / `5.6.2-wb.…`)。
51
+ #: 插件缓存里 `SKILL.md` 直接躺在版本目录下,那种目录名不能当技能名。
52
+ _VERSION_DIR_RE = re.compile(r"^\d+\.\d+")
53
+
54
+
55
+ def _skill_name_from_dir(entry: Path) -> str:
56
+ """技能名 = 目录名;目录名是版本号时取上一层的插件名。
57
+
58
+ 判据没变(只有目录名能 import / 当命令,frontmatter 的 `name` 可以撒谎),
59
+ 但插件缓存是一种新形状:`<市场>/<插件>/<版本>/SKILL.md` ——
60
+ 那一层的目录名是版本号,直接用它会让所有技能叫 `1.0.0`。
61
+ 只认"以数字开头带点"这一种形状,不做通用猜测。
62
+ """
63
+ if _VERSION_DIR_RE.match(entry.name):
64
+ parent = entry.parent.name
65
+ if parent:
66
+ return parent
67
+ return entry.name
68
+
69
+ _MANIFEST = "manifest.yaml"
70
+ _SKILL_MD = "SKILL.md"
71
+
72
+ #: 共享根里 `SKILL.md` 解析问题的汇总口径(短标签 → 那句话,见
73
+ #: `skill_loader._parse_skill_md` 的 `on_problem`)。分两组:
74
+ #: · 致命 —— 这个 skill 收不进来(并进 `skipped` 那一行);
75
+ #: · 提示 —— 收进来了,只是某个字段不合规范(不影响使用,名字取目录名)。
76
+ _PARSE_FATAL = {
77
+ "no-frontmatter": "SKILL.md 没有 frontmatter",
78
+ "yaml": "SKILL.md 的 YAML 读不出",
79
+ "not-dict": "SKILL.md 的 frontmatter 不是字典",
80
+ "missing-name": "SKILL.md 缺 name",
81
+ "missing-description": "SKILL.md 缺 description",
82
+ }
83
+ _PARSE_ADVISORY = {
84
+ "bad-name": "name 不符合 agentskills.io 规范",
85
+ }
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class InstructionSkill:
90
+ """一个指令型 skill。字段全是"发现那一刻"的事实,没有运行时状态。"""
91
+
92
+ #: 命令名 = 目录名。
93
+ #: 理由:目录名是唯一无歧义的;frontmatter 的 `name` 可以撒谎或重复。
94
+ #: (现成的例子:我们自己的 `skills/file_parser/` 里 `name:` 写的是 `file-parser`
95
+ #: —— 同一个东西两个名字,而只有目录名能 `import`。)
96
+ #: 别人源码的 `文件:行号` 不写在这里 —— 源码来源棘轮
97
+ #: 只许降地钉着(它是发布前要清的东西)。
98
+ name: str
99
+
100
+ #: 绝对路径。 `Base directory for this skill:` 那行就是它 ——
101
+ #: 模型靠它把正文里的相对路径(`assets/…` / `references/…`)解析成真文件。
102
+ directory: Path
103
+
104
+ description: str
105
+
106
+ #: 正文(frontmatter 之后的部分)。发现阶段它没有读者 —— 留着是为了渲染,
107
+ #: 也是为了"解析真的成功了"这件事可断言(空正文与解析失败长得像)。
108
+ body: str
109
+
110
+ #: 来源。`"repo"` 或 `"external"`(两值,`skill_sources.source_of` 推)。
111
+ source: str = "repo"
112
+
113
+ #: 更细的来源(给界面分类用):`repo` / `agents` / `claude` /
114
+ #: `codex` / `workbuddy` / `explicit`。由根规格给,不由内容推。
115
+ origin: str = "explicit"
116
+
117
+ #: frontmatter 里的 `arguments:`(具名参数)。
118
+ #: 纯数字名在替换时会被跳过 —— 否则 `$0` 有两个意思。
119
+ named_args: dict = field(default_factory=dict)
120
+
121
+ #: 四态。发现时不判它(`discover_instruction_skills` 是纯发现);
122
+ #: 过滤在 `instruction_command_map` 里,因为那里才拿得到设置。
123
+ state: str = "on"
124
+
125
+ #: `allowed-tools`:这条命令/技能允许调用的工具。None = 不限制。
126
+ #: 名称已归一为框架工具名(`core/tool_names.py`)。
127
+ allowed_tools: object = None
128
+
129
+
130
+ def _as_specs(root) -> list[_sources.SkillRoot]:
131
+ """把 *root* 归一成根规格清单(带深度与来源)。
132
+
133
+ · `None`,全部根(`skill_sources.skill_root_specs()` = 仓内 + 共享)
134
+ · 单个 `str` / `Path`,或一个序列,就那几个;深度 1、
135
+ 来源按已知根反查(查不到记 `explicit`)
136
+
137
+ 反查而不是"调用方必须传规格" —— 现有的调用点传的是
138
+ `skill_roots()`(一个路径列表),那条路要继续能用,而且要拿到正确的
139
+ 来源与深度(否则插件缓存那种根会被按 1 层扫,一个都发现不了)。
140
+ """
141
+ if root is None:
142
+ return _sources.skill_root_specs()
143
+ if isinstance(root, (str, Path)):
144
+ paths = [Path(root)]
145
+ else:
146
+ items = list(root)
147
+ # 已经是 `SkillRoot` 的原样收(`instruction_command_map` 就是这么传的)。
148
+ if items and all(isinstance(x, _sources.SkillRoot) for x in items):
149
+ return items
150
+ paths = [Path(r) for r in items]
151
+ known: dict[str, _sources.SkillRoot] = {}
152
+ try:
153
+ for s in _sources.skill_root_specs(shared=True):
154
+ try:
155
+ known[str(s.path.resolve())] = s
156
+ except OSError:
157
+ continue
158
+ except Exception: # noqa: BLE001
159
+ known = {}
160
+ out: list[_sources.SkillRoot] = []
161
+ for p in paths:
162
+ try:
163
+ k = str(p.resolve())
164
+ except OSError:
165
+ k = str(p)
166
+ out.append(known.get(k)
167
+ or _sources.SkillRoot(p, 1, "explicit", "explicit"))
168
+ return out
169
+
170
+
171
+ #: 命令文件:`<插件>/commands/<名>.md` —— 文件名就是命令名。
172
+ #: frontmatter 可以只有 `description`(甚至没有),正文就是提示词。
173
+ _COMMAND_NAME = "commands"
174
+ _FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?(.*)", re.DOTALL)
175
+
176
+
177
+ def _walk_command_dirs(base: Path, depth: int) -> list[Path]:
178
+ """在 *base* 下最多走 *depth* 层,返回名为 `commands` 的目录。"""
179
+ out: list[Path] = []
180
+ if depth <= 0:
181
+ return out
182
+ try:
183
+ entries = sorted(base.iterdir(), key=lambda p: p.name)
184
+ except OSError:
185
+ return out
186
+ for entry in entries:
187
+ if entry.name.startswith(_SKIP_PREFIXES):
188
+ continue
189
+ try:
190
+ if not entry.is_dir():
191
+ continue
192
+ except OSError:
193
+ continue
194
+ if entry.name == _COMMAND_NAME:
195
+ out.append(entry)
196
+ continue
197
+ out.extend(_walk_command_dirs(entry, depth - 1))
198
+ return out
199
+
200
+
201
+ def _parse_command_md(path: Path) -> Optional[dict]:
202
+ """读一个命令文件。没有 frontmatter 也是合法的(整篇就是提示词)。"""
203
+ try:
204
+ text = path.read_text(encoding="utf-8")
205
+ except OSError:
206
+ return None
207
+ m = _FRONTMATTER_RE.match(text)
208
+ if not m:
209
+ return {"description": "", "body": text.strip()}
210
+ try:
211
+ meta = yaml.safe_load(m.group(1))
212
+ except yaml.YAMLError:
213
+ return None
214
+ if not isinstance(meta, dict):
215
+ meta = {}
216
+ return {"description": str(meta.get("description") or "").strip(),
217
+ "body": m.group(2).strip(),
218
+ "allowed_tools": meta.get("allowed-tools")}
219
+
220
+
221
+ def discover_plugin_commands(root=None) -> list[InstructionSkill]:
222
+ """扫插件里的 `commands/<名>.md`,文件名就是命令名。
223
+
224
+ 这是另一层:命令是"一段提示词模板",不是技能正文 ——
225
+ 所以 `origin` 记 `"command"`(不进模型面,只进 `/` 命令面)。
226
+ 与技能同一个判据来源(`_as_specs` 的根 + 深度),不另建一套根。
227
+ """
228
+ out: list[InstructionSkill] = []
229
+ seen: set[str] = set()
230
+ for spec in _as_specs(root):
231
+ base = spec.path
232
+ if not base.is_dir():
233
+ continue
234
+ for cmd_dir in _walk_command_dirs(base, spec.depth):
235
+ try:
236
+ files = sorted(cmd_dir.glob("*.md"), key=lambda p: p.name)
237
+ except OSError:
238
+ continue
239
+ for f in files:
240
+ try:
241
+ real = str(f.resolve())
242
+ except OSError:
243
+ real = str(f)
244
+ if real in seen:
245
+ continue
246
+ seen.add(real)
247
+ meta = _parse_command_md(f)
248
+ if meta is None:
249
+ print("[skill] 跳过命令文件(读不出 frontmatter):%s" % f)
250
+ continue
251
+ out.append(InstructionSkill(
252
+ name=f.stem,
253
+ directory=f.parent,
254
+ description=meta["description"],
255
+ body=meta["body"],
256
+ source=_sources.source_of(base),
257
+ origin="command",
258
+ allowed_tools=_normalise(meta.get("allowed_tools")),
259
+ ))
260
+ return out
261
+
262
+
263
+ def _walk_skill_dirs(base: Path, depth: int,
264
+ skipped: dict[str, int]) -> list[Path]:
265
+ """在 *base* 下最多走 *depth* 层,返回含 `SKILL.md` 的目录(找到就停)。
266
+
267
+ 找到就停:一个插件要么根上有 `SKILL.md`、要么在 `skills/<名>/` 下,
268
+ 两种不会同时是"技能";继续深入只会把同一份技能再收一次
269
+ (然后撞重名拒)。
270
+
271
+ 序是确定的(每层按名字排)—— 顺序漂了,缓存前缀就跟着漂。
272
+ """
273
+ out: list[Path] = []
274
+ if depth <= 0:
275
+ return out
276
+ try:
277
+ entries = sorted(base.iterdir(), key=lambda p: p.name)
278
+ except OSError as exc:
279
+ skipped["读不到(%s)" % type(exc).__name__] = \
280
+ skipped.get("读不到(%s)" % type(exc).__name__, 0) + 1
281
+ return out
282
+ for entry in entries:
283
+ if entry.name.startswith(_SKIP_PREFIXES):
284
+ continue
285
+ why = _sources.skip_reason(entry, base)
286
+ if why:
287
+ skipped[why] = skipped.get(why, 0) + 1
288
+ continue
289
+ try:
290
+ if not entry.is_dir():
291
+ continue
292
+ except OSError:
293
+ continue
294
+ if (entry / _SKILL_MD).is_file():
295
+ out.append(entry)
296
+ continue
297
+ out.extend(_walk_skill_dirs(entry, depth - 1, skipped))
298
+ return out
299
+
300
+
301
+ def discover_instruction_skills(root=None) -> list[InstructionSkill]:
302
+ """扫 *root*,返回指令型 skill,按目录名排序。*root* 三态见 `_as_specs`
303
+ (`None` = 仓内 + 共享;给了具体路径就只扫那一个)。
304
+
305
+ 序是确定的:顺序漂了,缓存前缀就跟着漂。
306
+
307
+ 两条降权在这里生效(共享目录的包):
308
+ ① 目录本身是符号链接,跳(`skill_sources.skip_reason`)
309
+ ② `SKILL.md` > 128 KB,跳(`skill_sources.skill_md_skipped`;仓内不限)
310
+ 两条都出声(`print`)—— 「静默跳过」是反模式。
311
+ ①在本机会命中:`~/.claude/skills/*` 那 27 项全是指向
312
+ `~/.agents/skills/*` 的符号链接(见 `core/skill_sources` 的 docstring)。
313
+
314
+ 共享根里的解析问题也按根汇总 ——
315
+ 那里会出现非法 YAML(`description_en:` 里一个裸冒号)与中文 `name:`;
316
+ 逐条打全路径会把启动日志刷爆,而这些不是我们能修的。
317
+ · 致命(拿不到 frontmatter / YAML 坏 / 不是字典 / 缺字段),并进 `skipped`;
318
+ · 提示(`name` 不符合 agentskills.io),单列,并说清不影响使用
319
+ (命令名取目录名,那个字段我们根本不读)。
320
+ 仓内那一个根仍然逐条打 —— 那里坏了是我们的 bug,需要精确的路径。
321
+
322
+ 它一个字节都不写(不注册、不落盘、不缓存)。调用方拿到的是那一刻的事实;
323
+ 要长期持有就自己存,并去 `core/state_registry.py` 登记一行。
324
+ """
325
+ out: list[InstructionSkill] = []
326
+ seen_dirs: set[str] = set()
327
+ for spec in _as_specs(root):
328
+ base = spec.path
329
+ if not base.is_dir():
330
+ continue
331
+
332
+ #: 跳过的按原因计数,末尾汇总成一行打出。
333
+ #: [!] 逐条 `print` 会把控制台刷爆(本机 `~/.claude/skills` 那 27 条 junction
334
+ #: 逐条一行、而这一段每次重建索引都跑)—— 但不许静默
335
+ #: (静默跳过是反模式),所以是汇总而不是删掉。
336
+ skipped: dict[str, int] = {}
337
+ #: 解析问题(同一条判据):致命的并进 `skipped`,提示性的单列。
338
+ _problems: dict[str, int] = {}
339
+ _external = _sources.is_external(base)
340
+
341
+ def _note(key: str) -> None:
342
+ _problems[key] = _problems.get(key, 0) + 1
343
+
344
+ # 同一个插件在缓存里可能留着多个版本(`<插件>/<版本>/SKILL.md`)
345
+ #同一根内先按技能名去重,只留 mtime 最新的那个,并出声。
346
+ # 只在本根内去重:跨根同名是真的冲突,交给
347
+ # `instruction_command_map` 拒(那条判据不许在这里提前吞掉)。
348
+ _found = _walk_skill_dirs(base, spec.depth, skipped)
349
+ if _found:
350
+ _by_name: dict[str, Path] = {}
351
+ _old = 0
352
+ for e in _found:
353
+ n = _skill_name_from_dir(e)
354
+ cur = _by_name.get(n)
355
+ if cur is None:
356
+ _by_name[n] = e
357
+ continue
358
+ _old += 1
359
+ try:
360
+ if e.stat().st_mtime > cur.stat().st_mtime:
361
+ _by_name[n] = e
362
+ except OSError:
363
+ continue
364
+ if _old:
365
+ skipped["同一插件的旧版本(只留最新)"] = _old
366
+ _found = [_by_name[k] for k in sorted(_by_name)]
367
+
368
+ for entry in _found:
369
+ if (entry / _MANIFEST).is_file():
370
+ continue # 工具型 —— 不归这里,它走 `skill_loader` 那条
371
+ md = entry / _SKILL_MD
372
+ if not md.is_file():
373
+ continue # 两个都没有:它本来就不是 skill 目录,静默跳过是对的
374
+ if _sources.skill_md_skipped(md, base):
375
+ why = "SKILL.md 超过 %d KB(§5.2 共享目录的上限)" % (
376
+ _sources.MAX_EXTERNAL_SKILL_MD_BYTES // 1024)
377
+ skipped[why] = skipped.get(why, 0) + 1
378
+ continue
379
+
380
+ # 跨根去重按真实路径 —— 同一个包经两个根解析到同一个目录算一份
381
+ # (名字相同而真实路径不同,才是 `instruction_command_map` 要拒的那种)。
382
+ try:
383
+ real = str(entry.resolve())
384
+ except OSError:
385
+ real = str(entry)
386
+ if real in seen_dirs:
387
+ continue
388
+ seen_dirs.add(real)
389
+
390
+ # 复用已有的那个解析器(别写第二个)。
391
+ # 共享根:把问题交给下面的汇总(逐条打会刷屏,且那些文件不归我们修);
392
+ # 仓内:照旧逐条出声 —— 那里坏了是我们自己的 bug,路径要精确。
393
+ meta = _parse_skill_md(entry, on_problem=None if not _external else _note)
394
+ if meta is None:
395
+ continue # 致命解析问题:已计入 `_problems`(或已自己出声)
396
+
397
+ # 具名参数只认"字典形"的 `arguments:`(`{名: 值}`)。
398
+ # 它是列表形(`[name1, name2]` —— 只声明名字不给值)时不填 ——
399
+ # 那种形状下「`$name` 的值从哪来」我们没有核实过
400
+ # (只记了"`arguments:` frontmatter 声明的",没记值怎么绑)。
401
+ #不猜(不许承诺兑现不了的):宁可 `$name` 保持原样,
402
+ # 也不要按一个猜的语义去替换。
403
+ raw_args = (meta.get("raw_metadata") or {}).get("arguments")
404
+ named = dict(raw_args) if isinstance(raw_args, dict) else {}
405
+
406
+ out.append(InstructionSkill(
407
+ name=_skill_name_from_dir(entry),
408
+ directory=entry.resolve(),
409
+ description=(meta.get("description") or "").strip(),
410
+ body=(meta.get("body") or "").strip(),
411
+ # 来源从根推(不硬编码 `"repo"`)。
412
+ source=_sources.source_of(base),
413
+ origin=spec.origin,
414
+ named_args=named,
415
+ allowed_tools=_normalise(
416
+ (meta.get("raw_metadata") or {}).get("allowed-tools")),
417
+ ))
418
+
419
+ # 解析问题并进同一套汇总(判据见 `_parse_skill_md` 的 `on_problem`)。
420
+ advisory: dict[str, int] = {}
421
+ for _key, _n in _problems.items():
422
+ _label = _PARSE_FATAL.get(_key)
423
+ if _label is None:
424
+ advisory[_PARSE_ADVISORY.get(_key, _key)] = _n
425
+ else:
426
+ skipped[_label] = skipped.get(_label, 0) + _n
427
+
428
+ for why, n in sorted(skipped.items()):
429
+ print("[skill] 跳过 %d 个(%s)—— 根:%s" % (n, why, base))
430
+ for why, n in sorted(advisory.items()):
431
+ # 点破"不影响使用":命令名取目录名,frontmatter 那个 `name`
432
+ # 我们根本不读 —— 不说的话,用户会以为这个技能坏了。
433
+ print("[skill] %d 个 %s(不影响使用:命令名取目录名)—— 根:%s"
434
+ % (n, why, base))
435
+ return out
436
+
437
+
438
+ # 参数替换 · 四态 · 命令表
439
+
440
+ #: 四态:
441
+ #:
442
+ #: on 模型看得见 + `/名字` 能用(默认)
443
+ #: name-only 列出来但不带描述(省钱)
444
+ #: user-invocable-only 模型看不见,但 `/名字` 还在
445
+ #: off 两边都藏
446
+ #:
447
+ #: 判据:按 skill 名覆盖;缺席 = on。
448
+ #:读不到不是错误,是默认(同一句判据也适用于坏掉的设置文件)。
449
+ SKILL_STATES = ("on", "name-only", "user-invocable-only", "off")
450
+
451
+ #: 内联 shell 关闭。
452
+ #:
453
+ #: 是换成占位符,不是删掉 —— 删掉会让正文读起来断片
454
+ #: (模型看到前后不接,会自己去猜那里原本是什么)。
455
+ #: 判据:外来 skill 的正文是「别人写的提示词进你的 agent」,
456
+ #: 只让它说话,不让它动手。
457
+ SHELL_DISABLED_PLACEHOLDER = "[shell command execution disabled by policy]"
458
+
459
+ #: 内联 shell 的形状:`` !`cmd` ``。
460
+ _INLINE_SHELL_RE = re.compile(r"!`[^`]*`")
461
+
462
+ _SETTINGS_PATH = Path("data/settings.json")
463
+
464
+
465
+ def _skill_states() -> dict:
466
+ """`{skill 名: 四态}`。读不到 / 坏 JSON,`{}`(= 全默认 `on`)。
467
+
468
+ 不抛:一个坏掉的设置文件不该让所有 skill 一起消失
469
+ (同 `core/mail_config` 那条:读不到,`{}`)。
470
+ 未知的态,当 `on`(读到了但读不懂时,默认方向是"照常",
471
+ 因为这一根是呈现轴不是安全轴)。
472
+ """
473
+ try:
474
+ raw = json.loads(_SETTINGS_PATH.read_text(encoding="utf-8"))
475
+ except (OSError, ValueError):
476
+ return {}
477
+ cfg = (raw or {}).get("skill_configs") or {}
478
+ out = {}
479
+ for name, entry in cfg.items():
480
+ if isinstance(entry, dict):
481
+ st = entry.get("state")
482
+ if isinstance(st, str) and st.strip():
483
+ out[name] = st.strip()
484
+ return out
485
+
486
+
487
+ def substitute_args(text: str, args: str, named=None) -> str:
488
+ """参数替换。
489
+
490
+ | 写法 | 换成 |
491
+ |---|---|
492
+ | `$ARGUMENTS` | 全部参数 |
493
+ | `$ARGUMENTS[n]` / `$n` | 第 n 个(0 基) |
494
+ | `$name` | `arguments:` frontmatter 里声明的具名参数(纯数字名不算 —— 否则和 `$0` 撞) |
495
+ | 一个占位符都没有、但有参数 | 尾部追加 `\\n\\nARGUMENTS: <全部>` |
496
+ | 没传参 | 全部占位符换成空串 |
497
+
498
+ 具名参数先替换:`$ARGUMENTS` 是 `$A…` 形的,若先做 `$0..$n` 那一轮
499
+ 不会有问题,但先替换具名能让"名字恰好是 `ARGUMENTS`"这种边角也落对。
500
+ """
501
+ named = named or {}
502
+ parts = args.split() if args else []
503
+ # 必须在替换之前判 —— 替换之后占位符都被吃掉了,那时再判就是恒假
504
+ # (否则"没占位符"那条路永远走,尾注每次都追加)。
505
+ had_placeholder = bool(_HAS_PLACEHOLDER.search(text))
506
+
507
+ def _pos(i):
508
+ return parts[i] if 0 <= i < len(parts) else ""
509
+
510
+ # ① 具名(纯数字名不算 —— 那是 `$0` 的写法)
511
+ for k, v in named.items():
512
+ key = str(k)
513
+ if key.isdigit():
514
+ continue
515
+ text = text.replace("${%s}" % key, str(v)).replace("$%s" % key, str(v))
516
+
517
+ # ② `$ARGUMENTS[n]` 与 `$ARGUMENTS`
518
+ text = re.sub(r"\$ARGUMENTS\[(\d+)\]", lambda m: _pos(int(m.group(1))), text)
519
+ text = text.replace("$ARGUMENTS", args)
520
+
521
+ # ③ `$0` `$1` …(只认 0-9:单位数)
522
+ text = re.sub(r"\$([0-9])", lambda m: _pos(int(m.group(1))), text)
523
+
524
+ # ④ 一个占位符都没有过、但用户给了参数,尾部追加
525
+ if args and not had_placeholder:
526
+ text = text.rstrip() + "\n\nARGUMENTS: " + args
527
+ return text
528
+
529
+
530
+ #: `substitute_args` 第 ④ 步的判据。它问的是「原始正文里有没有过占位符」,
531
+ #: 所以必须在替换之前查(替换之后一律为假 —— 见上面那行注释)。
532
+ _HAS_PLACEHOLDER = re.compile(r"\$ARGUMENTS|\$[0-9]|\$\{[A-Za-z_]")
533
+
534
+
535
+ def render_skill_content(skill, args: str = "") -> str:
536
+ """把正文包成那个壳(外壳逐字固定)。
537
+
538
+ ```
539
+ <skill_content name="…">
540
+ <skill_resources>
541
+ Base directory for this skill: <绝对路径>
542
+ Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.
543
+ </skill_resources>
544
+ <skill_instructions>
545
+ …正文(过参数替换 + 内联 shell 关掉)…
546
+ </skill_instructions>
547
+ </skill_content>
548
+ ```
549
+
550
+ 外壳形状与那两句英文与 dsh 的 `renderSkillContent` 相同(MIT,见
551
+ `THIRD-PARTY.md` 第 17 节)。
552
+
553
+ `Base directory for this skill:` 那两句逐字固定 ——
554
+ 这是「别人的 skill 拿过来就能用」的关键:正文里的相对路径
555
+ (`assets/template.html` / `references/themes.md`)模型靠这一句才解析得对。
556
+ `references/` / `scripts/` 不枚举,正文自己点名,模型用自己的工具读。
557
+ 不做资源加载器。
558
+
559
+ 正文过 `sanitize_text`:
560
+ 与「框架拼进 prompt 的块」同一条不变量。
561
+ 包裹照发、只打码内容(打码只打内容这条不变量)。
562
+ 这是我们的加强,可推翻。
563
+ """
564
+ body = substitute_args(skill.body, args, getattr(skill, "named_args", None))
565
+ # 内联 shell 关闭:换成占位符,不是删掉。
566
+ body = _INLINE_SHELL_RE.sub(SHELL_DISABLED_PLACEHOLDER, body)
567
+ body = sanitize_text(body)
568
+ return (
569
+ '<skill_content name="%s">\n'
570
+ "<skill_resources>\n"
571
+ "Base directory for this skill: %s\n"
572
+ "Resolve relative paths mentioned by this skill against the base directory "
573
+ "before using them. Load referenced resources only as needed.\n"
574
+ "</skill_resources>\n"
575
+ "<skill_instructions>\n"
576
+ "%s\n"
577
+ "</skill_instructions>\n"
578
+ "</skill_content>"
579
+ ) % (skill.name, skill.directory.as_posix(), body)
580
+
581
+
582
+ #: 进程级缓存。
583
+ #:
584
+ #: 为什么必须有它:扫一遍 `skills/` 要读每一个 `SKILL.md`
585
+ #: (真实的 skill 那个 `SKILL.md` 有 36 KB),每条消息扫一次是不可接受的 ——
586
+ #: 而 `_is_framework_command` 正是每条消息都会走的那条路。
587
+ #:
588
+ #: 它必须能被失效 —— 否则「用户放一个 skill 进去就能用」这句话就是假的。
589
+ #: 失效点只有一处:`skill_loader.reload_skills`
590
+ #: (生效要人按一下,缓存跟着那一下走)。
591
+ #:
592
+ #: 它是进程级,登记在 `core/state_registry.py` 的 `PROCESS_SHARED`,
593
+ #: 并明说 `/clear` 不清它 —— 清了不是错,只是白扫一遍(与 `_sibling_cache` 同族)。
594
+ #: 显式传 `states` 时不走缓存(测试与一次性诊断要的是"此刻的事实")。
595
+ _map_cache: dict = {}
596
+
597
+
598
+ def invalidate_command_map() -> None:
599
+ """清掉 `instruction_command_map` 的缓存。 `/skill reload` 调它(唯一失效点)。"""
600
+ _map_cache.clear()
601
+
602
+
603
+ def instruction_command_map(root=None, reserved=(), states=None):
604
+ """`{命令名: InstructionSkill}`,外加被拒的。
605
+
606
+ Returns:
607
+ `(visible, rejected)`:
608
+ · *visible* —— 可以当 `/命令` 用的(含 `user-invocable-only`:
609
+ 它只是不进模型面,`/` 照样敲得到)
610
+ · *rejected* —— `[(名字, 原因)]`。出声用,绝不静默 ——
611
+ 判据:在有权限含义的地方必须拒,
612
+ 不采用「静默跳过 + 后者覆盖」那种做法。
613
+
614
+ ## 两条拒法
615
+
616
+ 1. 与内置命令撞(`/clear` 之类)—— `reserved` 由调用方注入
617
+ (`core/` 与 `bus/` 的叶子规矩:这里不 import `pre_process`)。
618
+ 2. 两个 skill 同目录名 —— 同一目录里不可能,但多 root 时可能
619
+ (`~/.agents/skills` 等),判据写在这儿,到时不用改。
620
+
621
+ ## 四态
622
+
623
+ `off`,不进 / 列表(也不进模型面);其余三态都进来。
624
+ `off` 不算"被拒" —— 那是用户的选择,不是冲突(两者不许同形:
625
+ 一个是"你得处理",一个是"就这样")。
626
+ """
627
+ cacheable = states is None
628
+ #: 缓存键必须是根清单(不是那个可能为 `None` 的入参)—— 两串不同的根
629
+ #: 解析出同一份清单时,键也该相同;而 `None` 每次现算 cwd/home(`skill_sources` 那条)。
630
+ specs = _as_specs(root)
631
+ #: 缓存键要含深度与来源 —— 只拿路径当键的话,
632
+ #: 同一个根换个深度扫出来的清单会串(后一次静默拿到前一次的结果)。
633
+ ck = (tuple((str(s.path), s.depth, s.origin) for s in specs),
634
+ tuple(sorted(str(r) for r in reserved)))
635
+ if cacheable and ck in _map_cache:
636
+ return _map_cache[ck]
637
+
638
+ st = _skill_states() if states is None else states
639
+ reserved = {r.lower() for r in reserved}
640
+ visible, rejected, seen = {}, [], set()
641
+
642
+ for s in list(discover_instruction_skills(specs)) + list(
643
+ discover_plugin_commands(specs)):
644
+ key = ("/" + s.name).lower()
645
+ state = st.get(s.name, "on")
646
+ if state not in SKILL_STATES:
647
+ state = "on" # 读不懂,照常(呈现轴,见 `_skill_states`)
648
+ if state == "off":
649
+ continue
650
+ if key in reserved:
651
+ rejected.append((s.name, "与内置命令 %s 撞名" % key))
652
+ continue
653
+ if key in seen:
654
+ rejected.append((s.name, "与另一个 skill 撞名(%s)" % key))
655
+ continue
656
+ seen.add(key)
657
+ visible[key] = s
658
+ if cacheable:
659
+ _map_cache[ck] = (visible, rejected)
660
+ return visible, rejected
661
+
662
+
663
+ def report_line(skills: list) -> str:
664
+ """一行汇总(给启动日志 / `/skill` 回执用)。0 个时返回空串。
665
+
666
+ 判据:"不再静默" —— 有指令型 skill 时必须
667
+ 说得出有几个、分别是谁。
668
+
669
+ 0 个时返回空串是有意的:一个每次启动都打的「指令型 skill: 0 个」
670
+ 会变成背景噪声,而噪声里的真信号不会被看见
671
+ (一个"什么都没发生"的行会让下一条真的"什么都没发生"消失)。
672
+ """
673
+ if not skills:
674
+ return ""
675
+ names = ", ".join(s.name for s in skills)
676
+ return "instruction-type skills: %d [%s]" % (len(skills), names)