@mebular/mcp 0.2.3 → 0.3.0

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/src/serve.mjs CHANGED
@@ -19,6 +19,22 @@ import { attachFleetEvents, resolveFleetNamespace } from './fleet-events.mjs';
19
19
  import { READ_ROUTES, buildHandoffPlan } from './admin.mjs';
20
20
  import { configPath } from './config.mjs';
21
21
  import { createServiceFacade } from './service-facade.mjs';
22
+ import { createDetailMaintenance } from './detail-maintenance.mjs';
23
+ import {
24
+ createMemoryCapabilityHandler,
25
+ isMemoryCapabilityPath,
26
+ isMemoryRuntimeEnabled,
27
+ } from './memory-capability.mjs';
28
+ import {
29
+ MemoryRuntimeSupervisor,
30
+ disabledMemoryRuntimeStatus,
31
+ } from './memory-runtime-supervisor.mjs';
32
+ import {
33
+ DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
34
+ MEMORY_RUNTIME_MODEL_SOURCES,
35
+ normalizeMemoryRuntimeModelSource,
36
+ readMemoryRuntimeModelSource,
37
+ } from './memory-runtime-config.mjs';
22
38
  import { APP_VERSION } from './version.mjs';
23
39
  import { resolveStaticAssetRoots } from './asset-roots.mjs';
24
40
 
@@ -872,12 +888,22 @@ export async function startHttpServer({
872
888
  initializeRuntime = null,
873
889
  // 关闭钩子:热初始化后由 server.mjs 关闭 app / join / 广播计时器(HTTP server 本身由本函数关闭)
874
890
  onClose = null,
891
+ // Memory Runtime sidecar 生命周期:只在 MCP daemon(HTTP 模式)启用。
892
+ // 测试可直接关掉;生产入口 server.mjs 显式传 true。
893
+ manageMemoryRuntime = true,
875
894
  }) {
876
895
  // P1:生命周期状态。所有路由共用**可变**上下文;create/join 成功后就地切换,不重启进程 / 端口。
877
896
  let app = initialApp;
878
897
  let service = initialService;
879
898
  let config = initialConfig ?? {};
880
899
  let runtime = initialRuntime;
900
+
901
+ // 0.3 详情保留维护:service 就绪后启动(启动一次 + 每 24h),热切换复用同一 timer。
902
+ // 失败只记录状态/日志,不阻断 MCP;关闭时显式清理,避免测试/宿主进程残留 timer。
903
+ const detailMaintenance = createDetailMaintenance({ getService: () => service });
904
+
905
+ // 0.3 模型目录/安装/引擎/来源全部由 Memory Runtime sidecar 拥有。
906
+ // MCP 不再读取 <home>/models 或 <home>/inference.json,也不改写 runtime.model。
881
907
  let deviceId = initialDeviceId;
882
908
  let namespace = initialNamespace;
883
909
  let joinEndpoint = initialJoinEndpoint;
@@ -927,6 +953,8 @@ export async function startHttpServer({
927
953
  cloudId = cloud.available ? await profileIdForHome(cloud.root, home).catch(() => null) : null;
928
954
  phase = 'READY';
929
955
  if (viaHotInit) hotInitialized = true;
956
+ // 热初始化:同一个 scheduler 动态读取新 service;当天已成功扫过则不重复。
957
+ detailMaintenance.start();
930
958
  return { phase, cloudId };
931
959
  }
932
960
 
@@ -955,6 +983,558 @@ export async function startHttpServer({
955
983
  // 热初始化后同一会话内的 tools/call 直接转发到真实 MemoryService(不重连、不重新 initialize)。
956
984
  const runtimeReady = () => phase === 'READY' && Boolean(service);
957
985
  const serviceFacade = createServiceFacade({ getService: () => service, isReady: runtimeReady });
986
+
987
+ // 0.3 Memory Capability API:内部接口 `/internal/memory/v1`(读 + 写 + 内部对象 + sync)。
988
+ // 只有 memoryRuntime.enabled=true 时挂载/生成 token;轻量模式零目录/文件/进程副作用。
989
+ // capability 不是公共 MCP 工具;29 工具面不变。
990
+ const memoryCapability = createMemoryCapabilityHandler({
991
+ home,
992
+ getConfig: () => config,
993
+ getService: () => service,
994
+ getApp: () => app,
995
+ getIdentity: () => ({
996
+ // /healthz 的 cloudId 是既有 profile 语义;capability 的稳定 cloudTrustId 暂不可得。
997
+ cloudId: null,
998
+ cloudTrustId: null,
999
+ profileId: cloudId,
1000
+ userId: 'user',
1001
+ deviceId: app?.deviceId ?? null,
1002
+ }),
1003
+ ttlMs: (() => {
1004
+ const raw = Number(process.env.MEBULAR_CAPABILITY_TOKEN_TTL_MS ?? '');
1005
+ return Number.isFinite(raw) && raw > 0 ? raw : undefined;
1006
+ })(),
1007
+ });
1008
+
1009
+ // 0.3 Memory Runtime sidecar 生命周期适配:只 spawn/health/stop,不 import sidecar 业务。
1010
+ // 轻量模式(enabled=false)不会创建目录/token/进程/端口;自动启动在 listen 后异步进行,
1011
+ // 不阻塞 MCP READY/29 工具。关闭时只停止本进程启动的 sidecar(attach 的不动)。
1012
+ const memoryRuntimeSupervisor = manageMemoryRuntime
1013
+ ? new MemoryRuntimeSupervisor({
1014
+ home,
1015
+ config: () => config,
1016
+ env: process.env,
1017
+ profileId: () => cloudId,
1018
+ cloudId: () => null,
1019
+ mcpUrl: () => origin,
1020
+ })
1021
+ : null;
1022
+
1023
+ // ---------- 0.3 模型薄代理:模型目录/安装/引擎/来源全部由 sidecar 拥有 ----------
1024
+ // 浏览器只看到 sidecar 的脱敏视图;host token 只在服务端使用。
1025
+ function uniqueStrings(values) {
1026
+ return [...new Set(values.filter((value) => typeof value === 'string' && value.length > 0))];
1027
+ }
1028
+
1029
+ function proxyFailure(result, fallbackMessage) {
1030
+ const error = result?.error && typeof result.error === 'object'
1031
+ ? result.error
1032
+ : { code: 'sidecar_request_failed', message: fallbackMessage, retryable: false };
1033
+ const status = Number.isInteger(result?.status) ? result.status : 503;
1034
+ return {
1035
+ status,
1036
+ body: {
1037
+ ok: false,
1038
+ error: {
1039
+ code: error.code,
1040
+ message: error.message ?? fallbackMessage,
1041
+ retryable: error.retryable === true,
1042
+ ...(error.details ? { details: error.details } : {}),
1043
+ },
1044
+ code: error.code,
1045
+ message: error.message ?? fallbackMessage,
1046
+ enabled: result?.enabled === true,
1047
+ state: result?.state ?? 'stopped',
1048
+ ...(result?.disabled === true ? { disabled: true } : {}),
1049
+ },
1050
+ };
1051
+ }
1052
+
1053
+ const modelPackId = (input) => {
1054
+ const value = input?.pack ?? input?.packId ?? input?.id;
1055
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
1056
+ };
1057
+
1058
+ function modelDownloadView(install) {
1059
+ if (!install || typeof install !== 'object') return null;
1060
+ return {
1061
+ pack: install.packId ?? null,
1062
+ packId: install.packId ?? null,
1063
+ state: install.state ?? null,
1064
+ phase: install.phase ?? null,
1065
+ progress: install.progress ?? 0,
1066
+ downloadedBytes: install.downloadedBytes ?? 0,
1067
+ totalBytes: install.totalBytes ?? 0,
1068
+ speedBytesPerSecond: install.speedBytesPerSecond ?? 0,
1069
+ etaMs: install.etaMs ?? null,
1070
+ updatedAt: install.updatedAt ?? null,
1071
+ ...(install.error ? { error: install.error } : {}),
1072
+ };
1073
+ }
1074
+
1075
+ function modelPackView(pack) {
1076
+ return {
1077
+ ...pack,
1078
+ selected: pack?.active === true,
1079
+ manifestAvailable: pack?.manifest?.available === true,
1080
+ ...(pack?.install ? { download: modelDownloadView(pack.install) } : {}),
1081
+ };
1082
+ }
1083
+
1084
+ function modelListBody(catalog) {
1085
+ const data = catalog ?? {};
1086
+ const active = data.active ?? {};
1087
+ return {
1088
+ ok: true,
1089
+ schema: 1,
1090
+ selectedPack: active.packId ?? null,
1091
+ effectivePack: active.packId ?? null,
1092
+ selectionSource: 'sidecar',
1093
+ runtime: {
1094
+ source: active.source ?? 'heuristic',
1095
+ pack: active.packId ?? null,
1096
+ selectionSource: 'sidecar',
1097
+ },
1098
+ packs: Array.isArray(data.packs) ? data.packs.map(modelPackView) : [],
1099
+ hardware: data.hardware ?? null,
1100
+ recommended: data.recommended ?? null,
1101
+ active,
1102
+ providers: Array.isArray(data.providers) ? data.providers : [],
1103
+ install: data.install ?? null,
1104
+ engine: data.engine ?? null,
1105
+ warnings: Array.isArray(data.warnings) ? data.warnings : [],
1106
+ };
1107
+ }
1108
+
1109
+ function modelStatusBody(catalog, inference) {
1110
+ const data = catalog ?? {};
1111
+ const runtime = inference ?? {};
1112
+ const active = runtime.active ?? data.active ?? {};
1113
+ const recommended = runtime.recommended ?? data.recommended ?? null;
1114
+ const warnings = uniqueStrings([
1115
+ ...(Array.isArray(data.warnings) ? data.warnings : []),
1116
+ ...(Array.isArray(runtime.warnings) ? runtime.warnings : []),
1117
+ ]);
1118
+ return {
1119
+ ok: true,
1120
+ schema: 1,
1121
+ selectedPack: active.packId ?? null,
1122
+ effectivePack: active.packId ?? null,
1123
+ selectionSource: 'sidecar',
1124
+ runtime: {
1125
+ source: active.source ?? 'heuristic',
1126
+ pack: active.packId ?? null,
1127
+ selectionSource: 'sidecar',
1128
+ },
1129
+ engine: runtime.engine ?? data.engine ?? null,
1130
+ hardware: data.hardware ?? null,
1131
+ recommendation: recommended,
1132
+ install: runtime.install ?? data.install ?? null,
1133
+ active,
1134
+ installedPackIds: Array.isArray(runtime.installedPackIds)
1135
+ ? runtime.installedPackIds
1136
+ : (Array.isArray(data.packs) ? data.packs.filter((pack) => pack?.installed === true).map((pack) => pack.packId) : []),
1137
+ packs: Array.isArray(data.packs)
1138
+ ? data.packs.map((pack) => ({
1139
+ packId: pack.packId,
1140
+ modelId: pack.modelId,
1141
+ tier: pack.tier,
1142
+ state: pack.state,
1143
+ selected: pack.active === true,
1144
+ installed: pack.installed === true,
1145
+ installedBytes: pack.installedBytes ?? 0,
1146
+ expectedBytes: pack.expectedBytes ?? 0,
1147
+ }))
1148
+ : [],
1149
+ downloads: [],
1150
+ warnings,
1151
+ };
1152
+ }
1153
+
1154
+ async function modelListResponse() {
1155
+ if (!memoryRuntimeSupervisor) {
1156
+ return proxyFailure({
1157
+ status: 409,
1158
+ enabled: false,
1159
+ disabled: true,
1160
+ state: 'stopped',
1161
+ error: { code: 'memory_runtime_disabled', message: '记忆运行时未启用', retryable: false },
1162
+ }, '记忆运行时未启用');
1163
+ }
1164
+ const result = await memoryRuntimeSupervisor.listModels();
1165
+ if (!result.ok) return proxyFailure(result, '模型列表不可用');
1166
+ return { status: 200, body: modelListBody(result.data) };
1167
+ }
1168
+
1169
+ async function modelStatusResponse() {
1170
+ if (!memoryRuntimeSupervisor) {
1171
+ return proxyFailure({
1172
+ status: 409,
1173
+ enabled: false,
1174
+ disabled: true,
1175
+ state: 'stopped',
1176
+ error: { code: 'memory_runtime_disabled', message: '记忆运行时未启用', retryable: false },
1177
+ }, '记忆运行时未启用');
1178
+ }
1179
+ const [catalog, inference] = await Promise.all([
1180
+ memoryRuntimeSupervisor.listModels(),
1181
+ memoryRuntimeSupervisor.inferenceStatus(),
1182
+ ]);
1183
+ if (!catalog.ok) return proxyFailure(catalog, '模型目录不可用');
1184
+ return {
1185
+ status: 200,
1186
+ body: modelStatusBody(catalog.data, inference.ok ? inference.data : null),
1187
+ };
1188
+ }
1189
+
1190
+ function modelActionSuccess(result, extra = {}) {
1191
+ const data = result.data ?? {};
1192
+ return {
1193
+ status: Number.isInteger(result.status) && result.status >= 200 && result.status < 300 ? result.status : 200,
1194
+ body: {
1195
+ ok: true,
1196
+ ...data,
1197
+ ...extra,
1198
+ warnings: Array.isArray(data.warnings) ? data.warnings : [],
1199
+ },
1200
+ };
1201
+ }
1202
+
1203
+ async function handleModelAction(action, input) {
1204
+ const rawAction = typeof action === 'string' ? action : '';
1205
+ const name = rawAction === 'uninstall' ? 'remove'
1206
+ : rawAction === 'download' ? 'install'
1207
+ : rawAction;
1208
+ if (name === 'pause' || name === 'resume' || name === 'import') {
1209
+ return {
1210
+ status: 501,
1211
+ body: {
1212
+ ok: false,
1213
+ error: {
1214
+ code: 'unsupported',
1215
+ message: `${rawAction} 由 sidecar 模型安装任务取代:请使用 cancel 或重新 install`,
1216
+ retryable: false,
1217
+ },
1218
+ code: 'unsupported',
1219
+ message: `${rawAction} 暂不支持`,
1220
+ },
1221
+ };
1222
+ }
1223
+ if (!['install', 'select', 'cancel', 'remove', 'start', 'stop', 'test'].includes(name)) {
1224
+ return {
1225
+ status: 404,
1226
+ body: {
1227
+ ok: false,
1228
+ error: { code: 'unknown_action', message: `未知模型操作:${rawAction}`, retryable: false },
1229
+ code: 'unknown_action',
1230
+ message: `未知模型操作:${rawAction}`,
1231
+ },
1232
+ };
1233
+ }
1234
+ if (!memoryRuntimeSupervisor) {
1235
+ return proxyFailure({
1236
+ status: 409,
1237
+ enabled: false,
1238
+ disabled: true,
1239
+ state: 'stopped',
1240
+ error: { code: 'memory_runtime_disabled', message: '记忆运行时未启用', retryable: false },
1241
+ }, '记忆运行时未启用');
1242
+ }
1243
+ const pack = modelPackId(input);
1244
+
1245
+ if (name === 'install') {
1246
+ if (!pack) {
1247
+ return {
1248
+ status: 400,
1249
+ body: { ok: false, error: { code: 'invalid_request', message: '缺少 pack', retryable: false } },
1250
+ };
1251
+ }
1252
+ const result = await memoryRuntimeSupervisor.installModel(pack, {
1253
+ force: input?.force === true || input?.force === 'true' || input?.force === '1',
1254
+ });
1255
+ if (!result.ok) return proxyFailure(result, '模型安装失败');
1256
+ const job = result.data ?? {};
1257
+ return {
1258
+ status: result.status === 202 ? 202 : 200,
1259
+ body: {
1260
+ ok: true,
1261
+ accepted: result.status === 202,
1262
+ pack: job.packId ?? pack,
1263
+ job,
1264
+ ...job,
1265
+ warnings: Array.isArray(job.warnings) ? job.warnings : [],
1266
+ },
1267
+ };
1268
+ }
1269
+
1270
+ if (name === 'select') {
1271
+ if (!pack) {
1272
+ return {
1273
+ status: 400,
1274
+ body: { ok: false, error: { code: 'invalid_request', message: '缺少 pack', retryable: false } },
1275
+ };
1276
+ }
1277
+ const result = await memoryRuntimeSupervisor.activateModel(pack);
1278
+ if (!result.ok) return proxyFailure(result, '模型激活失败');
1279
+ const data = result.data ?? {};
1280
+ return {
1281
+ status: 200,
1282
+ body: {
1283
+ ok: true,
1284
+ selected: data.activated === true,
1285
+ selectedPack: data.packId ?? pack,
1286
+ activated: data.activated === true,
1287
+ active: data.active ?? 'heuristic',
1288
+ runtime: {
1289
+ source: data.active ?? 'heuristic',
1290
+ pack: data.active === 'local' ? (data.packId ?? pack) : null,
1291
+ selectionSource: 'sidecar',
1292
+ },
1293
+ requiresRestart: false,
1294
+ warnings: Array.isArray(data.warnings) ? data.warnings : [],
1295
+ },
1296
+ };
1297
+ }
1298
+
1299
+ if (name === 'cancel') {
1300
+ let jobId = typeof input?.jobId === 'string' ? input.jobId.trim() : '';
1301
+ if (jobId.length === 0) {
1302
+ const status = await memoryRuntimeSupervisor.inferenceStatus();
1303
+ if (status.ok && typeof status.data?.install?.jobId === 'string') {
1304
+ jobId = status.data.install.jobId;
1305
+ }
1306
+ }
1307
+ if (jobId.length === 0) {
1308
+ return {
1309
+ status: 409,
1310
+ body: { ok: false, error: { code: 'install_not_running', message: '没有正在进行的安装任务', retryable: false } },
1311
+ };
1312
+ }
1313
+ const result = await memoryRuntimeSupervisor.cancelInstall(jobId);
1314
+ if (!result.ok) return proxyFailure(result, '取消安装失败');
1315
+ return modelActionSuccess(result, {
1316
+ pack,
1317
+ cancelled: result.data?.state === 'cancelled',
1318
+ });
1319
+ }
1320
+
1321
+ if (name === 'test') {
1322
+ const inference = await memoryRuntimeSupervisor.inferenceStatus();
1323
+ if (!inference.ok) return proxyFailure(inference, '模型状态检查失败');
1324
+ let status = null;
1325
+ if (pack) {
1326
+ status = await memoryRuntimeSupervisor.modelStatus(pack);
1327
+ if (!status.ok) return proxyFailure(status, '模型状态检查失败');
1328
+ }
1329
+ return {
1330
+ status: 200,
1331
+ body: {
1332
+ ok: true,
1333
+ tested: true,
1334
+ pack: pack ?? inference.data?.active?.packId ?? null,
1335
+ state: status?.data?.state ?? null,
1336
+ installed: status?.data?.installed ?? null,
1337
+ engine: inference.data?.engine ?? null,
1338
+ active: inference.data?.active ?? null,
1339
+ warnings: uniqueStrings([
1340
+ ...(Array.isArray(inference.warnings) ? inference.warnings : []),
1341
+ ...(Array.isArray(status?.warnings) ? status.warnings : []),
1342
+ ]),
1343
+ },
1344
+ };
1345
+ }
1346
+
1347
+ if (!pack) {
1348
+ return {
1349
+ status: 400,
1350
+ body: { ok: false, error: { code: 'invalid_request', message: '缺少 pack', retryable: false } },
1351
+ };
1352
+ }
1353
+ const result = name === 'remove'
1354
+ ? await memoryRuntimeSupervisor.removeModel(pack)
1355
+ : name === 'start'
1356
+ ? await memoryRuntimeSupervisor.startEngine(pack)
1357
+ : await memoryRuntimeSupervisor.stopEngine(pack);
1358
+ if (!result.ok) return proxyFailure(result, `模型 ${name} 失败`);
1359
+ if (name === 'remove') {
1360
+ return modelActionSuccess(result, {
1361
+ pack: result.data?.packId ?? pack,
1362
+ removed: result.data?.removed === true,
1363
+ });
1364
+ }
1365
+ return modelActionSuccess(result, { pack: result.data?.packId ?? pack });
1366
+ }
1367
+
1368
+ function modelSourceModelView(data) {
1369
+ const active = data?.active ?? {};
1370
+ const providers = Array.isArray(data?.providers) ? data.providers : [];
1371
+ return {
1372
+ configured: data?.config?.source ?? active.source ?? null,
1373
+ active: active.source ?? null,
1374
+ degraded: data?.degraded === true,
1375
+ reason: null,
1376
+ sources: providers.map((provider) => provider.id).filter((id) => typeof id === 'string'),
1377
+ };
1378
+ }
1379
+
1380
+ function modelSourceSuccess(result, source) {
1381
+ const data = result.data ?? {};
1382
+ return {
1383
+ status: 200,
1384
+ body: {
1385
+ ok: true,
1386
+ source,
1387
+ defaultSource: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
1388
+ values: [...MEMORY_RUNTIME_MODEL_SOURCES],
1389
+ exists: true,
1390
+ enabled: true,
1391
+ available: true,
1392
+ state: result.state,
1393
+ degraded: result.degraded === true,
1394
+ reason: null,
1395
+ error: null,
1396
+ model: modelSourceModelView(data),
1397
+ applies: 'hot',
1398
+ },
1399
+ };
1400
+ }
1401
+
1402
+ async function readModelSourceResponse() {
1403
+ const enabled = memoryRuntimeSupervisor?.isEnabled() === true;
1404
+ if (enabled) {
1405
+ const result = await memoryRuntimeSupervisor.inferenceStatus();
1406
+ if (result.ok) {
1407
+ const data = result.data ?? {};
1408
+ const source = normalizeMemoryRuntimeModelSource(data?.config?.source)
1409
+ ?? normalizeMemoryRuntimeModelSource(data?.active?.source)
1410
+ ?? DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE;
1411
+ return modelSourceSuccess(result, source);
1412
+ }
1413
+ // 未就绪时仍返回可读视图;写入会返回结构化 unavailable。
1414
+ const fallback = await readMemoryRuntimeModelSource({ home }).catch(() => null);
1415
+ const snapshot = memoryRuntimeSupervisor.snapshot();
1416
+ return {
1417
+ status: 200,
1418
+ body: {
1419
+ ok: true,
1420
+ source: fallback?.source ?? DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
1421
+ defaultSource: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
1422
+ values: [...MEMORY_RUNTIME_MODEL_SOURCES],
1423
+ exists: fallback?.exists === true,
1424
+ enabled: true,
1425
+ available: false,
1426
+ state: snapshot.state,
1427
+ degraded: snapshot.state === 'degraded',
1428
+ reason: snapshot.reason ?? null,
1429
+ error: result.error,
1430
+ model: null,
1431
+ applies: 'next_start',
1432
+ },
1433
+ };
1434
+ }
1435
+ let fallback;
1436
+ try {
1437
+ fallback = await readMemoryRuntimeModelSource({ home });
1438
+ } catch (error) {
1439
+ fallback = {
1440
+ source: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
1441
+ defaultSource: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
1442
+ values: [...MEMORY_RUNTIME_MODEL_SOURCES],
1443
+ exists: false,
1444
+ warnings: [error?.code ?? 'config_unreadable'],
1445
+ };
1446
+ }
1447
+ return {
1448
+ status: 200,
1449
+ body: {
1450
+ ok: true,
1451
+ ...fallback,
1452
+ enabled: false,
1453
+ available: false,
1454
+ state: 'stopped',
1455
+ degraded: false,
1456
+ reason: 'disabled',
1457
+ error: null,
1458
+ model: null,
1459
+ applies: 'next_start',
1460
+ },
1461
+ };
1462
+ }
1463
+
1464
+ // model-source 保持既有 `error: '<code>'` 信封(Console 兼容);模型操作使用 error 对象。
1465
+ function modelSourceFailure(result, fallbackCode, fallbackMessage) {
1466
+ const code = typeof result?.error?.code === 'string' ? result.error.code : fallbackCode;
1467
+ const message = typeof result?.error?.message === 'string' ? result.error.message : fallbackMessage;
1468
+ const status = Number.isInteger(result?.status) ? result.status : 503;
1469
+ return {
1470
+ status,
1471
+ body: {
1472
+ ok: false,
1473
+ error: code,
1474
+ code,
1475
+ message,
1476
+ enabled: result?.enabled === true,
1477
+ state: result?.state ?? 'stopped',
1478
+ ...(result?.disabled === true ? { disabled: true } : {}),
1479
+ },
1480
+ };
1481
+ }
1482
+
1483
+ async function writeModelSourceResponse(input) {
1484
+ const source = normalizeMemoryRuntimeModelSource(input?.source);
1485
+ if (!source) {
1486
+ return {
1487
+ status: 400,
1488
+ body: {
1489
+ ok: false,
1490
+ error: 'invalid_model_source',
1491
+ code: 'invalid_model_source',
1492
+ message: '模型来源不合法',
1493
+ },
1494
+ };
1495
+ }
1496
+ if (!memoryRuntimeSupervisor || memoryRuntimeSupervisor.isEnabled() !== true) {
1497
+ return modelSourceFailure({
1498
+ status: 409,
1499
+ enabled: false,
1500
+ disabled: true,
1501
+ state: 'stopped',
1502
+ error: { code: 'memory_runtime_disabled', message: '记忆模式为轻量 MCP:切换到沉浸式后才能调整模型来源', retryable: false },
1503
+ }, 'memory_runtime_disabled', '记忆模式为轻量 MCP');
1504
+ }
1505
+ if (source === 'local') {
1506
+ const pack = modelPackId(input);
1507
+ if (!pack) {
1508
+ return {
1509
+ status: 400,
1510
+ body: {
1511
+ ok: false,
1512
+ error: 'pack_required',
1513
+ code: 'pack_required',
1514
+ message: 'source=local 需要 pack,并通过模型包激活设置',
1515
+ },
1516
+ };
1517
+ }
1518
+ const result = await memoryRuntimeSupervisor.activateModel(pack);
1519
+ if (!result.ok) return modelSourceFailure(result, 'model_activation_failed', '模型激活失败');
1520
+ const data = result.data ?? {};
1521
+ const response = modelSourceSuccess(result, normalizeMemoryRuntimeModelSource(data.active) ?? source);
1522
+ return {
1523
+ ...response,
1524
+ body: {
1525
+ ...response.body,
1526
+ selectedPack: data.packId ?? pack,
1527
+ activated: data.activated === true,
1528
+ requiresRestart: false,
1529
+ warnings: Array.isArray(data.warnings) ? data.warnings : [],
1530
+ },
1531
+ };
1532
+ }
1533
+ const result = await memoryRuntimeSupervisor.updateInferenceSettings({ source });
1534
+ if (!result.ok) return modelSourceFailure(result, 'model_source_failed', '模型来源保存失败');
1535
+ return modelSourceSuccess(result, source);
1536
+ }
1537
+
958
1538
  const mcpSessions = new Map(); // sessionId → { transport, server }
959
1539
  async function transportFor(sessionId) {
960
1540
  if (sessionId) return mcpSessions.get(sessionId)?.transport ?? null;
@@ -1162,7 +1742,17 @@ export async function startHttpServer({
1162
1742
 
1163
1743
  async function handleAdminRead(req, res, path, url) {
1164
1744
  const builder = READ_ROUTES[path];
1165
- if (!builder) return false;
1745
+ const memoryRuntimeTrace = /^\/admin\/api\/memory-runtime\/traces\/([^/]+)$/.exec(path);
1746
+ const modelRead = path === '/admin/api/models'
1747
+ || path === '/admin/api/models/status'
1748
+ || path === '/admin/api/inference/models'
1749
+ || path === '/admin/api/inference/status';
1750
+ const memoryRuntimeRead = modelRead
1751
+ || path === '/admin/api/memory-runtime/status'
1752
+ || path === '/admin/api/memory-runtime/model-source'
1753
+ || path === '/admin/api/memory-runtime/traces'
1754
+ || memoryRuntimeTrace !== null;
1755
+ if (!builder && !memoryRuntimeRead) return false;
1166
1756
  // P2:助手列表只读本机配置,UNINITIALIZED 也开放;其余 admin 读数据面仍需 READY。
1167
1757
  if ((!app || !service) && path !== '/admin/api/clients') {
1168
1758
  return sendJson(res, 503, { error: 'console_unavailable', message: 'Mebular 尚未初始化' });
@@ -1173,6 +1763,81 @@ export async function startHttpServer({
1173
1763
  if (check.challenge) res.setHeader('www-authenticate', check.challenge);
1174
1764
  return sendJson(res, check.status, { error: 'unauthorized', message: check.message });
1175
1765
  }
1766
+ if (memoryRuntimeRead) {
1767
+ // 只读薄代理:浏览器不接触 sidecar host token;轻量模式返回明确 disabled/stopped。
1768
+ if (modelRead) {
1769
+ const result = path.endsWith('/status')
1770
+ ? await modelStatusResponse()
1771
+ : await modelListResponse();
1772
+ return sendJson(res, result.status, result.body);
1773
+ }
1774
+ if (path === '/admin/api/memory-runtime/status') {
1775
+ const status = memoryRuntimeSupervisor
1776
+ ? await memoryRuntimeSupervisor.status().catch(() => memoryRuntimeSupervisor.snapshot())
1777
+ : disabledMemoryRuntimeStatus();
1778
+ const detail = memoryRuntimeSupervisor
1779
+ ? await memoryRuntimeSupervisor.readStatus().catch(() => null)
1780
+ : null;
1781
+ // 只合并模式/版本/模型状态;host token、endpoint、keyRef、模型路径永不出服务端。
1782
+ return sendJson(res, 200, {
1783
+ ...status,
1784
+ mode: status.enabled ? 'immersive' : 'lightweight',
1785
+ runtimeVersion: status.runtimeVersion ?? detail?.runtimeVersion ?? null,
1786
+ model: detail?.model ?? null,
1787
+ });
1788
+ }
1789
+ if (path === '/admin/api/memory-runtime/model-source') {
1790
+ const result = await readModelSourceResponse();
1791
+ return sendJson(res, result.status, result.body);
1792
+ }
1793
+ if (!memoryRuntimeSupervisor) {
1794
+ if (memoryRuntimeTrace) {
1795
+ return sendJson(res, 200, {
1796
+ ok: true,
1797
+ enabled: false,
1798
+ available: false,
1799
+ disabled: true,
1800
+ state: 'stopped',
1801
+ reason: 'disabled',
1802
+ trace: null,
1803
+ error: null,
1804
+ });
1805
+ }
1806
+ return sendJson(res, 200, {
1807
+ ok: true,
1808
+ enabled: false,
1809
+ available: false,
1810
+ disabled: true,
1811
+ state: 'stopped',
1812
+ reason: 'disabled',
1813
+ traces: [],
1814
+ total: 0,
1815
+ degraded: false,
1816
+ warnings: [],
1817
+ });
1818
+ }
1819
+ if (memoryRuntimeTrace) {
1820
+ const trace = await memoryRuntimeSupervisor.readTrace(decodeURIComponent(memoryRuntimeTrace[1]));
1821
+ return sendJson(res, 200, trace);
1822
+ }
1823
+ const traces = await memoryRuntimeSupervisor.readTraces({ limit: url.searchParams.get('limit') ?? 20 });
1824
+ return sendJson(res, 200, traces);
1825
+ }
1826
+ // 内部对象只在管理面显式调试时可见;includeInternal 不能由普通读 token 打开。
1827
+ if (path === '/admin/api/memories') {
1828
+ const includeInternal = url.searchParams.get('includeInternal');
1829
+ if (includeInternal === '1' || includeInternal === 'true') {
1830
+ const adminCheck = await authenticate(req, Buffer.alloc(0), 'memory.admin');
1831
+ if (!adminCheck.ok) {
1832
+ res.statusCode = adminCheck.status;
1833
+ if (adminCheck.challenge) res.setHeader('www-authenticate', adminCheck.challenge);
1834
+ return sendJson(res, adminCheck.status, {
1835
+ error: 'forbidden',
1836
+ message: 'includeInternal 需要 memory.admin scope',
1837
+ });
1838
+ }
1839
+ }
1840
+ }
1176
1841
  // 注意:CSRF token 只在 /console/ 页面加载时签发。若在 overview 轮询里重新签发,
1177
1842
  // cookie 会被每次轮询改写,与并发的写请求竞争(读 cookie 后、发出写之前又来一次
1178
1843
  // overview)→ header 与 cookie 不一致而 403。token 12h 有效,页面加载签发一次即可。
@@ -1193,6 +1858,10 @@ export async function startHttpServer({
1193
1858
  }
1194
1859
  if (path === '/admin/api/overview') {
1195
1860
  payload.features = { writes: Boolean(writesEnabled) };
1861
+ // 只读状态;不包含 token/tokenFile。禁用/未安装/失败都明确呈现,失败开放。
1862
+ payload.memoryRuntime = memoryRuntimeSupervisor
1863
+ ? await memoryRuntimeSupervisor.status().catch(() => memoryRuntimeSupervisor.snapshot())
1864
+ : disabledMemoryRuntimeStatus();
1196
1865
  }
1197
1866
  return sendJson(res, 200, payload);
1198
1867
  }
@@ -1341,10 +2010,17 @@ export async function startHttpServer({
1341
2010
  /^\/admin\/api\/security\/recovery\/(generate|rotate)$/,
1342
2011
  /^\/admin\/api\/namespaces\/([^/]+)\/(rejoin|leave)$/,
1343
2012
  /^\/admin\/api\/service\/(install|uninstall)$/,
2013
+ /^\/admin\/api\/repair$/,
1344
2014
  /^\/admin\/api\/clients\/([^/]+)\/(connect|rollback|skills|preview|verify|recheck)$/,
1345
2015
  /^\/admin\/api\/assistants$/,
1346
2016
  /^\/admin\/api\/assistants\/([^/]+)$/,
1347
2017
  /^\/admin\/api\/assistants\/([^/]+)\/remove$/,
2018
+ // 0.3 本地模型:sidecar 薄代理;同走 Origin + CSRF + memory.admin。
2019
+ /^\/admin\/api\/(?:models|inference)\/(install|select|download|pause|resume|cancel|import|uninstall|remove|start|stop|test)$/,
2020
+ // 0.3 记忆运行时:召回反馈经 MCP 薄代理转发 sidecar;host token 不出服务端。
2021
+ /^\/admin\/api\/memory-runtime\/feedback$/,
2022
+ // 0.3 高级模型来源:经 sidecar `/inference/settings` 或 `/models/:pack/activate`。
2023
+ /^\/admin\/api\/memory-runtime\/model-source$/,
1348
2024
  ];
1349
2025
 
1350
2026
  // P2:UNINITIALIZED 仅开放本机助手配置所需的读写动作(列表 / 预览 / 接入 / 验证 / 重探)。
@@ -1859,6 +2535,24 @@ export async function startHttpServer({
1859
2535
  }
1860
2536
  }
1861
2537
 
2538
+ // 设置 · 常用「自动修复」:只重跑客户端接入(MCP 条目 + Skill),不碰 memory/identity/cloud/task/audit。
2539
+ async function handleRepair(req, res) {
2540
+ const { repairClients, assistantUserHome, daemonMcpUrl } = await import('./clients.mjs');
2541
+ const mcpUrl = daemonMcpUrl({ host: req.headers?.host, encrypted: Boolean(req.socket?.encrypted) });
2542
+ try {
2543
+ const result = await repairClients({ home, cwd: process.cwd(), mcpUrl, userHome: assistantUserHome() });
2544
+ // 逐项失败也是有效结果:200 + per-client report,由 UI 展示摘要。
2545
+ return sendJson(res, 200, result);
2546
+ } catch (error) {
2547
+ return sendJson(res, 500, {
2548
+ ok: false,
2549
+ scope: 'client-integration',
2550
+ error: 'repair_failed',
2551
+ message: `自动修复失败:${String(error?.message ?? error)}`,
2552
+ });
2553
+ }
2554
+ }
2555
+
1862
2556
  // D2 写端点实现(memory.admin scope + CSRF 已在 handleAdminWrite 校验)
1863
2557
  async function applyAdminWrite(req, res, path, body) {
1864
2558
  if (!app || !service) {
@@ -1874,6 +2568,52 @@ export async function startHttpServer({
1874
2568
  if (path === '/admin/api/clouds/join') return handleCloudJoin(req, res, body);
1875
2569
  if (path === '/admin/api/clouds/rename') return handleCloudRename(req, res, body);
1876
2570
 
2571
+ // 自动修复:客户端接入修复,**不**经 securityWriteGate(不写记忆/安全状态)。
2572
+ if (path === '/admin/api/repair') return handleRepair(req, res);
2573
+
2574
+ // 0.3 高级模型来源:sidecar 拥有 config.model.source;MCP 只做薄代理。
2575
+ // local 必须带 pack 并通过 sidecar activate;不直接写 config.json、不重启 sidecar。
2576
+ if (path === '/admin/api/memory-runtime/model-source') {
2577
+ const input = parseJsonBody(body);
2578
+ if (!input) {
2579
+ return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 JSON 请求体' });
2580
+ }
2581
+ const result = await writeModelSourceResponse(input);
2582
+ return sendJson(res, result.status, result.body);
2583
+ }
2584
+
2585
+ // 0.3 记忆运行时:召回反馈经 MCP 薄代理转发 sidecar(host token 只在服务端使用)。
2586
+ if (path === '/admin/api/memory-runtime/feedback') {
2587
+ const input = parseJsonBody(body);
2588
+ if (!input) {
2589
+ return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 JSON 请求体' });
2590
+ }
2591
+ const traceId = typeof input.traceId === 'string' ? input.traceId : '';
2592
+ const result = memoryRuntimeSupervisor
2593
+ ? await memoryRuntimeSupervisor.submitRecallFeedback(traceId, input)
2594
+ : {
2595
+ statusCode: 409,
2596
+ body: {
2597
+ ok: false,
2598
+ error: 'memory_runtime_disabled',
2599
+ enabled: false,
2600
+ state: 'stopped',
2601
+ message: '记忆运行时未启用',
2602
+ },
2603
+ };
2604
+ return sendJson(res, result.statusCode, result.body);
2605
+ }
2606
+
2607
+ // 0.3 本地模型:只代理 sidecar;不经 securityWriteGate(不写记忆/安全状态)。
2608
+ const modelAction = path.match(/^\/admin\/api\/(?:models|inference)\/([^/]+)$/);
2609
+ if (modelAction) {
2610
+ const result = await handleModelAction(
2611
+ decodeURIComponent(modelAction[1]),
2612
+ parseJsonBody(body) ?? {},
2613
+ );
2614
+ return sendJson(res, result.status, result.body);
2615
+ }
2616
+
1877
2617
  // S2:安全三档写端点门禁(medium 动态码 / high 会签或恢复码;low 放行)。
1878
2618
  const gateInput = parseJsonBody(body) ?? {};
1879
2619
  const gate = await securityWriteGate({ app, home, path, input: gateInput, namespace });
@@ -2367,6 +3107,33 @@ export async function startHttpServer({
2367
3107
  const backup = existsSync(`${cfgFile}.bak`) ? `${cfgFile}.bak` : null;
2368
3108
  const base = { ok: true, applied: changedPaths, backup, path: cfgFile, config: merged };
2369
3109
 
3110
+ // memoryRuntime.enabled 是热开关:同步内存配置,立即生成/撤销 capability token,
3111
+ // 并启动/停止 sidecar(sidecar 失败不影响配置写入与 MCP 本身)。
3112
+ if (changedPaths.some((changed) => changed === 'memoryRuntime' || changed.startsWith('memoryRuntime.'))) {
3113
+ if (merged?.memoryRuntime === undefined) {
3114
+ const next = { ...(config ?? {}) };
3115
+ delete next.memoryRuntime;
3116
+ config = next;
3117
+ } else {
3118
+ config = { ...(config ?? {}), memoryRuntime: merged.memoryRuntime };
3119
+ }
3120
+ if (isMemoryRuntimeEnabled(config)) {
3121
+ await memoryCapability.prepare();
3122
+ if (memoryRuntimeSupervisor) {
3123
+ const commandChanged = changedPaths.some((changed) => changed === 'memoryRuntime.command'
3124
+ || changed === 'memoryRuntime.startTimeoutMs');
3125
+ if (commandChanged) {
3126
+ void memoryRuntimeSupervisor.restart({ includeAttached: true, force: false }).catch(() => undefined);
3127
+ } else {
3128
+ void memoryRuntimeSupervisor.start().catch(() => undefined);
3129
+ }
3130
+ }
3131
+ } else {
3132
+ await memoryRuntimeSupervisor?.stop({ includeAttached: false }).catch(() => undefined);
3133
+ await memoryCapability.revoke();
3134
+ }
3135
+ }
3136
+
2370
3137
  // G1:全部即时生效项 → 不重启,就地生效(前端随即刷新 effective)
2371
3138
  if (restartPaths.length === 0) {
2372
3139
  return sendJson(res, 200, { ...base, restartRequired: false, effectiveImmediately: true, restart: { mode: 'none' }, immediatePaths });
@@ -2961,6 +3728,11 @@ export async function startHttpServer({
2961
3728
  res.setHeader('cache-control', 'no-store');
2962
3729
  return sendJson(res, 200, buildEmbedInfo({ origin, loopback: isLoopback }));
2963
3730
  }
3731
+ // 0.3 Memory Capability API(内部):loopback + capability token,独立于 /mcp 鉴权。
3732
+ // 轻量模式(memoryRuntime.enabled=false)返回 404 capability_disabled,不创建 token/目录。
3733
+ if (isMemoryCapabilityPath(path)) {
3734
+ return memoryCapability({ req, res, url, body });
3735
+ }
2964
3736
  if (auth === 'oauth') {
2965
3737
  if (path === '/.well-known/oauth-protected-resource' && req.method === 'GET') {
2966
3738
  return sendJson(res, 200, metadata.protectedResource);
@@ -3254,6 +4026,32 @@ export async function startHttpServer({
3254
4026
  },
3255
4027
  });
3256
4028
  await activateRuntime(next, { viaHotInit: true });
4029
+ // 首次初始化成功:对已检测到的客户端 ensure Skill(后台执行;失败不阻断初始化响应)。
4030
+ void import('./clients.mjs')
4031
+ .then(({ autoEnsureSkills, assistantUserHome }) => autoEnsureSkills({ home, userHome: assistantUserHome(), cwd: process.cwd() }))
4032
+ .then((result) => {
4033
+ if (result?.summary?.failed > 0 || (result?.ok === false && result?.skipped !== true)) {
4034
+ console.error(`SKILL_ENSURE_PENDING_REPAIR ${result?.reason ?? `${result?.summary?.failed ?? 1} client(s)`}`);
4035
+ }
4036
+ })
4037
+ .catch((error) => console.error(`SKILL_ENSURE_FAILED ${error?.code ?? 'ERROR'}`));
4038
+ // 自动自愈(主路径):热初始化后实际端口已确定 → 只更新已存在的本机 loopback Mebular 条目。
4039
+ void import('./clients.mjs')
4040
+ .then(({ reconcileClientEndpoints, assistantUserHome, daemonMcpUrl }) => {
4041
+ const reconcileHost = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host;
4042
+ return reconcileClientEndpoints({
4043
+ home,
4044
+ userHome: assistantUserHome(),
4045
+ cwd: process.cwd(),
4046
+ mcpUrl: daemonMcpUrl({ host: `${reconcileHost}:${boundPort}`, encrypted: tls }),
4047
+ });
4048
+ })
4049
+ .then((result) => {
4050
+ if (result?.summary?.failed > 0) {
4051
+ console.error(`CLIENT_ENDPOINT_RECONCILE_PARTIAL ${result.summary.failed} client(s)`);
4052
+ }
4053
+ })
4054
+ .catch((error) => console.error(`CLIENT_ENDPOINT_RECONCILE_FAILED ${error?.code ?? 'ERROR'}`));
3257
4055
  return sendJson(res, 200, {
3258
4056
  ok: true,
3259
4057
  ...result,
@@ -3301,7 +4099,17 @@ export async function startHttpServer({
3301
4099
  const out = await buildHandoffPlan({ app }, decodeURIComponent(planMatch[1]), successor);
3302
4100
  return sendJson(res, out.status, out.body);
3303
4101
  }
3304
- if (req.method === 'GET' && READ_ROUTES[path]) return handleAdminRead(req, res, path, url);
4102
+ if (req.method === 'GET' && (READ_ROUTES[path]
4103
+ || path === '/admin/api/models'
4104
+ || path === '/admin/api/models/status'
4105
+ || path === '/admin/api/inference/models'
4106
+ || path === '/admin/api/inference/status'
4107
+ || path === '/admin/api/memory-runtime/status'
4108
+ || path === '/admin/api/memory-runtime/model-source'
4109
+ || path === '/admin/api/memory-runtime/traces'
4110
+ || /^\/admin\/api\/memory-runtime\/traces\/[^/]+$/.test(path))) {
4111
+ return handleAdminRead(req, res, path, url);
4112
+ }
3305
4113
  // 写端点路径:任何方法都交给 handleAdminWrite(非 POST/PUT/PATCH → 405;Origin/CSRF/scope 同处校验)
3306
4114
  if (WRITE_PATTERNS.some((re) => re.test(path))) {
3307
4115
  const done = await handleAdminWrite(req, res, path, body);
@@ -3327,8 +4135,10 @@ export async function startHttpServer({
3327
4135
  });
3328
4136
  }
3329
4137
  if (path === '/app/namespaces' && req.method === 'GET') {
3330
- const nodes = await app.graph.listNodes({});
3331
- const namespaces = [...new Set(nodes.map((n) => n.namespace ?? 'default'))].sort();
4138
+ const stats = service && typeof service.stats === 'function' ? await service.stats() : null;
4139
+ const namespaces = stats
4140
+ ? stats.domains.map((entry) => entry.domain).sort()
4141
+ : (await app.getNamespaceDirectory()).sort();
3332
4142
  return sendJson(res, 200, { ok: true, namespaces, count: namespaces.length });
3333
4143
  }
3334
4144
  if (path === '/app/nodes' && req.method === 'POST') {
@@ -3348,6 +4158,10 @@ export async function startHttpServer({
3348
4158
  );
3349
4159
  return sendJson(res, 200, { ok: true, node: { id: node.id, type: node.type, namespace: node.namespace ?? 'default' } });
3350
4160
  }
4161
+ // [raw-graph-debug] 原始图调试/接入端点(调试例外):不做内部对象、归档或
4162
+ // 墓碑过滤,仅供 daemon/fleet 原始图读写与排障。普通记忆列表与域统计必须走
4163
+ // MemoryService.listRecords()/namespaceStats()(Console 见 admin.mjs),
4164
+ // 不得把这里当作普通记忆读路径。
3351
4165
  if (path === '/app/nodes' && req.method === 'GET') {
3352
4166
  const filter = {};
3353
4167
  const ns = url.searchParams.get('namespace');
@@ -3442,6 +4256,9 @@ export async function startHttpServer({
3442
4256
  ? await acquireActiveLock({ root: cloud.root, home, profileId: cloudId })
3443
4257
  : null;
3444
4258
 
4259
+ // capability token 在监听前生成(sidecar 首次握手可读);监听失败由下方 catch 撤销。
4260
+ if (isMemoryRuntimeEnabled(config)) await memoryCapability.prepare();
4261
+
3445
4262
  let server;
3446
4263
  try {
3447
4264
  if (tls) {
@@ -3454,6 +4271,7 @@ export async function startHttpServer({
3454
4271
  server.listen(port, host, () => resolve());
3455
4272
  });
3456
4273
  } catch (error) {
4274
+ await memoryCapability.dispose().catch(() => undefined);
3457
4275
  await activeLock?.release?.().catch(() => undefined);
3458
4276
  throw error;
3459
4277
  }
@@ -3472,12 +4290,23 @@ export async function startHttpServer({
3472
4290
  }).catch((error) => {
3473
4291
  console.error(`RUNTIME_FILE_WRITE_FAILED ${error?.code ?? 'ERROR'}`);
3474
4292
  });
4293
+ // MCP 已就绪后再异步拉起 sidecar:失败只影响沉浸式记忆,不阻塞 READY/29 工具。
4294
+ if (memoryRuntimeSupervisor && isMemoryRuntimeEnabled(config)) {
4295
+ void memoryRuntimeSupervisor.start().catch((error) => {
4296
+ console.error(`MEMORY_RUNTIME_START_FAILED ${error?.code ?? 'ERROR'}`);
4297
+ });
4298
+ }
4299
+ // 详情保留维护同样在 listen 后异步启动:过期扫描失败只记录状态,不影响 MCP。
4300
+ detailMaintenance.start();
3475
4301
  let closePromise = null;
3476
4302
  const close = () => {
3477
4303
  if (closePromise) return closePromise;
3478
4304
  closePromise = (async () => {
3479
4305
  // 优雅停止的顺序很重要:MCP/SSE/keep-alive 连接不会自己断,
3480
4306
  // 先收 MCP sessions,再主动结束连接,最后才等 listener(带有限超时)。
4307
+ // 详情维护先停 timer;进行中的 prune 最多等一个 session 预算,不拖死关闭。
4308
+ detailMaintenance.stop();
4309
+ await settleWithin(detailMaintenance.idle(), SESSION_CLOSE_TIMEOUT_MS);
3481
4310
  const deadline = Date.now() + CLOSE_TIMEOUT_MS;
3482
4311
  try {
3483
4312
  // 1) 先让每个 MCP session 的 transport/server 正常收尾。
@@ -3515,7 +4344,11 @@ export async function startHttpServer({
3515
4344
  } finally {
3516
4345
  // 4) 无论前面如何都要清理;pid 守卫保证不误删新实例的 runtime.json。
3517
4346
  await clearRuntimeFile(home, { pid: process.pid }).catch(() => undefined);
3518
- // 5) 保留最新 main 的生命周期收尾:root 单活锁 + 热初始化上下文(app/join/广播)。
4347
+ // 5) 本地模型进程由 sidecar 拥有;MCP 不持有推理引擎,无需本地清理。
4348
+ // 6) 保留最新 main 的生命周期收尾:root 单活锁 + 热初始化上下文(app/join/广播)。
4349
+ // 先停止本进程启动的 sidecar(attach 的不动),再撤销 capability token。
4350
+ await memoryRuntimeSupervisor?.dispose().catch(() => undefined);
4351
+ await memoryCapability.dispose().catch(() => undefined);
3519
4352
  await activeLock?.release?.().catch(() => undefined);
3520
4353
  await onClose?.().catch(() => undefined);
3521
4354
  }
@@ -3529,6 +4362,15 @@ export async function startHttpServer({
3529
4362
  auth,
3530
4363
  issuer,
3531
4364
  close,
3532
- getState: () => ({ phase, hotInitialized, app, service, config, runtime, deviceId }),
4365
+ getState: () => ({
4366
+ phase,
4367
+ hotInitialized,
4368
+ app,
4369
+ service,
4370
+ config,
4371
+ runtime,
4372
+ deviceId,
4373
+ detailMaintenance: detailMaintenance.status(),
4374
+ }),
3533
4375
  };
3534
4376
  }