@mebular/mcp 0.2.2 → 0.2.4
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/bin/mebular.mjs +145 -15
- package/package.json +3 -3
- package/src/admin.mjs +7 -8
- package/src/clients.mjs +472 -34
- package/src/config-schema.mjs +0 -2
- package/src/config.mjs +110 -23
- package/src/home-identity.mjs +389 -0
- package/src/profiles.mjs +18 -1
- package/src/provision.mjs +80 -19
- package/src/runtime-supervisor.mjs +24 -0
- package/src/serve.mjs +34 -1
- package/src/server.mjs +20 -5
- package/src/tools.mjs +20 -17
- package/src/version.mjs +1 -1
package/src/clients.mjs
CHANGED
|
@@ -19,13 +19,15 @@
|
|
|
19
19
|
//
|
|
20
20
|
// 纯函数式:home/cwd/platform/env/run 可注入,便于单元测试(不触碰真实用户目录)。
|
|
21
21
|
|
|
22
|
+
import { createHash } from 'node:crypto';
|
|
22
23
|
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
23
|
-
import { chmod, copyFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
24
|
+
import { chmod, copyFile, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
24
25
|
import { exec, spawnSync } from 'node:child_process';
|
|
25
26
|
import { promisify } from 'node:util';
|
|
26
|
-
import { homedir } from 'node:os';
|
|
27
|
+
import { homedir, tmpdir } from 'node:os';
|
|
27
28
|
import { delimiter, dirname, join, sep } from 'node:path';
|
|
28
29
|
import { fileURLToPath } from 'node:url';
|
|
30
|
+
import { APP_VERSION } from './version.mjs';
|
|
29
31
|
|
|
30
32
|
// ---------------------------------------------------------------------------
|
|
31
33
|
// 格式适配器(落面形状的唯一真源;A-17 以 `opencode mcp add` 产出为准)
|
|
@@ -243,7 +245,7 @@ export function builtinAssistants(options = {}) {
|
|
|
243
245
|
'opencode.managed.json 为 App 所有且会被重写,禁写',
|
|
244
246
|
'opencode mcp list 经运行服务回答,只读但勿频繁调用',
|
|
245
247
|
],
|
|
246
|
-
skillsDirs: [join(userHome, '.config', 'opencode', 'skills')],
|
|
248
|
+
skillsDirs: [join(userHome, '.config', 'opencode', 'skills'), join(cwd, '.opencode', 'skills')],
|
|
247
249
|
reuseOf: 'opencode',
|
|
248
250
|
note: 'OpenChamber 复用 OpenCode 的 global 配置(接一次即可)',
|
|
249
251
|
},
|
|
@@ -253,6 +255,7 @@ export function builtinAssistants(options = {}) {
|
|
|
253
255
|
probe: {
|
|
254
256
|
signals: [
|
|
255
257
|
{ kind: 'config-path', paths: [hermesPath] },
|
|
258
|
+
{ kind: 'dir', paths: [join(userHome, '.hermes')] },
|
|
256
259
|
{ kind: 'cli', command: 'hermes --version', timeoutMs: 2500 },
|
|
257
260
|
{ kind: 'path', paths: [join(userHome, '.local', 'bin', 'hermes')] },
|
|
258
261
|
],
|
|
@@ -267,7 +270,7 @@ export function builtinAssistants(options = {}) {
|
|
|
267
270
|
'Hermes 无法 env 沙箱(HERMES_CONFIG_PATH 被剥离)→ 写前字节级备份 + 失败回滚为硬要求',
|
|
268
271
|
'写入仅经 `hermes config set --force`(ruamel 保注释);未知子键必须 --force',
|
|
269
272
|
],
|
|
270
|
-
skillsDirs: [join(userHome, '.
|
|
273
|
+
skillsDirs: [join(userHome, '.hermes', 'skills')],
|
|
271
274
|
reuseOf: null,
|
|
272
275
|
note: 'Hermes 的 MCP 配置在 ~/.hermes/config.yaml',
|
|
273
276
|
},
|
|
@@ -285,19 +288,19 @@ export function builtinAssistants(options = {}) {
|
|
|
285
288
|
verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
|
|
286
289
|
activation: { kind: 'user-reload', note: 'OpenCode 侧重载/重启后生效' },
|
|
287
290
|
risks: ['opencode mcp list 经运行服务回答,只读但勿频繁调用'],
|
|
288
|
-
skillsDirs: [join(userHome, '.config', 'opencode', 'skills'), join(
|
|
291
|
+
skillsDirs: [join(userHome, '.config', 'opencode', 'skills'), join(cwd, '.opencode', 'skills')],
|
|
289
292
|
reuseOf: null,
|
|
290
293
|
note: null,
|
|
291
294
|
},
|
|
292
295
|
{
|
|
293
296
|
id: 'claude-code', name: 'Claude Code', kind: 'file', format: 'json-mcpServers',
|
|
294
297
|
landing: { primaryPath: join(userHome, '.claude.json'), keyPath: 'mcpServers.mebular', forbiddenPaths: [], format: 'json-mcpServers', httpShape: 'claude-http' },
|
|
295
|
-
probe: { signals: [{ kind: 'config-path', paths: [join(userHome, '.claude.json')] }, { kind: 'cli', command: 'claude --version', timeoutMs: 1500 }] },
|
|
298
|
+
probe: { signals: [{ kind: 'config-path', paths: [join(userHome, '.claude.json')] }, { kind: 'dir', paths: [join(userHome, '.claude')] }, { kind: 'cli', command: 'claude --version', timeoutMs: 1500 }] },
|
|
296
299
|
writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
|
|
297
300
|
verify: { configReadback: true },
|
|
298
301
|
activation: { kind: 'user-reload', note: '重启 Claude Code 后生效' },
|
|
299
302
|
risks: [],
|
|
300
|
-
skillsDirs: [join(userHome, '.
|
|
303
|
+
skillsDirs: [join(userHome, '.claude', 'skills'), join(cwd, '.claude', 'skills')],
|
|
301
304
|
reuseOf: null, note: null,
|
|
302
305
|
},
|
|
303
306
|
{
|
|
@@ -317,17 +320,24 @@ export function builtinAssistants(options = {}) {
|
|
|
317
320
|
writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
|
|
318
321
|
verify: { configReadback: true },
|
|
319
322
|
activation: { kind: 'user-reload', note: '重启 Cursor 后生效' },
|
|
320
|
-
risks: ['HTTP /mcp 默认只监听回环:客户端与守护须**同机**(跨机请在 config 里启用 TLS+鉴权并用可达主机名)'],
|
|
323
|
+
risks: ['HTTP /mcp 默认只监听回环:客户端与守护须**同机**(跨机请在 config 里启用 TLS+鉴权并用可达主机名)'],
|
|
324
|
+
skillsDirs: [join(userHome, '.cursor', 'skills'), join(cwd, '.cursor', 'skills')], reuseOf: null, note: null,
|
|
321
325
|
},
|
|
322
326
|
{
|
|
323
327
|
id: 'dsh', name: 'DeepSeek Harness (DSH)', kind: 'file', format: 'dsh',
|
|
324
328
|
landing: { primaryPath: join(cwd, '.dsh', 'cordis.yml'), keyPath: 'plugins', forbiddenPaths: [], format: 'dsh' },
|
|
325
|
-
probe: {
|
|
329
|
+
probe: {
|
|
330
|
+
signals: [
|
|
331
|
+
{ kind: 'config-path', paths: [join(cwd, '.dsh', 'cordis.yml')] },
|
|
332
|
+
// DSH_HOME 默认 ~/.dsh;全局安装也要能被自动检测(Skill 仍写 ~/.agents/skills)。
|
|
333
|
+
{ kind: 'dir', paths: [join(cwd, '.dsh'), join(userHome, '.dsh')] },
|
|
334
|
+
],
|
|
335
|
+
},
|
|
326
336
|
writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
|
|
327
337
|
verify: { configReadback: true },
|
|
328
338
|
activation: { kind: 'user-reload', note: '重启 DSH 后生效' },
|
|
329
339
|
risks: ['DSH 配置为 YAML 插件列表:结构未知时不自动改写', 'HTTP /mcp 默认只监听回环:客户端与守护须同机(跨机请启用 TLS+鉴权并用可达主机名)'],
|
|
330
|
-
skillsDirs: [join(
|
|
340
|
+
skillsDirs: [join(userHome, '.agents', 'skills'), join(cwd, '.dsh', 'skills')], reuseOf: null, note: null,
|
|
331
341
|
},
|
|
332
342
|
{
|
|
333
343
|
id: 'generic', name: '其他 AI 助手(复制片段)', kind: 'snippet', format: 'generic-snippet',
|
|
@@ -1032,6 +1042,19 @@ async function connectViaCli(assistant, options = {}) {
|
|
|
1032
1042
|
};
|
|
1033
1043
|
}
|
|
1034
1044
|
|
|
1045
|
+
/** 接入成功后顺带 ensure 该客户端的 Skill;失败只记录,绝不阻断 MCP 接入。 */
|
|
1046
|
+
async function attachSkills(result, id, options = {}) {
|
|
1047
|
+
if (!result?.ok || options.skipSkills === true) return result;
|
|
1048
|
+
const assistant = descriptorFor(id, options);
|
|
1049
|
+
if ((assistant?.skillsDirs ?? []).length === 0) return result;
|
|
1050
|
+
try {
|
|
1051
|
+
result.skills = await installSkills(id, options);
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
result.skills = { ok: false, id, reason: `Skill 安装失败:${redactSecrets(error?.message ?? error)}` };
|
|
1054
|
+
}
|
|
1055
|
+
return result;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1035
1058
|
/** 接入:merge-key(备份 → 原子写)/ cli-set(官方 CLI)/ manual(仅片段)。 */
|
|
1036
1059
|
export async function connectClient(id, options = {}) {
|
|
1037
1060
|
const assistant = descriptorFor(id, options);
|
|
@@ -1044,7 +1067,7 @@ export async function connectClient(id, options = {}) {
|
|
|
1044
1067
|
if (isForbidden(assistant, primary)) {
|
|
1045
1068
|
return { ok: false, reason: `禁写路径(landing.forbiddenPaths):${primary}` };
|
|
1046
1069
|
}
|
|
1047
|
-
if (strategy === 'cli-set') return connectViaCli(assistant, options);
|
|
1070
|
+
if (strategy === 'cli-set') return attachSkills(await connectViaCli(assistant, options), id, options);
|
|
1048
1071
|
const existing = safeReadText(primary);
|
|
1049
1072
|
const merged = computeMerged(assistant, existing, options);
|
|
1050
1073
|
if (merged.error) {
|
|
@@ -1052,7 +1075,7 @@ export async function connectClient(id, options = {}) {
|
|
|
1052
1075
|
}
|
|
1053
1076
|
const preview = lineDiff(existing ?? '', merged.text);
|
|
1054
1077
|
if (!merged.changed) {
|
|
1055
|
-
return { ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' };
|
|
1078
|
+
return attachSkills({ ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' }, id, options);
|
|
1056
1079
|
}
|
|
1057
1080
|
const backupPath = existing !== null ? `${primary}.bak-${tsStamp()}` : null;
|
|
1058
1081
|
if (backupPath) await copyFile(primary, backupPath);
|
|
@@ -1063,7 +1086,7 @@ export async function connectClient(id, options = {}) {
|
|
|
1063
1086
|
if (backupPath) await copyFile(backupPath, primary); // 失败回滚
|
|
1064
1087
|
return { ok: false, changed: false, rolledBack: Boolean(backupPath), backupPath, reason: `写入失败已回滚:${redactSecrets(error?.message ?? error)}` };
|
|
1065
1088
|
}
|
|
1066
|
-
return { ok: true, changed: true, configPath: primary, backupPath, preview };
|
|
1089
|
+
return attachSkills({ ok: true, changed: true, configPath: primary, backupPath, preview }, id, options);
|
|
1067
1090
|
}
|
|
1068
1091
|
|
|
1069
1092
|
/** 回滚:显式备份优先;否则最近一次备份;无备份则删除 mebular 条目(DSH 除外)。 */
|
|
@@ -1206,37 +1229,452 @@ export async function verifyAssistant(id, options = {}) {
|
|
|
1206
1229
|
}
|
|
1207
1230
|
|
|
1208
1231
|
// ---------------------------------------------------------------------------
|
|
1209
|
-
// Skill
|
|
1232
|
+
// Skill 安装(单一实现:缺失安装 / 受管旧版更新 / 用户修改保留 / force 覆盖)
|
|
1210
1233
|
// ---------------------------------------------------------------------------
|
|
1211
1234
|
|
|
1235
|
+
/**
|
|
1236
|
+
* 受管版本标记:每个 Skill 目录一份 `.mebular-skill.json`。
|
|
1237
|
+
*
|
|
1238
|
+
* - 有标记 ∧ `managedBy=mebular` ∧ 文件哈希与标记一致 → Mebular 管理且用户未改;
|
|
1239
|
+
* - 无标记 / 哈希不一致 → 用户自定义或用户改过 → 默认保留;
|
|
1240
|
+
* - `force`(自动修复)→ 完整覆盖已知 Skill 文件(不删除用户额外文件)。
|
|
1241
|
+
*
|
|
1242
|
+
* `files` 记录 **Mebular 写入的受管文件**哈希(含 `mcp/` 片段),因此「受管旧版」既能按版本号识别,
|
|
1243
|
+
* 也能识别同版本但内容漂移的安装;用户额外添加的文件不参与判定,也不会被删除。
|
|
1244
|
+
*/
|
|
1245
|
+
export const SKILL_MANIFEST_FILE = '.mebular-skill.json';
|
|
1246
|
+
const SKILL_MANIFEST_SCHEMA = 1;
|
|
1247
|
+
const SKILL_SPECS = [
|
|
1248
|
+
{
|
|
1249
|
+
name: 'mebular-memory',
|
|
1250
|
+
files: [
|
|
1251
|
+
['SKILL.md', 'SKILL.md'],
|
|
1252
|
+
['MEMORY_POLICY.md', 'MEMORY_POLICY.md'],
|
|
1253
|
+
['SETUP.md', 'SETUP.md'],
|
|
1254
|
+
],
|
|
1255
|
+
copyDirs: [['mcp', 'mcp']],
|
|
1256
|
+
},
|
|
1257
|
+
{
|
|
1258
|
+
name: 'mebular-tasks',
|
|
1259
|
+
files: [
|
|
1260
|
+
['tasks/SKILL.md', 'SKILL.md'],
|
|
1261
|
+
['SETUP.md', 'SETUP.md'],
|
|
1262
|
+
],
|
|
1263
|
+
copyDirs: [],
|
|
1264
|
+
},
|
|
1265
|
+
];
|
|
1266
|
+
|
|
1212
1267
|
function moduleSkillRoot() {
|
|
1213
1268
|
return join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skill');
|
|
1214
1269
|
}
|
|
1215
1270
|
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
const desc = descriptorFor(id, options);
|
|
1219
|
-
if (!desc) return { ok: false, reason: `未知客户端:${id}` };
|
|
1220
|
-
const dirs = (desc.skillsDirs ?? []).filter(Boolean);
|
|
1221
|
-
if (dirs.length === 0) return { ok: false, reason: '该客户端没有已知的 Skill 目录' };
|
|
1222
|
-
const candidates = [
|
|
1271
|
+
function skillRootCandidates(options = {}) {
|
|
1272
|
+
return [
|
|
1223
1273
|
options.skillRoot,
|
|
1224
1274
|
moduleSkillRoot(),
|
|
1225
1275
|
join(options.repoRoot ?? process.cwd(), 'packages', 'skill'),
|
|
1226
1276
|
].filter((p) => typeof p === 'string' && p.length > 0);
|
|
1227
|
-
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
function resolveSkillRoot(options = {}) {
|
|
1280
|
+
return skillRootCandidates(options).find((p) => existsSync(join(p, 'SKILL.md'))) ?? null;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
function skillSourceVersion(rootDir) {
|
|
1284
|
+
try {
|
|
1285
|
+
const pkg = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf-8'));
|
|
1286
|
+
if (typeof pkg.version === 'string' && pkg.version.length > 0) return pkg.version;
|
|
1287
|
+
} catch {
|
|
1288
|
+
// 独立/测试 Skill 源可以没有 package.json:回落到 MCP 对外版本。
|
|
1289
|
+
}
|
|
1290
|
+
return APP_VERSION;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
function sha256Buffer(buffer) {
|
|
1294
|
+
return createHash('sha256').update(buffer).digest('hex');
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
function listRelativeFiles(root) {
|
|
1298
|
+
if (!existsSync(root)) return [];
|
|
1299
|
+
const out = [];
|
|
1300
|
+
const walk = (dir, prefix) => {
|
|
1301
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1302
|
+
if (entry.name === SKILL_MANIFEST_FILE || entry.name === '.DS_Store') continue;
|
|
1303
|
+
const rel = prefix.length > 0 ? `${prefix}/${entry.name}` : entry.name;
|
|
1304
|
+
if (entry.isDirectory()) walk(join(dir, entry.name), rel);
|
|
1305
|
+
else if (entry.isFile()) out.push(rel);
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
walk(root, '');
|
|
1309
|
+
return out;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
function hashSkillDir(dir) {
|
|
1313
|
+
const out = {};
|
|
1314
|
+
for (const rel of listRelativeFiles(dir)) {
|
|
1315
|
+
out[rel] = sha256Buffer(readFileSync(join(dir, ...rel.split('/'))));
|
|
1316
|
+
}
|
|
1317
|
+
return out;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
/**
|
|
1321
|
+
* 受管文件相对路径校验(POSIX / Windows 共用):
|
|
1322
|
+
* 拒绝绝对路径、盘符、反斜杠分隔、空段、`.`/`..` 段与非字符串。
|
|
1323
|
+
* 只用于 `marker.files` 的清理;不安全的 key 直接跳过,绝不触碰 Skill 目录外。
|
|
1324
|
+
*/
|
|
1325
|
+
export function isSafeManagedRelPath(rel) {
|
|
1326
|
+
if (typeof rel !== 'string' || rel.length === 0 || rel.includes('\0') || rel.includes('\\')) return false;
|
|
1327
|
+
if (rel.startsWith('/') || /^[A-Za-z]:/.test(rel)) return false;
|
|
1328
|
+
return rel.split('/').every((part) => part.length > 0 && part !== '.' && part !== '..');
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
function readSkillMarker(dir) {
|
|
1332
|
+
try {
|
|
1333
|
+
const data = JSON.parse(readFileSync(join(dir, SKILL_MANIFEST_FILE), 'utf-8'));
|
|
1334
|
+
if (data?.schema !== SKILL_MANIFEST_SCHEMA || data?.managedBy !== 'mebular') return null;
|
|
1335
|
+
if (data.files === null || typeof data.files !== 'object' || Array.isArray(data.files)) return null;
|
|
1336
|
+
const files = {};
|
|
1337
|
+
for (const [key, value] of Object.entries(data.files)) {
|
|
1338
|
+
if (typeof value === 'string') files[key] = value;
|
|
1339
|
+
}
|
|
1340
|
+
return { ...data, files };
|
|
1341
|
+
} catch {
|
|
1342
|
+
return null;
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
function skillSourcePairs(rootDir, spec) {
|
|
1347
|
+
const pairs = [];
|
|
1348
|
+
for (const [src, rel] of spec.files) {
|
|
1349
|
+
const abs = join(rootDir, ...src.split('/'));
|
|
1350
|
+
if (!existsSync(abs)) throw new Error(`Skill 源缺少 ${src}`);
|
|
1351
|
+
pairs.push([abs, rel]);
|
|
1352
|
+
}
|
|
1353
|
+
for (const [srcDir, relDir] of spec.copyDirs ?? []) {
|
|
1354
|
+
const absDir = join(rootDir, srcDir);
|
|
1355
|
+
if (!existsSync(absDir)) throw new Error(`Skill 源缺少 ${srcDir}/(Skill 承诺随包安装接入片段)`);
|
|
1356
|
+
for (const rel of listRelativeFiles(absDir)) {
|
|
1357
|
+
pairs.push([join(absDir, ...rel.split('/')), `${relDir}/${rel}`]);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
return pairs;
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
function hashesForPairs(pairs) {
|
|
1364
|
+
return Object.fromEntries(pairs.map(([abs, rel]) => [rel, sha256Buffer(readFileSync(abs))]));
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
async function writeSkillFiles(dir, pairs, marker, { version, source, skill, managedHashes }) {
|
|
1368
|
+
for (const [abs, rel] of pairs) {
|
|
1369
|
+
const dest = join(dir, ...rel.split('/'));
|
|
1370
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
1371
|
+
await copyFile(abs, dest);
|
|
1372
|
+
}
|
|
1373
|
+
// 受管旧版的多余文件(例如上一版有、这一版已移除)只按旧标记清理;绝不扫描/删除用户文件。
|
|
1374
|
+
if (marker) {
|
|
1375
|
+
const keep = new Set(pairs.map(([, rel]) => rel));
|
|
1376
|
+
for (const rel of Object.keys(marker.files ?? {})) {
|
|
1377
|
+
if (keep.has(rel) || !isSafeManagedRelPath(rel)) continue;
|
|
1378
|
+
await rm(join(dir, ...rel.split('/')), { force: true });
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
const files = managedHashes ?? hashesForPairs(pairs);
|
|
1382
|
+
await writeFile(join(dir, SKILL_MANIFEST_FILE), `${JSON.stringify({
|
|
1383
|
+
schema: SKILL_MANIFEST_SCHEMA,
|
|
1384
|
+
managedBy: 'mebular',
|
|
1385
|
+
skill,
|
|
1386
|
+
version,
|
|
1387
|
+
installedAt: new Date().toISOString(),
|
|
1388
|
+
source,
|
|
1389
|
+
files,
|
|
1390
|
+
}, null, 2)}\n`, 'utf-8');
|
|
1391
|
+
return files;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
async function installSkillSpec(rootDir, targetDir, spec, { force = false, version, source } = {}) {
|
|
1395
|
+
const dir = join(targetDir, spec.name);
|
|
1396
|
+
const existed = existsSync(join(dir, 'SKILL.md'));
|
|
1397
|
+
const marker = existed ? readSkillMarker(dir) : null;
|
|
1398
|
+
const currentHashes = existed ? hashSkillDir(dir) : {};
|
|
1399
|
+
const pairs = skillSourcePairs(rootDir, spec);
|
|
1400
|
+
const sourceHashes = hashesForPairs(pairs);
|
|
1401
|
+
|
|
1402
|
+
if (existed && force !== true) {
|
|
1403
|
+
if (!marker) return { name: spec.name, status: 'kept', dir, reason: '无受管标记(用户自定义),未覆盖' };
|
|
1404
|
+
// 只比较标记登记的受管文件;用户额外添加的文件不阻止更新,也不会被删除。
|
|
1405
|
+
const managedUnchanged = Object.entries(marker.files).every(([rel, hash]) => currentHashes[rel] === hash);
|
|
1406
|
+
if (!managedUnchanged) {
|
|
1407
|
+
return { name: spec.name, status: 'kept', dir, reason: '文件与受管标记不一致(用户修改过),未覆盖' };
|
|
1408
|
+
}
|
|
1409
|
+
const sourceCurrent = Object.entries(sourceHashes).every(([rel, hash]) => marker.files[rel] === hash);
|
|
1410
|
+
if (marker.version === version && sourceCurrent) {
|
|
1411
|
+
return { name: spec.name, status: 'unchanged', dir, version };
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
await writeSkillFiles(dir, pairs, marker, { version, source, skill: spec.name, managedHashes: sourceHashes });
|
|
1416
|
+
return { name: spec.name, status: existed ? 'updated' : 'installed', dir, version };
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
function summarizeSkillResults(targetDir, results, { version, source } = {}) {
|
|
1420
|
+
const failed = results.filter((r) => r.status === 'failed');
|
|
1421
|
+
const by = (status) => results.filter((r) => r.status === status).map((r) => r.dir);
|
|
1422
|
+
let status = 'unchanged';
|
|
1423
|
+
if (failed.length > 0) status = 'failed';
|
|
1424
|
+
else if (results.some((r) => r.status === 'installed')) status = 'installed';
|
|
1425
|
+
else if (results.some((r) => r.status === 'updated')) status = 'updated';
|
|
1426
|
+
else if (results.some((r) => r.status === 'kept')) status = 'kept';
|
|
1427
|
+
return {
|
|
1428
|
+
ok: failed.length === 0,
|
|
1429
|
+
status,
|
|
1430
|
+
targetDir,
|
|
1431
|
+
version: version ?? null,
|
|
1432
|
+
source: source ?? null,
|
|
1433
|
+
installed: by('installed'),
|
|
1434
|
+
updated: by('updated'),
|
|
1435
|
+
kept: by('kept'),
|
|
1436
|
+
unchanged: by('unchanged'),
|
|
1437
|
+
skills: results,
|
|
1438
|
+
...(failed.length > 0 ? { reason: failed.map((r) => `${r.name}: ${r.reason ?? '安装失败'}`).join(';') } : {}),
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/** 安装到指定目录(install.mjs / 显式安装共用;默认保留用户修改,force 覆盖)。 */
|
|
1443
|
+
export async function installSkillsToDir(targetDir, options = {}) {
|
|
1444
|
+
if (typeof targetDir !== 'string' || targetDir.length === 0) {
|
|
1445
|
+
return { ok: false, reason: '缺少 Skill 目标目录', skills: [], installed: [], updated: [], kept: [], unchanged: [] };
|
|
1446
|
+
}
|
|
1447
|
+
const rootDir = resolveSkillRoot(options);
|
|
1228
1448
|
if (!rootDir) {
|
|
1229
|
-
return {
|
|
1449
|
+
return {
|
|
1450
|
+
ok: false,
|
|
1451
|
+
reason: `未找到 Skill 源(试过:${skillRootCandidates(options).join('、')})`,
|
|
1452
|
+
targetDir,
|
|
1453
|
+
skills: [],
|
|
1454
|
+
installed: [],
|
|
1455
|
+
updated: [],
|
|
1456
|
+
kept: [],
|
|
1457
|
+
unchanged: [],
|
|
1458
|
+
};
|
|
1230
1459
|
}
|
|
1231
|
-
const
|
|
1232
|
-
const
|
|
1233
|
-
const
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
return
|
|
1460
|
+
const version = skillSourceVersion(rootDir);
|
|
1461
|
+
const source = 'mebular';
|
|
1462
|
+
const results = [];
|
|
1463
|
+
for (const spec of SKILL_SPECS) {
|
|
1464
|
+
try {
|
|
1465
|
+
results.push(await installSkillSpec(rootDir, targetDir, spec, { force: options.force === true, version, source }));
|
|
1466
|
+
} catch (error) {
|
|
1467
|
+
results.push({ name: spec.name, status: 'failed', dir: join(targetDir, spec.name), reason: redactSecrets(error?.message ?? error) });
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
return summarizeSkillResults(targetDir, results, { version, source });
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
function preferredSkillTarget(dirs) {
|
|
1474
|
+
// 与既有 installSkills 行为一致:descriptor 的首个目录 = 客户端全局 Skill 目录。
|
|
1475
|
+
// 不优先挑“已存在的 cwd 目录”,否则 cwd=仓库时会误把 Skill 写进项目。
|
|
1476
|
+
return dirs[0];
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
/**
|
|
1480
|
+
* 安装 mebular-memory + mebular-tasks 到该客户端首个已知 Skill 目录。
|
|
1481
|
+
* 默认语义 = ensure:缺失安装、受管旧版更新、用户修改/无标记保留;`force:true` 完整覆盖。
|
|
1482
|
+
*/
|
|
1483
|
+
export async function installSkills(id, options = {}) {
|
|
1484
|
+
const desc = descriptorFor(id, options);
|
|
1485
|
+
if (!desc) return { ok: false, id, reason: `未知客户端:${id}`, skills: [], installed: [], updated: [], kept: [], unchanged: [] };
|
|
1486
|
+
const dirs = (desc.skillsDirs ?? []).filter(Boolean);
|
|
1487
|
+
if (dirs.length === 0) return { ok: false, id, reason: '该客户端没有已知的 Skill 目录', skills: [], installed: [], updated: [], kept: [], unchanged: [] };
|
|
1488
|
+
const target = options.skillDir ?? preferredSkillTarget(dirs);
|
|
1489
|
+
const result = await installSkillsToDir(target, options);
|
|
1490
|
+
return { ...result, id };
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
function skillStateDetected(state) {
|
|
1494
|
+
return Boolean(state?.anySignalHit || state?.installed);
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/**
|
|
1498
|
+
* 对所有**已检测到的客户端**做 Skill ensure(单一实现)。
|
|
1499
|
+
*
|
|
1500
|
+
* - 目录只来自 descriptor 的 `skillsDirs`;未检测到的客户端不创建任何目录;
|
|
1501
|
+
* - 同一 Skill 目录被多个客户端共享时只处理一次(OpenCode / OpenChamber);
|
|
1502
|
+
* - 单个 Skill/客户端失败只记录,不抛出。
|
|
1503
|
+
*/
|
|
1504
|
+
export async function ensureSkills(options = {}) {
|
|
1505
|
+
const wanted = Array.isArray(options.clientIds) ? new Set(options.clientIds) : null;
|
|
1506
|
+
const reg = registry(options);
|
|
1507
|
+
const clients = [];
|
|
1508
|
+
const seenTargets = new Map();
|
|
1509
|
+
for (const assistant of reg.assistants) {
|
|
1510
|
+
if (wanted && !wanted.has(assistant.id)) continue;
|
|
1511
|
+
const dirs = (assistant.skillsDirs ?? []).filter(Boolean);
|
|
1512
|
+
if (dirs.length === 0) {
|
|
1513
|
+
clients.push({ id: assistant.id, name: assistant.name, detected: false, status: 'skipped', reason: '该客户端没有已知的 Skill 目录' });
|
|
1514
|
+
continue;
|
|
1515
|
+
}
|
|
1516
|
+
let state;
|
|
1517
|
+
try {
|
|
1518
|
+
state = await assistantStateAsync(assistant, options);
|
|
1519
|
+
} catch (error) {
|
|
1520
|
+
clients.push({ id: assistant.id, name: assistant.name, detected: false, status: 'failed', reason: `检测失败:${redactSecrets(error?.message ?? error)}` });
|
|
1521
|
+
continue;
|
|
1522
|
+
}
|
|
1523
|
+
if (!skillStateDetected(state)) {
|
|
1524
|
+
clients.push({ id: assistant.id, name: assistant.name, detected: false, status: 'skipped', reason: '未检测到该客户端' });
|
|
1525
|
+
continue;
|
|
1526
|
+
}
|
|
1527
|
+
const target = preferredSkillTarget(dirs);
|
|
1528
|
+
if (seenTargets.has(target)) {
|
|
1529
|
+
clients.push({
|
|
1530
|
+
id: assistant.id, name: assistant.name, detected: true, status: 'skipped',
|
|
1531
|
+
targetDir: target, reason: `与 ${seenTargets.get(target)} 共享 Skill 目录,已由前者处理`,
|
|
1532
|
+
});
|
|
1533
|
+
continue;
|
|
1534
|
+
}
|
|
1535
|
+
seenTargets.set(target, assistant.id);
|
|
1536
|
+
try {
|
|
1537
|
+
const result = await installSkills(assistant.id, options);
|
|
1538
|
+
clients.push({ ...result, name: assistant.name, detected: true });
|
|
1539
|
+
} catch (error) {
|
|
1540
|
+
clients.push({
|
|
1541
|
+
id: assistant.id, name: assistant.name, detected: true, status: 'failed',
|
|
1542
|
+
targetDir: target, reason: redactSecrets(error?.message ?? error), skills: [],
|
|
1543
|
+
installed: [], updated: [], kept: [], unchanged: [],
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
const failed = clients.filter((c) => c.status === 'failed');
|
|
1548
|
+
return {
|
|
1549
|
+
ok: failed.length === 0,
|
|
1550
|
+
clients,
|
|
1551
|
+
summary: {
|
|
1552
|
+
total: clients.length,
|
|
1553
|
+
installed: clients.filter((c) => c.status === 'installed').length,
|
|
1554
|
+
updated: clients.filter((c) => c.status === 'updated').length,
|
|
1555
|
+
kept: clients.filter((c) => c.status === 'kept').length,
|
|
1556
|
+
unchanged: clients.filter((c) => c.status === 'unchanged').length,
|
|
1557
|
+
skipped: clients.filter((c) => c.status === 'skipped').length,
|
|
1558
|
+
failed: failed.length,
|
|
1559
|
+
},
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
/**
|
|
1564
|
+
* 启动/初始化收敛入口(**永不阻断**调用方):
|
|
1565
|
+
* 测试环境默认关闭,避免验证脚本写真实 `~/.config/opencode/skills`;
|
|
1566
|
+
* 需要显式验证自动接线时设置 `MEBULAR_SKILL_AUTOWIRE=1`。
|
|
1567
|
+
*/
|
|
1568
|
+
export async function autoEnsureSkills(options = {}) {
|
|
1569
|
+
const forcedOn = process.env.MEBULAR_SKILL_AUTOWIRE === '1';
|
|
1570
|
+
// 安全网:临时 MEBULAR home + 真实用户主目录 = 验证脚本形态,绝不写真实 Skill 目录。
|
|
1571
|
+
const tempHomeWithRealUser = typeof options.home === 'string'
|
|
1572
|
+
&& options.home.startsWith(tmpdir())
|
|
1573
|
+
&& typeof options.userHome === 'string'
|
|
1574
|
+
&& !options.userHome.startsWith(tmpdir());
|
|
1575
|
+
const disabled = options.enabled === false
|
|
1576
|
+
|| (!forcedOn && (process.env.MEBULAR_SKILL_AUTOWIRE === '0'
|
|
1577
|
+
|| process.env.JEST_WORKER_ID !== undefined
|
|
1578
|
+
|| process.env.NODE_ENV === 'test'
|
|
1579
|
+
|| tempHomeWithRealUser));
|
|
1580
|
+
if (disabled) {
|
|
1581
|
+
return { ok: true, skipped: true, reason: 'skill auto-wire disabled', clients: [], summary: { total: 0, installed: 0, updated: 0, kept: 0, unchanged: 0, skipped: 0, failed: 0 } };
|
|
1582
|
+
}
|
|
1583
|
+
try {
|
|
1584
|
+
return await ensureSkills(options);
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
return {
|
|
1587
|
+
ok: false,
|
|
1588
|
+
skipped: false,
|
|
1589
|
+
reason: `Skill 自动安装失败:${redactSecrets(error?.message ?? error)}`,
|
|
1590
|
+
clients: [],
|
|
1591
|
+
summary: { total: 0, installed: 0, updated: 0, kept: 0, unchanged: 0, skipped: 0, failed: 1 },
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
/**
|
|
1597
|
+
* 自动修复(只做客户端接入):
|
|
1598
|
+
* 对**已检测到的**助手逐个重新执行 MCP 接入(connectClient)+ Skill force 安装 + 验证。
|
|
1599
|
+
* 不触碰 memory / identity / cloud / task / audit;单项失败不影响其他项。
|
|
1600
|
+
*/
|
|
1601
|
+
export async function repairClients(options = {}) {
|
|
1602
|
+
const list = await listAssistantsAsync({ ...options, refresh: true });
|
|
1603
|
+
const candidates = list.assistants.filter((assistant) => skillStateDetected(assistant));
|
|
1604
|
+
const clients = [];
|
|
1605
|
+
const seenSkillTargets = new Map();
|
|
1606
|
+
for (const assistant of candidates) {
|
|
1607
|
+
const base = {
|
|
1608
|
+
id: assistant.id,
|
|
1609
|
+
name: assistant.name,
|
|
1610
|
+
detected: true,
|
|
1611
|
+
stateBefore: assistant.state ?? null,
|
|
1612
|
+
connect: null,
|
|
1613
|
+
skills: null,
|
|
1614
|
+
verify: null,
|
|
1615
|
+
stateAfter: null,
|
|
1616
|
+
};
|
|
1617
|
+
if (assistant.writer?.strategy === 'manual' || !assistant.landing?.primaryPath) {
|
|
1618
|
+
clients.push({ ...base, connect: { ok: false, skipped: true, reason: '该客户端不支持自动写入:只提供片段' }, skills: { ok: true, skipped: true, reason: '无自动接入目录' } });
|
|
1619
|
+
continue;
|
|
1620
|
+
}
|
|
1621
|
+
try {
|
|
1622
|
+
base.connect = await connectClient(assistant.id, { ...options, skipSkills: true });
|
|
1623
|
+
} catch (error) {
|
|
1624
|
+
base.connect = { ok: false, reason: `接入失败:${redactSecrets(error?.message ?? error)}` };
|
|
1625
|
+
}
|
|
1626
|
+
const skillDirs = (assistant.skillsDirs ?? []).filter(Boolean);
|
|
1627
|
+
if (skillDirs.length > 0) {
|
|
1628
|
+
// 与 ensureSkills 同判据:共享全局目录(OpenChamber / OpenCode)只 force 安装一次。
|
|
1629
|
+
const target = preferredSkillTarget(skillDirs);
|
|
1630
|
+
const shared = seenSkillTargets.get(target);
|
|
1631
|
+
if (shared) {
|
|
1632
|
+
// 共享目录(OpenChamber / OpenCode)复用首次安装结果,但明确标注 skipped;实际只写一次。
|
|
1633
|
+
base.skills = {
|
|
1634
|
+
...(shared.result ?? {}),
|
|
1635
|
+
id: assistant.id,
|
|
1636
|
+
ok: shared.result?.ok ?? true,
|
|
1637
|
+
skipped: true,
|
|
1638
|
+
targetDir: target,
|
|
1639
|
+
sharedWith: shared.id,
|
|
1640
|
+
reason: `与 ${shared.id} 共享 Skill 目录,已由前者处理`,
|
|
1641
|
+
};
|
|
1642
|
+
} else {
|
|
1643
|
+
seenSkillTargets.set(target, { id: assistant.id, result: null });
|
|
1644
|
+
try {
|
|
1645
|
+
const result = await installSkills(assistant.id, { ...options, force: true });
|
|
1646
|
+
seenSkillTargets.set(target, { id: assistant.id, result });
|
|
1647
|
+
base.skills = result;
|
|
1648
|
+
} catch (error) {
|
|
1649
|
+
const failure = { ok: false, targetDir: target, reason: `Skill 安装失败:${redactSecrets(error?.message ?? error)}` };
|
|
1650
|
+
seenSkillTargets.set(target, { id: assistant.id, result: failure });
|
|
1651
|
+
base.skills = failure;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
} else {
|
|
1655
|
+
base.skills = { ok: true, skipped: true, reason: '该客户端没有已知的 Skill 目录' };
|
|
1656
|
+
}
|
|
1657
|
+
try {
|
|
1658
|
+
base.verify = await verifyAssistant(assistant.id, options);
|
|
1659
|
+
base.stateAfter = base.verify?.state ?? null;
|
|
1660
|
+
} catch (error) {
|
|
1661
|
+
base.verify = { ok: false, reason: `验证失败:${redactSecrets(error?.message ?? error)}` };
|
|
1662
|
+
}
|
|
1663
|
+
clients.push(base);
|
|
1664
|
+
}
|
|
1665
|
+
const failed = clients.filter((entry) => (entry.connect?.ok === false && entry.connect?.skipped !== true)
|
|
1666
|
+
|| entry.skills?.ok === false);
|
|
1667
|
+
const repaired = clients.filter((entry) => entry.connect?.ok === true && entry.connect?.skipped !== true);
|
|
1668
|
+
return {
|
|
1669
|
+
ok: failed.length === 0,
|
|
1670
|
+
scope: 'client-integration',
|
|
1671
|
+
repairedAt: new Date().toISOString(),
|
|
1672
|
+
clients,
|
|
1673
|
+
summary: {
|
|
1674
|
+
total: clients.length,
|
|
1675
|
+
repaired: repaired.length,
|
|
1676
|
+
failed: failed.length,
|
|
1677
|
+
skipped: clients.filter((entry) => entry.connect?.skipped === true).length,
|
|
1678
|
+
},
|
|
1679
|
+
};
|
|
1242
1680
|
}
|
package/src/config-schema.mjs
CHANGED
|
@@ -609,8 +609,6 @@ export const CONFIG_SCHEMA = [
|
|
|
609
609
|
{ path: 'semantic.cacheDir', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '模型缓存目录' } },
|
|
610
610
|
{ path: 'storagePath', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '存储路径' } },
|
|
611
611
|
{ path: 'storageAdapter', kind: 'enum', spec: { values: ['json', 'sqlite'] }, exposure: 'internal', writable: false, requiresRestart: true, default: 'json', ui: { type: 'select', label: '存储适配器' } },
|
|
612
|
-
{ path: 'deviceId', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '设备标识' } },
|
|
613
|
-
{ path: 'deviceName', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '设备名' } },
|
|
614
612
|
{ path: 'identity.mode', kind: 'enum', spec: { values: ['root', 'delegated'] }, exposure: 'internal', writable: false, requiresRestart: true, default: 'root', ui: { type: 'select', label: '身份模式' } },
|
|
615
613
|
{ path: 'encryption.level', kind: 'enum', spec: { values: ['none', 'at-rest'] }, exposure: 'internal', writable: false, requiresRestart: true, default: 'none', ui: { type: 'select', label: '加密级别' } },
|
|
616
614
|
{ path: 'encryption.passphraseEnv', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '口令环境变量名' } },
|