@duanz/pi-skill-search 0.0.0-stage → 1.0.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 (3) hide show
  1. package/index.ts +402 -0
  2. package/package.json +39 -4
  3. package/README.md +0 -3
package/index.ts ADDED
@@ -0,0 +1,402 @@
1
+ /**
2
+ * skill-search — 让模型按需检索本机全部技能(pi 扩展)
3
+ *
4
+ * 问题:pi 的技能目录常驻系统提示。本机 82 个技能,全部摊开约 21164 字符
5
+ * (≈6500 tokens),每一轮都在烧,不管这次用不用得上。
6
+ *
7
+ * 现成的解法有两个,都不合适:
8
+ * 1) 把低频技能设成 disable-model-invocation(省 token)——但那样模型
9
+ * **完全看不见**它们,除非用户记得打 /skill:名字。
10
+ * 2) 把技能索引全量注入每轮上下文——省下的 token 又原样花回去。
11
+ *
12
+ * 本扩展补的是这个缝:技能目录不必常驻,只要「查询入口」常驻。
13
+ * 一个工具 schema 约 120 tokens/轮,模型需要时自己来查。
14
+ * 这跟 d-reach 把 9 个搜索通道收成 1 个入口是同一个模式。
15
+ *
16
+ * 三条设计约束(都来自实测结论,别随手放宽):
17
+ * 1) **只给路径,不返回正文**。arxiv 2603.22455 (SkillRouter) 在 80K 候选上
18
+ * 实测:只暴露 name+description 会让路由准确率掉 37-44 个百分点,
19
+ * 必须 body-aware。本机的做法是让模型拿到路径后用 read 读正文再定,
20
+ * 所以 path 是必返回字段,不能省。
21
+ * 2) **不做自动注入**。before_agent_start 里塞提示等于把省下的 token 花回去;
22
+ * 工具躺在工具列表里,模型知道有它可用就够了。
23
+ * 3) **不碰 frontmatter**。扩展只在 extensions 目录,uipro update /
24
+ * npx impeccable update 不会覆盖它——这是插件相对改 SKILL.md 的关键优势。
25
+ *
26
+ * 与 ask-me 技能的关系:ask-me 是给人的入口(显式 /skill:ask-me),
27
+ * 本工具是给模型的入口。装了扩展后,ask-me 的扫描脚本可以退居备用
28
+ * (Minis / DSH 等没有本扩展的环境仍用它)。
29
+ *
30
+ * 修改本文件后需重启 pi 才生效。
31
+ */
32
+
33
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
34
+ import { homedir } from "node:os";
35
+ import { join } from "node:path";
36
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
37
+ import { Type } from "typebox";
38
+
39
+ /** 描述截断长度:够模型判断,又不至于把上下文撑大 */
40
+ const DESC_MAX = 200;
41
+ /** 默认返回条数 */
42
+ const DEFAULT_LIMIT = 8;
43
+ /** 只读文件头这么多字节取 frontmatter,避免为解析元数据把全文读进来 */
44
+ const HEAD_BYTES = 8192;
45
+
46
+ interface Skill {
47
+ name: string;
48
+ /** auto = 模型可见并可能自动触发;explicit = 已从模型上下文中隐藏 */
49
+ mode: "auto" | "explicit";
50
+ description: string;
51
+ path: string;
52
+ /** 来源标签,用于输出时分组与排障 */
53
+ source: string;
54
+ }
55
+
56
+ /** 扫描根:(来源标签, 路径)。与 ask-me/scripts/scan_skills.py 保持同一套根目录。 */
57
+ function scanRoots(cwd: string): Array<[string, string]> {
58
+ const agentDir = process.env.PI_AGENT_DIR || join(homedir(), ".pi", "agent");
59
+ const roots: Array<[string, string]> = [
60
+ ["user", join(agentDir, "skills")],
61
+ ["user", join(homedir(), ".agents", "skills")],
62
+ ["project", join(cwd, ".pi", "skills")],
63
+ ["project", join(cwd, ".agents", "skills")],
64
+ ];
65
+ // pi 包自带的技能
66
+ const npm = join(agentDir, "npm", "node_modules");
67
+ if (existsSync(npm)) {
68
+ for (const pkg of safeReaddir(npm)) {
69
+ roots.push(["package", join(npm, pkg, "skills")]);
70
+ const plugins = join(npm, pkg, "plugins");
71
+ if (existsSync(plugins)) {
72
+ for (const plugin of safeReaddir(plugins)) {
73
+ roots.push(["package", join(plugins, plugin)]);
74
+ }
75
+ }
76
+ }
77
+ }
78
+ return roots;
79
+ }
80
+
81
+ function safeReaddir(dir: string): string[] {
82
+ try {
83
+ return readdirSync(dir);
84
+ } catch {
85
+ return [];
86
+ }
87
+ }
88
+
89
+ /**
90
+ * 极简 frontmatter 解析:只取 name / description / disable-model-invocation。
91
+ * 刻意不引 YAML 库——技能头部的结构是可预测的,而扩展应当零依赖好维护。
92
+ * 能处理 `key: value`、`key:` 后换行缩进的块标量(`>` / `>-` / `|`)两种形态。
93
+ */
94
+ function parseFrontmatter(head: string): Record<string, string> {
95
+ const out: Record<string, string> = {};
96
+ if (!head.startsWith("---")) return out;
97
+ const end = head.indexOf("\n---", 3);
98
+ if (end === -1) return out;
99
+ const lines = head.slice(3, end).split("\n");
100
+
101
+ let currentKey: string | null = null;
102
+ let buffer: string[] = [];
103
+
104
+ const flush = () => {
105
+ if (currentKey) {
106
+ out[currentKey] = buffer.join(" ").trim().replace(/\s+/g, " ");
107
+ }
108
+ currentKey = null;
109
+ buffer = [];
110
+ };
111
+
112
+ for (const line of lines) {
113
+ const m = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line);
114
+ if (m) {
115
+ flush();
116
+ const [, key, value] = m;
117
+ if (value === "" || /^[>|][-+]?$/.test(value)) {
118
+ // 块标量:值在后续缩进行里
119
+ currentKey = key;
120
+ } else {
121
+ out[key] = value.trim().replace(/^["']|["']$/g, "");
122
+ }
123
+ continue;
124
+ }
125
+ // 缩进行属于上一个 key 的块标量
126
+ if (currentKey && /^\s+\S/.test(line)) {
127
+ buffer.push(line.trim());
128
+ }
129
+ }
130
+ flush();
131
+ return out;
132
+ }
133
+
134
+ function collectSkills(cwd: string): Skill[] {
135
+ const skills: Skill[] = [];
136
+ const seen = new Set<string>();
137
+
138
+ for (const [source, root] of scanRoots(cwd)) {
139
+ if (!existsSync(root)) continue;
140
+
141
+ // root 自身也可能是技能目录(pi 包把 plugins/<name>/ 直接当技能)
142
+ const candidates: string[] = [];
143
+ if (existsSync(join(root, "SKILL.md"))) candidates.push(join(root, "SKILL.md"));
144
+ for (const entry of safeReaddir(root)) {
145
+ const p = join(root, entry, "SKILL.md");
146
+ if (existsSync(p)) candidates.push(p);
147
+ }
148
+
149
+ for (const file of candidates) {
150
+ const real = (() => {
151
+ try {
152
+ return statSync(file).ino + ":" + file;
153
+ } catch {
154
+ return file;
155
+ }
156
+ })();
157
+ if (seen.has(real)) continue;
158
+ seen.add(real);
159
+
160
+ let head: string;
161
+ try {
162
+ head = readFileSync(file, "utf8").slice(0, HEAD_BYTES);
163
+ } catch {
164
+ continue;
165
+ }
166
+ const meta = parseFrontmatter(head);
167
+ if (!meta.name) continue;
168
+
169
+ skills.push({
170
+ name: meta.name,
171
+ mode: /^true$/i.test(meta["disable-model-invocation"] ?? "") ? "explicit" : "auto",
172
+ description: (meta.description ?? "").replace(/\s+/g, " ").trim(),
173
+ path: file,
174
+ source,
175
+ });
176
+ }
177
+ }
178
+ return skills;
179
+ }
180
+
181
+ /**
182
+ * 把查询切成检索词:英文按 3+ 字符单词,中文按 2-gram。
183
+ * 中文没有空格,整串匹配太脆——「设计一个落地页」不该只匹配字面包含的。
184
+ */
185
+ function queryTerms(query: string): string[] {
186
+ const terms = new Set<string>();
187
+ for (const w of query.toLowerCase().match(/[a-z0-9_-]{3,}/g) ?? []) terms.add(w);
188
+ for (const run of query.replace(/[^\u4e00-\u9fff]+/g, " ").split(/\s+/)) {
189
+ for (let i = 0; i + 1 < run.length; i++) terms.add(run.slice(i, i + 2));
190
+ }
191
+ return [...terms];
192
+ }
193
+
194
+ /** 名称命中权重远高于描述:技能名是人挑过的,信号更干净。 */
195
+ const W_NAME = 8;
196
+ const W_DESC = 1.5;
197
+
198
+ /**
199
+ * 词在技能库里的文档频率。
200
+ *
201
+ * 必须有这个才能压住「长描述偏置」:d-reach 的描述 849 字符,几乎含全了
202
+ * 各类技术词,不加权它会把每次查询都捞进来。df 越大 = 越不值钱。
203
+ */
204
+ function documentFrequencies(skills: Skill[], terms: string[]): Map<string, number> {
205
+ const df = new Map<string, number>();
206
+ for (const t of terms) {
207
+ let n = 0;
208
+ for (const s of skills) {
209
+ if (s.name.toLowerCase().includes(t) || s.description.toLowerCase().includes(t)) n++;
210
+ }
211
+ df.set(t, n);
212
+ }
213
+ return df;
214
+ }
215
+
216
+ function inverseDocumentFrequency(term: string, df: Map<string, number>, total: number): number {
217
+ return Math.log(1 + total / (1 + (df.get(term) ?? 0)));
218
+ }
219
+
220
+ /**
221
+ * BM25 的文档长度归一化。
222
+ *
223
+ * 光有 IDF 不够:长描述天然覆盖更多词,反而靠“命中数量”堆分。实测发现
224
+ * d-reach(描述 849 字符)会篱占每一次查询结果,把真正相关的短描述技能挤掉。
225
+ * 按长度打折后,短描述的技能不再吃亏。
226
+ */
227
+ function lengthPenalty(descriptionLength: number, avgLength: number): number {
228
+ const K1 = 1.2;
229
+ const B = 0.75;
230
+ const dl = Math.max(1, descriptionLength);
231
+ const avg = Math.max(1, avgLength);
232
+ return (K1 + 1) / (K1 * (1 - B + (B * dl) / avg) + 1);
233
+ }
234
+
235
+ /** 描述命中只取 IDF 最高的这么多个:再多就是堆数量,不是相关性 */
236
+ const TOP_DESC_HITS = 4;
237
+
238
+ function scoreSkill(
239
+ skill: Skill,
240
+ terms: string[],
241
+ raw: string,
242
+ df: Map<string, number>,
243
+ total: number,
244
+ avgLength: number,
245
+ ): number {
246
+ const name = skill.name.toLowerCase();
247
+ const desc = skill.description.toLowerCase();
248
+ let score = 0;
249
+
250
+ const lowered = raw.toLowerCase();
251
+ if (lowered && name === lowered) score += 40;
252
+ else if (lowered && name.includes(lowered)) score += 15;
253
+
254
+ // 名称命中不吃长度惩罚:技能名是人挑过的,长度不意味着稀释
255
+ const descHits: number[] = [];
256
+ for (const t of terms) {
257
+ const w = inverseDocumentFrequency(t, df, total);
258
+ if (name.includes(t)) score += W_NAME * w;
259
+ else if (desc.includes(t)) descHits.push(w);
260
+ }
261
+
262
+ descHits.sort((a, b) => b - a);
263
+ const descScore = descHits.slice(0, TOP_DESC_HITS).reduce((a, b) => a + b, 0);
264
+ score += W_DESC * lengthPenalty(skill.description.length, avgLength) * descScore;
265
+
266
+ return score;
267
+ }
268
+
269
+ export default function (pi: ExtensionAPI) {
270
+ pi.registerTool({
271
+ name: "skill_search",
272
+ label: "搜索技能",
273
+ description:
274
+ "检索本机已安装的全部 agent 技能(包括已被隐藏、未出现在你上下文中的那些)," +
275
+ "按任务返回最匹配的几个及各自 SKILL.md 的绝对路径。当你拿不准该用哪个技能、" +
276
+ "或任务看起来需要一套专门流程而不只是内置工具时调用。不带 query 调用可列出全部技能名。" +
277
+ "拿到路径后用 read 读正文再动手——只凭描述下结论会选错。",
278
+ promptSnippet: "按任务检索本机技能库,返回匹配技能及其 SKILL.md 路径",
279
+ promptGuidelines: [
280
+ "不确定该用哪个技能时先调 skill_search,不要凭技能名猜。",
281
+ "skill_search 返回的路径要用 read 读正文确认后再执行;描述只够初筛。",
282
+ "想看本机装了哪些技能时,调 skill_search 且不带 query,会列出全部技能名。",
283
+ ],
284
+ parameters: Type.Object({
285
+ query: Type.Optional(
286
+ Type.String({
287
+ description:
288
+ "任务描述或关键词,用自然语言写清要做什么;省略则列出全部技能名",
289
+ }),
290
+ ),
291
+ limit: Type.Optional(
292
+ Type.Number({ description: `返回条数,默认 ${DEFAULT_LIMIT}` }),
293
+ ),
294
+ }),
295
+ async execute(_toolCallId, params) {
296
+ const query = String(params.query ?? "").trim();
297
+ const limit = Math.max(1, Math.min(30, Number(params.limit) || DEFAULT_LIMIT));
298
+ const cwd = process.cwd();
299
+
300
+ const all = collectSkills(cwd);
301
+ if (all.length === 0) {
302
+ return {
303
+ content: [
304
+ { type: "text", text: "没有扫到任何技能目录,请检查 ~/.agents/skills 是否存在。" },
305
+ ],
306
+ details: { scanned: 0, matched: 0 },
307
+ };
308
+ }
309
+
310
+ const terms = queryTerms(query);
311
+
312
+ // 不带 query:列出全部技能名,让模型自己认领。这是「检索落空」的兜底
313
+ // ——词法匹配对「写代码时少写点」→ ponytail 这类语义跳跃本来就无能为力,
314
+ // 与其给错候选,不如把名册摊开。
315
+ if (!query) {
316
+ const bySource = new Map<string, Skill[]>();
317
+ for (const s of all) {
318
+ const list = bySource.get(s.source) ?? [];
319
+ list.push(s);
320
+ bySource.set(s.source, list);
321
+ }
322
+ const label: Record<string, string> = {
323
+ user: "用户级",
324
+ project: "项目级",
325
+ package: "pi 包内",
326
+ };
327
+ const lines = [`本机共 ${all.length} 个技能(* = 已隐藏,不在你上下文里):`, ""];
328
+ for (const [source, list] of bySource) {
329
+ lines.push(`【${label[source] ?? source}】${list.length} 个`);
330
+ for (const s of list) {
331
+ lines.push(` ${s.mode === "explicit" ? "*" : " "} ${s.name}`);
332
+ }
333
+ lines.push("");
334
+ }
335
+ lines.push("需要某个技能的正文时,带 query 再查一次拿路径,或直接 read 它的 SKILL.md。");
336
+ return {
337
+ content: [{ type: "text", text: lines.join("\n") }],
338
+ details: { scanned: all.length, matched: all.length, listed: true },
339
+ };
340
+ }
341
+
342
+ const df = documentFrequencies(all, terms);
343
+ const avgLength =
344
+ all.reduce((sum, s) => sum + s.description.length, 0) / Math.max(1, all.length);
345
+ const ranked = all
346
+ .map((s) => ({
347
+ skill: s,
348
+ score: scoreSkill(s, terms, query, df, all.length, avgLength),
349
+ }))
350
+ .filter((r) => r.score > 0)
351
+ .sort((a, b) => b.score - a.score)
352
+ .slice(0, limit);
353
+
354
+ // 一条都没匹配上时,退回「全量名单」的极简形态,让模型自己挑,
355
+ // 这比返回空结果再让模型瞎猜要好。
356
+ const picked = ranked.length > 0 ? ranked.map((r) => r.skill) : all;
357
+
358
+ const lines: string[] = [];
359
+ if (ranked.length > 0) {
360
+ lines.push(`匹配 ${picked.length} 个(本机共 ${all.length} 个技能):`, "");
361
+ } else {
362
+ lines.push(
363
+ `没有技能命中「${query}」。与其硬凑,先把名册摊开,`,
364
+ `下面是本机全部 ${all.length} 个技能;挑中哪个再 read 它的 SKILL.md:`,
365
+ "",
366
+ );
367
+ }
368
+
369
+ for (const s of picked) {
370
+ const tag = s.mode === "explicit" ? "已隐藏" : "可见";
371
+ if (ranked.length === 0) {
372
+ lines.push(`- ${s.name} [${tag}] ${s.path}`);
373
+ continue;
374
+ }
375
+ const desc =
376
+ s.description.length > DESC_MAX
377
+ ? `${s.description.slice(0, DESC_MAX)}…`
378
+ : s.description;
379
+ lines.push(`- ${s.name} [${tag}]${desc ? ` ${desc}` : ""}`);
380
+ lines.push(` 路径: ${s.path}`);
381
+ }
382
+
383
+ if (ranked.length > 0) {
384
+ lines.push("", "选之前请先 read 正文核对——描述只够初筛,选错会白跑一轮。");
385
+ // 只有真的捞回了隐藏技能才提,否则是噪音(实测踩过:没隐藏技能也照打)
386
+ if (picked.some((s) => s.mode === "explicit")) {
387
+ lines.push("标 [已隐藏] 的技能不在你的上下文里,只有读它的 SKILL.md 才能用上。");
388
+ }
389
+ lines.push("没找到想要的?不带 query 再调一次可看全量技能名。");
390
+ }
391
+
392
+ return {
393
+ content: [{ type: "text", text: lines.join("\n") }],
394
+ details: {
395
+ scanned: all.length,
396
+ matched: ranked.length,
397
+ top: picked.slice(0, limit).map((s) => s.name),
398
+ },
399
+ };
400
+ },
401
+ });
402
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@duanz/pi-skill-search",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "按需检索本机全部技能,返回该用哪个和 SKILL.md 路径",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "pi-extension"
9
+ ],
10
+ "license": "MIT",
11
+ "author": "DuanZ",
12
+ "homepage": "https://github.com/DuanZGit/D-Hub/tree/master/extensions/skill-search",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/DuanZGit/D-Hub.git",
16
+ "directory": "extensions/skill-search"
17
+ },
18
+ "files": [
19
+ "index.ts"
20
+ ],
21
+ "pi": {
22
+ "extensions": [
23
+ "./index.ts"
24
+ ]
25
+ },
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "peerDependencies": {
30
+ "@earendil-works/pi-coding-agent": "*",
31
+ "typebox": "*"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "@earendil-works/pi-coding-agent": {
35
+ "optional": true
36
+ },
37
+ "typebox": {
38
+ "optional": true
39
+ }
40
+ }
41
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.