@mebular/mcp 0.2.3 → 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 +10 -0
- package/package.json +3 -3
- package/src/clients.mjs +472 -34
- package/src/serve.mjs +31 -0
- package/src/server.mjs +18 -2
- package/src/tools.mjs +20 -17
- package/src/version.mjs +1 -1
package/bin/mebular.mjs
CHANGED
|
@@ -308,6 +308,16 @@ async function runInit(flags) {
|
|
|
308
308
|
await writeFile(configFile, JSON.stringify(nextConfig, null, 2), 'utf-8');
|
|
309
309
|
console.log(`已写入配置:${configFile}(deviceId=${identity.deviceId},由身份文件提供)`);
|
|
310
310
|
}
|
|
311
|
+
// Skill 是部署产物:初始化成功后对已检测到的助手自动 ensure;失败只告警,不阻断 init。
|
|
312
|
+
try {
|
|
313
|
+
const { autoEnsureSkills, assistantUserHome } = await import('../src/clients.mjs');
|
|
314
|
+
const skills = await autoEnsureSkills({ home, userHome: assistantUserHome(), cwd: process.cwd() });
|
|
315
|
+
if (!skills.skipped && skills.summary?.total > 0) {
|
|
316
|
+
console.log(`Skill:安装 ${skills.summary.installed} · 更新 ${skills.summary.updated} · 保留 ${skills.summary.kept} · 失败 ${skills.summary.failed}`);
|
|
317
|
+
}
|
|
318
|
+
} catch (error) {
|
|
319
|
+
console.error(`warning: Skill 自动安装失败(不阻断初始化):${error?.message ?? error}`);
|
|
320
|
+
}
|
|
311
321
|
console.log(
|
|
312
322
|
[
|
|
313
323
|
'',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mebular/mcp",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"description": "Mebular MCP server(stdio + Streamable HTTP):把 Mebular 记忆能力暴露给任意 MCP client",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
"access": "public"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@mebular/core": "^0.2.
|
|
32
|
+
"@mebular/core": "^0.2.4",
|
|
33
33
|
"@modelcontextprotocol/server": "^2.3.1",
|
|
34
34
|
"zod": "^4.6.7",
|
|
35
|
-
"@mebular/fleet": "^0.2.
|
|
35
|
+
"@mebular/fleet": "^0.2.4"
|
|
36
36
|
}
|
|
37
37
|
}
|
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/serve.mjs
CHANGED
|
@@ -1341,6 +1341,7 @@ export async function startHttpServer({
|
|
|
1341
1341
|
/^\/admin\/api\/security\/recovery\/(generate|rotate)$/,
|
|
1342
1342
|
/^\/admin\/api\/namespaces\/([^/]+)\/(rejoin|leave)$/,
|
|
1343
1343
|
/^\/admin\/api\/service\/(install|uninstall)$/,
|
|
1344
|
+
/^\/admin\/api\/repair$/,
|
|
1344
1345
|
/^\/admin\/api\/clients\/([^/]+)\/(connect|rollback|skills|preview|verify|recheck)$/,
|
|
1345
1346
|
/^\/admin\/api\/assistants$/,
|
|
1346
1347
|
/^\/admin\/api\/assistants\/([^/]+)$/,
|
|
@@ -1859,6 +1860,24 @@ export async function startHttpServer({
|
|
|
1859
1860
|
}
|
|
1860
1861
|
}
|
|
1861
1862
|
|
|
1863
|
+
// 设置 · 常用「自动修复」:只重跑客户端接入(MCP 条目 + Skill),不碰 memory/identity/cloud/task/audit。
|
|
1864
|
+
async function handleRepair(req, res) {
|
|
1865
|
+
const { repairClients, assistantUserHome, daemonMcpUrl } = await import('./clients.mjs');
|
|
1866
|
+
const mcpUrl = daemonMcpUrl({ host: req.headers?.host, encrypted: Boolean(req.socket?.encrypted) });
|
|
1867
|
+
try {
|
|
1868
|
+
const result = await repairClients({ home, cwd: process.cwd(), mcpUrl, userHome: assistantUserHome() });
|
|
1869
|
+
// 逐项失败也是有效结果:200 + per-client report,由 UI 展示摘要。
|
|
1870
|
+
return sendJson(res, 200, result);
|
|
1871
|
+
} catch (error) {
|
|
1872
|
+
return sendJson(res, 500, {
|
|
1873
|
+
ok: false,
|
|
1874
|
+
scope: 'client-integration',
|
|
1875
|
+
error: 'repair_failed',
|
|
1876
|
+
message: `自动修复失败:${String(error?.message ?? error)}`,
|
|
1877
|
+
});
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1862
1881
|
// D2 写端点实现(memory.admin scope + CSRF 已在 handleAdminWrite 校验)
|
|
1863
1882
|
async function applyAdminWrite(req, res, path, body) {
|
|
1864
1883
|
if (!app || !service) {
|
|
@@ -1874,6 +1893,9 @@ export async function startHttpServer({
|
|
|
1874
1893
|
if (path === '/admin/api/clouds/join') return handleCloudJoin(req, res, body);
|
|
1875
1894
|
if (path === '/admin/api/clouds/rename') return handleCloudRename(req, res, body);
|
|
1876
1895
|
|
|
1896
|
+
// 自动修复:客户端接入修复,**不**经 securityWriteGate(不写记忆/安全状态)。
|
|
1897
|
+
if (path === '/admin/api/repair') return handleRepair(req, res);
|
|
1898
|
+
|
|
1877
1899
|
// S2:安全三档写端点门禁(medium 动态码 / high 会签或恢复码;low 放行)。
|
|
1878
1900
|
const gateInput = parseJsonBody(body) ?? {};
|
|
1879
1901
|
const gate = await securityWriteGate({ app, home, path, input: gateInput, namespace });
|
|
@@ -3254,6 +3276,15 @@ export async function startHttpServer({
|
|
|
3254
3276
|
},
|
|
3255
3277
|
});
|
|
3256
3278
|
await activateRuntime(next, { viaHotInit: true });
|
|
3279
|
+
// 首次初始化成功:对已检测到的客户端 ensure Skill(后台执行;失败不阻断初始化响应)。
|
|
3280
|
+
void import('./clients.mjs')
|
|
3281
|
+
.then(({ autoEnsureSkills, assistantUserHome }) => autoEnsureSkills({ home, userHome: assistantUserHome(), cwd: process.cwd() }))
|
|
3282
|
+
.then((result) => {
|
|
3283
|
+
if (result?.summary?.failed > 0 || (result?.ok === false && result?.skipped !== true)) {
|
|
3284
|
+
console.error(`SKILL_ENSURE_PENDING_REPAIR ${result?.reason ?? `${result?.summary?.failed ?? 1} client(s)`}`);
|
|
3285
|
+
}
|
|
3286
|
+
})
|
|
3287
|
+
.catch((error) => console.error(`SKILL_ENSURE_FAILED ${error?.code ?? 'ERROR'}`));
|
|
3257
3288
|
return sendJson(res, 200, {
|
|
3258
3289
|
ok: true,
|
|
3259
3290
|
...result,
|
package/src/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// MCP server 装配(G6.2 + R1):stdio 传输 + **
|
|
1
|
+
// MCP server 装配(G6.2 + R1):stdio 传输 + **29 工具**(记忆 13 + 任务 16)+ memory_policy prompt。
|
|
2
2
|
// 全部委托 MemoryService(D33 单一实现)。
|
|
3
3
|
|
|
4
4
|
import { McpServer } from '@modelcontextprotocol/server';
|
|
@@ -26,8 +26,15 @@ const MEMORY_POLICY = `# Mebular 记忆使用规约(memory_policy)
|
|
|
26
26
|
5. 隐私:不要写入密钥、口令、完整身份证件等高敏感信息。
|
|
27
27
|
6. 无结果别编:召回为空就如实说明,不要臆造记忆。`;
|
|
28
28
|
|
|
29
|
+
/** MCP initialize 返回的全局行为说明(不替代 memory_policy prompt)。 */
|
|
30
|
+
export const MCP_INSTRUCTIONS = `Mebular 是本地优先的图式记忆与任务协作层。
|
|
31
|
+
1. 先查后写:写入记忆前先用 memory_query/memory_search 查重;只写可复用的稳定事实/偏好,不要把一次会话的过程产物当跨设备记忆。
|
|
32
|
+
2. 任务派发前先 task_targets 确认可派对象,再 task_submit;非幂等/失败重试的语义以工具描述为准。
|
|
33
|
+
3. 工具描述首行的「何时用」是首选路由信号;优先按它选择工具。`;
|
|
34
|
+
|
|
29
35
|
export function buildServer(service, options = {}) {
|
|
30
|
-
|
|
36
|
+
// McpServer(serverInfo, options):instructions 必须放在第二参数,initialize/discover 才会下发。
|
|
37
|
+
const server = new McpServer({ name: 'mebular', version: APP_VERSION }, { instructions: MCP_INSTRUCTIONS });
|
|
31
38
|
registerTools(server, service, options);
|
|
32
39
|
server.registerPrompt(
|
|
33
40
|
'memory_policy',
|
|
@@ -388,6 +395,15 @@ export async function startServeServer(options = {}) {
|
|
|
388
395
|
current.runtime.mcp.auth = httpServer.auth;
|
|
389
396
|
// G:装配完成后写「已监听」标记——supervisor 用它判定新实例健康(join 失败则不写)
|
|
390
397
|
await finalizeRuntime(current);
|
|
398
|
+
// Skill 收敛(启动/升级):受管旧版更新、用户修改保留;失败只记录,绝不阻断 serve。
|
|
399
|
+
void import('./clients.mjs')
|
|
400
|
+
.then(({ autoEnsureSkills, assistantUserHome }) => autoEnsureSkills({ home, userHome: assistantUserHome(), cwd: process.cwd() }))
|
|
401
|
+
.then((result) => {
|
|
402
|
+
if (result?.summary?.failed > 0 || (result?.ok === false && result?.skipped !== true)) {
|
|
403
|
+
console.error(`SKILL_ENSURE_PENDING_REPAIR ${result?.reason ?? `${result?.summary?.failed ?? 1} client(s)`}`);
|
|
404
|
+
}
|
|
405
|
+
})
|
|
406
|
+
.catch((error) => console.error(`SKILL_ENSURE_FAILED ${error?.code ?? 'ERROR'}`));
|
|
391
407
|
}
|
|
392
408
|
|
|
393
409
|
const shutdown = async () => {
|
package/src/tools.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// MCP 工具面(G6.2 / D35 + R1 统一入口):**
|
|
1
|
+
// MCP 工具面(G6.2 / D35 + R1 统一入口):**29 个** agent 中立工具 = 记忆 13(薄壳委托 MemoryService)
|
|
2
2
|
// + 任务 16(复用 @mebular/fleet 的 TASK_TOOLS handler;同 handler 不复制)。
|
|
3
3
|
//
|
|
4
4
|
// 钳制:limit ≤ 50(默认 10)、depth ≤ 5、batch ≤ 100。
|
|
@@ -90,12 +90,15 @@ const namespaceFilter = z.union([z.string(), z.array(z.string())]).optional();
|
|
|
90
90
|
|
|
91
91
|
const internalTypes = z.array(z.enum(['fact', 'episode', 'skill', 'preference', 'observation']));
|
|
92
92
|
|
|
93
|
+
/** 工具描述首行 = 首要路由信号「何时用」;原始语义/约束保留在第二行。 */
|
|
94
|
+
const when = (whenToUse, description) => `何时用:${whenToUse}\n${description}`;
|
|
95
|
+
|
|
93
96
|
/** 工具注册表:handler(service, args) → MCP 结果对象(CLI 直接取 `structuredContent`)。 */
|
|
94
97
|
export const TOOL_SPECS = [
|
|
95
98
|
{
|
|
96
99
|
name: 'memory_write',
|
|
97
100
|
title: '写入记忆',
|
|
98
|
-
description: '写入单条记忆(fact/episode/skill/preference/observation)',
|
|
101
|
+
description: when('需要把用户明确、可复用的稳定事实/偏好写入长期记忆时;先查后写,用 memory_query/memory_search 查重。', '写入单条记忆(fact/episode/skill/preference/observation)'),
|
|
99
102
|
inputSchema: z.object({ items: z.array(memoryInputSchema).min(1) }),
|
|
100
103
|
handler: async (service, { items }) => {
|
|
101
104
|
try {
|
|
@@ -108,7 +111,7 @@ export const TOOL_SPECS = [
|
|
|
108
111
|
{
|
|
109
112
|
name: 'memory_write_batch',
|
|
110
113
|
title: '批量写入记忆',
|
|
111
|
-
description: `批量写入记忆(最多 ${MAX_BATCH}
|
|
114
|
+
description: when('一次会话结束有 2 条以上稳定事实/偏好要落库,且已查重时。', `批量写入记忆(最多 ${MAX_BATCH} 条)`),
|
|
112
115
|
inputSchema: z.object({ items: z.array(memoryInputSchema).min(1) }),
|
|
113
116
|
handler: async (service, { items }) => {
|
|
114
117
|
if (items.length > MAX_BATCH) return fail(`批量写入超过上限:${items.length} > ${MAX_BATCH}`);
|
|
@@ -122,7 +125,7 @@ export const TOOL_SPECS = [
|
|
|
122
125
|
{
|
|
123
126
|
name: 'memory_query',
|
|
124
127
|
title: '查询记忆',
|
|
125
|
-
description: '语义/关键词召回(配置向量索引时走语义)',
|
|
128
|
+
description: when('回答前需要按语义召回已有记忆,或不确定某事实是否已记录时。', '语义/关键词召回(配置向量索引时走语义)'),
|
|
126
129
|
inputSchema: z.object({
|
|
127
130
|
query: z.string().optional(),
|
|
128
131
|
types: internalTypes.optional(),
|
|
@@ -161,7 +164,7 @@ export const TOOL_SPECS = [
|
|
|
161
164
|
{
|
|
162
165
|
name: 'memory_search',
|
|
163
166
|
title: '关键词搜索',
|
|
164
|
-
description: '关键词检索基线,可选一跳关系',
|
|
167
|
+
description: when('已知关键词/专有名词,需要精确检索或查重时(比 memory_query 更可控)。', '关键词检索基线,可选一跳关系'),
|
|
165
168
|
inputSchema: z.object({
|
|
166
169
|
query: z.string(),
|
|
167
170
|
types: z.array(z.string()).optional(),
|
|
@@ -196,7 +199,7 @@ export const TOOL_SPECS = [
|
|
|
196
199
|
{
|
|
197
200
|
name: 'memory_profile',
|
|
198
201
|
title: '用户画像',
|
|
199
|
-
description: '返回用户偏好与属性(默认不含已归档)',
|
|
202
|
+
description: when('需要用户偏好/属性做个性化回答,或判断写入是否符合用户约束时。', '返回用户偏好与属性(默认不含已归档)'),
|
|
200
203
|
inputSchema: z.object({ includeArchived: z.boolean().optional() }),
|
|
201
204
|
handler: async (service, args) => {
|
|
202
205
|
try {
|
|
@@ -209,7 +212,7 @@ export const TOOL_SPECS = [
|
|
|
209
212
|
{
|
|
210
213
|
name: 'memory_skills',
|
|
211
214
|
title: '技能列表',
|
|
212
|
-
description: '按分类/关键词/标签筛选技能',
|
|
215
|
+
description: when('需要复用已有技能步骤,或查找某类可复用流程时。', '按分类/关键词/标签筛选技能'),
|
|
213
216
|
inputSchema: z.object({
|
|
214
217
|
category: z.string().optional(),
|
|
215
218
|
search: z.string().optional(),
|
|
@@ -233,7 +236,7 @@ export const TOOL_SPECS = [
|
|
|
233
236
|
{
|
|
234
237
|
name: 'memory_history',
|
|
235
238
|
title: '会话历史',
|
|
236
|
-
description: '按会话/时间/主题筛选会话情节',
|
|
239
|
+
description: when('需要回看某次会话/任务过程,而不是稳定事实时。', '按会话/时间/主题筛选会话情节'),
|
|
237
240
|
inputSchema: z.object({
|
|
238
241
|
sessionIds: z.array(z.string()).optional(),
|
|
239
242
|
startTime: z.number().optional(),
|
|
@@ -262,7 +265,7 @@ export const TOOL_SPECS = [
|
|
|
262
265
|
{
|
|
263
266
|
name: 'memory_graph',
|
|
264
267
|
title: '图遍历',
|
|
265
|
-
description: `从起点遍历(深度 ≤ ${MAX_DEPTH}
|
|
268
|
+
description: when('需要沿关系边查上下文(相关实体/事实/技能)时。', `从起点遍历(深度 ≤ ${MAX_DEPTH})`),
|
|
266
269
|
inputSchema: z.object({
|
|
267
270
|
startId: z.string(),
|
|
268
271
|
direction: z.enum(['outgoing', 'incoming', 'both']).optional(),
|
|
@@ -288,7 +291,7 @@ export const TOOL_SPECS = [
|
|
|
288
291
|
{
|
|
289
292
|
name: 'memory_import',
|
|
290
293
|
title: '导入记忆',
|
|
291
|
-
description: '经适配器导入异构来源(kv/markdown/…)',
|
|
294
|
+
description: when('从外部 kv/markdown 等来源一次性导入历史记忆时。', '经适配器导入异构来源(kv/markdown/…)'),
|
|
292
295
|
inputSchema: z.object({ kind: z.string().optional(), data: z.unknown(), origin: z.string().optional() }),
|
|
293
296
|
handler: async (service, args) => {
|
|
294
297
|
try {
|
|
@@ -305,7 +308,7 @@ export const TOOL_SPECS = [
|
|
|
305
308
|
{
|
|
306
309
|
name: 'memory_status',
|
|
307
310
|
title: '记忆状态',
|
|
308
|
-
description: '返回设备/网络/计数/状态哈希/开关',
|
|
311
|
+
description: when('接入、排障或需要确认设备/网络/计数/状态哈希/开关时。', '返回设备/网络/计数/状态哈希/开关'),
|
|
309
312
|
inputSchema: z.object({}),
|
|
310
313
|
handler: async (service) => {
|
|
311
314
|
try {
|
|
@@ -318,7 +321,7 @@ export const TOOL_SPECS = [
|
|
|
318
321
|
{
|
|
319
322
|
name: 'memory_sync',
|
|
320
323
|
title: '同步对端',
|
|
321
|
-
description: '连接对端并等待一次双向同步(network.enabled 需为 true)',
|
|
324
|
+
description: when('需要立即拉取/推送某个对端,而不是等待自动同步时(network.enabled 需为 true)。', '连接对端并等待一次双向同步(network.enabled 需为 true)'),
|
|
322
325
|
inputSchema: z.object({ peerId: z.string(), address: z.string().optional() }),
|
|
323
326
|
handler: async (service, args) => {
|
|
324
327
|
try {
|
|
@@ -332,7 +335,7 @@ export const TOOL_SPECS = [
|
|
|
332
335
|
{
|
|
333
336
|
name: 'memory_delete',
|
|
334
337
|
title: '删除记忆',
|
|
335
|
-
description: '删除记忆:写墓碑(deletedAt)并随图事件同步到各端;删除后默认不再出现在任何召回。不可逆动作(对端已拷贝的旧快照无法强制回收)。需 memory.admin。',
|
|
338
|
+
description: when('确认内容要永久墓碑删除、且接受不可逆时;不确定时先用 memory_archive。', '删除记忆:写墓碑(deletedAt)并随图事件同步到各端;删除后默认不再出现在任何召回。不可逆动作(对端已拷贝的旧快照无法强制回收)。需 memory.admin。'),
|
|
336
339
|
inputSchema: z.object({ ids: z.array(z.string()).min(1) }),
|
|
337
340
|
handler: async (service, args) => {
|
|
338
341
|
try {
|
|
@@ -345,7 +348,7 @@ export const TOOL_SPECS = [
|
|
|
345
348
|
{
|
|
346
349
|
name: 'memory_archive',
|
|
347
350
|
title: '归档 / 解除归档记忆',
|
|
348
|
-
description: '归档记忆:打 metadata.archivedAt 标记(随图同步、无损、可逆),归档后默认不进入召回;archived=false 解除归档。删除(墓碑)节点会被跳过。',
|
|
351
|
+
description: when('内容暂时不该参与召回但将来可能有用(可逆);要永久删除请用 memory_delete。', '归档记忆:打 metadata.archivedAt 标记(随图同步、无损、可逆),归档后默认不进入召回;archived=false 解除归档。删除(墓碑)节点会被跳过。'),
|
|
349
352
|
inputSchema: z.object({ ids: z.array(z.string()).min(1), archived: z.boolean().optional() }),
|
|
350
353
|
handler: async (service, args) => {
|
|
351
354
|
try {
|
|
@@ -357,13 +360,13 @@ export const TOOL_SPECS = [
|
|
|
357
360
|
},
|
|
358
361
|
];
|
|
359
362
|
|
|
360
|
-
/** 统一工具注册表(记忆
|
|
363
|
+
/** 统一工具注册表(记忆 13 + 任务 16 = 29):`mebular mcp`(stdio)与 HTTP `/mcp` 都注册这一份。 */
|
|
361
364
|
export const ALL_TOOL_SPECS = [...TOOL_SPECS, ...TASK_TOOL_SPECS];
|
|
362
365
|
|
|
363
|
-
/** 统一工具名(
|
|
366
|
+
/** 统一工具名(29)——控制台「能力清单」与 CLI `mebular tools` 同源。 */
|
|
364
367
|
export const TOOL_NAMES = ALL_TOOL_SPECS.map((spec) => spec.name);
|
|
365
368
|
|
|
366
|
-
/** 统一 scope 表(记忆 + 任务,
|
|
369
|
+
/** 统一 scope 表(记忆 + 任务,29)。 */
|
|
367
370
|
export const TOOL_ALL_SCOPES = { ...TOOL_SCOPES, ...TASK_TOOL_SCOPES };
|
|
368
371
|
|
|
369
372
|
/** 工具名 → spec(记忆 + 任务;CLI 与 MCP 同 handler)。 */
|
package/src/version.mjs
CHANGED