dsh-plugin-skill-folder 0.0.0-stage → 0.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 (48) hide show
  1. package/License +21 -0
  2. package/README.md +91 -2
  3. package/cordis.patch.yml +4 -0
  4. package/dist/catalog.d.ts +56 -0
  5. package/dist/catalog.d.ts.map +1 -0
  6. package/dist/client/api.d.ts +14 -0
  7. package/dist/client/api.d.ts.map +1 -0
  8. package/dist/client/auto-group.d.ts +18 -0
  9. package/dist/client/auto-group.d.ts.map +1 -0
  10. package/dist/client/folder-card.d.ts +52 -0
  11. package/dist/client/folder-card.d.ts.map +1 -0
  12. package/dist/client/folder-form.d.ts +99 -0
  13. package/dist/client/folder-form.d.ts.map +1 -0
  14. package/dist/client/folder-page.d.ts +29 -0
  15. package/dist/client/folder-page.d.ts.map +1 -0
  16. package/dist/client/index.d.ts +11 -0
  17. package/dist/client/index.d.ts.map +1 -0
  18. package/dist/client/locales.d.ts +72 -0
  19. package/dist/client/locales.d.ts.map +1 -0
  20. package/dist/client/skill-chip.d.ts +32 -0
  21. package/dist/client/skill-chip.d.ts.map +1 -0
  22. package/dist/client/styles.d.ts +86 -0
  23. package/dist/client/styles.d.ts.map +1 -0
  24. package/dist/client.js +3756 -0
  25. package/dist/config.d.ts +45 -0
  26. package/dist/config.d.ts.map +1 -0
  27. package/dist/constants.d.ts +31 -0
  28. package/dist/constants.d.ts.map +1 -0
  29. package/dist/folders.d.ts +39 -0
  30. package/dist/folders.d.ts.map +1 -0
  31. package/dist/index.d.ts +12 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.mjs +701 -0
  34. package/dist/routes.d.ts +46 -0
  35. package/dist/routes.d.ts.map +1 -0
  36. package/dist/search-tool.d.ts +176 -0
  37. package/dist/search-tool.d.ts.map +1 -0
  38. package/dist/search.d.ts +54 -0
  39. package/dist/search.d.ts.map +1 -0
  40. package/dist/skills.d.ts +72 -0
  41. package/dist/skills.d.ts.map +1 -0
  42. package/dist/types.d.ts +8 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/utils.d.ts +4 -0
  45. package/dist/utils.d.ts.map +1 -0
  46. package/locale/en.json +6 -0
  47. package/locale/zh.json +6 -0
  48. package/package.json +103 -4
package/dist/index.mjs ADDED
@@ -0,0 +1,701 @@
1
+ import Schema from "@deepseek-ai/schemastery";
2
+ //#region src/constants.ts
3
+ /** 共享常量:插件标识、工具名、配置默认值与路由路径。 */
4
+ /** 插件标识,同时是包名、字典命名空间与 cordis.patch.yml 的行 id。 */
5
+ const PLUGIN_ID = "dsh-plugin-skill-folder";
6
+ /** 错误消息使用的插件标识。 */
7
+ const PLUGIN_LABEL = PLUGIN_ID;
8
+ /** 检索工具名。 */
9
+ const TOOL_NAME = "skill_search";
10
+ /** 全局技能列表路由。 */
11
+ const ROUTE_PATH = "/api/skill-folder/skills";
12
+ /** 折叠标记,写入目录消息的 source。 */
13
+ const FOLDED_BY = PLUGIN_ID;
14
+ /** 摘要字符上限范围。 */
15
+ const DESCRIPTION_MAX_LENGTH_RANGE = {
16
+ min: 40,
17
+ max: 2e3
18
+ };
19
+ //#endregion
20
+ //#region src/folders.ts
21
+ /** 比较名称用的键:忽略大小写与首尾空白。 */
22
+ function autoGroupNameKey(name) {
23
+ return name.trim().toLowerCase();
24
+ }
25
+ /** 按名称查找文件夹,忽略大小写。 */
26
+ function folderByName(folders, name) {
27
+ const key = autoGroupNameKey(name);
28
+ return folders.find((folder) => autoGroupNameKey(folder.name) === key);
29
+ }
30
+ /** 技能名到文件夹名的映射。 */
31
+ function folderIndex(folders) {
32
+ const index = /* @__PURE__ */ new Map();
33
+ for (const folder of folders) for (const skill of folder.skills) index.set(skill, folder.name);
34
+ return index;
35
+ }
36
+ /** 生成有成员的文件夹摘要,保持配置顺序。 */
37
+ function describeFolders(folders) {
38
+ return folders.filter((folder) => folder.skills.length > 0).map((folder) => ({
39
+ name: folder.name,
40
+ description: folder.description,
41
+ count: folder.skills.length
42
+ }));
43
+ }
44
+ //#endregion
45
+ //#region src/skills.ts
46
+ /** 判断技能是否可由模型调用。 */
47
+ function isModelInvocable(skill) {
48
+ return skill.invocation.modelInvocable === true;
49
+ }
50
+ /** 规范化路径,用于比较:统一分隔符并忽略大小写。 */
51
+ function normalizePath(value) {
52
+ return value.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase();
53
+ }
54
+ /**
55
+ * 判断技能是否是全局技能。
56
+ * 非 `project-` 来源直接算全局;`project-` 来源在与全局列表中的同名技能路径相同时也算全局,
57
+ * 这样会话根目录位于用户主目录时把全局技能标成项目来源仍能正确折叠。
58
+ */
59
+ function isGlobalSummary(skill, globalSkills) {
60
+ if (!skill.source.startsWith("project-")) return true;
61
+ if (skill.path === void 0) return false;
62
+ const path = normalizePath(skill.path);
63
+ return globalSkills.some((candidate) => candidate.name === skill.name && candidate.path !== void 0 && normalizePath(candidate.path) === path);
64
+ }
65
+ /** 把技能摘要投影为界面条目。 */
66
+ function toSkillItem(skill) {
67
+ return {
68
+ name: skill.name,
69
+ description: skill.description,
70
+ ...skill.whenToUse === void 0 ? {} : { whenToUse: skill.whenToUse },
71
+ source: skill.source,
72
+ ...skill.path === void 0 ? {} : { path: skill.path }
73
+ };
74
+ }
75
+ /** 读取全局技能:不传工作区与作用域,只保留可由模型调用的技能。 */
76
+ async function loadGlobalSkills(reader) {
77
+ const options = {};
78
+ const snapshot = reader.snapshot === void 0 ? void 0 : await reader.snapshot(options);
79
+ const listed = snapshot === void 0 ? await (reader.list?.(options) ?? Promise.resolve([])) : snapshot.skills;
80
+ return {
81
+ skills: listed.filter((skill) => isModelInvocable(skill)).filter((skill) => isGlobalSummary(skill, listed)).map(toSkillItem).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
82
+ complete: snapshot?.complete ?? true
83
+ };
84
+ }
85
+ //#endregion
86
+ //#region src/catalog.ts
87
+ /** 判断消息是否是原生技能目录。 */
88
+ function isSkillCatalogMessage(message) {
89
+ const { source } = message;
90
+ if (source["kind"] !== "skill-catalog") return false;
91
+ const entries = source["entries"];
92
+ return Array.isArray(entries);
93
+ }
94
+ /** 目录条目名集合,用于判断是否需要折叠。 */
95
+ function catalogNames(message) {
96
+ return message.source.entries.map((entry) => entry.name);
97
+ }
98
+ /** 折叠一个目录消息;没有可折叠条目时返回原对象。 */
99
+ function foldedMessage(message, context) {
100
+ if (!context.toolVisible) return message;
101
+ const byName = new Map(context.skills.map((skill) => [skill.name, skill]));
102
+ const globalSkills = context.skills.filter((skill) => isGlobalSummary(skill, context.skills));
103
+ const globalNames = new Set(globalSkills.map((skill) => skill.name));
104
+ const foldedNames = /* @__PURE__ */ new Set();
105
+ for (const folder of context.folders) for (const skill of folder.skills) if (globalNames.has(skill)) foldedNames.add(skill);
106
+ const present = catalogNames(message);
107
+ const folded = present.filter((name) => foldedNames.has(name) && byName.has(name));
108
+ if (folded.length === 0) return message;
109
+ const text = renderCatalog(present.filter((name) => !foldedNames.has(name)), describeFolders(context.folders.map((folder) => ({
110
+ ...folder,
111
+ skills: folder.skills.filter((skill) => folded.includes(skill))
112
+ }))), message);
113
+ return {
114
+ ...message,
115
+ content: [{
116
+ type: "text",
117
+ text
118
+ }],
119
+ source: {
120
+ ...message.source,
121
+ foldedBy: FOLDED_BY
122
+ }
123
+ };
124
+ }
125
+ /** 转义 XML 敏感字符。技能名已由宿主校验,不需要转义。 */
126
+ function escapeText(value) {
127
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
128
+ }
129
+ /** 渲染折叠后的目录正文。 */
130
+ function renderCatalog(visible, summaries, message) {
131
+ const header = message.source["update"] === true ? "The available skill catalog changed. Folders below replace their members; the skills listed above stay available." : "The following skills are available in this session. Folders group their members.";
132
+ const folderLines = summaries.map((folder) => `- \`${folder.name}\` (${folder.count} skills)${folder.description === "" ? "" : `: ${escapeText(folder.description)}`}`);
133
+ return [
134
+ "<system-reminder>",
135
+ header,
136
+ "",
137
+ "<available_skills>",
138
+ ...visible.map((name) => `- \`${name}\`: ${escapeText(descriptionOf(name, message))}`),
139
+ "</available_skills>",
140
+ "",
141
+ "<skill_folders>",
142
+ ...folderLines,
143
+ "</skill_folders>",
144
+ "",
145
+ "Skills inside a folder stay loadable. To find one, call `skill_search` with the folder name or with capability keywords, then load the chosen skill with `skill`. Load a listed skill directly when its description matches the task.",
146
+ "</system-reminder>"
147
+ ].join("\n");
148
+ }
149
+ /** 原生条目描述,找不到时返回空串。 */
150
+ function descriptionOf(name, message) {
151
+ return message.source.entries.find((entry) => entry.name === name)?.description ?? "";
152
+ }
153
+ /** 折叠消息列表中的目录消息,其余消息原样返回。 */
154
+ function foldCatalog(messages, context) {
155
+ return messages.map((message) => isSkillCatalogMessage(message) ? foldedMessage(message, context) : message);
156
+ }
157
+ //#endregion
158
+ //#region src/utils.ts
159
+ /** 零依赖工具函数。 */
160
+ /** 判断值是否为普通对象。 */
161
+ function isRecord(value) {
162
+ return typeof value === "object" && value !== null && !Array.isArray(value);
163
+ }
164
+ //#endregion
165
+ //#region src/config.ts
166
+ /**
167
+ * 插件配置:schema、默认值与严格校验。
168
+ * 导出 Config、PluginConfig、DEFAULT_CONFIG、resolveConfig 与 readConfig。
169
+ */
170
+ /** 文件夹 schema:结构校验交给 resolveConfig。 */
171
+ const folderSchema = Schema.object({
172
+ name: Schema.string().required(),
173
+ description: Schema.string().default(""),
174
+ skills: Schema.array(Schema.string()).default([])
175
+ });
176
+ /**
177
+ * 配置 schema。`.volatile()` 字段修改后不重启插件,并出现在“插件”面板的配置页。
178
+ * schema 不拒绝未知键,严格校验由 resolveConfig 完成。
179
+ */
180
+ const Config = Schema.object({
181
+ folders: Schema.array(folderSchema).default([]).volatile(),
182
+ defaultLimit: Schema.number().default(5).volatile(),
183
+ descriptionMaxLength: Schema.number().default(320).volatile()
184
+ });
185
+ /** 默认配置。 */
186
+ const DEFAULT_CONFIG = Object.freeze({
187
+ folders: [],
188
+ defaultLimit: 5,
189
+ descriptionMaxLength: 320
190
+ });
191
+ /** 合法的配置键。出现其他键时报错。 */
192
+ const CONFIG_KEYS = /* @__PURE__ */ new Set([
193
+ "folders",
194
+ "defaultLimit",
195
+ "descriptionMaxLength"
196
+ ]);
197
+ /** 把缺省或 null 的输入转为空对象。 */
198
+ function normalizeConfigInput(raw) {
199
+ if (raw === void 0 || raw === null) return {};
200
+ if (!isRecord(raw)) throw new Error(`${PLUGIN_LABEL}: config must be an object`);
201
+ return raw;
202
+ }
203
+ /** 校验一个文件夹,返回规范化副本。 */
204
+ function resolveFolder(raw, index) {
205
+ if (!isRecord(raw)) throw new Error(`${PLUGIN_LABEL}: config folders[${index}] must be an object`);
206
+ const name = typeof raw["name"] === "string" ? raw["name"].trim() : "";
207
+ if (name === "") throw new Error(`${PLUGIN_LABEL}: config folder name must be a non-empty string`);
208
+ if (name.length > 64) throw new Error(`${PLUGIN_LABEL}: config folder name holds at most 64 characters`);
209
+ const rawDescription = raw["description"];
210
+ if (rawDescription !== void 0 && rawDescription !== null && typeof rawDescription !== "string") throw new Error(`${PLUGIN_LABEL}: config folder description must be a string`);
211
+ const description = typeof rawDescription === "string" ? rawDescription.trim() : "";
212
+ if (description.length > 500) throw new Error(`${PLUGIN_LABEL}: config folder description holds at most 500 characters`);
213
+ const rawSkills = raw["skills"];
214
+ if (rawSkills !== void 0 && rawSkills !== null && !Array.isArray(rawSkills)) throw new Error(`${PLUGIN_LABEL}: config folder skills must be an array of strings`);
215
+ const skills = [];
216
+ for (const entry of Array.isArray(rawSkills) ? rawSkills : []) {
217
+ if (typeof entry !== "string" || entry.trim() === "") throw new Error(`${PLUGIN_LABEL}: config folder skills must be non-empty strings`);
218
+ skills.push(entry);
219
+ }
220
+ return {
221
+ name,
222
+ description,
223
+ skills
224
+ };
225
+ }
226
+ /** 校验文件夹列表:名称忽略大小写唯一,成员跨文件夹唯一。 */
227
+ function resolveFolders(raw) {
228
+ if (raw === void 0 || raw === null) return [];
229
+ if (!Array.isArray(raw)) throw new Error(`${PLUGIN_LABEL}: config folders must be an array`);
230
+ const folders = raw.map((entry, index) => resolveFolder(entry, index));
231
+ const names = /* @__PURE__ */ new Set();
232
+ const members = /* @__PURE__ */ new Set();
233
+ for (const folder of folders) {
234
+ const key = folder.name.toLowerCase();
235
+ if (names.has(key)) throw new Error(`${PLUGIN_LABEL}: duplicate folder name "${folder.name}"`);
236
+ names.add(key);
237
+ for (const skill of folder.skills) {
238
+ if (members.has(skill)) throw new Error(`${PLUGIN_LABEL}: skill "${skill}" belongs to more than one folder`);
239
+ members.add(skill);
240
+ }
241
+ }
242
+ return folders;
243
+ }
244
+ /** 校验一个整数配置项。只有缺省的 `undefined` 使用默认值。 */
245
+ function resolveInteger(key, value, min, max, fallback) {
246
+ if (value === void 0) return fallback;
247
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) throw new Error(`${PLUGIN_LABEL}: config ${key} must be an integer from ${min} to ${max}`);
248
+ return value;
249
+ }
250
+ /** 校验配置并与默认值合并,返回冻结的完整配置。 */
251
+ function resolveConfig(raw) {
252
+ const input = normalizeConfigInput(raw);
253
+ for (const key of Object.keys(input)) if (!CONFIG_KEYS.has(key)) throw new Error(`${PLUGIN_LABEL}: unknown config key "${key}"`);
254
+ const config = {
255
+ folders: resolveFolders(input["folders"]),
256
+ defaultLimit: resolveInteger("defaultLimit", input["defaultLimit"], 1, 20, DEFAULT_CONFIG.defaultLimit),
257
+ descriptionMaxLength: resolveInteger("descriptionMaxLength", input["descriptionMaxLength"], DESCRIPTION_MAX_LENGTH_RANGE.min, DESCRIPTION_MAX_LENGTH_RANGE.max, DEFAULT_CONFIG.descriptionMaxLength)
258
+ };
259
+ return Object.freeze(config);
260
+ }
261
+ /** 判断值是否是热重载引用。 */
262
+ function isVolatileRef(value) {
263
+ return isRecord(value) && typeof value.get === "function";
264
+ }
265
+ /** 读取宿主传入配置的当前值:展开热重载引用后交给 resolveConfig 校验。 */
266
+ function readConfig(config) {
267
+ if (!isRecord(config)) return resolveConfig(config);
268
+ const values = {};
269
+ for (const [key, value] of Object.entries(config)) values[key] = isVolatileRef(value) ? value.get() : value;
270
+ return resolveConfig(values);
271
+ }
272
+ //#endregion
273
+ //#region src/routes.ts
274
+ /**
275
+ * 同源路由:向配置页提供全局技能列表与检索完整性。
276
+ * 导出 registerSkillsRoute 与 JSON 编码辅助。
277
+ */
278
+ /** 构造 JSON 响应。 */
279
+ function jsonResponse(body, status = 200) {
280
+ return new Response(JSON.stringify(body), {
281
+ status,
282
+ headers: {
283
+ "content-type": "application/json; charset=utf-8",
284
+ "cache-control": "no-store"
285
+ }
286
+ });
287
+ }
288
+ /** 读取全局技能并按约定编码;失败时返回 500 与错误文本。 */
289
+ async function skillsResponse(reader) {
290
+ try {
291
+ const result = await loadGlobalSkills(reader);
292
+ return jsonResponse({
293
+ complete: result.complete,
294
+ skills: result.skills
295
+ });
296
+ } catch (error) {
297
+ return jsonResponse({ error: String(error) }, 500);
298
+ }
299
+ }
300
+ function registerSkillsRoute(ctx, reader) {
301
+ ctx.inject(["connection"], (child) => {
302
+ const fetchService = child.connection?.fetch;
303
+ if (fetchService === void 0) return;
304
+ fetchService.register({
305
+ path: ROUTE_PATH,
306
+ methods: ["GET"],
307
+ requestBody: "buffered",
308
+ fetch: async () => skillsResponse(reader)
309
+ });
310
+ });
311
+ }
312
+ //#endregion
313
+ //#region src/search.ts
314
+ /** 参与评分的字段与权重。名称命中权重最高。 */
315
+ const FIELD_WEIGHTS = {
316
+ name: 100,
317
+ whenToUse: 45,
318
+ description: 25
319
+ };
320
+ /** 准确名称命中的加权值。 */
321
+ const EXACT_NAME_BONUS = 1e4;
322
+ /** 不参与检索的通用词。 */
323
+ const STOP_WORDS = /* @__PURE__ */ new Set([
324
+ "a",
325
+ "an",
326
+ "the",
327
+ "and",
328
+ "or",
329
+ "to",
330
+ "for",
331
+ "of",
332
+ "in",
333
+ "with",
334
+ "use",
335
+ "using",
336
+ "please",
337
+ "help",
338
+ "me",
339
+ "skill",
340
+ "skills",
341
+ "search",
342
+ "find"
343
+ ]);
344
+ /** 规范化为小写用于比较。 */
345
+ function normalize(text) {
346
+ return text.normalize("NFKC").toLowerCase();
347
+ }
348
+ /** 按名称比较,用于稳定排序。 */
349
+ function compareName(a, b) {
350
+ return a < b ? -1 : a > b ? 1 : 0;
351
+ }
352
+ /**
353
+ * 把查询拆成可检索的词。
354
+ * 英文与数字按词切分并丢弃通用词;中文按二字组切分,两个字的中文词整体保留。
355
+ */
356
+ function queryTerms(query) {
357
+ const tokens = normalize(query).match(/[a-z0-9]+(?:[+#._-][a-z0-9]+)*|\p{Script=Han}+/gu) ?? [];
358
+ const terms = /* @__PURE__ */ new Set();
359
+ for (const token of tokens) {
360
+ if (STOP_WORDS.has(token)) continue;
361
+ if (/\p{Script=Han}/u.test(token)) {
362
+ const chars = Array.from(token);
363
+ if (chars.length <= 2) terms.add(token);
364
+ else for (let index = 0; index < chars.length - 1; index += 1) terms.add(chars.slice(index, index + 2).join(""));
365
+ } else terms.add(token);
366
+ }
367
+ return [...terms];
368
+ }
369
+ /** 按字符上限截断并加省略号。 */
370
+ function shorten(value, maxLength) {
371
+ const chars = Array.from(String(value ?? "").replaceAll(/\s+/g, " ").trim());
372
+ return chars.length <= maxLength ? chars.join("") : `${chars.slice(0, maxLength - 1).join("")}…`;
373
+ }
374
+ /** 计算技能对一个查询词的得分。 */
375
+ function scoreTerm(term, skill) {
376
+ const fields = [
377
+ [normalize(skill.name), FIELD_WEIGHTS.name],
378
+ [normalize(skill.whenToUse ?? ""), FIELD_WEIGHTS.whenToUse],
379
+ [normalize(skill.description), FIELD_WEIGHTS.description]
380
+ ];
381
+ let best = 0;
382
+ for (const [text, weight] of fields) if (text.includes(term) && weight > best) best = weight;
383
+ return best;
384
+ }
385
+ /** 对技能集合评分并按相关度排序。 */
386
+ function scoreSkills(skills, query) {
387
+ const terms = queryTerms(query);
388
+ const exact = normalize(query).trim();
389
+ const scored = [];
390
+ for (const skill of skills) {
391
+ if (!isModelInvocable(skill)) continue;
392
+ const scores = terms.map((term) => scoreTerm(term, skill));
393
+ const matched = scores.filter((score) => score > 0).length;
394
+ const exactName = normalize(skill.name) === exact;
395
+ if (!exactName && matched === 0) continue;
396
+ const score = scores.reduce((sum, value) => sum + value, 0) + (exactName ? EXACT_NAME_BONUS : 0);
397
+ scored.push({
398
+ skill,
399
+ matched,
400
+ score,
401
+ exactName
402
+ });
403
+ }
404
+ scored.sort((a, b) => Number(b.exactName) - Number(a.exactName) || b.matched - a.matched || b.score - a.score || compareName(a.skill.name, b.skill.name));
405
+ return scored;
406
+ }
407
+ /** 生成一条检索结果。 */
408
+ function toHit(skill, folder, match, maxLength) {
409
+ return {
410
+ name: skill.name,
411
+ description: shorten(skill.description, maxLength),
412
+ whenToUse: shorten(skill.whenToUse ?? "", maxLength),
413
+ folder,
414
+ match
415
+ };
416
+ }
417
+ /**
418
+ * 检索技能。
419
+ * 给出 `folder` 时先限定到该文件夹;同时给出 `query` 时在该文件夹内按关键词检索。
420
+ */
421
+ function rankSkills(skills, query, options) {
422
+ const maxLength = options.descriptionMaxLength ?? 320;
423
+ const index = folderIndex(options.folders);
424
+ const scoped = options.folder === void 0 ? void 0 : new Set(folderByName(options.folders, options.folder)?.skills ?? []);
425
+ const pool = scoped === void 0 ? skills : skills.filter((skill) => scoped.has(skill.name));
426
+ const trimmed = query?.trim() ?? "";
427
+ if (trimmed === "") {
428
+ const listed = pool.filter(isModelInvocable).slice().sort((a, b) => compareName(a.name, b.name));
429
+ const page = listed.slice(options.offset, options.offset + options.limit);
430
+ return {
431
+ total: listed.length,
432
+ results: page.map((skill) => toHit(skill, index.get(skill.name) ?? null, "folder", maxLength)),
433
+ more: options.offset + page.length < listed.length
434
+ };
435
+ }
436
+ const scored = scoreSkills(pool, trimmed);
437
+ const page = scored.slice(options.offset, options.offset + options.limit);
438
+ return {
439
+ total: scored.length,
440
+ results: page.map(({ skill, matched, exactName }) => toHit(skill, index.get(skill.name) ?? null, exactName || matched === queryTerms(trimmed).length ? "exact" : "partial", maxLength)),
441
+ more: options.offset + page.length < scored.length
442
+ };
443
+ }
444
+ //#endregion
445
+ //#region src/search-tool.ts
446
+ /** 工具说明。模型据此判断何时检索。 */
447
+ const SEARCH_TOOL_DESCRIPTION = "Discover skills by keywords or by folder name, including folded skills hidden from the catalog list. Search returns summaries only; load a chosen skill with `skill` and its exact name.";
448
+ /** 读取字符串参数,缺省返回 undefined。 */
449
+ function optionalString(value, key) {
450
+ if (value === void 0 || value === null) return void 0;
451
+ if (typeof value !== "string") throw new Error(`${TOOL_NAME}: ${key} must be a string`);
452
+ const trimmed = value.trim();
453
+ return trimmed === "" ? void 0 : trimmed;
454
+ }
455
+ /** 读取整数参数,缺省返回 fallback。 */
456
+ function optionalInteger(value, key, fallback) {
457
+ if (value === void 0 || value === null) return fallback;
458
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new Error(`${TOOL_NAME}: ${key} must be an integer`);
459
+ return value;
460
+ }
461
+ /** 校验并归一化工具参数。 */
462
+ function resolveArgs(args, folders, defaultLimit) {
463
+ const query = optionalString(args.query, "query");
464
+ const folderName = optionalString(args.folder, "folder");
465
+ if (query === void 0 && folderName === void 0) throw new Error(`${TOOL_NAME}: provide query or folder`);
466
+ if (query !== void 0 && query.length > 512) throw new Error(`${TOOL_NAME}: query must contain 1–512 characters`);
467
+ const folder = folderName === void 0 ? void 0 : folderByName(folders, folderName)?.name;
468
+ if (folderName !== void 0 && folder === void 0) throw new Error(`${TOOL_NAME}: unknown folder "${folderName}"`);
469
+ const limit = optionalInteger(args.limit, "limit", defaultLimit);
470
+ if (limit < 1 || limit > 20) throw new Error(`${TOOL_NAME}: limit must be an integer from 1 to 20`);
471
+ const offset = optionalInteger(args.offset, "offset", 0);
472
+ if (offset < 0) throw new Error(`${TOOL_NAME}: offset must be a nonnegative integer`);
473
+ return {
474
+ query,
475
+ folder,
476
+ limit,
477
+ offset
478
+ };
479
+ }
480
+ /**
481
+ * 可空字符串的 schema。
482
+ * 宿主只接受单个 `type`,可空字段用 `oneOf` 表达。
483
+ */
484
+ function nullableString() {
485
+ return { oneOf: [{ type: "string" }, { type: "null" }] };
486
+ }
487
+ /** 构造 `skill_search` 工具定义。 */
488
+ function buildSearchTool(options) {
489
+ return {
490
+ name: TOOL_NAME,
491
+ description: SEARCH_TOOL_DESCRIPTION,
492
+ parameters: {
493
+ type: "object",
494
+ additionalProperties: false,
495
+ properties: {
496
+ query: {
497
+ type: "string",
498
+ description: `Capability keywords or an exact skill name, at most 512 characters; Chinese and English are both supported.`
499
+ },
500
+ folder: {
501
+ type: "string",
502
+ description: "Folder name; lists every available member and matches case-insensitively."
503
+ },
504
+ limit: {
505
+ type: "integer",
506
+ description: `Maximum results, 1–20; default ${String(options.defaultLimit)}.`
507
+ },
508
+ offset: {
509
+ type: "integer",
510
+ description: "Skip this many ranked results for pagination; default 0."
511
+ }
512
+ }
513
+ },
514
+ output: {
515
+ schema: {
516
+ type: "object",
517
+ additionalProperties: false,
518
+ required: [
519
+ "query",
520
+ "folder",
521
+ "total",
522
+ "offset",
523
+ "more",
524
+ "complete",
525
+ "results"
526
+ ],
527
+ properties: {
528
+ query: nullableString(),
529
+ folder: nullableString(),
530
+ total: { type: "integer" },
531
+ offset: { type: "integer" },
532
+ more: { type: "boolean" },
533
+ complete: { type: "boolean" },
534
+ results: {
535
+ type: "array",
536
+ items: {
537
+ type: "object",
538
+ additionalProperties: false,
539
+ required: [
540
+ "name",
541
+ "description",
542
+ "whenToUse",
543
+ "folder",
544
+ "match"
545
+ ],
546
+ properties: {
547
+ name: { type: "string" },
548
+ description: { type: "string" },
549
+ whenToUse: { type: "string" },
550
+ folder: nullableString(),
551
+ match: {
552
+ type: "string",
553
+ enum: [
554
+ "exact",
555
+ "partial",
556
+ "folder"
557
+ ]
558
+ }
559
+ }
560
+ }
561
+ }
562
+ }
563
+ },
564
+ render(_args, value) {
565
+ return [{
566
+ type: "text",
567
+ text: `${JSON.stringify(value)}\nThese are discovery summaries only. Load applicable instructions with skill({name: "exact-name"}).${value.complete ? "" : " Discovery was incomplete; retry before concluding a skill is absent."}`
568
+ }];
569
+ }
570
+ },
571
+ async execute(args, context) {
572
+ const resolved = resolveArgs(args, options.folders, options.defaultLimit);
573
+ if (!options.hasSkillLoader(context)) throw new Error(`${PLUGIN_LABEL}: ${TOOL_NAME} needs the native skill loader`);
574
+ context.signal?.throwIfAborted();
575
+ const snapshot = await options.readSkills(context);
576
+ context.signal?.throwIfAborted();
577
+ const result = rankSkills(snapshot.skills, resolved.query, {
578
+ folders: options.folders,
579
+ folder: resolved.folder,
580
+ limit: resolved.limit,
581
+ offset: resolved.offset,
582
+ descriptionMaxLength: options.descriptionMaxLength
583
+ });
584
+ return {
585
+ query: resolved.query ?? null,
586
+ folder: resolved.folder ?? null,
587
+ total: result.total,
588
+ offset: resolved.offset,
589
+ more: result.more,
590
+ complete: snapshot.complete,
591
+ results: result.results.map((hit) => ({ ...hit }))
592
+ };
593
+ },
594
+ isConcurrencySafe: () => true,
595
+ presentCall: (args) => ({
596
+ card: "generic",
597
+ title: "Search skills",
598
+ kind: "read",
599
+ rawInput: typeof args.query === "string" ? args.query : String(args.folder ?? "")
600
+ })
601
+ };
602
+ }
603
+ //#endregion
604
+ //#region src/index.ts
605
+ /**
606
+ * 插件入口。导出宿主约定的 name、inject、apply 与 Config。
607
+ */
608
+ /** 插件名,与 cordis.patch.yml 的 id 一致。 */
609
+ const name = PLUGIN_LABEL;
610
+ /** 需要宿主注入的服务。`connection` 与 `sessionQuery` 按功能可选。 */
611
+ const inject = [
612
+ "tools",
613
+ "skills",
614
+ "workingDirectory"
615
+ ];
616
+ /** 判断消息来源是否是原生技能目录。 */
617
+ function isCatalogSource(message) {
618
+ return message.source?.kind === "skill-catalog";
619
+ }
620
+ /**
621
+ * 插件启用时调用:解析配置、改写模型目录、监听配置热更新。
622
+ * `config` 的字段是热重载引用,保存配置后读取新值。
623
+ */
624
+ function apply(ctx, config) {
625
+ let current = readConfig(config);
626
+ const services = ctx;
627
+ services.logger.info?.(`[${PLUGIN_LABEL}] apply: folders=${String(current.folders.length)}`);
628
+ /** 读取本 Agent 的技能快照。 */
629
+ const readSkills = async (context) => {
630
+ const agent = context.agent;
631
+ const cwd = await services.workingDirectory?.ensure(agent ?? {}, context.signal);
632
+ const snapshot = await services.skills?.snapshot({
633
+ cwd,
634
+ scope: agent,
635
+ signal: context.signal
636
+ });
637
+ if (snapshot === void 0) throw new Error(`${PLUGIN_LABEL}: skills service unavailable`);
638
+ return snapshot;
639
+ };
640
+ /** 按当前配置注册检索工具,返回注销函数。 */
641
+ const registerTool = () => {
642
+ const tool = buildSearchTool({
643
+ folders: current.folders,
644
+ defaultLimit: current.defaultLimit,
645
+ descriptionMaxLength: current.descriptionMaxLength,
646
+ readSkills,
647
+ hasSkillLoader: (context) => services.tools?.get("skill", context.agent) !== void 0
648
+ });
649
+ return services.tools?.register(tool) ?? (() => void 0);
650
+ };
651
+ let disposeTool = registerTool();
652
+ ctx.effect(() => () => {
653
+ disposeTool();
654
+ }, `${PLUGIN_LABEL}: search tool`);
655
+ registerSkillsRoute(ctx, { snapshot: async () => {
656
+ const snapshot = await services.skills?.snapshot({});
657
+ if (snapshot === void 0) throw new Error(`${PLUGIN_LABEL}: skills service unavailable`);
658
+ return snapshot;
659
+ } });
660
+ ctx.effect(() => ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
661
+ const decision = await next();
662
+ if (decision.kind === "reject") return decision;
663
+ if (!(services.tools?.get("skill_search", agent) !== void 0)) return decision;
664
+ if (!decision.messages.some(isCatalogSource)) return decision;
665
+ const cwd = await services.workingDirectory?.ensure(agent, signal);
666
+ let snapshot;
667
+ try {
668
+ snapshot = await services.skills?.snapshot({
669
+ cwd,
670
+ scope: agent,
671
+ signal
672
+ });
673
+ } catch (error) {
674
+ services.logger.warn?.(`[${PLUGIN_LABEL}] skill snapshot failed: ${String(error)}`);
675
+ return decision;
676
+ }
677
+ if (snapshot === void 0) return decision;
678
+ const folded = foldCatalog(decision.messages, {
679
+ skills: snapshot.skills,
680
+ folders: current.folders,
681
+ toolVisible: true
682
+ });
683
+ return {
684
+ ...decision,
685
+ messages: folded
686
+ };
687
+ }, { prepend: true }), `${PLUGIN_LABEL}: catalog`);
688
+ ctx.on("loader/volatile-update", () => {
689
+ try {
690
+ current = readConfig(config);
691
+ } catch (error) {
692
+ services.logger.warn?.(`[${PLUGIN_LABEL}] config update ignored: ${String(error)}`);
693
+ return;
694
+ }
695
+ disposeTool();
696
+ disposeTool = registerTool();
697
+ services.logger.info?.(`[${PLUGIN_LABEL}] config updated: folders=${String(current.folders.length)}`);
698
+ });
699
+ }
700
+ //#endregion
701
+ export { Config, apply, inject, name };