@spzhongwin/skill-logger-plugin 1.0.11 → 1.0.13

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 (54) hide show
  1. package/dist/active-skills.js +67 -0
  2. package/dist/active-skills.test.js +29 -0
  3. package/dist/config-sync.js +439 -0
  4. package/dist/config-sync.test.js +145 -0
  5. package/dist/hooks.js +337 -0
  6. package/dist/hooks.test.js +123 -0
  7. package/dist/http.js +54 -0
  8. package/dist/identity.js +56 -0
  9. package/dist/index.js +240 -78
  10. package/dist/index.test.js +39 -0
  11. package/dist/integration.test.js +102 -0
  12. package/dist/matcher.js +362 -0
  13. package/dist/matcher.test.js +139 -0
  14. package/dist/paths.js +62 -0
  15. package/dist/paths.test.js +49 -0
  16. package/dist/reporter.js +267 -0
  17. package/dist/reporter.test.js +128 -0
  18. package/dist/semver.js +64 -0
  19. package/dist/semver.test.js +21 -0
  20. package/dist/skill-version.js +23 -0
  21. package/dist/types.js +9 -0
  22. package/dist/updater.js +352 -0
  23. package/dist/updater.test.js +212 -0
  24. package/dist/ws-client.js +484 -0
  25. package/openclaw.plugin.json +50 -50
  26. package/package.json +37 -37
  27. package/src/active-skills.test.ts +32 -32
  28. package/src/active-skills.ts +77 -77
  29. package/src/config-sync.test.ts +165 -165
  30. package/src/config-sync.ts +544 -544
  31. package/src/hooks.test.ts +251 -251
  32. package/src/hooks.ts +517 -517
  33. package/src/http.ts +61 -61
  34. package/src/identity.ts +64 -64
  35. package/src/index.test.ts +53 -53
  36. package/src/index.ts +226 -226
  37. package/src/integration.test.ts +119 -119
  38. package/src/matcher.test.ts +170 -170
  39. package/src/matcher.ts +393 -393
  40. package/src/paths.test.ts +57 -57
  41. package/src/paths.ts +84 -84
  42. package/src/reporter.test.ts +139 -139
  43. package/src/reporter.ts +298 -298
  44. package/src/sample-config.json +72 -72
  45. package/src/semver.test.ts +23 -23
  46. package/src/semver.ts +60 -60
  47. package/src/skill-version.ts +53 -53
  48. package/src/types.ts +198 -198
  49. package/src/updater.test.ts +325 -237
  50. package/src/updater.ts +549 -433
  51. package/src/ws-client.test.ts +48 -37
  52. package/src/ws-client.ts +717 -642
  53. package/test-ws.ts +17 -17
  54. package/tsconfig.json +14 -14
package/src/matcher.ts CHANGED
@@ -1,393 +1,393 @@
1
- /**
2
- * 多策略匹配引擎(纯函数、无 I/O)。
3
- *
4
- * 职责:给定一次观测到的工具调用(toolName + params)和「本 session 已激活的 skill 集合」,
5
- * 判定它是否对应某 skill 的某功能点,并解析出参数。
6
- *
7
- * 四种策略(由标准配置里 `match.type` 判别):
8
- * - script :exec 跑 skill 自带脚本(.py/.sh/.js),按脚本路径后缀匹配
9
- * - command :exec 调包装 CLI(如 `mcporter call linear.list_issues`)
10
- * - tool :直接调非 exec 工具(MCP/SSE 工具),按 toolName(+参数谓词) 匹配
11
- * - http :curl/fetch 打 HTTP/SSE 端点,按 url/host 子串匹配
12
- *
13
- * 为保证 hook 热路径快:先用 buildIndex 预索引(按 basename / 命令头 / toolName / host 建桶),
14
- * match 时仅在小候选集上做精确判定。
15
- */
16
- import path from "node:path";
17
- import type {
18
- ArgRule,
19
- CommandMatchRule,
20
- HttpMatchRule,
21
- MatchResult,
22
- ScriptMatchRule,
23
- SkillStandardConfig,
24
- ToolCall,
25
- ToolMatchRule,
26
- WherePredicate,
27
- } from "./types.ts";
28
-
29
- /** 索引里每个功能点附带其所属 skill 信息。 */
30
- type IndexedFn = {
31
- skillName: string;
32
- skillVersion: string;
33
- functionId: string;
34
- functionName: string;
35
- rule: ScriptMatchRule | CommandMatchRule | ToolMatchRule | HttpMatchRule;
36
- /** tool 规则的 toolNameRegex 预编译结果:RegExp 命中、null 表示编译失败、undefined 表示无正则。 */
37
- compiledRegex?: RegExp | null;
38
- };
39
-
40
- export type MatchIndex = {
41
- /** script:按脚本 basename 建桶。 */
42
- scriptByBasename: Map<string, IndexedFn[]>;
43
- /** command:按命令头建桶。 */
44
- commandByHead: Map<string, IndexedFn[]>;
45
- /** tool:精确 toolName 建桶。 */
46
- toolByName: Map<string, IndexedFn[]>;
47
- /** tool:前缀/正则规则(无法用精确 key 命中,逐个判定)。 */
48
- toolFuzzy: IndexedFn[];
49
- /** http:规则量少,整体扫描。 */
50
- httpRules: IndexedFn[];
51
- };
52
-
53
- /** 已知解释器/包装前缀,用于在找「命令头」时跳过。 */
54
- const INTERPRETERS = new Set([
55
- "python", "python3", "py", "bash", "sh", "zsh", "node", "ts-node",
56
- "tsx", "deno", "ruby", "perl", "uv", "uvx", "npx", "pnpm", "yarn", "env",
57
- ]);
58
-
59
- /** 空索引。 */
60
- export function emptyIndex(): MatchIndex {
61
- return {
62
- scriptByBasename: new Map(),
63
- commandByHead: new Map(),
64
- toolByName: new Map(),
65
- toolFuzzy: [],
66
- httpRules: [],
67
- };
68
- }
69
-
70
- function pushBucket(map: Map<string, IndexedFn[]>, key: string, fn: IndexedFn): void {
71
- const arr = map.get(key);
72
- if (arr) arr.push(fn);
73
- else map.set(key, [fn]);
74
- }
75
-
76
- /** 把标准配置编译成可快速匹配的索引。 */
77
- export function buildIndex(configs: SkillStandardConfig[]): MatchIndex {
78
- const index = emptyIndex();
79
- for (const cfg of configs) {
80
- for (const fn of cfg.functions) {
81
- const indexed: IndexedFn = {
82
- skillName: cfg.skillName,
83
- skillVersion: cfg.version,
84
- functionId: fn.id,
85
- functionName: fn.name,
86
- rule: fn.match,
87
- };
88
- switch (fn.match.type) {
89
- case "script":
90
- pushBucket(index.scriptByBasename, path.basename(fn.match.script), indexed);
91
- break;
92
- case "command":
93
- pushBucket(index.commandByHead, fn.match.command, indexed);
94
- break;
95
- case "tool":
96
- if (fn.match.toolName) {
97
- pushBucket(index.toolByName, fn.match.toolName, indexed);
98
- } else {
99
- if (fn.match.toolNameRegex) {
100
- try {
101
- indexed.compiledRegex = new RegExp(fn.match.toolNameRegex);
102
- } catch {
103
- indexed.compiledRegex = null; // 非法正则:预编译失败,匹配时直接不命中
104
- }
105
- }
106
- index.toolFuzzy.push(indexed);
107
- }
108
- break;
109
- case "http":
110
- index.httpRules.push(indexed);
111
- break;
112
- }
113
- }
114
- }
115
- return index;
116
- }
117
-
118
- /**
119
- * 把 shell 命令切成 token,识别简单的单/双引号;不求完整 shell 语义,够匹配脚本路径与 flag 即可。
120
- */
121
- export function tokenize(command: string): string[] {
122
- const tokens: string[] = [];
123
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
124
- let m: RegExpExecArray | null;
125
- while ((m = re.exec(command)) !== null) {
126
- tokens.push(m[1] ?? m[2] ?? m[3] ?? "");
127
- }
128
- return tokens;
129
- }
130
-
131
- /** 路径后缀匹配(按路径分隔对齐,避免 `xfoo.py` 误判 `foo.py`)。 */
132
- export function pathEndsWith(token: string, scriptRel: string): boolean {
133
- const t = token.replace(/\\/g, "/");
134
- const s = scriptRel.replace(/\\/g, "/").replace(/^\.?\//, "");
135
- return t === s || t.endsWith("/" + s);
136
- }
137
-
138
- /** 解析命令行 flag:`--k v` / `--k=v` / `-k v` / 布尔 flag。返回去前缀的键值表。 */
139
- export function parseFlags(tokens: string[]): Record<string, unknown> {
140
- const out: Record<string, unknown> = {};
141
- for (let i = 0; i < tokens.length; i++) {
142
- const t = tokens[i];
143
- if (t.startsWith("--")) {
144
- const eq = t.indexOf("=");
145
- if (eq >= 0) {
146
- out[t.slice(2, eq)] = t.slice(eq + 1);
147
- } else {
148
- const next = tokens[i + 1];
149
- if (next !== undefined && !next.startsWith("-")) {
150
- out[t.slice(2)] = next;
151
- i++;
152
- } else {
153
- out[t.slice(2)] = true;
154
- }
155
- }
156
- } else if (t.length > 1 && t.startsWith("-") && !/^-\d/.test(t)) {
157
- const key = t.slice(1);
158
- const next = tokens[i + 1];
159
- if (next !== undefined && !next.startsWith("-")) {
160
- out[key] = next;
161
- i++;
162
- } else {
163
- out[key] = true;
164
- }
165
- }
166
- }
167
- return out;
168
- }
169
-
170
- /** argRules 全部命中才算命中(flag 去前缀比较;value 省略则只判存在)。 */
171
- function argRulesMatch(argRules: ArgRule[] | undefined, flags: Record<string, unknown>): boolean {
172
- if (!argRules || argRules.length === 0) return true;
173
- for (const rule of argRules) {
174
- const key = rule.flag.replace(/^-+/, "");
175
- if (!(key in flags)) return false;
176
- if (rule.value !== undefined && String(flags[key]) !== rule.value) return false;
177
- }
178
- return true;
179
- }
180
-
181
- /** 找命令头:跳过 `VAR=val` 环境前缀与已知解释器,返回首个真实命令名。 */
182
- export function commandHead(tokens: string[]): string | undefined {
183
- for (let i = 0; i < tokens.length; i++) {
184
- const t = tokens[i];
185
- if (/^[A-Za-z_][\w]*=/.test(t)) continue; // 环境变量前缀
186
- const base = path.basename(t);
187
- if (INTERPRETERS.has(base)) continue; // 解释器
188
- return base;
189
- }
190
- return undefined;
191
- }
192
-
193
- /** 解析 `k=v` / `k:v`(用于 mcporter 等),避开 URL 的 `://`。 */
194
- export function parseKeyValues(tokens: string[]): Record<string, unknown> {
195
- const out: Record<string, unknown> = {};
196
- for (const t of tokens) {
197
- if (t.includes("://")) continue;
198
- const m = /^([A-Za-z_][\w.-]*)[=:](.*)$/.exec(t);
199
- if (m) out[m[1]] = m[2];
200
- }
201
- return out;
202
- }
203
-
204
- /** 从字符串里抽第一个 URL。 */
205
- function extractUrl(s: string): string | undefined {
206
- const m = /https?:\/\/[^\s"'`]+/.exec(s);
207
- return m ? m[0] : undefined;
208
- }
209
-
210
- /** 解析 URL 的 query 参数为对象。 */
211
- function parseQuery(url: string): Record<string, unknown> {
212
- const out: Record<string, unknown> = {};
213
- const qi = url.indexOf("?");
214
- if (qi < 0) return out;
215
- for (const pair of url.slice(qi + 1).split("&")) {
216
- if (!pair) continue;
217
- const eq = pair.indexOf("=");
218
- const k = decodeURIComponent(eq >= 0 ? pair.slice(0, eq) : pair);
219
- const v = eq >= 0 ? decodeURIComponent(pair.slice(eq + 1)) : true;
220
- out[k] = v;
221
- }
222
- return out;
223
- }
224
-
225
- function httpMatchesUrl(url: string, rule: HttpMatchRule): boolean {
226
- if (rule.urlContains && !url.includes(rule.urlContains)) return false;
227
- if (rule.hostContains) {
228
- let host = "";
229
- try {
230
- host = new URL(url).host;
231
- } catch {
232
- host = url;
233
- }
234
- if (!host.includes(rule.hostContains)) return false;
235
- }
236
- return Boolean(rule.urlContains || rule.hostContains);
237
- }
238
-
239
- /** 点路径取嵌套字段。 */
240
- function getByPath(obj: Record<string, unknown>, dotted: string): unknown {
241
- let cur: unknown = obj;
242
- for (const seg of dotted.split(".")) {
243
- if (cur && typeof cur === "object" && seg in (cur as Record<string, unknown>)) {
244
- cur = (cur as Record<string, unknown>)[seg];
245
- } else {
246
- return undefined;
247
- }
248
- }
249
- return cur;
250
- }
251
-
252
- function whereMatches(where: WherePredicate[] | undefined, params: Record<string, unknown>): boolean {
253
- if (!where || where.length === 0) return true;
254
- for (const p of where) {
255
- if (String(getByPath(params, p.param)) !== p.equals) return false;
256
- }
257
- return true;
258
- }
259
-
260
- function toolNameMatches(f: IndexedFn, toolName: string): boolean {
261
- const rule = f.rule as ToolMatchRule;
262
- if (rule.toolName) return rule.toolName === toolName;
263
- if (rule.toolNamePrefix) return toolName.startsWith(rule.toolNamePrefix);
264
- if (rule.toolNameRegex) {
265
- // 预编译命中走缓存;null 表示编译失败不命中;undefined 仅为兜底(理论上 buildIndex 必已编译)。
266
- if (f.compiledRegex === null) return false;
267
- if (f.compiledRegex) return f.compiledRegex.test(toolName);
268
- try {
269
- return new RegExp(rule.toolNameRegex).test(toolName);
270
- } catch {
271
- return false;
272
- }
273
- }
274
- return false;
275
- }
276
-
277
- /** 从工具参数里挑一个 url 字段(fetch 类工具)。 */
278
- function pickUrlParam(params: Record<string, unknown>): string | undefined {
279
- for (const key of ["url", "endpoint", "uri", "href"]) {
280
- const v = params[key];
281
- if (typeof v === "string" && /^https?:\/\//.test(v)) return v;
282
- }
283
- return undefined;
284
- }
285
-
286
- type Candidate = { res: MatchResult; skillActive: boolean; strong: boolean };
287
-
288
- function toResult(f: IndexedFn, matchType: MatchResult["matchType"], args: Record<string, unknown>): MatchResult {
289
- return {
290
- skillName: f.skillName,
291
- skillVersion: f.skillVersion,
292
- functionId: f.functionId,
293
- functionName: f.functionName,
294
- matchType,
295
- args,
296
- };
297
- }
298
-
299
- /**
300
- * 主匹配。命中返回 MatchResult;无自信命中返回 null。
301
- * 多候选时优先归属到 `activeSkills`(本 session 已触发的 skill)以消歧。
302
- */
303
- export function match(
304
- call: ToolCall,
305
- activeSkills: ReadonlySet<string>,
306
- index: MatchIndex
307
- ): MatchResult | null {
308
- const candidates: Candidate[] = [];
309
- const add = (res: MatchResult, strong = true) =>
310
- candidates.push({ res, skillActive: activeSkills.has(res.skillName), strong });
311
-
312
- if (call.toolName === "exec") {
313
- const command = typeof call.params.command === "string" ? call.params.command : "";
314
- if (!command) return null;
315
- const tokens = tokenize(command);
316
- const flags = parseFlags(tokens);
317
-
318
- // script:按 token 的 basename 命中桶。
319
- // - 强匹配:token 路径以配置脚本相对路径结尾(如完整 baseDir 路径)。
320
- // - 弱匹配:仅 basename 相同(如 `cd` 进目录后 `python model_usage.py`);
321
- // 弱匹配只有在「该 skill 已激活」时才会被采纳,避免跨 skill 同名脚本误判。
322
- for (const tok of tokens) {
323
- const fns = index.scriptByBasename.get(path.basename(tok));
324
- if (!fns) continue;
325
- for (const f of fns) {
326
- const rule = f.rule as ScriptMatchRule;
327
- if (!argRulesMatch(rule.argRules, flags)) continue;
328
- add(toResult(f, "script", flags), pathEndsWith(tok, rule.script));
329
- }
330
- }
331
-
332
- // command:命令头命中桶,再校验 targetPattern 出现在命令里(空白归一以增强鲁棒性)
333
- const head = commandHead(tokens);
334
- if (head) {
335
- const fns = index.commandByHead.get(head);
336
- if (fns) {
337
- const normCmd = command.replace(/\s+/g, " ");
338
- for (const f of fns) {
339
- const rule = f.rule as CommandMatchRule;
340
- if (normCmd.includes(rule.targetPattern.replace(/\s+/g, " "))) {
341
- add(toResult(f, "command", parseKeyValues(tokens)));
342
- }
343
- }
344
- }
345
- }
346
-
347
- // http:curl/wget 命令里的 URL
348
- if (index.httpRules.length > 0) {
349
- const url = extractUrl(command);
350
- if (url) {
351
- for (const f of index.httpRules) {
352
- if (httpMatchesUrl(url, f.rule as HttpMatchRule)) {
353
- add(toResult(f, "http", parseQuery(url)));
354
- }
355
- }
356
- }
357
- }
358
- } else {
359
- // 非 exec:tool 直调
360
- const exact = index.toolByName.get(call.toolName) ?? [];
361
- for (const f of exact) {
362
- const rule = f.rule as ToolMatchRule;
363
- if (whereMatches(rule.where, call.params)) add(toResult(f, "tool", { ...call.params }));
364
- }
365
- for (const f of index.toolFuzzy) {
366
- const rule = f.rule as ToolMatchRule;
367
- if (toolNameMatches(f, call.toolName) && whereMatches(rule.where, call.params)) {
368
- add(toResult(f, "tool", { ...call.params }));
369
- }
370
- }
371
-
372
- // http:fetch 类工具的 url 参数
373
- if (index.httpRules.length > 0) {
374
- const url = pickUrlParam(call.params);
375
- if (url) {
376
- for (const f of index.httpRules) {
377
- if (httpMatchesUrl(url, f.rule as HttpMatchRule)) {
378
- add(toResult(f, "http", parseQuery(url)));
379
- }
380
- }
381
- }
382
- }
383
- }
384
-
385
- if (candidates.length === 0) return null;
386
- // 丢弃「弱匹配且 skill 未激活」的低置信候选。
387
- const eligible = candidates.filter((c) => c.strong || c.skillActive);
388
- if (eligible.length === 0) return null;
389
- // 置信度排序:强且激活 > 强 > 弱且激活。sort 在 V8 稳定,平手时保留配置顺序。
390
- const rank = (c: Candidate) => (c.strong ? 2 : 0) + (c.skillActive ? 1 : 0);
391
- eligible.sort((a, b) => rank(b) - rank(a));
392
- return eligible[0].res;
393
- }
1
+ /**
2
+ * 多策略匹配引擎(纯函数、无 I/O)。
3
+ *
4
+ * 职责:给定一次观测到的工具调用(toolName + params)和「本 session 已激活的 skill 集合」,
5
+ * 判定它是否对应某 skill 的某功能点,并解析出参数。
6
+ *
7
+ * 四种策略(由标准配置里 `match.type` 判别):
8
+ * - script :exec 跑 skill 自带脚本(.py/.sh/.js),按脚本路径后缀匹配
9
+ * - command :exec 调包装 CLI(如 `mcporter call linear.list_issues`)
10
+ * - tool :直接调非 exec 工具(MCP/SSE 工具),按 toolName(+参数谓词) 匹配
11
+ * - http :curl/fetch 打 HTTP/SSE 端点,按 url/host 子串匹配
12
+ *
13
+ * 为保证 hook 热路径快:先用 buildIndex 预索引(按 basename / 命令头 / toolName / host 建桶),
14
+ * match 时仅在小候选集上做精确判定。
15
+ */
16
+ import path from "node:path";
17
+ import type {
18
+ ArgRule,
19
+ CommandMatchRule,
20
+ HttpMatchRule,
21
+ MatchResult,
22
+ ScriptMatchRule,
23
+ SkillStandardConfig,
24
+ ToolCall,
25
+ ToolMatchRule,
26
+ WherePredicate,
27
+ } from "./types.ts";
28
+
29
+ /** 索引里每个功能点附带其所属 skill 信息。 */
30
+ type IndexedFn = {
31
+ skillName: string;
32
+ skillVersion: string;
33
+ functionId: string;
34
+ functionName: string;
35
+ rule: ScriptMatchRule | CommandMatchRule | ToolMatchRule | HttpMatchRule;
36
+ /** tool 规则的 toolNameRegex 预编译结果:RegExp 命中、null 表示编译失败、undefined 表示无正则。 */
37
+ compiledRegex?: RegExp | null;
38
+ };
39
+
40
+ export type MatchIndex = {
41
+ /** script:按脚本 basename 建桶。 */
42
+ scriptByBasename: Map<string, IndexedFn[]>;
43
+ /** command:按命令头建桶。 */
44
+ commandByHead: Map<string, IndexedFn[]>;
45
+ /** tool:精确 toolName 建桶。 */
46
+ toolByName: Map<string, IndexedFn[]>;
47
+ /** tool:前缀/正则规则(无法用精确 key 命中,逐个判定)。 */
48
+ toolFuzzy: IndexedFn[];
49
+ /** http:规则量少,整体扫描。 */
50
+ httpRules: IndexedFn[];
51
+ };
52
+
53
+ /** 已知解释器/包装前缀,用于在找「命令头」时跳过。 */
54
+ const INTERPRETERS = new Set([
55
+ "python", "python3", "py", "bash", "sh", "zsh", "node", "ts-node",
56
+ "tsx", "deno", "ruby", "perl", "uv", "uvx", "npx", "pnpm", "yarn", "env",
57
+ ]);
58
+
59
+ /** 空索引。 */
60
+ export function emptyIndex(): MatchIndex {
61
+ return {
62
+ scriptByBasename: new Map(),
63
+ commandByHead: new Map(),
64
+ toolByName: new Map(),
65
+ toolFuzzy: [],
66
+ httpRules: [],
67
+ };
68
+ }
69
+
70
+ function pushBucket(map: Map<string, IndexedFn[]>, key: string, fn: IndexedFn): void {
71
+ const arr = map.get(key);
72
+ if (arr) arr.push(fn);
73
+ else map.set(key, [fn]);
74
+ }
75
+
76
+ /** 把标准配置编译成可快速匹配的索引。 */
77
+ export function buildIndex(configs: SkillStandardConfig[]): MatchIndex {
78
+ const index = emptyIndex();
79
+ for (const cfg of configs) {
80
+ for (const fn of cfg.functions) {
81
+ const indexed: IndexedFn = {
82
+ skillName: cfg.skillName,
83
+ skillVersion: cfg.version,
84
+ functionId: fn.id,
85
+ functionName: fn.name,
86
+ rule: fn.match,
87
+ };
88
+ switch (fn.match.type) {
89
+ case "script":
90
+ pushBucket(index.scriptByBasename, path.basename(fn.match.script), indexed);
91
+ break;
92
+ case "command":
93
+ pushBucket(index.commandByHead, fn.match.command, indexed);
94
+ break;
95
+ case "tool":
96
+ if (fn.match.toolName) {
97
+ pushBucket(index.toolByName, fn.match.toolName, indexed);
98
+ } else {
99
+ if (fn.match.toolNameRegex) {
100
+ try {
101
+ indexed.compiledRegex = new RegExp(fn.match.toolNameRegex);
102
+ } catch {
103
+ indexed.compiledRegex = null; // 非法正则:预编译失败,匹配时直接不命中
104
+ }
105
+ }
106
+ index.toolFuzzy.push(indexed);
107
+ }
108
+ break;
109
+ case "http":
110
+ index.httpRules.push(indexed);
111
+ break;
112
+ }
113
+ }
114
+ }
115
+ return index;
116
+ }
117
+
118
+ /**
119
+ * 把 shell 命令切成 token,识别简单的单/双引号;不求完整 shell 语义,够匹配脚本路径与 flag 即可。
120
+ */
121
+ export function tokenize(command: string): string[] {
122
+ const tokens: string[] = [];
123
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
124
+ let m: RegExpExecArray | null;
125
+ while ((m = re.exec(command)) !== null) {
126
+ tokens.push(m[1] ?? m[2] ?? m[3] ?? "");
127
+ }
128
+ return tokens;
129
+ }
130
+
131
+ /** 路径后缀匹配(按路径分隔对齐,避免 `xfoo.py` 误判 `foo.py`)。 */
132
+ export function pathEndsWith(token: string, scriptRel: string): boolean {
133
+ const t = token.replace(/\\/g, "/");
134
+ const s = scriptRel.replace(/\\/g, "/").replace(/^\.?\//, "");
135
+ return t === s || t.endsWith("/" + s);
136
+ }
137
+
138
+ /** 解析命令行 flag:`--k v` / `--k=v` / `-k v` / 布尔 flag。返回去前缀的键值表。 */
139
+ export function parseFlags(tokens: string[]): Record<string, unknown> {
140
+ const out: Record<string, unknown> = {};
141
+ for (let i = 0; i < tokens.length; i++) {
142
+ const t = tokens[i];
143
+ if (t.startsWith("--")) {
144
+ const eq = t.indexOf("=");
145
+ if (eq >= 0) {
146
+ out[t.slice(2, eq)] = t.slice(eq + 1);
147
+ } else {
148
+ const next = tokens[i + 1];
149
+ if (next !== undefined && !next.startsWith("-")) {
150
+ out[t.slice(2)] = next;
151
+ i++;
152
+ } else {
153
+ out[t.slice(2)] = true;
154
+ }
155
+ }
156
+ } else if (t.length > 1 && t.startsWith("-") && !/^-\d/.test(t)) {
157
+ const key = t.slice(1);
158
+ const next = tokens[i + 1];
159
+ if (next !== undefined && !next.startsWith("-")) {
160
+ out[key] = next;
161
+ i++;
162
+ } else {
163
+ out[key] = true;
164
+ }
165
+ }
166
+ }
167
+ return out;
168
+ }
169
+
170
+ /** argRules 全部命中才算命中(flag 去前缀比较;value 省略则只判存在)。 */
171
+ function argRulesMatch(argRules: ArgRule[] | undefined, flags: Record<string, unknown>): boolean {
172
+ if (!argRules || argRules.length === 0) return true;
173
+ for (const rule of argRules) {
174
+ const key = rule.flag.replace(/^-+/, "");
175
+ if (!(key in flags)) return false;
176
+ if (rule.value !== undefined && String(flags[key]) !== rule.value) return false;
177
+ }
178
+ return true;
179
+ }
180
+
181
+ /** 找命令头:跳过 `VAR=val` 环境前缀与已知解释器,返回首个真实命令名。 */
182
+ export function commandHead(tokens: string[]): string | undefined {
183
+ for (let i = 0; i < tokens.length; i++) {
184
+ const t = tokens[i];
185
+ if (/^[A-Za-z_][\w]*=/.test(t)) continue; // 环境变量前缀
186
+ const base = path.basename(t);
187
+ if (INTERPRETERS.has(base)) continue; // 解释器
188
+ return base;
189
+ }
190
+ return undefined;
191
+ }
192
+
193
+ /** 解析 `k=v` / `k:v`(用于 mcporter 等),避开 URL 的 `://`。 */
194
+ export function parseKeyValues(tokens: string[]): Record<string, unknown> {
195
+ const out: Record<string, unknown> = {};
196
+ for (const t of tokens) {
197
+ if (t.includes("://")) continue;
198
+ const m = /^([A-Za-z_][\w.-]*)[=:](.*)$/.exec(t);
199
+ if (m) out[m[1]] = m[2];
200
+ }
201
+ return out;
202
+ }
203
+
204
+ /** 从字符串里抽第一个 URL。 */
205
+ function extractUrl(s: string): string | undefined {
206
+ const m = /https?:\/\/[^\s"'`]+/.exec(s);
207
+ return m ? m[0] : undefined;
208
+ }
209
+
210
+ /** 解析 URL 的 query 参数为对象。 */
211
+ function parseQuery(url: string): Record<string, unknown> {
212
+ const out: Record<string, unknown> = {};
213
+ const qi = url.indexOf("?");
214
+ if (qi < 0) return out;
215
+ for (const pair of url.slice(qi + 1).split("&")) {
216
+ if (!pair) continue;
217
+ const eq = pair.indexOf("=");
218
+ const k = decodeURIComponent(eq >= 0 ? pair.slice(0, eq) : pair);
219
+ const v = eq >= 0 ? decodeURIComponent(pair.slice(eq + 1)) : true;
220
+ out[k] = v;
221
+ }
222
+ return out;
223
+ }
224
+
225
+ function httpMatchesUrl(url: string, rule: HttpMatchRule): boolean {
226
+ if (rule.urlContains && !url.includes(rule.urlContains)) return false;
227
+ if (rule.hostContains) {
228
+ let host = "";
229
+ try {
230
+ host = new URL(url).host;
231
+ } catch {
232
+ host = url;
233
+ }
234
+ if (!host.includes(rule.hostContains)) return false;
235
+ }
236
+ return Boolean(rule.urlContains || rule.hostContains);
237
+ }
238
+
239
+ /** 点路径取嵌套字段。 */
240
+ function getByPath(obj: Record<string, unknown>, dotted: string): unknown {
241
+ let cur: unknown = obj;
242
+ for (const seg of dotted.split(".")) {
243
+ if (cur && typeof cur === "object" && seg in (cur as Record<string, unknown>)) {
244
+ cur = (cur as Record<string, unknown>)[seg];
245
+ } else {
246
+ return undefined;
247
+ }
248
+ }
249
+ return cur;
250
+ }
251
+
252
+ function whereMatches(where: WherePredicate[] | undefined, params: Record<string, unknown>): boolean {
253
+ if (!where || where.length === 0) return true;
254
+ for (const p of where) {
255
+ if (String(getByPath(params, p.param)) !== p.equals) return false;
256
+ }
257
+ return true;
258
+ }
259
+
260
+ function toolNameMatches(f: IndexedFn, toolName: string): boolean {
261
+ const rule = f.rule as ToolMatchRule;
262
+ if (rule.toolName) return rule.toolName === toolName;
263
+ if (rule.toolNamePrefix) return toolName.startsWith(rule.toolNamePrefix);
264
+ if (rule.toolNameRegex) {
265
+ // 预编译命中走缓存;null 表示编译失败不命中;undefined 仅为兜底(理论上 buildIndex 必已编译)。
266
+ if (f.compiledRegex === null) return false;
267
+ if (f.compiledRegex) return f.compiledRegex.test(toolName);
268
+ try {
269
+ return new RegExp(rule.toolNameRegex).test(toolName);
270
+ } catch {
271
+ return false;
272
+ }
273
+ }
274
+ return false;
275
+ }
276
+
277
+ /** 从工具参数里挑一个 url 字段(fetch 类工具)。 */
278
+ function pickUrlParam(params: Record<string, unknown>): string | undefined {
279
+ for (const key of ["url", "endpoint", "uri", "href"]) {
280
+ const v = params[key];
281
+ if (typeof v === "string" && /^https?:\/\//.test(v)) return v;
282
+ }
283
+ return undefined;
284
+ }
285
+
286
+ type Candidate = { res: MatchResult; skillActive: boolean; strong: boolean };
287
+
288
+ function toResult(f: IndexedFn, matchType: MatchResult["matchType"], args: Record<string, unknown>): MatchResult {
289
+ return {
290
+ skillName: f.skillName,
291
+ skillVersion: f.skillVersion,
292
+ functionId: f.functionId,
293
+ functionName: f.functionName,
294
+ matchType,
295
+ args,
296
+ };
297
+ }
298
+
299
+ /**
300
+ * 主匹配。命中返回 MatchResult;无自信命中返回 null。
301
+ * 多候选时优先归属到 `activeSkills`(本 session 已触发的 skill)以消歧。
302
+ */
303
+ export function match(
304
+ call: ToolCall,
305
+ activeSkills: ReadonlySet<string>,
306
+ index: MatchIndex
307
+ ): MatchResult | null {
308
+ const candidates: Candidate[] = [];
309
+ const add = (res: MatchResult, strong = true) =>
310
+ candidates.push({ res, skillActive: activeSkills.has(res.skillName), strong });
311
+
312
+ if (call.toolName === "exec") {
313
+ const command = typeof call.params.command === "string" ? call.params.command : "";
314
+ if (!command) return null;
315
+ const tokens = tokenize(command);
316
+ const flags = parseFlags(tokens);
317
+
318
+ // script:按 token 的 basename 命中桶。
319
+ // - 强匹配:token 路径以配置脚本相对路径结尾(如完整 baseDir 路径)。
320
+ // - 弱匹配:仅 basename 相同(如 `cd` 进目录后 `python model_usage.py`);
321
+ // 弱匹配只有在「该 skill 已激活」时才会被采纳,避免跨 skill 同名脚本误判。
322
+ for (const tok of tokens) {
323
+ const fns = index.scriptByBasename.get(path.basename(tok));
324
+ if (!fns) continue;
325
+ for (const f of fns) {
326
+ const rule = f.rule as ScriptMatchRule;
327
+ if (!argRulesMatch(rule.argRules, flags)) continue;
328
+ add(toResult(f, "script", flags), pathEndsWith(tok, rule.script));
329
+ }
330
+ }
331
+
332
+ // command:命令头命中桶,再校验 targetPattern 出现在命令里(空白归一以增强鲁棒性)
333
+ const head = commandHead(tokens);
334
+ if (head) {
335
+ const fns = index.commandByHead.get(head);
336
+ if (fns) {
337
+ const normCmd = command.replace(/\s+/g, " ");
338
+ for (const f of fns) {
339
+ const rule = f.rule as CommandMatchRule;
340
+ if (normCmd.includes(rule.targetPattern.replace(/\s+/g, " "))) {
341
+ add(toResult(f, "command", parseKeyValues(tokens)));
342
+ }
343
+ }
344
+ }
345
+ }
346
+
347
+ // http:curl/wget 命令里的 URL
348
+ if (index.httpRules.length > 0) {
349
+ const url = extractUrl(command);
350
+ if (url) {
351
+ for (const f of index.httpRules) {
352
+ if (httpMatchesUrl(url, f.rule as HttpMatchRule)) {
353
+ add(toResult(f, "http", parseQuery(url)));
354
+ }
355
+ }
356
+ }
357
+ }
358
+ } else {
359
+ // 非 exec:tool 直调
360
+ const exact = index.toolByName.get(call.toolName) ?? [];
361
+ for (const f of exact) {
362
+ const rule = f.rule as ToolMatchRule;
363
+ if (whereMatches(rule.where, call.params)) add(toResult(f, "tool", { ...call.params }));
364
+ }
365
+ for (const f of index.toolFuzzy) {
366
+ const rule = f.rule as ToolMatchRule;
367
+ if (toolNameMatches(f, call.toolName) && whereMatches(rule.where, call.params)) {
368
+ add(toResult(f, "tool", { ...call.params }));
369
+ }
370
+ }
371
+
372
+ // http:fetch 类工具的 url 参数
373
+ if (index.httpRules.length > 0) {
374
+ const url = pickUrlParam(call.params);
375
+ if (url) {
376
+ for (const f of index.httpRules) {
377
+ if (httpMatchesUrl(url, f.rule as HttpMatchRule)) {
378
+ add(toResult(f, "http", parseQuery(url)));
379
+ }
380
+ }
381
+ }
382
+ }
383
+ }
384
+
385
+ if (candidates.length === 0) return null;
386
+ // 丢弃「弱匹配且 skill 未激活」的低置信候选。
387
+ const eligible = candidates.filter((c) => c.strong || c.skillActive);
388
+ if (eligible.length === 0) return null;
389
+ // 置信度排序:强且激活 > 强 > 弱且激活。sort 在 V8 稳定,平手时保留配置顺序。
390
+ const rank = (c: Candidate) => (c.strong ? 2 : 0) + (c.skillActive ? 1 : 0);
391
+ eligible.sort((a, b) => rank(b) - rank(a));
392
+ return eligible[0].res;
393
+ }