@mebular/mcp 0.3.0 → 0.3.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/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 +1002 -176
- package/src/serve.mjs +752 -45
- package/src/server.mjs +17 -4
- package/src/version.mjs +1 -1
package/src/serve.mjs
CHANGED
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
readMemoryRuntimeModelSource,
|
|
37
37
|
} from './memory-runtime-config.mjs';
|
|
38
38
|
import { APP_VERSION } from './version.mjs';
|
|
39
|
+
import { acquireConfigFileLock } from './config-lock.mjs';
|
|
39
40
|
import { resolveStaticAssetRoots } from './asset-roots.mjs';
|
|
40
41
|
|
|
41
42
|
// 兼容既有导入方:APP_VERSION 的真源是 ./version.mjs。
|
|
@@ -682,6 +683,26 @@ export function loadFleetSecurity() {
|
|
|
682
683
|
return fleetSecurityPromise;
|
|
683
684
|
}
|
|
684
685
|
|
|
686
|
+
let fleetCardsPromise = null;
|
|
687
|
+
|
|
688
|
+
/** CR-002:延迟加载 fleet 能力卡 canonical/schema/签名逻辑(唯一实现仍在 fleet)。 */
|
|
689
|
+
export function loadFleetCards() {
|
|
690
|
+
if (fleetCardsPromise === null) {
|
|
691
|
+
fleetCardsPromise = import('../../fleet/dist/index.js').catch(() => null);
|
|
692
|
+
}
|
|
693
|
+
return fleetCardsPromise;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
let fleetPlansPromise = null;
|
|
697
|
+
|
|
698
|
+
/** P2:延迟加载 fleet plan 节点 schema/幂等逻辑(唯一实现仍在 fleet)。 */
|
|
699
|
+
export function loadFleetPlans() {
|
|
700
|
+
if (fleetPlansPromise === null) {
|
|
701
|
+
fleetPlansPromise = import('../../fleet/dist/index.js').catch(() => null);
|
|
702
|
+
}
|
|
703
|
+
return fleetPlansPromise;
|
|
704
|
+
}
|
|
705
|
+
|
|
685
706
|
/**
|
|
686
707
|
* 写端点门禁:medium 要动态码;high 要会签批准/恢复码;low 放行。
|
|
687
708
|
* 导出供 S2-3 单测直接断言(HTTP 层同样走这里)。
|
|
@@ -882,6 +903,9 @@ export async function startHttpServer({
|
|
|
882
903
|
writesEnabled: initialWritesEnabled = false,
|
|
883
904
|
// C:一键重启执行器(可注入;verify:config 用 MEBULAR_RESTART_DRY_RUN 或注入替身)
|
|
884
905
|
restartRunner = null,
|
|
906
|
+
// 测试注入:配置写盘前钩子,用于验证 close 与配置写入的线性化。
|
|
907
|
+
beforeConfigWrite = null,
|
|
908
|
+
afterConfigRename = null,
|
|
885
909
|
// 引导态(空家目录):只服务 /healthz + /console 引导页 + /app/provision/*;其余 409 provision_required
|
|
886
910
|
provision: initialProvision = false,
|
|
887
911
|
// P1:同一进程内热初始化。返回新的运行时上下文;成功后本 server 从 UNINITIALIZED → READY。
|
|
@@ -897,6 +921,10 @@ export async function startHttpServer({
|
|
|
897
921
|
let service = initialService;
|
|
898
922
|
let config = initialConfig ?? {};
|
|
899
923
|
let runtime = initialRuntime;
|
|
924
|
+
// CR-002:守护内串行化能力卡签名/写入,避免同版本并发请求产生重复节点。
|
|
925
|
+
let cardWriteQueue = Promise.resolve();
|
|
926
|
+
// P5:角色卡写入串行化(同版本幂等/冲突与能力卡同语义)。
|
|
927
|
+
let roleCardWriteQueue = Promise.resolve();
|
|
900
928
|
|
|
901
929
|
// 0.3 详情保留维护:service 就绪后启动(启动一次 + 每 24h),热切换复用同一 timer。
|
|
902
930
|
// 失败只记录状态/日志,不阻断 MCP;关闭时显式清理,避免测试/宿主进程残留 timer。
|
|
@@ -1019,6 +1047,20 @@ export async function startHttpServer({
|
|
|
1019
1047
|
mcpUrl: () => origin,
|
|
1020
1048
|
})
|
|
1021
1049
|
: null;
|
|
1050
|
+
let memoryRuntimeLifecycle = Promise.resolve();
|
|
1051
|
+
let lifecycleClosing = false;
|
|
1052
|
+
let capabilityDrain = null;
|
|
1053
|
+
let configWriteQueue = Promise.resolve();
|
|
1054
|
+
const enqueueMemoryRuntimeLifecycle = (operation) => {
|
|
1055
|
+
if (lifecycleClosing) {
|
|
1056
|
+
const error = new Error('MCP 正在关闭:拒绝新的 Memory Runtime 生命周期操作');
|
|
1057
|
+
error.code = 'closing';
|
|
1058
|
+
return Promise.reject(error);
|
|
1059
|
+
}
|
|
1060
|
+
const run = memoryRuntimeLifecycle.then(operation, operation);
|
|
1061
|
+
memoryRuntimeLifecycle = run.catch(() => undefined);
|
|
1062
|
+
return run;
|
|
1063
|
+
};
|
|
1022
1064
|
|
|
1023
1065
|
// ---------- 0.3 模型薄代理:模型目录/安装/引擎/来源全部由 sidecar 拥有 ----------
|
|
1024
1066
|
// 浏览器只看到 sidecar 的脱敏视图;host token 只在服务端使用。
|
|
@@ -1055,11 +1097,23 @@ export async function startHttpServer({
|
|
|
1055
1097
|
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
|
|
1056
1098
|
};
|
|
1057
1099
|
|
|
1100
|
+
function modelErrorView(error) {
|
|
1101
|
+
if (!error || typeof error !== 'object') return null;
|
|
1102
|
+
return {
|
|
1103
|
+
code: error.code ?? null,
|
|
1104
|
+
message: error.message ?? null,
|
|
1105
|
+
retryable: error.retryable === true,
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1058
1109
|
function modelDownloadView(install) {
|
|
1059
1110
|
if (!install || typeof install !== 'object') return null;
|
|
1060
1111
|
return {
|
|
1112
|
+
schema: install.schema ?? null,
|
|
1113
|
+
jobId: install.jobId ?? null,
|
|
1061
1114
|
pack: install.packId ?? null,
|
|
1062
1115
|
packId: install.packId ?? null,
|
|
1116
|
+
modelId: install.modelId ?? null,
|
|
1063
1117
|
state: install.state ?? null,
|
|
1064
1118
|
phase: install.phase ?? null,
|
|
1065
1119
|
progress: install.progress ?? 0,
|
|
@@ -1067,16 +1121,129 @@ export async function startHttpServer({
|
|
|
1067
1121
|
totalBytes: install.totalBytes ?? 0,
|
|
1068
1122
|
speedBytesPerSecond: install.speedBytesPerSecond ?? 0,
|
|
1069
1123
|
etaMs: install.etaMs ?? null,
|
|
1124
|
+
startedAt: install.startedAt ?? null,
|
|
1070
1125
|
updatedAt: install.updatedAt ?? null,
|
|
1071
|
-
|
|
1126
|
+
completedAt: install.completedAt ?? null,
|
|
1127
|
+
error: modelErrorView(install.error),
|
|
1128
|
+
warnings: uniqueStrings(Array.isArray(install.warnings) ? install.warnings : []),
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
function modelEngineView(engine) {
|
|
1133
|
+
if (!engine || typeof engine !== 'object') return null;
|
|
1134
|
+
return {
|
|
1135
|
+
state: engine.state ?? null,
|
|
1136
|
+
health: engine.health ?? null,
|
|
1137
|
+
packId: engine.packId ?? null,
|
|
1138
|
+
modelId: engine.modelId ?? null,
|
|
1139
|
+
startedAt: engine.startedAt ?? null,
|
|
1140
|
+
crashCount: engine.crashCount ?? 0,
|
|
1141
|
+
restartCount: engine.restartCount ?? 0,
|
|
1142
|
+
lastError: modelErrorView(engine.lastError),
|
|
1143
|
+
installed: engine.installed === true,
|
|
1144
|
+
release: engine.release ?? null,
|
|
1145
|
+
platform: engine.platform ?? null,
|
|
1146
|
+
arch: engine.arch ?? null,
|
|
1147
|
+
binaryReady: engine.binaryReady === true,
|
|
1148
|
+
reason: engine.reason ?? null,
|
|
1149
|
+
progress: engine.progress ?? null,
|
|
1150
|
+
installedAt: engine.installedAt ?? null,
|
|
1151
|
+
verifiedAt: engine.verifiedAt ?? null,
|
|
1152
|
+
supported: typeof engine.supported === 'boolean' ? engine.supported : null,
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
function modelActiveView(active) {
|
|
1157
|
+
const value = active ?? {};
|
|
1158
|
+
return {
|
|
1159
|
+
source: value.source ?? null,
|
|
1160
|
+
packId: value.packId ?? null,
|
|
1161
|
+
modelId: value.modelId ?? null,
|
|
1162
|
+
engine: modelEngineView(value.engine),
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
function modelProviderView(provider) {
|
|
1167
|
+
return {
|
|
1168
|
+
id: provider?.id ?? null,
|
|
1169
|
+
kind: provider?.kind ?? null,
|
|
1170
|
+
configured: provider?.configured === true,
|
|
1171
|
+
available: provider?.available === true,
|
|
1172
|
+
active: provider?.active === true,
|
|
1173
|
+
reason: provider?.reason ?? null,
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
function modelHardwareView(hardware) {
|
|
1178
|
+
if (!hardware || typeof hardware !== 'object') return null;
|
|
1179
|
+
const gpu = hardware.gpu ?? {};
|
|
1180
|
+
return {
|
|
1181
|
+
platform: hardware.platform ?? null,
|
|
1182
|
+
arch: hardware.arch ?? null,
|
|
1183
|
+
osVersion: hardware.osVersion ?? null,
|
|
1184
|
+
cpuModel: hardware.cpuModel ?? null,
|
|
1185
|
+
cpuCores: hardware.cpuCores ?? null,
|
|
1186
|
+
totalMemoryBytes: hardware.totalMemoryBytes ?? null,
|
|
1187
|
+
freeMemoryBytes: hardware.freeMemoryBytes ?? null,
|
|
1188
|
+
diskAvailableBytes: hardware.diskAvailableBytes ?? null,
|
|
1189
|
+
diskTotalBytes: hardware.diskTotalBytes ?? null,
|
|
1190
|
+
gpu: {
|
|
1191
|
+
vendor: gpu.vendor ?? null,
|
|
1192
|
+
name: gpu.name ?? null,
|
|
1193
|
+
vramBytes: gpu.vramBytes ?? null,
|
|
1194
|
+
unifiedMemory: gpu.unifiedMemory === true,
|
|
1195
|
+
},
|
|
1196
|
+
detectedAt: hardware.detectedAt ?? null,
|
|
1197
|
+
warnings: uniqueStrings(Array.isArray(hardware.warnings) ? hardware.warnings : []),
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
function modelRecommendationView(recommended) {
|
|
1202
|
+
if (!recommended || typeof recommended !== 'object') return null;
|
|
1203
|
+
return {
|
|
1204
|
+
kind: recommended.kind ?? null,
|
|
1205
|
+
packId: recommended.packId ?? null,
|
|
1206
|
+
modelId: recommended.modelId ?? null,
|
|
1207
|
+
tier: recommended.tier ?? null,
|
|
1208
|
+
displayName: recommended.displayName ?? null,
|
|
1209
|
+
sizeBytes: recommended.sizeBytes ?? null,
|
|
1210
|
+
minMemoryBytes: recommended.minMemoryBytes ?? null,
|
|
1211
|
+
reason: recommended.reason ?? null,
|
|
1212
|
+
warnings: uniqueStrings(Array.isArray(recommended.warnings) ? recommended.warnings : []),
|
|
1213
|
+
alternatives: uniqueStrings(Array.isArray(recommended.alternatives) ? recommended.alternatives : []).slice(0, 100),
|
|
1072
1214
|
};
|
|
1073
1215
|
}
|
|
1074
1216
|
|
|
1075
1217
|
function modelPackView(pack) {
|
|
1218
|
+
// 明确允许列表:attached producer 的额外 debug/keyRef/path 不得 spread 到浏览器。
|
|
1076
1219
|
return {
|
|
1077
|
-
|
|
1220
|
+
packId: pack?.packId ?? null,
|
|
1221
|
+
modelId: pack?.modelId ?? null,
|
|
1222
|
+
tier: pack?.tier ?? null,
|
|
1223
|
+
displayName: pack?.displayName ?? null,
|
|
1224
|
+
description: pack?.description ?? null,
|
|
1225
|
+
sizeBytes: pack?.sizeBytes ?? null,
|
|
1226
|
+
quantization: pack?.quantization ?? null,
|
|
1227
|
+
contextLength: pack?.contextLength ?? null,
|
|
1228
|
+
estimatedDownloadBytes: pack?.estimatedDownloadBytes ?? null,
|
|
1229
|
+
requirements: pack?.requirements ? {
|
|
1230
|
+
platforms: Array.isArray(pack.requirements.platforms) ? pack.requirements.platforms : [],
|
|
1231
|
+
architectures: pack.requirements.architectures ?? null,
|
|
1232
|
+
minMemoryBytes: pack.requirements.minMemoryBytes ?? null,
|
|
1233
|
+
minDiskBytes: pack.requirements.minDiskBytes ?? null,
|
|
1234
|
+
recommendedMemoryBytes: pack.requirements.recommendedMemoryBytes ?? null,
|
|
1235
|
+
gpu: pack.requirements.gpu ?? null,
|
|
1236
|
+
} : null,
|
|
1237
|
+
state: pack?.state ?? null,
|
|
1238
|
+
installed: pack?.installed === true,
|
|
1239
|
+
installedBytes: pack?.installedBytes ?? 0,
|
|
1240
|
+
expectedBytes: pack?.expectedBytes ?? 0,
|
|
1241
|
+
verifiedAt: pack?.verifiedAt ?? null,
|
|
1242
|
+
supported: typeof pack?.supported === 'boolean' ? pack.supported : null,
|
|
1243
|
+
active: pack?.active === true,
|
|
1078
1244
|
selected: pack?.active === true,
|
|
1079
1245
|
manifestAvailable: pack?.manifest?.available === true,
|
|
1246
|
+
warnings: Array.isArray(pack?.warnings) ? pack.warnings : [],
|
|
1080
1247
|
...(pack?.install ? { download: modelDownloadView(pack.install) } : {}),
|
|
1081
1248
|
};
|
|
1082
1249
|
}
|
|
@@ -1096,12 +1263,12 @@ export async function startHttpServer({
|
|
|
1096
1263
|
selectionSource: 'sidecar',
|
|
1097
1264
|
},
|
|
1098
1265
|
packs: Array.isArray(data.packs) ? data.packs.map(modelPackView) : [],
|
|
1099
|
-
hardware: data.hardware
|
|
1100
|
-
recommended: data.recommended
|
|
1101
|
-
active,
|
|
1102
|
-
providers: Array.isArray(data.providers) ? data.providers : [],
|
|
1103
|
-
install: data.install
|
|
1104
|
-
engine: data.engine
|
|
1266
|
+
hardware: modelHardwareView(data.hardware),
|
|
1267
|
+
recommended: modelRecommendationView(data.recommended),
|
|
1268
|
+
active: modelActiveView(active),
|
|
1269
|
+
providers: Array.isArray(data.providers) ? data.providers.map(modelProviderView) : [],
|
|
1270
|
+
install: modelDownloadView(data.install),
|
|
1271
|
+
engine: modelEngineView(data.engine),
|
|
1105
1272
|
warnings: Array.isArray(data.warnings) ? data.warnings : [],
|
|
1106
1273
|
};
|
|
1107
1274
|
}
|
|
@@ -1126,11 +1293,11 @@ export async function startHttpServer({
|
|
|
1126
1293
|
pack: active.packId ?? null,
|
|
1127
1294
|
selectionSource: 'sidecar',
|
|
1128
1295
|
},
|
|
1129
|
-
engine: runtime.engine ?? data.engine
|
|
1130
|
-
hardware: data.hardware
|
|
1131
|
-
recommendation: recommended,
|
|
1132
|
-
install: runtime.install ?? data.install
|
|
1133
|
-
active,
|
|
1296
|
+
engine: modelEngineView(runtime.engine ?? data.engine),
|
|
1297
|
+
hardware: modelHardwareView(data.hardware),
|
|
1298
|
+
recommendation: modelRecommendationView(recommended),
|
|
1299
|
+
install: modelDownloadView(runtime.install ?? data.install),
|
|
1300
|
+
active: modelActiveView(active),
|
|
1134
1301
|
installedPackIds: Array.isArray(runtime.installedPackIds)
|
|
1135
1302
|
? runtime.installedPackIds
|
|
1136
1303
|
: (Array.isArray(data.packs) ? data.packs.filter((pack) => pack?.installed === true).map((pack) => pack.packId) : []),
|
|
@@ -1193,9 +1360,16 @@ export async function startHttpServer({
|
|
|
1193
1360
|
status: Number.isInteger(result.status) && result.status >= 200 && result.status < 300 ? result.status : 200,
|
|
1194
1361
|
body: {
|
|
1195
1362
|
ok: true,
|
|
1196
|
-
...data,
|
|
1363
|
+
...modelDownloadView(data),
|
|
1364
|
+
packId: data.packId ?? null,
|
|
1365
|
+
started: data.started === true,
|
|
1366
|
+
stopped: data.stopped === true,
|
|
1367
|
+
removed: data.removed === true,
|
|
1368
|
+
wasActive: data.wasActive === true,
|
|
1369
|
+
reason: data.reason ?? null,
|
|
1370
|
+
engine: modelEngineView(data.engine),
|
|
1197
1371
|
...extra,
|
|
1198
|
-
warnings: Array.isArray(data.warnings) ? data.warnings : [],
|
|
1372
|
+
warnings: uniqueStrings(Array.isArray(data.warnings) ? data.warnings : []),
|
|
1199
1373
|
},
|
|
1200
1374
|
};
|
|
1201
1375
|
}
|
|
@@ -1253,7 +1427,7 @@ export async function startHttpServer({
|
|
|
1253
1427
|
force: input?.force === true || input?.force === 'true' || input?.force === '1',
|
|
1254
1428
|
});
|
|
1255
1429
|
if (!result.ok) return proxyFailure(result, '模型安装失败');
|
|
1256
|
-
const job = result.data ?? {};
|
|
1430
|
+
const job = modelDownloadView(result.data ?? {});
|
|
1257
1431
|
return {
|
|
1258
1432
|
status: result.status === 202 ? 202 : 200,
|
|
1259
1433
|
body: {
|
|
@@ -1262,7 +1436,7 @@ export async function startHttpServer({
|
|
|
1262
1436
|
pack: job.packId ?? pack,
|
|
1263
1437
|
job,
|
|
1264
1438
|
...job,
|
|
1265
|
-
warnings:
|
|
1439
|
+
warnings: job.warnings,
|
|
1266
1440
|
},
|
|
1267
1441
|
};
|
|
1268
1442
|
}
|
|
@@ -1334,8 +1508,8 @@ export async function startHttpServer({
|
|
|
1334
1508
|
pack: pack ?? inference.data?.active?.packId ?? null,
|
|
1335
1509
|
state: status?.data?.state ?? null,
|
|
1336
1510
|
installed: status?.data?.installed ?? null,
|
|
1337
|
-
engine: inference.data?.engine
|
|
1338
|
-
active: inference.data?.active
|
|
1511
|
+
engine: modelEngineView(inference.data?.engine),
|
|
1512
|
+
active: modelActiveView(inference.data?.active),
|
|
1339
1513
|
warnings: uniqueStrings([
|
|
1340
1514
|
...(Array.isArray(inference.warnings) ? inference.warnings : []),
|
|
1341
1515
|
...(Array.isArray(status?.warnings) ? status.warnings : []),
|
|
@@ -1778,11 +1952,14 @@ export async function startHttpServer({
|
|
|
1778
1952
|
const detail = memoryRuntimeSupervisor
|
|
1779
1953
|
? await memoryRuntimeSupervisor.readStatus().catch(() => null)
|
|
1780
1954
|
: null;
|
|
1781
|
-
//
|
|
1955
|
+
// 进程、capability 与模型是独立观察;不得用进程存活伪造 capability ready。
|
|
1782
1956
|
return sendJson(res, 200, {
|
|
1783
1957
|
...status,
|
|
1784
|
-
mode: status.enabled ? 'immersive' : 'lightweight',
|
|
1958
|
+
mode: status.enabled ? (detail?.mode ?? (status.available ? 'immersive' : null)) : 'lightweight',
|
|
1785
1959
|
runtimeVersion: status.runtimeVersion ?? detail?.runtimeVersion ?? null,
|
|
1960
|
+
degraded: status.degraded === true || detail?.degraded === true,
|
|
1961
|
+
capability: detail?.capability ?? null,
|
|
1962
|
+
capabilityError: detail?.error ?? null,
|
|
1786
1963
|
model: detail?.model ?? null,
|
|
1787
1964
|
});
|
|
1788
1965
|
}
|
|
@@ -2418,6 +2595,7 @@ export async function startHttpServer({
|
|
|
2418
2595
|
const attempt = applyAttempt;
|
|
2419
2596
|
await writeApplyPending(home, {
|
|
2420
2597
|
attempt,
|
|
2598
|
+
applyId: randomUUID(),
|
|
2421
2599
|
at: new Date().toISOString(),
|
|
2422
2600
|
fields,
|
|
2423
2601
|
attempts: 1,
|
|
@@ -3063,6 +3241,33 @@ export async function startHttpServer({
|
|
|
3063
3241
|
|
|
3064
3242
|
// 控制台配置写入:curated 合并 + 原子写 + .bak 备份(全部需重启生效)
|
|
3065
3243
|
if (path === '/admin/api/config') {
|
|
3244
|
+
if (lifecycleClosing) {
|
|
3245
|
+
return sendJson(res, 409, {
|
|
3246
|
+
ok: false,
|
|
3247
|
+
error: 'closing',
|
|
3248
|
+
message: 'MCP 正在关闭:不再接受配置写入或新的生命周期操作',
|
|
3249
|
+
});
|
|
3250
|
+
}
|
|
3251
|
+
const cfgFile = configPath(home);
|
|
3252
|
+
const previousConfigWrite = configWriteQueue;
|
|
3253
|
+
let releaseConfigWrite;
|
|
3254
|
+
configWriteQueue = new Promise((resolveWrite) => { releaseConfigWrite = resolveWrite; });
|
|
3255
|
+
await previousConfigWrite;
|
|
3256
|
+
let releaseConfigFileLock = null;
|
|
3257
|
+
try {
|
|
3258
|
+
releaseConfigFileLock = await acquireConfigFileLock(cfgFile, {
|
|
3259
|
+
timeoutMs: (() => {
|
|
3260
|
+
const configured = Number(process.env.MEBULAR_CONFIG_LOCK_TIMEOUT_MS ?? '');
|
|
3261
|
+
return Number.isFinite(configured) && configured >= 0 ? configured : 5000;
|
|
3262
|
+
})(),
|
|
3263
|
+
});
|
|
3264
|
+
if (!releaseConfigFileLock) {
|
|
3265
|
+
return sendJson(res, 409, {
|
|
3266
|
+
ok: false,
|
|
3267
|
+
error: 'config_busy',
|
|
3268
|
+
message: '配置正在被其他进程写入,请稍后重试',
|
|
3269
|
+
});
|
|
3270
|
+
}
|
|
3066
3271
|
const input = parseJsonBody(body);
|
|
3067
3272
|
if (!input || typeof input.patch !== 'object') {
|
|
3068
3273
|
return sendJson(res, 400, { error: 'bad_request', errorKey: 'config_patch_invalid', message: '需要 { patch: { ... } }' });
|
|
@@ -3071,10 +3276,11 @@ export async function startHttpServer({
|
|
|
3071
3276
|
if (errors.length > 0) {
|
|
3072
3277
|
return sendJson(res, 400, { error: 'bad_request', errorKey: 'config_patch_invalid', message: errors.join(';'), details: errors });
|
|
3073
3278
|
}
|
|
3074
|
-
const cfgFile = configPath(home);
|
|
3075
3279
|
let current = {};
|
|
3280
|
+
let originalRaw = null;
|
|
3076
3281
|
try {
|
|
3077
|
-
|
|
3282
|
+
originalRaw = await readFile(cfgFile, 'utf-8');
|
|
3283
|
+
current = JSON.parse(originalRaw);
|
|
3078
3284
|
} catch {
|
|
3079
3285
|
current = {};
|
|
3080
3286
|
}
|
|
@@ -3101,15 +3307,97 @@ export async function startHttpServer({
|
|
|
3101
3307
|
});
|
|
3102
3308
|
}
|
|
3103
3309
|
const tmp = `${cfgFile}.tmp-${process.pid}`;
|
|
3104
|
-
|
|
3310
|
+
const writtenRaw = JSON.stringify(merged, null, 2);
|
|
3311
|
+
const readConfigRaw = async () => {
|
|
3312
|
+
try {
|
|
3313
|
+
return await readFile(cfgFile, 'utf-8');
|
|
3314
|
+
} catch {
|
|
3315
|
+
return null;
|
|
3316
|
+
}
|
|
3317
|
+
};
|
|
3318
|
+
const rollbackIfUnchanged = async () => {
|
|
3319
|
+
if (await readConfigRaw() !== writtenRaw) return false;
|
|
3320
|
+
if (originalRaw === null) {
|
|
3321
|
+
await rm(cfgFile, { force: true }).catch(() => undefined);
|
|
3322
|
+
return true;
|
|
3323
|
+
}
|
|
3324
|
+
const restoreTmp = `${cfgFile}.rollback-${process.pid}`;
|
|
3325
|
+
await writeFile(restoreTmp, originalRaw, 'utf-8');
|
|
3326
|
+
await rename(restoreTmp, cfgFile);
|
|
3327
|
+
return true;
|
|
3328
|
+
};
|
|
3329
|
+
// 入口后 close 可能已开始:写盘前二次检查,避免“已写文件但返回 409”。
|
|
3330
|
+
if (beforeConfigWrite) await beforeConfigWrite();
|
|
3331
|
+
if (lifecycleClosing) {
|
|
3332
|
+
return sendJson(res, 409, {
|
|
3333
|
+
ok: false,
|
|
3334
|
+
error: 'closing',
|
|
3335
|
+
message: 'MCP 正在关闭:配置未写入',
|
|
3336
|
+
});
|
|
3337
|
+
}
|
|
3338
|
+
// CAS:读-改-写窗口内若文件被其他写入方修改,不覆盖对方结果。
|
|
3339
|
+
if (await readConfigRaw() !== originalRaw) {
|
|
3340
|
+
return sendJson(res, 409, {
|
|
3341
|
+
ok: false,
|
|
3342
|
+
error: 'config_conflict',
|
|
3343
|
+
message: '配置已被其他写入修改,请刷新后重试',
|
|
3344
|
+
});
|
|
3345
|
+
}
|
|
3346
|
+
await writeFile(tmp, writtenRaw, 'utf-8');
|
|
3347
|
+
if (lifecycleClosing) {
|
|
3348
|
+
await rm(tmp, { force: true }).catch(() => undefined);
|
|
3349
|
+
return sendJson(res, 409, {
|
|
3350
|
+
ok: false,
|
|
3351
|
+
error: 'closing',
|
|
3352
|
+
message: 'MCP 正在关闭:配置未写入',
|
|
3353
|
+
});
|
|
3354
|
+
}
|
|
3355
|
+
if (await readConfigRaw() !== originalRaw) {
|
|
3356
|
+
await rm(tmp, { force: true }).catch(() => undefined);
|
|
3357
|
+
return sendJson(res, 409, {
|
|
3358
|
+
ok: false,
|
|
3359
|
+
error: 'config_conflict',
|
|
3360
|
+
message: '配置已被其他写入修改,请刷新后重试',
|
|
3361
|
+
});
|
|
3362
|
+
}
|
|
3105
3363
|
if (existsSync(cfgFile)) await copyFile(cfgFile, `${cfgFile}.bak`);
|
|
3106
3364
|
await rename(tmp, cfgFile);
|
|
3365
|
+
if (afterConfigRename) await afterConfigRename();
|
|
3366
|
+
if (lifecycleClosing) {
|
|
3367
|
+
// rename 与 close 竞态:只有文件仍是本次写入内容时才原子回滚,避免覆盖并发修改。
|
|
3368
|
+
if (!await rollbackIfUnchanged()) {
|
|
3369
|
+
return sendJson(res, 409, {
|
|
3370
|
+
ok: false,
|
|
3371
|
+
error: 'config_conflict',
|
|
3372
|
+
message: '配置在关闭回滚前已被修改,未覆盖并发写入',
|
|
3373
|
+
});
|
|
3374
|
+
}
|
|
3375
|
+
return sendJson(res, 409, {
|
|
3376
|
+
ok: false,
|
|
3377
|
+
error: 'closing',
|
|
3378
|
+
message: 'MCP 正在关闭:配置已回滚',
|
|
3379
|
+
});
|
|
3380
|
+
}
|
|
3107
3381
|
const backup = existsSync(`${cfgFile}.bak`) ? `${cfgFile}.bak` : null;
|
|
3108
3382
|
const base = { ok: true, applied: changedPaths, backup, path: cfgFile, config: merged };
|
|
3109
3383
|
|
|
3110
3384
|
// memoryRuntime.enabled 是热开关:同步内存配置,立即生成/撤销 capability token,
|
|
3111
3385
|
// 并启动/停止 sidecar(sidecar 失败不影响配置写入与 MCP 本身)。
|
|
3112
3386
|
if (changedPaths.some((changed) => changed === 'memoryRuntime' || changed.startsWith('memoryRuntime.'))) {
|
|
3387
|
+
if (lifecycleClosing) {
|
|
3388
|
+
if (!await rollbackIfUnchanged()) {
|
|
3389
|
+
return sendJson(res, 409, {
|
|
3390
|
+
ok: false,
|
|
3391
|
+
error: 'config_conflict',
|
|
3392
|
+
message: '配置在关闭回滚前已被修改,未覆盖并发写入',
|
|
3393
|
+
});
|
|
3394
|
+
}
|
|
3395
|
+
return sendJson(res, 409, {
|
|
3396
|
+
ok: false,
|
|
3397
|
+
error: 'closing',
|
|
3398
|
+
message: 'MCP 正在关闭:配置已回滚',
|
|
3399
|
+
});
|
|
3400
|
+
}
|
|
3113
3401
|
if (merged?.memoryRuntime === undefined) {
|
|
3114
3402
|
const next = { ...(config ?? {}) };
|
|
3115
3403
|
delete next.memoryRuntime;
|
|
@@ -3117,20 +3405,39 @@ export async function startHttpServer({
|
|
|
3117
3405
|
} else {
|
|
3118
3406
|
config = { ...(config ?? {}), memoryRuntime: merged.memoryRuntime };
|
|
3119
3407
|
}
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3408
|
+
const targetEnabled = isMemoryRuntimeEnabled(config);
|
|
3409
|
+
const commandChanged = changedPaths.some((changed) => changed === 'memoryRuntime.command'
|
|
3410
|
+
|| changed === 'memoryRuntime.startTimeoutMs');
|
|
3411
|
+
try {
|
|
3412
|
+
await enqueueMemoryRuntimeLifecycle(async () => {
|
|
3413
|
+
// 较新的配置已改变目标时,旧操作不得撤销新 token 或停止新 child。
|
|
3414
|
+
if (isMemoryRuntimeEnabled(config) !== targetEnabled) return;
|
|
3415
|
+
if (targetEnabled) {
|
|
3416
|
+
await memoryCapability.prepare();
|
|
3417
|
+
if (memoryRuntimeSupervisor && isMemoryRuntimeEnabled(config)) {
|
|
3418
|
+
if (commandChanged) {
|
|
3419
|
+
await memoryRuntimeSupervisor.restart({ includeAttached: false, force: false }).catch(() => undefined);
|
|
3420
|
+
} else {
|
|
3421
|
+
await memoryRuntimeSupervisor.start().catch(() => undefined);
|
|
3422
|
+
}
|
|
3423
|
+
}
|
|
3127
3424
|
} else {
|
|
3128
|
-
|
|
3425
|
+
// 先进入 draining 并等待在途写,再撤销 capability;drain 不清时保留 token 并报告 incomplete。
|
|
3426
|
+
const drain = await memoryCapability.close({ timeoutMs: 5000 })
|
|
3427
|
+
.catch(() => ({ clean: false }));
|
|
3428
|
+
if (!drain.clean) console.error('MEMORY_CAPABILITY_DRAIN_INCOMPLETE');
|
|
3429
|
+
await memoryRuntimeSupervisor?.stop({ includeAttached: false }).catch(() => undefined);
|
|
3129
3430
|
}
|
|
3431
|
+
});
|
|
3432
|
+
} catch (error) {
|
|
3433
|
+
if (error?.code === 'closing') {
|
|
3434
|
+
return sendJson(res, 409, {
|
|
3435
|
+
ok: false,
|
|
3436
|
+
error: 'closing',
|
|
3437
|
+
message: 'MCP 正在关闭:Memory Runtime 生命周期操作未执行',
|
|
3438
|
+
});
|
|
3130
3439
|
}
|
|
3131
|
-
|
|
3132
|
-
await memoryRuntimeSupervisor?.stop({ includeAttached: false }).catch(() => undefined);
|
|
3133
|
-
await memoryCapability.revoke();
|
|
3440
|
+
throw error;
|
|
3134
3441
|
}
|
|
3135
3442
|
}
|
|
3136
3443
|
|
|
@@ -3174,6 +3481,10 @@ export async function startHttpServer({
|
|
|
3174
3481
|
timeoutMs,
|
|
3175
3482
|
},
|
|
3176
3483
|
});
|
|
3484
|
+
} finally {
|
|
3485
|
+
if (releaseConfigFileLock) await releaseConfigFileLock();
|
|
3486
|
+
releaseConfigWrite();
|
|
3487
|
+
}
|
|
3177
3488
|
}
|
|
3178
3489
|
|
|
3179
3490
|
// G-ML-1:记忆生命周期(动作式,无开关)——归档/解除归档(可逆)+ 删除(墓碑)
|
|
@@ -4134,6 +4445,31 @@ export async function startHttpServer({
|
|
|
4134
4445
|
multiaddrs: app.node?.getLocalMultiaddrs?.() ?? [],
|
|
4135
4446
|
});
|
|
4136
4447
|
}
|
|
4448
|
+
// P6:守护内部已验证在线 peer 公钥(loopback + memory.read)。
|
|
4449
|
+
// 只来自 sync 握手登记的在线 peer,绝不回退 config.peers 地址簿;
|
|
4450
|
+
// 供 daemon fleet 校验远端能力卡签名,补足无本地 Mebular 句柄的读路径。
|
|
4451
|
+
if (path === '/app/peers' && req.method === 'GET') {
|
|
4452
|
+
const peers = [];
|
|
4453
|
+
try {
|
|
4454
|
+
const sync = app?.sync;
|
|
4455
|
+
if (sync && typeof sync.getOnlinePeers === 'function') {
|
|
4456
|
+
for (const peer of sync.getOnlinePeers()) {
|
|
4457
|
+
const key = typeof sync.getPeerPublicKey === 'function'
|
|
4458
|
+
? sync.getPeerPublicKey(peer.deviceId)
|
|
4459
|
+
: undefined;
|
|
4460
|
+
if (key === undefined) continue;
|
|
4461
|
+
peers.push({
|
|
4462
|
+
device: peer.deviceId,
|
|
4463
|
+
peerId: typeof peer.peerId === 'string' ? peer.peerId : null,
|
|
4464
|
+
publicKeyHex: Buffer.from(key).toString('hex'),
|
|
4465
|
+
});
|
|
4466
|
+
}
|
|
4467
|
+
}
|
|
4468
|
+
} catch {
|
|
4469
|
+
// 同步未启用/未就绪:返回空集合;调用方 fail-closed。
|
|
4470
|
+
}
|
|
4471
|
+
return sendJson(res, 200, { ok: true, count: peers.length, peers });
|
|
4472
|
+
}
|
|
4137
4473
|
if (path === '/app/namespaces' && req.method === 'GET') {
|
|
4138
4474
|
const stats = service && typeof service.stats === 'function' ? await service.stats() : null;
|
|
4139
4475
|
const namespaces = stats
|
|
@@ -4150,18 +4486,47 @@ export async function startHttpServer({
|
|
|
4150
4486
|
}
|
|
4151
4487
|
const type = typeof payload.type === 'string' && payload.type.length > 0 ? payload.type : null;
|
|
4152
4488
|
if (!type) return sendJson(res, 400, { ok: false, error: 'type 必填' });
|
|
4489
|
+
if (payload.metadata !== undefined
|
|
4490
|
+
&& (typeof payload.metadata !== 'object' || payload.metadata === null || Array.isArray(payload.metadata))) {
|
|
4491
|
+
return sendJson(res, 400, { ok: false, error: 'metadata 必须为对象' });
|
|
4492
|
+
}
|
|
4493
|
+
// [raw-graph-debug] 不是内部对象写路径:能力卡必须走专用 /app/capability-cards,
|
|
4494
|
+
// 角色卡/plan 也不能从这里的通用 metadata 写入口伪造。
|
|
4495
|
+
const protectedInternalTypes = new Set(['agent_capability_card', 'agent_role_card', 'task_plan']);
|
|
4496
|
+
const requestedInternalKind = payload.metadata?.internalObject?.kind;
|
|
4497
|
+
const declaresInternal = payload.metadata?.internal === true;
|
|
4498
|
+
if (declaresInternal || protectedInternalTypes.has(type) || protectedInternalTypes.has(requestedInternalKind)) {
|
|
4499
|
+
return sendJson(res, 403, {
|
|
4500
|
+
ok: false,
|
|
4501
|
+
error: 'internal_object_write_forbidden',
|
|
4502
|
+
message: '内部对象必须走各自专用写入端点(能力卡:/app/capability-cards;角色卡:/app/role-cards;plan:/app/plans)',
|
|
4503
|
+
});
|
|
4504
|
+
}
|
|
4153
4505
|
const node = await app.graph.createNode(
|
|
4154
4506
|
type,
|
|
4155
4507
|
typeof payload.content === 'object' && payload.content !== null ? payload.content : {},
|
|
4156
4508
|
Array.isArray(payload.edges) ? payload.edges : [],
|
|
4157
|
-
|
|
4509
|
+
{
|
|
4510
|
+
...(payload.namespace ? { namespace: payload.namespace } : {}),
|
|
4511
|
+
...(payload.metadata !== undefined ? { metadata: payload.metadata } : {}),
|
|
4512
|
+
},
|
|
4158
4513
|
);
|
|
4159
|
-
return sendJson(res, 200, {
|
|
4514
|
+
return sendJson(res, 200, {
|
|
4515
|
+
ok: true,
|
|
4516
|
+
node: {
|
|
4517
|
+
id: node.id,
|
|
4518
|
+
type: node.type,
|
|
4519
|
+
namespace: node.namespace ?? 'default',
|
|
4520
|
+
createdBy: node.createdBy,
|
|
4521
|
+
...(node.metadata !== undefined ? { metadata: node.metadata } : {}),
|
|
4522
|
+
},
|
|
4523
|
+
});
|
|
4160
4524
|
}
|
|
4161
4525
|
// [raw-graph-debug] 原始图调试/接入端点(调试例外):不做内部对象、归档或
|
|
4162
4526
|
// 墓碑过滤,仅供 daemon/fleet 原始图读写与排障。普通记忆列表与域统计必须走
|
|
4163
4527
|
// MemoryService.listRecords()/namespaceStats()(Console 见 admin.mjs),
|
|
4164
4528
|
// 不得把这里当作普通记忆读路径。
|
|
4529
|
+
// P5:即使 raw debug 也不返回角色卡原文;角色卡只能走 /app/role-cards。
|
|
4165
4530
|
if (path === '/app/nodes' && req.method === 'GET') {
|
|
4166
4531
|
const filter = {};
|
|
4167
4532
|
const ns = url.searchParams.get('namespace');
|
|
@@ -4170,11 +4535,331 @@ export async function startHttpServer({
|
|
|
4170
4535
|
if (ns) filter.namespace = ns;
|
|
4171
4536
|
if (type) filter.type = type;
|
|
4172
4537
|
const nodes = await app.graph.listNodes(filter);
|
|
4173
|
-
const
|
|
4538
|
+
const visible = nodes.filter((n) => n.type !== 'agent_role_card'
|
|
4539
|
+
&& n.metadata?.internalObject?.kind !== 'agent_role_card');
|
|
4540
|
+
const trimmed = Number.isInteger(limit) && limit > 0 ? visible.slice(0, limit) : visible;
|
|
4174
4541
|
return sendJson(res, 200, {
|
|
4175
4542
|
ok: true,
|
|
4176
4543
|
count: trimmed.length,
|
|
4177
|
-
nodes: trimmed.map((n) => ({
|
|
4544
|
+
nodes: trimmed.map((n) => ({
|
|
4545
|
+
id: n.id,
|
|
4546
|
+
type: n.type,
|
|
4547
|
+
namespace: n.namespace ?? 'default',
|
|
4548
|
+
createdBy: n.createdBy,
|
|
4549
|
+
content: n.content,
|
|
4550
|
+
...(n.metadata !== undefined ? { metadata: n.metadata } : {}),
|
|
4551
|
+
})),
|
|
4552
|
+
});
|
|
4553
|
+
}
|
|
4554
|
+
// P2:plan 节点专用内部端点(loopback + memory.write/read)。
|
|
4555
|
+
// 唯一写入路径仍是 fleet materializer/plan store;这里只做 schema/幂等与 internal metadata,
|
|
4556
|
+
// 不开放 task_plan 到 /app/nodes,也不新增公共 MCP 方法/UI。
|
|
4557
|
+
if (path === '/app/plans' && req.method === 'POST') {
|
|
4558
|
+
if (!app) return sendJson(res, 503, { ok: false, error: 'plans_unavailable', message: '图存储尚未初始化' });
|
|
4559
|
+
if (!writesEnabled) return sendJson(res, 403, { ok: false, error: 'read_only', message: '写能力已关闭' });
|
|
4560
|
+
let payload;
|
|
4561
|
+
try {
|
|
4562
|
+
payload = JSON.parse(body.toString('utf-8') || '{}');
|
|
4563
|
+
} catch {
|
|
4564
|
+
return sendJson(res, 400, { ok: false, error: 'invalid json' });
|
|
4565
|
+
}
|
|
4566
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
|
|
4567
|
+
return sendJson(res, 400, { ok: false, error: 'plan body 必须为对象' });
|
|
4568
|
+
}
|
|
4569
|
+
const lib = await loadFleetPlans();
|
|
4570
|
+
if (!lib || typeof lib.appendValidatedTaskPlanNode !== 'function') {
|
|
4571
|
+
return sendJson(res, 503, { ok: false, error: 'plans_unavailable', message: 'plan 模块不可用' });
|
|
4572
|
+
}
|
|
4573
|
+
const fleetNamespace = await resolveFleetNamespace({ home, fallback: namespace });
|
|
4574
|
+
const requestedNamespace = typeof payload.namespace === 'string' && payload.namespace.length > 0
|
|
4575
|
+
? payload.namespace
|
|
4576
|
+
: fleetNamespace;
|
|
4577
|
+
if (requestedNamespace !== fleetNamespace) {
|
|
4578
|
+
return sendJson(res, 400, {
|
|
4579
|
+
ok: false,
|
|
4580
|
+
error: 'namespace_invalid',
|
|
4581
|
+
message: `plan 只能写入任务板 namespace:${fleetNamespace}`,
|
|
4582
|
+
});
|
|
4583
|
+
}
|
|
4584
|
+
const planInput = payload.plan !== undefined ? payload.plan : payload.content;
|
|
4585
|
+
try {
|
|
4586
|
+
const result = await lib.appendValidatedTaskPlanNode(app, planInput, { namespace: fleetNamespace });
|
|
4587
|
+
return sendJson(res, 200, {
|
|
4588
|
+
ok: true,
|
|
4589
|
+
plan: result.plan,
|
|
4590
|
+
nodeId: result.nodeId,
|
|
4591
|
+
createdBy: result.createdBy,
|
|
4592
|
+
replayed: result.replayed === true,
|
|
4593
|
+
});
|
|
4594
|
+
} catch (error) {
|
|
4595
|
+
const code = typeof error?.code === 'string' ? error.code : null;
|
|
4596
|
+
const reason = typeof error?.reason === 'string' ? error.reason : null;
|
|
4597
|
+
const status = code === 'PLAN_CONFLICT' || code === 'PLAN_VERSION' || code === 'PLAN_STATE_INVALID'
|
|
4598
|
+
? 409
|
|
4599
|
+
: code === 'PLAN_SCHEMA' || code === 'PLAN_BUDGET' || code === 'PLAN_POLICY'
|
|
4600
|
+
|| code === 'PLAN_JOIN' || code === 'PLAN_MR' || code === 'PLAN_ACCEPTANCE'
|
|
4601
|
+
|| code === 'PLAN_REUSE' || code === 'PLAN_DUP_STEP' || code === 'PLAN_MISSING_DEP'
|
|
4602
|
+
|| code === 'PLAN_CYCLE'
|
|
4603
|
+
? 422
|
|
4604
|
+
: 500;
|
|
4605
|
+
return sendJson(res, status, {
|
|
4606
|
+
ok: false,
|
|
4607
|
+
...(code !== null ? { error: code } : { error: 'plan_write_failed' }),
|
|
4608
|
+
...(reason !== null ? { reason } : {}),
|
|
4609
|
+
errors: Array.isArray(error?.errors) ? error.errors : [String(error?.message ?? error)],
|
|
4610
|
+
});
|
|
4611
|
+
}
|
|
4612
|
+
}
|
|
4613
|
+
if (path === '/app/plans' && req.method === 'GET') {
|
|
4614
|
+
if (!app) return sendJson(res, 503, { ok: false, error: 'plans_unavailable', message: '图存储尚未初始化' });
|
|
4615
|
+
const lib = await loadFleetPlans();
|
|
4616
|
+
if (!lib || typeof lib.listTaskPlanNodes !== 'function') {
|
|
4617
|
+
return sendJson(res, 503, { ok: false, error: 'plans_unavailable', message: 'plan 模块不可用' });
|
|
4618
|
+
}
|
|
4619
|
+
const fleetNamespace = await resolveFleetNamespace({ home, fallback: namespace });
|
|
4620
|
+
const requestedNamespace = url.searchParams.get('namespace');
|
|
4621
|
+
if (requestedNamespace !== null && requestedNamespace.length > 0 && requestedNamespace !== fleetNamespace) {
|
|
4622
|
+
return sendJson(res, 400, {
|
|
4623
|
+
ok: false,
|
|
4624
|
+
error: 'namespace_invalid',
|
|
4625
|
+
message: `plan 只能读取任务板 namespace:${fleetNamespace}`,
|
|
4626
|
+
});
|
|
4627
|
+
}
|
|
4628
|
+
const planId = url.searchParams.get('planId');
|
|
4629
|
+
const version = Number(url.searchParams.get('version') ?? '0');
|
|
4630
|
+
let nodes = await lib.listTaskPlanNodes(app, { namespace: fleetNamespace });
|
|
4631
|
+
if (planId) nodes = nodes.filter((entry) => entry.plan.planId === planId);
|
|
4632
|
+
if (Number.isInteger(version) && version > 0) nodes = nodes.filter((entry) => entry.plan.version === version);
|
|
4633
|
+
return sendJson(res, 200, {
|
|
4634
|
+
ok: true,
|
|
4635
|
+
count: nodes.length,
|
|
4636
|
+
plans: nodes.map((entry) => entry.plan),
|
|
4637
|
+
nodes: nodes.map((entry) => ({
|
|
4638
|
+
id: entry.nodeId,
|
|
4639
|
+
type: 'task_plan',
|
|
4640
|
+
namespace: fleetNamespace,
|
|
4641
|
+
createdBy: entry.createdBy,
|
|
4642
|
+
content: entry.plan,
|
|
4643
|
+
metadata: {
|
|
4644
|
+
internal: true,
|
|
4645
|
+
internalObject: { kind: 'task_plan' },
|
|
4646
|
+
},
|
|
4647
|
+
})),
|
|
4648
|
+
});
|
|
4649
|
+
}
|
|
4650
|
+
// CR-002:daemon 身份签名能力卡(draft 无 signature),写 agents 域 internal 节点。
|
|
4651
|
+
if (path === '/app/capability-cards' && req.method === 'POST') {
|
|
4652
|
+
if (!app) return sendJson(res, 503, { ok: false, error: 'capability_cards_unavailable', message: '图存储尚未初始化' });
|
|
4653
|
+
if (!writesEnabled) return sendJson(res, 403, { ok: false, error: 'read_only', message: '写能力已关闭' });
|
|
4654
|
+
let payload;
|
|
4655
|
+
try {
|
|
4656
|
+
payload = JSON.parse(body.toString('utf-8') || '{}');
|
|
4657
|
+
} catch {
|
|
4658
|
+
return sendJson(res, 400, { ok: false, error: 'invalid json' });
|
|
4659
|
+
}
|
|
4660
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
|
|
4661
|
+
return sendJson(res, 400, { ok: false, error: 'card body 必须为对象' });
|
|
4662
|
+
}
|
|
4663
|
+
const lib = await loadFleetCards();
|
|
4664
|
+
if (!lib || typeof lib.signAgentCapabilityCard !== 'function'
|
|
4665
|
+
|| typeof lib.validateCapabilityCardDraft !== 'function'
|
|
4666
|
+
|| typeof lib.appendCapabilityCard !== 'function') {
|
|
4667
|
+
return sendJson(res, 503, { ok: false, error: 'capability_cards_unavailable', message: '能力卡模块不可用' });
|
|
4668
|
+
}
|
|
4669
|
+
const namespace = typeof payload.namespace === 'string' && payload.namespace.length > 0
|
|
4670
|
+
? payload.namespace
|
|
4671
|
+
: 'agents';
|
|
4672
|
+
if (namespace !== 'agents') {
|
|
4673
|
+
return sendJson(res, 400, { ok: false, error: 'namespace_invalid', message: '能力卡只能写入 agents 域' });
|
|
4674
|
+
}
|
|
4675
|
+
const draft = payload.card;
|
|
4676
|
+
const validation = lib.validateCapabilityCardDraft(draft);
|
|
4677
|
+
if (!validation.ok) {
|
|
4678
|
+
return sendJson(res, 422, { ok: false, error: 'card_invalid', errors: validation.errors });
|
|
4679
|
+
}
|
|
4680
|
+
if (!deviceId) {
|
|
4681
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备身份不可用' });
|
|
4682
|
+
}
|
|
4683
|
+
if (draft.device !== deviceId) {
|
|
4684
|
+
return sendJson(res, 403, { ok: false, error: 'device_mismatch', message: '能力卡 device 必须是本机守护设备' });
|
|
4685
|
+
}
|
|
4686
|
+
const serialize = (fn) => {
|
|
4687
|
+
const run = cardWriteQueue.then(fn, fn);
|
|
4688
|
+
cardWriteQueue = run.catch(() => undefined);
|
|
4689
|
+
return run;
|
|
4690
|
+
};
|
|
4691
|
+
try {
|
|
4692
|
+
const result = await serialize(async () => {
|
|
4693
|
+
const latest = lib.latestCapabilityCards(await lib.listCapabilityCards(app, 'agents'))
|
|
4694
|
+
.find((card) => card.device === draft.device && card.agent === draft.agent) ?? null;
|
|
4695
|
+
if (latest !== null) {
|
|
4696
|
+
const sameContent = lib.capabilityCardFingerprint(latest) === lib.capabilityCardFingerprint(draft);
|
|
4697
|
+
if (latest.version === draft.version) {
|
|
4698
|
+
return sameContent
|
|
4699
|
+
? { status: 200, body: { ok: true, card: latest, nodeId: null, replayed: true } }
|
|
4700
|
+
: { status: 409, body: { ok: false, error: 'card_version_conflict', message: '同版本能力卡内容冲突' } };
|
|
4701
|
+
}
|
|
4702
|
+
if (latest.version > draft.version) {
|
|
4703
|
+
return { status: 409, body: { ok: false, error: 'card_stale', message: '能力卡版本落后于已发布版本' } };
|
|
4704
|
+
}
|
|
4705
|
+
if (draft.version !== latest.version + 1) {
|
|
4706
|
+
return { status: 409, body: { ok: false, error: 'card_version_gap', message: '能力卡版本必须紧邻上一版本' } };
|
|
4707
|
+
}
|
|
4708
|
+
} else if (draft.version !== 1) {
|
|
4709
|
+
return { status: 409, body: { ok: false, error: 'card_version_gap', message: '首版能力卡 version 必须为 1' } };
|
|
4710
|
+
}
|
|
4711
|
+
let signed;
|
|
4712
|
+
try {
|
|
4713
|
+
signed = await lib.signAgentCapabilityCard(app, draft);
|
|
4714
|
+
} catch (error) {
|
|
4715
|
+
if (error?.code === 'CARD_SIGNER_UNAVAILABLE') {
|
|
4716
|
+
return { status: 409, body: { ok: false, error: 'identity_unavailable', message: '本机设备身份不可用,无法签名能力卡' } };
|
|
4717
|
+
}
|
|
4718
|
+
throw error;
|
|
4719
|
+
}
|
|
4720
|
+
const signedCheck = lib.validateAgentCapabilityCard(signed);
|
|
4721
|
+
if (!signedCheck.ok) {
|
|
4722
|
+
return { status: 500, body: { ok: false, error: 'card_invalid', errors: signedCheck.errors } };
|
|
4723
|
+
}
|
|
4724
|
+
const nodeId = await lib.appendCapabilityCard(app, signed, 'agents');
|
|
4725
|
+
return { status: 200, body: { ok: true, card: signed, nodeId, replayed: false } };
|
|
4726
|
+
});
|
|
4727
|
+
return sendJson(res, result.status, result.body);
|
|
4728
|
+
} catch (error) {
|
|
4729
|
+
return sendJson(res, 500, { ok: false, error: 'capability_card_write_failed', message: String(error?.message ?? error) });
|
|
4730
|
+
}
|
|
4731
|
+
}
|
|
4732
|
+
// P5:daemon 角色卡写入/读取(loopback + memory.write/read)。
|
|
4733
|
+
// 只服务 fleet 内部 runtime job/route;不新增公共 MCP 方法/UI,
|
|
4734
|
+
// 也不开放 agent_role_card 到 /app/nodes。author = 本机守护设备。
|
|
4735
|
+
if (path === '/app/role-cards' && req.method === 'POST') {
|
|
4736
|
+
if (!app) return sendJson(res, 503, { ok: false, error: 'role_cards_unavailable', message: '图存储尚未初始化' });
|
|
4737
|
+
if (!writesEnabled) return sendJson(res, 403, { ok: false, error: 'read_only', message: '写能力已关闭' });
|
|
4738
|
+
let payload;
|
|
4739
|
+
try {
|
|
4740
|
+
payload = JSON.parse(body.toString('utf-8') || '{}');
|
|
4741
|
+
} catch {
|
|
4742
|
+
return sendJson(res, 400, { ok: false, error: 'invalid json' });
|
|
4743
|
+
}
|
|
4744
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
|
|
4745
|
+
return sendJson(res, 400, { ok: false, error: 'role card body 必须为对象' });
|
|
4746
|
+
}
|
|
4747
|
+
const lib = await loadFleetCards();
|
|
4748
|
+
if (!lib || typeof lib.validateAgentRoleCard !== 'function'
|
|
4749
|
+
|| typeof lib.sanitizeAgentRoleCardForWrite !== 'function'
|
|
4750
|
+
|| typeof lib.listAgentRoleCards !== 'function'
|
|
4751
|
+
|| typeof lib.latestAgentRoleCards !== 'function'
|
|
4752
|
+
|| typeof lib.roleCardFingerprint !== 'function'
|
|
4753
|
+
|| typeof lib.appendAgentRoleCard !== 'function') {
|
|
4754
|
+
return sendJson(res, 503, { ok: false, error: 'role_cards_unavailable', message: '角色卡模块不可用' });
|
|
4755
|
+
}
|
|
4756
|
+
const cardNamespace = typeof payload.namespace === 'string' && payload.namespace.length > 0
|
|
4757
|
+
? payload.namespace
|
|
4758
|
+
: 'agents';
|
|
4759
|
+
if (cardNamespace !== 'agents') {
|
|
4760
|
+
return sendJson(res, 400, { ok: false, error: 'namespace_invalid', message: '角色卡只能写入 agents 域' });
|
|
4761
|
+
}
|
|
4762
|
+
const card = payload.card !== undefined ? payload.card : payload.content;
|
|
4763
|
+
const validation = lib.validateAgentRoleCard(card);
|
|
4764
|
+
if (!validation.ok) {
|
|
4765
|
+
return sendJson(res, 422, { ok: false, error: 'role_card_invalid', errors: validation.errors });
|
|
4766
|
+
}
|
|
4767
|
+
// B3:服务端按安全字段重建 summary;客户端传入的原文 summary 一律丢弃。
|
|
4768
|
+
const writeCard = lib.sanitizeAgentRoleCardForWrite(card);
|
|
4769
|
+
const writeValidation = lib.validateAgentRoleCard(writeCard);
|
|
4770
|
+
if (!writeValidation.ok) {
|
|
4771
|
+
return sendJson(res, 422, { ok: false, error: 'role_card_invalid', errors: writeValidation.errors });
|
|
4772
|
+
}
|
|
4773
|
+
if (typeof deviceId !== 'string' || deviceId.length === 0) {
|
|
4774
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备身份不可用' });
|
|
4775
|
+
}
|
|
4776
|
+
if (writeCard.device !== deviceId) {
|
|
4777
|
+
return sendJson(res, 403, { ok: false, error: 'device_mismatch', message: '角色卡 device 必须是本机守护设备' });
|
|
4778
|
+
}
|
|
4779
|
+
const serialize = (fn) => {
|
|
4780
|
+
const run = roleCardWriteQueue.then(fn, fn);
|
|
4781
|
+
roleCardWriteQueue = run.catch(() => undefined);
|
|
4782
|
+
return run;
|
|
4783
|
+
};
|
|
4784
|
+
try {
|
|
4785
|
+
const result = await serialize(async () => {
|
|
4786
|
+
const latest = lib.latestAgentRoleCards(await lib.listAgentRoleCards(app, 'agents'))
|
|
4787
|
+
.find((entry) => entry.device === writeCard.device && entry.agent === writeCard.agent) ?? null;
|
|
4788
|
+
if (latest !== null) {
|
|
4789
|
+
const sameContent = lib.roleCardFingerprint(latest) === lib.roleCardFingerprint(writeCard);
|
|
4790
|
+
if (latest.version === writeCard.version) {
|
|
4791
|
+
return sameContent
|
|
4792
|
+
? { status: 200, body: { ok: true, card: latest, nodeId: null, createdBy: latest.device, replayed: true } }
|
|
4793
|
+
: { status: 409, body: { ok: false, error: 'ROLE_CARD_CONFLICT', message: '同版本角色卡内容冲突' } };
|
|
4794
|
+
}
|
|
4795
|
+
if (latest.version > writeCard.version) {
|
|
4796
|
+
return { status: 409, body: { ok: false, error: 'ROLE_CARD_STALE', message: '角色卡版本落后于已发布版本' } };
|
|
4797
|
+
}
|
|
4798
|
+
if (writeCard.version !== latest.version + 1) {
|
|
4799
|
+
return { status: 409, body: { ok: false, error: 'ROLE_CARD_VERSION_GAP', message: '角色卡版本必须紧邻上一版本' } };
|
|
4800
|
+
}
|
|
4801
|
+
} else if (writeCard.version !== 1) {
|
|
4802
|
+
return { status: 409, body: { ok: false, error: 'ROLE_CARD_VERSION_GAP', message: '首版角色卡 version 必须为 1' } };
|
|
4803
|
+
}
|
|
4804
|
+
const appended = await lib.appendAgentRoleCard(app, writeCard, 'agents');
|
|
4805
|
+
return {
|
|
4806
|
+
status: 200,
|
|
4807
|
+
body: {
|
|
4808
|
+
ok: true,
|
|
4809
|
+
card: appended.card,
|
|
4810
|
+
nodeId: appended.nodeId,
|
|
4811
|
+
createdBy: appended.createdBy,
|
|
4812
|
+
replayed: appended.replayed === true,
|
|
4813
|
+
},
|
|
4814
|
+
};
|
|
4815
|
+
});
|
|
4816
|
+
return sendJson(res, result.status, result.body);
|
|
4817
|
+
} catch (error) {
|
|
4818
|
+
const code = typeof error?.code === 'string' ? error.code : null;
|
|
4819
|
+
const status = code === 'ROLE_CARD_CONFLICT' || code === 'ROLE_CARD_STALE' || code === 'ROLE_CARD_VERSION_GAP'
|
|
4820
|
+
? 409
|
|
4821
|
+
: code === 'ROLE_CARD_AUTHOR'
|
|
4822
|
+
? 403
|
|
4823
|
+
: code === 'ROLE_CARD_SCHEMA'
|
|
4824
|
+
? 422
|
|
4825
|
+
: 500;
|
|
4826
|
+
return sendJson(res, status, {
|
|
4827
|
+
ok: false,
|
|
4828
|
+
...(code !== null ? { error: code } : { error: 'role_card_write_failed' }),
|
|
4829
|
+
...(Array.isArray(error?.errors) ? { errors: error.errors } : { message: String(error?.message ?? error) }),
|
|
4830
|
+
});
|
|
4831
|
+
}
|
|
4832
|
+
}
|
|
4833
|
+
if (path === '/app/role-cards' && req.method === 'GET') {
|
|
4834
|
+
if (!app) return sendJson(res, 503, { ok: false, error: 'role_cards_unavailable', message: '图存储尚未初始化' });
|
|
4835
|
+
const lib = await loadFleetCards();
|
|
4836
|
+
if (!lib || typeof lib.listAgentRoleCardNodes !== 'function') {
|
|
4837
|
+
return sendJson(res, 503, { ok: false, error: 'role_cards_unavailable', message: '角色卡模块不可用' });
|
|
4838
|
+
}
|
|
4839
|
+
const requested = url.searchParams.get('namespace');
|
|
4840
|
+
if (requested !== null && requested.length > 0 && requested !== 'agents') {
|
|
4841
|
+
return sendJson(res, 400, { ok: false, error: 'namespace_invalid', message: '角色卡只能读取 agents 域' });
|
|
4842
|
+
}
|
|
4843
|
+
const device = url.searchParams.get('device');
|
|
4844
|
+
const agent = url.searchParams.get('agent');
|
|
4845
|
+
let nodes = await lib.listAgentRoleCardNodes(app, { namespace: 'agents' });
|
|
4846
|
+
if (device) nodes = nodes.filter((entry) => entry.card.device === device);
|
|
4847
|
+
if (agent) nodes = nodes.filter((entry) => entry.card.agent === agent);
|
|
4848
|
+
return sendJson(res, 200, {
|
|
4849
|
+
ok: true,
|
|
4850
|
+
count: nodes.length,
|
|
4851
|
+
cards: nodes.map((entry) => entry.card),
|
|
4852
|
+
nodes: nodes.map((entry) => ({
|
|
4853
|
+
id: entry.nodeId,
|
|
4854
|
+
type: 'agent_role_card',
|
|
4855
|
+
namespace: 'agents',
|
|
4856
|
+
createdBy: entry.createdBy,
|
|
4857
|
+
content: entry.card,
|
|
4858
|
+
metadata: {
|
|
4859
|
+
internal: true,
|
|
4860
|
+
internalObject: { kind: 'agent_role_card' },
|
|
4861
|
+
},
|
|
4862
|
+
})),
|
|
4178
4863
|
});
|
|
4179
4864
|
}
|
|
4180
4865
|
// W2 A4:join 邀请(守护用自身身份生成令牌)
|
|
@@ -4292,7 +4977,7 @@ export async function startHttpServer({
|
|
|
4292
4977
|
});
|
|
4293
4978
|
// MCP 已就绪后再异步拉起 sidecar:失败只影响沉浸式记忆,不阻塞 READY/29 工具。
|
|
4294
4979
|
if (memoryRuntimeSupervisor && isMemoryRuntimeEnabled(config)) {
|
|
4295
|
-
void memoryRuntimeSupervisor.start().catch((error) => {
|
|
4980
|
+
void enqueueMemoryRuntimeLifecycle(() => memoryRuntimeSupervisor.start()).catch((error) => {
|
|
4296
4981
|
console.error(`MEMORY_RUNTIME_START_FAILED ${error?.code ?? 'ERROR'}`);
|
|
4297
4982
|
});
|
|
4298
4983
|
}
|
|
@@ -4302,6 +4987,14 @@ export async function startHttpServer({
|
|
|
4302
4987
|
const close = () => {
|
|
4303
4988
|
if (closePromise) return closePromise;
|
|
4304
4989
|
closePromise = (async () => {
|
|
4990
|
+
lifecycleClosing = true;
|
|
4991
|
+
// 先排空热生命周期,再在 listener 仍可达时撤销 capability。
|
|
4992
|
+
// attached/manual 同时由 dispose 撤销匹配 discovery,覆盖网络已断开的场景。
|
|
4993
|
+
await memoryRuntimeLifecycle.catch(() => undefined);
|
|
4994
|
+
capabilityDrain = await memoryCapability.close({ timeoutMs: 5000 }).catch(() => ({ clean: false }));
|
|
4995
|
+
if (!capabilityDrain.clean) {
|
|
4996
|
+
console.error('MEMORY_CAPABILITY_DRAIN_INCOMPLETE');
|
|
4997
|
+
}
|
|
4305
4998
|
// 优雅停止的顺序很重要:MCP/SSE/keep-alive 连接不会自己断,
|
|
4306
4999
|
// 先收 MCP sessions,再主动结束连接,最后才等 listener(带有限超时)。
|
|
4307
5000
|
// 详情维护先停 timer;进行中的 prune 最多等一个 session 预算,不拖死关闭。
|
|
@@ -4318,19 +5011,26 @@ export async function startHttpServer({
|
|
|
4318
5011
|
Promise.resolve().then(() => entry.server.close()),
|
|
4319
5012
|
sessionBudget,
|
|
4320
5013
|
)));
|
|
4321
|
-
// 2)
|
|
5014
|
+
// 2) 只结束空闲 keep-alive;仍活跃的请求需要机会完成响应。
|
|
5015
|
+
// 直接 closeAllConnections 会让已经进入 config rename 回滚的 PATCH
|
|
5016
|
+
// 在慢 CI 上只看到 socket closed,而不是契约要求的 409。
|
|
4322
5017
|
server.closeIdleConnections?.();
|
|
4323
|
-
|
|
4324
|
-
//
|
|
5018
|
+
// 3) 给已接受的请求一个很短的完成窗口,再强制断开 SSE/长连接;
|
|
5019
|
+
// 否则 server.close 会一直等到 5s 截止时间。
|
|
4325
5020
|
await new Promise((resolve) => {
|
|
4326
5021
|
let done = false;
|
|
4327
5022
|
let timer = null;
|
|
5023
|
+
let graceTimer = null;
|
|
4328
5024
|
const finish = () => {
|
|
4329
5025
|
if (done) return;
|
|
4330
5026
|
done = true;
|
|
4331
5027
|
clearTimeout(timer);
|
|
5028
|
+
clearTimeout(graceTimer);
|
|
4332
5029
|
resolve();
|
|
4333
5030
|
};
|
|
5031
|
+
graceTimer = setTimeout(() => {
|
|
5032
|
+
server.closeAllConnections?.();
|
|
5033
|
+
}, Math.min(500, Math.max(0, deadline - Date.now())));
|
|
4334
5034
|
timer = setTimeout(() => {
|
|
4335
5035
|
server.closeAllConnections?.();
|
|
4336
5036
|
finish();
|
|
@@ -4346,9 +5046,13 @@ export async function startHttpServer({
|
|
|
4346
5046
|
await clearRuntimeFile(home, { pid: process.pid }).catch(() => undefined);
|
|
4347
5047
|
// 5) 本地模型进程由 sidecar 拥有;MCP 不持有推理引擎,无需本地清理。
|
|
4348
5048
|
// 6) 保留最新 main 的生命周期收尾:root 单活锁 + 热初始化上下文(app/join/广播)。
|
|
4349
|
-
//
|
|
5049
|
+
// capability 只有 drain clean 后才撤销;drain 失败时明确放弃,不声明已撤销。
|
|
4350
5050
|
await memoryRuntimeSupervisor?.dispose().catch(() => undefined);
|
|
4351
|
-
|
|
5051
|
+
if (capabilityDrain?.clean) {
|
|
5052
|
+
await memoryCapability.dispose().catch(() => undefined);
|
|
5053
|
+
} else {
|
|
5054
|
+
memoryCapability.abandon();
|
|
5055
|
+
}
|
|
4352
5056
|
await activeLock?.release?.().catch(() => undefined);
|
|
4353
5057
|
await onClose?.().catch(() => undefined);
|
|
4354
5058
|
}
|
|
@@ -4365,6 +5069,9 @@ export async function startHttpServer({
|
|
|
4365
5069
|
getState: () => ({
|
|
4366
5070
|
phase,
|
|
4367
5071
|
hotInitialized,
|
|
5072
|
+
closing: lifecycleClosing,
|
|
5073
|
+
capabilityDrain,
|
|
5074
|
+
capabilityDraining: memoryCapability.isDraining?.() === true,
|
|
4368
5075
|
app,
|
|
4369
5076
|
service,
|
|
4370
5077
|
config,
|