@spzhongwin/skill-logger-plugin 1.0.2
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.
- package/dist/active-skills.js +67 -0
- package/dist/active-skills.test.js +29 -0
- package/dist/config-sync.js +439 -0
- package/dist/config-sync.test.js +145 -0
- package/dist/hooks.js +337 -0
- package/dist/hooks.test.js +123 -0
- package/dist/http.js +54 -0
- package/dist/identity.js +56 -0
- package/dist/index.js +2286 -0
- package/dist/index.test.js +39 -0
- package/dist/integration.test.js +102 -0
- package/dist/matcher.js +362 -0
- package/dist/matcher.test.js +139 -0
- package/dist/paths.js +62 -0
- package/dist/paths.test.js +49 -0
- package/dist/reporter.js +267 -0
- package/dist/reporter.test.js +128 -0
- package/dist/semver.js +64 -0
- package/dist/semver.test.js +21 -0
- package/dist/skill-version.js +23 -0
- package/dist/types.js +9 -0
- package/dist/updater.js +352 -0
- package/dist/updater.test.js +212 -0
- package/dist/ws-client.js +484 -0
- package/openclaw.plugin.json +50 -0
- package/package.json +35 -0
- package/src/active-skills.test.ts +32 -0
- package/src/active-skills.ts +77 -0
- package/src/config-sync.test.ts +165 -0
- package/src/config-sync.ts +485 -0
- package/src/hooks.test.ts +156 -0
- package/src/hooks.ts +405 -0
- package/src/http.ts +61 -0
- package/src/identity.ts +64 -0
- package/src/index.test.ts +53 -0
- package/src/index.ts +226 -0
- package/src/integration.test.ts +119 -0
- package/src/matcher.test.ts +170 -0
- package/src/matcher.ts +393 -0
- package/src/paths.test.ts +57 -0
- package/src/paths.ts +84 -0
- package/src/reporter.test.ts +139 -0
- package/src/reporter.ts +298 -0
- package/src/sample-config.json +72 -0
- package/src/semver.test.ts +23 -0
- package/src/semver.ts +60 -0
- package/src/skill-version.ts +22 -0
- package/src/types.ts +198 -0
- package/src/updater.test.ts +237 -0
- package/src/updater.ts +400 -0
- package/src/ws-client.ts +516 -0
- package/test-ws.ts +17 -0
- package/tsconfig.json +14 -0
package/src/matcher.ts
ADDED
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { describe, it, beforeEach, afterEach } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { resolveAgentSkillDirs } from "./paths.ts";
|
|
7
|
+
|
|
8
|
+
let home: string;
|
|
9
|
+
|
|
10
|
+
beforeEach(async () => {
|
|
11
|
+
home = path.join(os.tmpdir(), `slp-paths-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
12
|
+
await fs.mkdir(home, { recursive: true });
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
afterEach(async () => {
|
|
16
|
+
await fs.rm(home, { recursive: true, force: true });
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe("resolveAgentSkillDirs", () => {
|
|
20
|
+
it("从 openclaw.json 收集各 agent workspace 的 skills 目录(含默认与顶层)", async () => {
|
|
21
|
+
const cfg = {
|
|
22
|
+
agents: {
|
|
23
|
+
defaults: { workspace: path.join(home, "workspace") },
|
|
24
|
+
list: [
|
|
25
|
+
{ id: "main" }, // 无 workspace → 落到默认
|
|
26
|
+
{ id: "coder", workspace: path.join(home, "workspace-coder") },
|
|
27
|
+
{ id: "proj", workspace: path.join(home, "agency-agents", "proj") },
|
|
28
|
+
],
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
const configPath = path.join(home, "openclaw.json");
|
|
32
|
+
await fs.writeFile(configPath, JSON.stringify(cfg));
|
|
33
|
+
|
|
34
|
+
const dirs = resolveAgentSkillDirs(home, configPath);
|
|
35
|
+
|
|
36
|
+
assert.ok(dirs.includes(path.join(home, "skills")), "应含顶层全局 skills");
|
|
37
|
+
assert.ok(dirs.includes(path.join(home, "workspace", "skills")), "应含默认 workspace skills");
|
|
38
|
+
assert.ok(dirs.includes(path.join(home, "workspace-coder", "skills")), "应含 coder workspace skills");
|
|
39
|
+
assert.ok(dirs.includes(path.join(home, "agency-agents", "proj", "skills")), "应含 proj workspace skills");
|
|
40
|
+
// 去重:main 落到默认 workspace,不应产生重复项
|
|
41
|
+
assert.equal(new Set(dirs).size, dirs.length);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("openclaw.json 缺失时回退到顶层 skills + 默认 workspace skills,且不抛", async () => {
|
|
45
|
+
const dirs = resolveAgentSkillDirs(home, path.join(home, "does-not-exist.json"));
|
|
46
|
+
assert.ok(dirs.includes(path.join(home, "skills")));
|
|
47
|
+
assert.ok(dirs.includes(path.join(home, "workspace", "skills")));
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("非法 JSON 不抛,回退到默认目录", async () => {
|
|
51
|
+
const configPath = path.join(home, "openclaw.json");
|
|
52
|
+
await fs.writeFile(configPath, "{ not valid json ");
|
|
53
|
+
const dirs = resolveAgentSkillDirs(home, configPath);
|
|
54
|
+
assert.ok(dirs.includes(path.join(home, "skills")));
|
|
55
|
+
assert.ok(dirs.includes(path.join(home, "workspace", "skills")));
|
|
56
|
+
});
|
|
57
|
+
});
|
package/src/paths.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 集中管理插件用到的所有文件系统路径。
|
|
3
|
+
*
|
|
4
|
+
* 为什么集中:① 单测可注入临时目录;② openclaw 安全策略下插件不读环境变量,
|
|
5
|
+
* 路径在此固定,运行时不依赖外部配置。
|
|
6
|
+
*/
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
|
|
11
|
+
/** 所有可注入路径的集合;不传时回落到 `~/.openclaw` 下的默认位置。 */
|
|
12
|
+
export type PluginPaths = {
|
|
13
|
+
/** 事件日志队列:待上报事件追加写入;成功上报后清理已确认行。 */
|
|
14
|
+
eventsLogPath: string;
|
|
15
|
+
/** 配置同步状态:已装 skill 签名 + 缓存的标准配置。 */
|
|
16
|
+
syncStatePath: string;
|
|
17
|
+
/** 更新冷却期状态:skill@version → 上次尝试时间戳。 */
|
|
18
|
+
cooldownStatePath: string;
|
|
19
|
+
/** openclaw 扩展安装目录,用于扫描已装 skill。 */
|
|
20
|
+
extensionsDir: string;
|
|
21
|
+
/** openclaw 主配置文件路径(含 agents 列表),用于动态解析各 agent workspace 的 skills 目录。 */
|
|
22
|
+
openclawConfigPath: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** 默认根目录 `~/.openclaw`。 */
|
|
26
|
+
export function openclawHome(): string {
|
|
27
|
+
return path.join(os.homedir(), ".openclaw");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 解析所有 agent workspace 下的 skill 扫描目录。
|
|
32
|
+
*
|
|
33
|
+
* 来源:
|
|
34
|
+
* - 顶层全局 skills:`<home>/skills`
|
|
35
|
+
* - 默认 workspace:`<agents.defaults.workspace>/skills`(缺省为 `<home>/workspace`)
|
|
36
|
+
* - 各 agent:`<agents.list[].workspace>/skills`(未显式配置 workspace 的 agent 落到默认)
|
|
37
|
+
*
|
|
38
|
+
* openclaw.json 不存在 / 解析失败 / 字段缺失时,回退到「顶层 skills + 默认 workspace skills」,
|
|
39
|
+
* 至少不弱于历史行为,且整段被 try/catch 包裹,绝不抛。
|
|
40
|
+
*/
|
|
41
|
+
export function resolveAgentSkillDirs(home: string, configPath: string): string[] {
|
|
42
|
+
const dirs = new Set<string>();
|
|
43
|
+
// 永远纳入的兜底目录(即便 openclaw.json 缺失也能工作)。
|
|
44
|
+
dirs.add(path.join(home, "skills"));
|
|
45
|
+
const defaultWorkspaceFallback = path.join(home, "workspace");
|
|
46
|
+
dirs.add(path.join(defaultWorkspaceFallback, "skills"));
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
const raw = fs.readFileSync(configPath, "utf-8");
|
|
50
|
+
const cfg = JSON.parse(raw) as {
|
|
51
|
+
agents?: { defaults?: { workspace?: unknown }; list?: Array<{ workspace?: unknown }> };
|
|
52
|
+
};
|
|
53
|
+
const agents = cfg?.agents;
|
|
54
|
+
const defaultWs =
|
|
55
|
+
typeof agents?.defaults?.workspace === "string" ? agents.defaults.workspace : defaultWorkspaceFallback;
|
|
56
|
+
dirs.add(path.join(defaultWs, "skills"));
|
|
57
|
+
|
|
58
|
+
const list = Array.isArray(agents?.list) ? agents!.list! : [];
|
|
59
|
+
for (const a of list) {
|
|
60
|
+
const ws = typeof a?.workspace === "string" ? a.workspace : defaultWs;
|
|
61
|
+
dirs.add(path.join(ws, "skills"));
|
|
62
|
+
}
|
|
63
|
+
} catch {
|
|
64
|
+
// openclaw.json 不存在 / 非法 JSON / 权限不足 → 用上面的兜底目录,绝不影响插件启动。
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return [...dirs];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 生成一组路径。`overrides` 仅供测试注入(如指向临时目录)。
|
|
72
|
+
*/
|
|
73
|
+
export function resolvePaths(overrides?: Partial<PluginPaths>): PluginPaths {
|
|
74
|
+
const home = openclawHome();
|
|
75
|
+
const logsDir = path.join(home, "logs");
|
|
76
|
+
return {
|
|
77
|
+
eventsLogPath: path.join(logsDir, "skill-logger-plugin.jsonl"),
|
|
78
|
+
syncStatePath: path.join(logsDir, "skill-logger-plugin.sync.json"),
|
|
79
|
+
cooldownStatePath: path.join(logsDir, "skill-logger-plugin.cooldown.json"),
|
|
80
|
+
extensionsDir: path.join(home, "extensions"),
|
|
81
|
+
openclawConfigPath: path.join(home, "openclaw.json"),
|
|
82
|
+
...overrides,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { describe, it, beforeEach, afterEach } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { Reporter } from "./reporter.ts";
|
|
7
|
+
import type { PluginConfig, SkillEvent } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
const identityProvider = {
|
|
10
|
+
getIdentity: async () => ({ user_id: "", git_name: "n", git_email: "e", machine_id: "m" }),
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
function makeEvent(i: number): SkillEvent {
|
|
14
|
+
return { event_id: `id${i}`, event_type: "function_call", skill_name: "s", called_at: new Date().toISOString() };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
let dir: string;
|
|
18
|
+
let paths: { eventsLogPath: string };
|
|
19
|
+
|
|
20
|
+
beforeEach(async () => {
|
|
21
|
+
dir = path.join(os.tmpdir(), `slp-reporter-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
22
|
+
await fs.mkdir(dir, { recursive: true });
|
|
23
|
+
paths = {
|
|
24
|
+
eventsLogPath: path.join(dir, "events.jsonl"),
|
|
25
|
+
};
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
afterEach(async () => {
|
|
29
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
/** 缺文件视为空,匹配轮转模型下「上报成功即删除」的形态。 */
|
|
33
|
+
async function readEventsOrEmpty(p: string): Promise<string> {
|
|
34
|
+
try {
|
|
35
|
+
return await fs.readFile(p, "utf-8");
|
|
36
|
+
} catch {
|
|
37
|
+
return "";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 列出已轮转、待上报的日志文件(排除活跃的 events.jsonl)。 */
|
|
42
|
+
async function listRotated(d: string): Promise<string[]> {
|
|
43
|
+
try {
|
|
44
|
+
const entries = await fs.readdir(d);
|
|
45
|
+
return entries.filter((f) => f.startsWith("events.") && f.endsWith(".jsonl") && f !== "events.jsonl");
|
|
46
|
+
} catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
describe("Reporter.appendEvent", () => {
|
|
52
|
+
it("目录自动创建并追加写", async () => {
|
|
53
|
+
const r = new Reporter({ paths, getConfig: () => ({}), identityProvider });
|
|
54
|
+
await r.appendEvent(makeEvent(1));
|
|
55
|
+
await r.appendEvent(makeEvent(2));
|
|
56
|
+
const lines = (await fs.readFile(paths.eventsLogPath, "utf-8")).trim().split("\n");
|
|
57
|
+
assert.equal(lines.length, 2);
|
|
58
|
+
assert.equal(JSON.parse(lines[1]).event_id, "id2");
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe("Reporter.flush", () => {
|
|
63
|
+
it("未配置 reportBaseUrl 时不上报", async () => {
|
|
64
|
+
let called = 0;
|
|
65
|
+
const r = new Reporter({
|
|
66
|
+
paths,
|
|
67
|
+
getConfig: () => ({}),
|
|
68
|
+
identityProvider,
|
|
69
|
+
fetchImpl: async () => {
|
|
70
|
+
called++;
|
|
71
|
+
return { ok: true, status: 200 };
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
await r.appendEvent(makeEvent(1));
|
|
75
|
+
await r.flush();
|
|
76
|
+
assert.equal(called, 0);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("成功上报后清理本地日志,再次 flush 不重复发", async () => {
|
|
80
|
+
const sent: number[] = [];
|
|
81
|
+
const config: PluginConfig = { reportBaseUrl: "https://x" };
|
|
82
|
+
const r = new Reporter({
|
|
83
|
+
paths,
|
|
84
|
+
getConfig: () => config,
|
|
85
|
+
identityProvider,
|
|
86
|
+
fetchImpl: async (_url, init) => {
|
|
87
|
+
const body = JSON.parse(String(init.body));
|
|
88
|
+
sent.push(body.events.length);
|
|
89
|
+
return { ok: true, status: 200 };
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
await r.appendEvent(makeEvent(1));
|
|
93
|
+
await r.appendEvent(makeEvent(2));
|
|
94
|
+
await r.flush();
|
|
95
|
+
await r.flush(); // 无新事件
|
|
96
|
+
assert.deepEqual(sent, [2]);
|
|
97
|
+
// 轮转文件已全部上报并删除,活跃日志清空
|
|
98
|
+
assert.equal(await readEventsOrEmpty(paths.eventsLogPath), "");
|
|
99
|
+
assert.equal((await listRotated(dir)).length, 0);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("保留 flush 期间新追加的事件(轮转隔离读写)", async () => {
|
|
103
|
+
let appendedDuringFlush = false;
|
|
104
|
+
const r = new Reporter({
|
|
105
|
+
paths,
|
|
106
|
+
getConfig: () => ({ reportBaseUrl: "https://x" }),
|
|
107
|
+
identityProvider,
|
|
108
|
+
fetchImpl: async () => {
|
|
109
|
+
if (!appendedDuringFlush) {
|
|
110
|
+
appendedDuringFlush = true;
|
|
111
|
+
await fs.appendFile(paths.eventsLogPath, JSON.stringify(makeEvent(2)) + "\n");
|
|
112
|
+
}
|
|
113
|
+
return { ok: true, status: 200 };
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
await r.appendEvent(makeEvent(1));
|
|
117
|
+
await r.flush();
|
|
118
|
+
const lines = (await readEventsOrEmpty(paths.eventsLogPath)).trim().split("\n").filter(Boolean);
|
|
119
|
+
assert.equal(lines.length, 1);
|
|
120
|
+
assert.equal(JSON.parse(lines[0]).event_id, "id2");
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("上报失败保留轮转文件,下轮重试成功后清空", async () => {
|
|
124
|
+
let ok = false;
|
|
125
|
+
const r = new Reporter({
|
|
126
|
+
paths,
|
|
127
|
+
getConfig: () => ({ reportBaseUrl: "https://x" }),
|
|
128
|
+
identityProvider,
|
|
129
|
+
fetchImpl: async () => ({ ok, status: ok ? 200 : 500 }),
|
|
130
|
+
});
|
|
131
|
+
await r.appendEvent(makeEvent(1));
|
|
132
|
+
await r.flush(); // 失败:轮转文件保留待重试
|
|
133
|
+
assert.equal((await listRotated(dir)).length, 1);
|
|
134
|
+
ok = true;
|
|
135
|
+
await r.flush(); // 成功:清空
|
|
136
|
+
assert.equal((await listRotated(dir)).length, 0);
|
|
137
|
+
assert.equal(await readEventsOrEmpty(paths.eventsLogPath), "");
|
|
138
|
+
});
|
|
139
|
+
});
|