@mebular/mcp 0.3.0 → 0.3.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 +211 -7
- package/package.json +5 -5
- package/src/admin.mjs +9 -3
- package/src/config-apply.mjs +254 -6
- package/src/config-lock.mjs +167 -0
- package/src/config.mjs +17 -1
- package/src/detail-maintenance.mjs +17 -1
- package/src/home-identity.mjs +13 -1
- package/src/memory-capability.mjs +813 -154
- package/src/memory-runtime-diagnostics.mjs +716 -0
- package/src/memory-runtime-supervisor.mjs +1005 -177
- package/src/serve.mjs +752 -45
- package/src/server.mjs +17 -4
- package/src/version.mjs +1 -1
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// 跨进程配置文件写锁。
|
|
2
|
+
//
|
|
3
|
+
// 配置 writer 必须在读取 → 修改 → rename/rollback 全程持有 `<config>.write-lock`。
|
|
4
|
+
// 锁文件包含 pid/at/owner:owner 用于 release 只删自己的锁。
|
|
5
|
+
// 锁内容优先通过临时文件 + link 原子创建;不支持硬链接的文件系统回退到 open('wx')。
|
|
6
|
+
// 持锁进程会周期性续租 mtime;活 PID 的锁在超过 staleMs 未续租后也可被接管(防 PID 复用)。
|
|
7
|
+
// 无法解析的锁只有在 mtime 超过 staleMs 后才可接管;读锁/stat 的非 ENOENT 瞬态错误一律按 busy 处理。
|
|
8
|
+
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
10
|
+
import { link, open, readFile, stat, unlink, utimes, writeFile } from 'node:fs/promises';
|
|
11
|
+
|
|
12
|
+
export const CONFIG_LOCK_STALE_MS = 30_000;
|
|
13
|
+
const LINK_UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS', 'EACCES', 'EINVAL', 'EMLINK']);
|
|
14
|
+
|
|
15
|
+
function pidAlive(pid) {
|
|
16
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
17
|
+
try {
|
|
18
|
+
process.kill(pid, 0);
|
|
19
|
+
return true;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return error?.code === 'EPERM';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function acquireConfigFileLock(configFile, {
|
|
26
|
+
timeoutMs = null,
|
|
27
|
+
staleMs = CONFIG_LOCK_STALE_MS,
|
|
28
|
+
linkImpl = link,
|
|
29
|
+
openImpl = open,
|
|
30
|
+
now = Date.now,
|
|
31
|
+
} = {}) {
|
|
32
|
+
const lockPath = `${configFile}.write-lock`;
|
|
33
|
+
const configured = Number(process.env.MEBULAR_CONFIG_LOCK_TIMEOUT_MS ?? '');
|
|
34
|
+
const effectiveTimeout = Number.isFinite(timeoutMs) && timeoutMs !== null
|
|
35
|
+
? Math.max(0, timeoutMs)
|
|
36
|
+
: (Number.isFinite(configured) && configured >= 0 ? configured : 5000);
|
|
37
|
+
const deadline = now() + effectiveTimeout;
|
|
38
|
+
const owner = randomBytes(12).toString('hex');
|
|
39
|
+
|
|
40
|
+
const snapshot = async () => {
|
|
41
|
+
let raw;
|
|
42
|
+
try {
|
|
43
|
+
raw = await readFile(lockPath, 'utf-8');
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error?.code === 'ENOENT') {
|
|
46
|
+
return { exists: false, unreadable: false, raw: null, parsed: null, mtimeMs: null };
|
|
47
|
+
}
|
|
48
|
+
// EACCES/EMFILE 等瞬态错误:不能当作锁不存在,更不能 unlink。
|
|
49
|
+
return {
|
|
50
|
+
exists: true,
|
|
51
|
+
unreadable: true,
|
|
52
|
+
error: error?.code ?? 'read_failed',
|
|
53
|
+
raw: null,
|
|
54
|
+
parsed: null,
|
|
55
|
+
mtimeMs: null,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
let info;
|
|
59
|
+
try {
|
|
60
|
+
info = await stat(lockPath);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error?.code === 'ENOENT') {
|
|
63
|
+
return { exists: false, unreadable: false, raw: null, parsed: null, mtimeMs: null };
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
exists: true,
|
|
67
|
+
unreadable: true,
|
|
68
|
+
error: error?.code ?? 'stat_failed',
|
|
69
|
+
raw,
|
|
70
|
+
parsed: null,
|
|
71
|
+
mtimeMs: null,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
let parsed = null;
|
|
75
|
+
try {
|
|
76
|
+
parsed = JSON.parse(raw);
|
|
77
|
+
} catch {
|
|
78
|
+
parsed = null;
|
|
79
|
+
}
|
|
80
|
+
return { exists: true, unreadable: false, raw, parsed, mtimeMs: info.mtimeMs };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const startHeartbeat = () => {
|
|
84
|
+
const period = Math.max(1, Math.min(Math.max(10, Math.floor(staleMs / 3)), Math.max(1, staleMs - 1)));
|
|
85
|
+
const timer = setInterval(() => {
|
|
86
|
+
void (async () => {
|
|
87
|
+
const current = await snapshot();
|
|
88
|
+
if (current.unreadable || current.parsed?.owner !== owner) return;
|
|
89
|
+
const at = new Date(now());
|
|
90
|
+
await utimes(lockPath, at, at).catch(() => undefined);
|
|
91
|
+
})();
|
|
92
|
+
}, period);
|
|
93
|
+
timer.unref?.();
|
|
94
|
+
return timer;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const createOnce = async () => {
|
|
98
|
+
const payload = JSON.stringify({ pid: process.pid, at: now(), owner });
|
|
99
|
+
const tmp = `${lockPath}.${owner}.tmp`;
|
|
100
|
+
try {
|
|
101
|
+
await writeFile(tmp, payload, { mode: 0o600 });
|
|
102
|
+
try {
|
|
103
|
+
await linkImpl(tmp, lockPath);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (LINK_UNSUPPORTED.has(error?.code)) {
|
|
106
|
+
// 文件系统不支持硬链接:回退到 O_EXCL 原子创建;写入失败必须清理半截锁。
|
|
107
|
+
const handle = await openImpl(lockPath, 'wx', 0o600);
|
|
108
|
+
try {
|
|
109
|
+
await handle.writeFile(payload, 'utf-8');
|
|
110
|
+
} catch (writeError) {
|
|
111
|
+
await handle.close().catch(() => undefined);
|
|
112
|
+
await unlink(lockPath).catch(() => undefined);
|
|
113
|
+
throw writeError;
|
|
114
|
+
}
|
|
115
|
+
await handle.close().catch(() => undefined);
|
|
116
|
+
} else {
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
} finally {
|
|
121
|
+
await unlink(tmp).catch(() => undefined);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
for (;;) {
|
|
126
|
+
try {
|
|
127
|
+
await createOnce();
|
|
128
|
+
const heartbeat = startHeartbeat();
|
|
129
|
+
return async () => {
|
|
130
|
+
clearInterval(heartbeat);
|
|
131
|
+
// release 只删除自己的锁;已被 stale 接管或替换的锁不得误删。
|
|
132
|
+
const current = await snapshot();
|
|
133
|
+
if (!current.unreadable && current.parsed?.owner === owner) {
|
|
134
|
+
await unlink(lockPath).catch(() => undefined);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
139
|
+
|
|
140
|
+
const held = await snapshot();
|
|
141
|
+
let stale = false;
|
|
142
|
+
if (held.unreadable) {
|
|
143
|
+
stale = false;
|
|
144
|
+
} else if (held.exists && held.parsed && Number.isInteger(held.parsed.pid)) {
|
|
145
|
+
// 活 PID 也可能来自复用的旧进程:只有死 PID 或超时未续租才可接管。
|
|
146
|
+
stale = !pidAlive(held.parsed.pid)
|
|
147
|
+
|| (typeof held.mtimeMs === 'number' && now() - held.mtimeMs > staleMs);
|
|
148
|
+
} else {
|
|
149
|
+
stale = !held.exists
|
|
150
|
+
|| (typeof held.mtimeMs === 'number' && now() - held.mtimeMs > staleMs);
|
|
151
|
+
}
|
|
152
|
+
if (stale) {
|
|
153
|
+
// 重新读取确认仍是同一个锁,再接管,避免删除刚创建的新锁。
|
|
154
|
+
const confirmed = await snapshot();
|
|
155
|
+
if (!confirmed.unreadable
|
|
156
|
+
&& confirmed.exists === held.exists
|
|
157
|
+
&& confirmed.raw === held.raw
|
|
158
|
+
&& confirmed.mtimeMs === held.mtimeMs) {
|
|
159
|
+
await unlink(lockPath).catch(() => undefined);
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (now() >= deadline) return null;
|
|
164
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
package/src/config.mjs
CHANGED
|
@@ -72,6 +72,22 @@ export async function loadConfigFile(home) {
|
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/** fleet 任务面所需的额外同步域(能力卡/Agent 目录)。 */
|
|
76
|
+
export const FLEET_AGENT_NAMESPACE = 'agents';
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* CR-002/B4:旧 daemon 配置只订阅 `tasks` 时,启动期幂等补齐 `agents`。
|
|
80
|
+
* - 空数组/缺省 = 订阅全部,保持原语义(不强行收窄);
|
|
81
|
+
* - 已有非空 namespaces → 追加 agents(去重、保持原顺序)。
|
|
82
|
+
*/
|
|
83
|
+
export function ensureFleetSyncNamespaces(config) {
|
|
84
|
+
const namespaces = config?.sync?.namespaces;
|
|
85
|
+
if (!Array.isArray(namespaces) || namespaces.length === 0) return config;
|
|
86
|
+
const merged = [...new Set([...namespaces, FLEET_AGENT_NAMESPACE])];
|
|
87
|
+
if (merged.length === namespaces.length) return config;
|
|
88
|
+
return { ...config, sync: { ...config.sync, namespaces: merged } };
|
|
89
|
+
}
|
|
90
|
+
|
|
75
91
|
function truthy(value, fallback) {
|
|
76
92
|
if (value === undefined) return fallback;
|
|
77
93
|
return value === true || value === 'true' || value === '1';
|
|
@@ -185,7 +201,7 @@ export async function resolveMasterPublicKey(home, config) {
|
|
|
185
201
|
/** 依配置构建并初始化 Mebular 门面 */
|
|
186
202
|
export async function createMebular() {
|
|
187
203
|
const home = homeDir();
|
|
188
|
-
const config = await loadConfigFile(home);
|
|
204
|
+
const config = ensureFleetSyncNamespaces(await loadConfigFile(home));
|
|
189
205
|
const storageAdapter = config.storageAdapter ?? 'json';
|
|
190
206
|
const storagePath = storagePathForHome(home, config, process.env);
|
|
191
207
|
// F-IDENT-1:身份文件是 deviceId/deviceName 的唯一权威;env/config 只在身份缺失时作为 bootstrap。
|
|
@@ -16,6 +16,19 @@ function errorCode(error) {
|
|
|
16
16
|
return typeof error?.code === 'string' && error.code.length > 0 ? error.code : 'ERROR';
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
function safeErrorMessage(error) {
|
|
20
|
+
return String(error?.message ?? error ?? 'detail maintenance failed')
|
|
21
|
+
.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[redacted]')
|
|
22
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi, 'Bearer [redacted]')
|
|
23
|
+
.replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
|
|
24
|
+
.replace(/\bgh[pousr]_[A-Za-z0-9]{16,}\b/g, '[redacted]')
|
|
25
|
+
.replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, '[redacted]')
|
|
26
|
+
.replace(/\bAKIA[0-9A-Z]{16}\b/g, '[redacted]')
|
|
27
|
+
.replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g, '[redacted]')
|
|
28
|
+
.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|authorization)\b(\s*[:=]\s*)(["']?)[^\s"',;]{4,}\3/gi, '$1$2$3[redacted]$3')
|
|
29
|
+
.slice(0, 512);
|
|
30
|
+
}
|
|
31
|
+
|
|
19
32
|
/**
|
|
20
33
|
* @param {{
|
|
21
34
|
* getService: () => ({ pruneExpiredDetails?: (options?: { now?: number }) => Promise<string[]> } | null),
|
|
@@ -77,6 +90,9 @@ export function createDetailMaintenance({
|
|
|
77
90
|
lastResult = {
|
|
78
91
|
reason,
|
|
79
92
|
pruned: Array.isArray(pruned) ? pruned.length : 0,
|
|
93
|
+
// 现有 MemoryService 维护结果不含正文统计;明确未知,不伪造零值。
|
|
94
|
+
bytes: null,
|
|
95
|
+
oldestAgeMs: null,
|
|
80
96
|
at,
|
|
81
97
|
};
|
|
82
98
|
lastError = null;
|
|
@@ -85,7 +101,7 @@ export function createDetailMaintenance({
|
|
|
85
101
|
lastError = {
|
|
86
102
|
reason,
|
|
87
103
|
code: errorCode(error),
|
|
88
|
-
message:
|
|
104
|
+
message: safeErrorMessage(error),
|
|
89
105
|
at,
|
|
90
106
|
};
|
|
91
107
|
logger?.error?.(`DETAIL_MAINTENANCE_FAILED ${lastError.code} ${lastError.message}`);
|
package/src/home-identity.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
|
15
15
|
import { chmod, copyFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
16
16
|
import { hostname } from 'node:os';
|
|
17
17
|
import { dirname, join } from 'node:path';
|
|
18
|
+
import { acquireConfigFileLock } from './config-lock.mjs';
|
|
18
19
|
|
|
19
20
|
/** 旧 config 身份字段的备份名(与 config-apply 的 config.json.bak 区分)。 */
|
|
20
21
|
export const LEGACY_CONFIG_BACKUP_SUFFIX = '.identity-legacy.bak';
|
|
@@ -349,10 +350,18 @@ export async function createIdentityForStorage(input) {
|
|
|
349
350
|
* 无论旧值是否与身份一致都移除(身份是唯一权威);文件不存在或无字段时 no-op。
|
|
350
351
|
* 备份只在首次迁移时创建,保留最早的 legacy 快照。
|
|
351
352
|
*/
|
|
352
|
-
export async function cleanLegacyConfig({ configPath: cfgPath, identity = null } = {}) {
|
|
353
|
+
export async function cleanLegacyConfig({ configPath: cfgPath, identity = null, lock = true } = {}) {
|
|
353
354
|
if (typeof cfgPath !== 'string' || cfgPath.length === 0 || !existsSync(cfgPath)) {
|
|
354
355
|
return { migrated: false, backupPath: null, warnings: [] };
|
|
355
356
|
}
|
|
357
|
+
const releaseConfigLock = lock ? await acquireConfigFileLock(cfgPath) : null;
|
|
358
|
+
if (lock && !releaseConfigLock) {
|
|
359
|
+
throw errorWith('CONFIG_BUSY', `配置文件正在被其他进程写入:${cfgPath}`);
|
|
360
|
+
}
|
|
361
|
+
try {
|
|
362
|
+
if (!existsSync(cfgPath)) {
|
|
363
|
+
return { migrated: false, backupPath: null, warnings: [] };
|
|
364
|
+
}
|
|
356
365
|
let current;
|
|
357
366
|
try {
|
|
358
367
|
current = JSON.parse(await readFile(cfgPath, 'utf-8'));
|
|
@@ -386,4 +395,7 @@ export async function cleanLegacyConfig({ configPath: cfgPath, identity = null }
|
|
|
386
395
|
warnings.push(`已从 config.json 移除旧身份字段,设备身份以 ${identity.deviceId} 为准`);
|
|
387
396
|
}
|
|
388
397
|
return { migrated: true, backupPath, warnings };
|
|
398
|
+
} finally {
|
|
399
|
+
if (releaseConfigLock) await releaseConfigLock();
|
|
400
|
+
}
|
|
389
401
|
}
|