@mebular/mcp 0.2.4 → 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 +606 -2
- package/package.json +5 -4
- package/src/admin.mjs +69 -47
- package/src/clients.mjs +699 -33
- package/src/config-apply.mjs +254 -6
- package/src/config-lock.mjs +167 -0
- package/src/config-schema.mjs +7 -0
- package/src/config.mjs +17 -1
- package/src/detail-maintenance.mjs +150 -0
- package/src/fleet-events.mjs +1 -1
- package/src/home-identity.mjs +13 -1
- package/src/memory-capability.mjs +5393 -0
- package/src/memory-runtime-config.mjs +86 -0
- package/src/memory-runtime-diagnostics.mjs +716 -0
- package/src/memory-runtime-supervisor.mjs +2670 -0
- package/src/memory-runtime-token.mjs +193 -0
- package/src/serve.mjs +1534 -16
- package/src/server.mjs +36 -4
- package/src/task-tools.mjs +10 -1
- package/src/version.mjs +1 -1
package/src/serve.mjs
CHANGED
|
@@ -19,7 +19,24 @@ 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';
|
|
39
|
+
import { acquireConfigFileLock } from './config-lock.mjs';
|
|
23
40
|
import { resolveStaticAssetRoots } from './asset-roots.mjs';
|
|
24
41
|
|
|
25
42
|
// 兼容既有导入方:APP_VERSION 的真源是 ./version.mjs。
|
|
@@ -666,6 +683,26 @@ export function loadFleetSecurity() {
|
|
|
666
683
|
return fleetSecurityPromise;
|
|
667
684
|
}
|
|
668
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
|
+
|
|
669
706
|
/**
|
|
670
707
|
* 写端点门禁:medium 要动态码;high 要会签批准/恢复码;low 放行。
|
|
671
708
|
* 导出供 S2-3 单测直接断言(HTTP 层同样走这里)。
|
|
@@ -866,18 +903,35 @@ export async function startHttpServer({
|
|
|
866
903
|
writesEnabled: initialWritesEnabled = false,
|
|
867
904
|
// C:一键重启执行器(可注入;verify:config 用 MEBULAR_RESTART_DRY_RUN 或注入替身)
|
|
868
905
|
restartRunner = null,
|
|
906
|
+
// 测试注入:配置写盘前钩子,用于验证 close 与配置写入的线性化。
|
|
907
|
+
beforeConfigWrite = null,
|
|
908
|
+
afterConfigRename = null,
|
|
869
909
|
// 引导态(空家目录):只服务 /healthz + /console 引导页 + /app/provision/*;其余 409 provision_required
|
|
870
910
|
provision: initialProvision = false,
|
|
871
911
|
// P1:同一进程内热初始化。返回新的运行时上下文;成功后本 server 从 UNINITIALIZED → READY。
|
|
872
912
|
initializeRuntime = null,
|
|
873
913
|
// 关闭钩子:热初始化后由 server.mjs 关闭 app / join / 广播计时器(HTTP server 本身由本函数关闭)
|
|
874
914
|
onClose = null,
|
|
915
|
+
// Memory Runtime sidecar 生命周期:只在 MCP daemon(HTTP 模式)启用。
|
|
916
|
+
// 测试可直接关掉;生产入口 server.mjs 显式传 true。
|
|
917
|
+
manageMemoryRuntime = true,
|
|
875
918
|
}) {
|
|
876
919
|
// P1:生命周期状态。所有路由共用**可变**上下文;create/join 成功后就地切换,不重启进程 / 端口。
|
|
877
920
|
let app = initialApp;
|
|
878
921
|
let service = initialService;
|
|
879
922
|
let config = initialConfig ?? {};
|
|
880
923
|
let runtime = initialRuntime;
|
|
924
|
+
// CR-002:守护内串行化能力卡签名/写入,避免同版本并发请求产生重复节点。
|
|
925
|
+
let cardWriteQueue = Promise.resolve();
|
|
926
|
+
// P5:角色卡写入串行化(同版本幂等/冲突与能力卡同语义)。
|
|
927
|
+
let roleCardWriteQueue = Promise.resolve();
|
|
928
|
+
|
|
929
|
+
// 0.3 详情保留维护:service 就绪后启动(启动一次 + 每 24h),热切换复用同一 timer。
|
|
930
|
+
// 失败只记录状态/日志,不阻断 MCP;关闭时显式清理,避免测试/宿主进程残留 timer。
|
|
931
|
+
const detailMaintenance = createDetailMaintenance({ getService: () => service });
|
|
932
|
+
|
|
933
|
+
// 0.3 模型目录/安装/引擎/来源全部由 Memory Runtime sidecar 拥有。
|
|
934
|
+
// MCP 不再读取 <home>/models 或 <home>/inference.json,也不改写 runtime.model。
|
|
881
935
|
let deviceId = initialDeviceId;
|
|
882
936
|
let namespace = initialNamespace;
|
|
883
937
|
let joinEndpoint = initialJoinEndpoint;
|
|
@@ -927,6 +981,8 @@ export async function startHttpServer({
|
|
|
927
981
|
cloudId = cloud.available ? await profileIdForHome(cloud.root, home).catch(() => null) : null;
|
|
928
982
|
phase = 'READY';
|
|
929
983
|
if (viaHotInit) hotInitialized = true;
|
|
984
|
+
// 热初始化:同一个 scheduler 动态读取新 service;当天已成功扫过则不重复。
|
|
985
|
+
detailMaintenance.start();
|
|
930
986
|
return { phase, cloudId };
|
|
931
987
|
}
|
|
932
988
|
|
|
@@ -955,6 +1011,704 @@ export async function startHttpServer({
|
|
|
955
1011
|
// 热初始化后同一会话内的 tools/call 直接转发到真实 MemoryService(不重连、不重新 initialize)。
|
|
956
1012
|
const runtimeReady = () => phase === 'READY' && Boolean(service);
|
|
957
1013
|
const serviceFacade = createServiceFacade({ getService: () => service, isReady: runtimeReady });
|
|
1014
|
+
|
|
1015
|
+
// 0.3 Memory Capability API:内部接口 `/internal/memory/v1`(读 + 写 + 内部对象 + sync)。
|
|
1016
|
+
// 只有 memoryRuntime.enabled=true 时挂载/生成 token;轻量模式零目录/文件/进程副作用。
|
|
1017
|
+
// capability 不是公共 MCP 工具;29 工具面不变。
|
|
1018
|
+
const memoryCapability = createMemoryCapabilityHandler({
|
|
1019
|
+
home,
|
|
1020
|
+
getConfig: () => config,
|
|
1021
|
+
getService: () => service,
|
|
1022
|
+
getApp: () => app,
|
|
1023
|
+
getIdentity: () => ({
|
|
1024
|
+
// /healthz 的 cloudId 是既有 profile 语义;capability 的稳定 cloudTrustId 暂不可得。
|
|
1025
|
+
cloudId: null,
|
|
1026
|
+
cloudTrustId: null,
|
|
1027
|
+
profileId: cloudId,
|
|
1028
|
+
userId: 'user',
|
|
1029
|
+
deviceId: app?.deviceId ?? null,
|
|
1030
|
+
}),
|
|
1031
|
+
ttlMs: (() => {
|
|
1032
|
+
const raw = Number(process.env.MEBULAR_CAPABILITY_TOKEN_TTL_MS ?? '');
|
|
1033
|
+
return Number.isFinite(raw) && raw > 0 ? raw : undefined;
|
|
1034
|
+
})(),
|
|
1035
|
+
});
|
|
1036
|
+
|
|
1037
|
+
// 0.3 Memory Runtime sidecar 生命周期适配:只 spawn/health/stop,不 import sidecar 业务。
|
|
1038
|
+
// 轻量模式(enabled=false)不会创建目录/token/进程/端口;自动启动在 listen 后异步进行,
|
|
1039
|
+
// 不阻塞 MCP READY/29 工具。关闭时只停止本进程启动的 sidecar(attach 的不动)。
|
|
1040
|
+
const memoryRuntimeSupervisor = manageMemoryRuntime
|
|
1041
|
+
? new MemoryRuntimeSupervisor({
|
|
1042
|
+
home,
|
|
1043
|
+
config: () => config,
|
|
1044
|
+
env: process.env,
|
|
1045
|
+
profileId: () => cloudId,
|
|
1046
|
+
cloudId: () => null,
|
|
1047
|
+
mcpUrl: () => origin,
|
|
1048
|
+
})
|
|
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
|
+
};
|
|
1064
|
+
|
|
1065
|
+
// ---------- 0.3 模型薄代理:模型目录/安装/引擎/来源全部由 sidecar 拥有 ----------
|
|
1066
|
+
// 浏览器只看到 sidecar 的脱敏视图;host token 只在服务端使用。
|
|
1067
|
+
function uniqueStrings(values) {
|
|
1068
|
+
return [...new Set(values.filter((value) => typeof value === 'string' && value.length > 0))];
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
function proxyFailure(result, fallbackMessage) {
|
|
1072
|
+
const error = result?.error && typeof result.error === 'object'
|
|
1073
|
+
? result.error
|
|
1074
|
+
: { code: 'sidecar_request_failed', message: fallbackMessage, retryable: false };
|
|
1075
|
+
const status = Number.isInteger(result?.status) ? result.status : 503;
|
|
1076
|
+
return {
|
|
1077
|
+
status,
|
|
1078
|
+
body: {
|
|
1079
|
+
ok: false,
|
|
1080
|
+
error: {
|
|
1081
|
+
code: error.code,
|
|
1082
|
+
message: error.message ?? fallbackMessage,
|
|
1083
|
+
retryable: error.retryable === true,
|
|
1084
|
+
...(error.details ? { details: error.details } : {}),
|
|
1085
|
+
},
|
|
1086
|
+
code: error.code,
|
|
1087
|
+
message: error.message ?? fallbackMessage,
|
|
1088
|
+
enabled: result?.enabled === true,
|
|
1089
|
+
state: result?.state ?? 'stopped',
|
|
1090
|
+
...(result?.disabled === true ? { disabled: true } : {}),
|
|
1091
|
+
},
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
const modelPackId = (input) => {
|
|
1096
|
+
const value = input?.pack ?? input?.packId ?? input?.id;
|
|
1097
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
|
|
1098
|
+
};
|
|
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
|
+
|
|
1109
|
+
function modelDownloadView(install) {
|
|
1110
|
+
if (!install || typeof install !== 'object') return null;
|
|
1111
|
+
return {
|
|
1112
|
+
schema: install.schema ?? null,
|
|
1113
|
+
jobId: install.jobId ?? null,
|
|
1114
|
+
pack: install.packId ?? null,
|
|
1115
|
+
packId: install.packId ?? null,
|
|
1116
|
+
modelId: install.modelId ?? null,
|
|
1117
|
+
state: install.state ?? null,
|
|
1118
|
+
phase: install.phase ?? null,
|
|
1119
|
+
progress: install.progress ?? 0,
|
|
1120
|
+
downloadedBytes: install.downloadedBytes ?? 0,
|
|
1121
|
+
totalBytes: install.totalBytes ?? 0,
|
|
1122
|
+
speedBytesPerSecond: install.speedBytesPerSecond ?? 0,
|
|
1123
|
+
etaMs: install.etaMs ?? null,
|
|
1124
|
+
startedAt: install.startedAt ?? null,
|
|
1125
|
+
updatedAt: install.updatedAt ?? null,
|
|
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),
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function modelPackView(pack) {
|
|
1218
|
+
// 明确允许列表:attached producer 的额外 debug/keyRef/path 不得 spread 到浏览器。
|
|
1219
|
+
return {
|
|
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,
|
|
1244
|
+
selected: pack?.active === true,
|
|
1245
|
+
manifestAvailable: pack?.manifest?.available === true,
|
|
1246
|
+
warnings: Array.isArray(pack?.warnings) ? pack.warnings : [],
|
|
1247
|
+
...(pack?.install ? { download: modelDownloadView(pack.install) } : {}),
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
function modelListBody(catalog) {
|
|
1252
|
+
const data = catalog ?? {};
|
|
1253
|
+
const active = data.active ?? {};
|
|
1254
|
+
return {
|
|
1255
|
+
ok: true,
|
|
1256
|
+
schema: 1,
|
|
1257
|
+
selectedPack: active.packId ?? null,
|
|
1258
|
+
effectivePack: active.packId ?? null,
|
|
1259
|
+
selectionSource: 'sidecar',
|
|
1260
|
+
runtime: {
|
|
1261
|
+
source: active.source ?? 'heuristic',
|
|
1262
|
+
pack: active.packId ?? null,
|
|
1263
|
+
selectionSource: 'sidecar',
|
|
1264
|
+
},
|
|
1265
|
+
packs: Array.isArray(data.packs) ? data.packs.map(modelPackView) : [],
|
|
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),
|
|
1272
|
+
warnings: Array.isArray(data.warnings) ? data.warnings : [],
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
function modelStatusBody(catalog, inference) {
|
|
1277
|
+
const data = catalog ?? {};
|
|
1278
|
+
const runtime = inference ?? {};
|
|
1279
|
+
const active = runtime.active ?? data.active ?? {};
|
|
1280
|
+
const recommended = runtime.recommended ?? data.recommended ?? null;
|
|
1281
|
+
const warnings = uniqueStrings([
|
|
1282
|
+
...(Array.isArray(data.warnings) ? data.warnings : []),
|
|
1283
|
+
...(Array.isArray(runtime.warnings) ? runtime.warnings : []),
|
|
1284
|
+
]);
|
|
1285
|
+
return {
|
|
1286
|
+
ok: true,
|
|
1287
|
+
schema: 1,
|
|
1288
|
+
selectedPack: active.packId ?? null,
|
|
1289
|
+
effectivePack: active.packId ?? null,
|
|
1290
|
+
selectionSource: 'sidecar',
|
|
1291
|
+
runtime: {
|
|
1292
|
+
source: active.source ?? 'heuristic',
|
|
1293
|
+
pack: active.packId ?? null,
|
|
1294
|
+
selectionSource: 'sidecar',
|
|
1295
|
+
},
|
|
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),
|
|
1301
|
+
installedPackIds: Array.isArray(runtime.installedPackIds)
|
|
1302
|
+
? runtime.installedPackIds
|
|
1303
|
+
: (Array.isArray(data.packs) ? data.packs.filter((pack) => pack?.installed === true).map((pack) => pack.packId) : []),
|
|
1304
|
+
packs: Array.isArray(data.packs)
|
|
1305
|
+
? data.packs.map((pack) => ({
|
|
1306
|
+
packId: pack.packId,
|
|
1307
|
+
modelId: pack.modelId,
|
|
1308
|
+
tier: pack.tier,
|
|
1309
|
+
state: pack.state,
|
|
1310
|
+
selected: pack.active === true,
|
|
1311
|
+
installed: pack.installed === true,
|
|
1312
|
+
installedBytes: pack.installedBytes ?? 0,
|
|
1313
|
+
expectedBytes: pack.expectedBytes ?? 0,
|
|
1314
|
+
}))
|
|
1315
|
+
: [],
|
|
1316
|
+
downloads: [],
|
|
1317
|
+
warnings,
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
async function modelListResponse() {
|
|
1322
|
+
if (!memoryRuntimeSupervisor) {
|
|
1323
|
+
return proxyFailure({
|
|
1324
|
+
status: 409,
|
|
1325
|
+
enabled: false,
|
|
1326
|
+
disabled: true,
|
|
1327
|
+
state: 'stopped',
|
|
1328
|
+
error: { code: 'memory_runtime_disabled', message: '记忆运行时未启用', retryable: false },
|
|
1329
|
+
}, '记忆运行时未启用');
|
|
1330
|
+
}
|
|
1331
|
+
const result = await memoryRuntimeSupervisor.listModels();
|
|
1332
|
+
if (!result.ok) return proxyFailure(result, '模型列表不可用');
|
|
1333
|
+
return { status: 200, body: modelListBody(result.data) };
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
async function modelStatusResponse() {
|
|
1337
|
+
if (!memoryRuntimeSupervisor) {
|
|
1338
|
+
return proxyFailure({
|
|
1339
|
+
status: 409,
|
|
1340
|
+
enabled: false,
|
|
1341
|
+
disabled: true,
|
|
1342
|
+
state: 'stopped',
|
|
1343
|
+
error: { code: 'memory_runtime_disabled', message: '记忆运行时未启用', retryable: false },
|
|
1344
|
+
}, '记忆运行时未启用');
|
|
1345
|
+
}
|
|
1346
|
+
const [catalog, inference] = await Promise.all([
|
|
1347
|
+
memoryRuntimeSupervisor.listModels(),
|
|
1348
|
+
memoryRuntimeSupervisor.inferenceStatus(),
|
|
1349
|
+
]);
|
|
1350
|
+
if (!catalog.ok) return proxyFailure(catalog, '模型目录不可用');
|
|
1351
|
+
return {
|
|
1352
|
+
status: 200,
|
|
1353
|
+
body: modelStatusBody(catalog.data, inference.ok ? inference.data : null),
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
function modelActionSuccess(result, extra = {}) {
|
|
1358
|
+
const data = result.data ?? {};
|
|
1359
|
+
return {
|
|
1360
|
+
status: Number.isInteger(result.status) && result.status >= 200 && result.status < 300 ? result.status : 200,
|
|
1361
|
+
body: {
|
|
1362
|
+
ok: true,
|
|
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),
|
|
1371
|
+
...extra,
|
|
1372
|
+
warnings: uniqueStrings(Array.isArray(data.warnings) ? data.warnings : []),
|
|
1373
|
+
},
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
async function handleModelAction(action, input) {
|
|
1378
|
+
const rawAction = typeof action === 'string' ? action : '';
|
|
1379
|
+
const name = rawAction === 'uninstall' ? 'remove'
|
|
1380
|
+
: rawAction === 'download' ? 'install'
|
|
1381
|
+
: rawAction;
|
|
1382
|
+
if (name === 'pause' || name === 'resume' || name === 'import') {
|
|
1383
|
+
return {
|
|
1384
|
+
status: 501,
|
|
1385
|
+
body: {
|
|
1386
|
+
ok: false,
|
|
1387
|
+
error: {
|
|
1388
|
+
code: 'unsupported',
|
|
1389
|
+
message: `${rawAction} 由 sidecar 模型安装任务取代:请使用 cancel 或重新 install`,
|
|
1390
|
+
retryable: false,
|
|
1391
|
+
},
|
|
1392
|
+
code: 'unsupported',
|
|
1393
|
+
message: `${rawAction} 暂不支持`,
|
|
1394
|
+
},
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
if (!['install', 'select', 'cancel', 'remove', 'start', 'stop', 'test'].includes(name)) {
|
|
1398
|
+
return {
|
|
1399
|
+
status: 404,
|
|
1400
|
+
body: {
|
|
1401
|
+
ok: false,
|
|
1402
|
+
error: { code: 'unknown_action', message: `未知模型操作:${rawAction}`, retryable: false },
|
|
1403
|
+
code: 'unknown_action',
|
|
1404
|
+
message: `未知模型操作:${rawAction}`,
|
|
1405
|
+
},
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
if (!memoryRuntimeSupervisor) {
|
|
1409
|
+
return proxyFailure({
|
|
1410
|
+
status: 409,
|
|
1411
|
+
enabled: false,
|
|
1412
|
+
disabled: true,
|
|
1413
|
+
state: 'stopped',
|
|
1414
|
+
error: { code: 'memory_runtime_disabled', message: '记忆运行时未启用', retryable: false },
|
|
1415
|
+
}, '记忆运行时未启用');
|
|
1416
|
+
}
|
|
1417
|
+
const pack = modelPackId(input);
|
|
1418
|
+
|
|
1419
|
+
if (name === 'install') {
|
|
1420
|
+
if (!pack) {
|
|
1421
|
+
return {
|
|
1422
|
+
status: 400,
|
|
1423
|
+
body: { ok: false, error: { code: 'invalid_request', message: '缺少 pack', retryable: false } },
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
const result = await memoryRuntimeSupervisor.installModel(pack, {
|
|
1427
|
+
force: input?.force === true || input?.force === 'true' || input?.force === '1',
|
|
1428
|
+
});
|
|
1429
|
+
if (!result.ok) return proxyFailure(result, '模型安装失败');
|
|
1430
|
+
const job = modelDownloadView(result.data ?? {});
|
|
1431
|
+
return {
|
|
1432
|
+
status: result.status === 202 ? 202 : 200,
|
|
1433
|
+
body: {
|
|
1434
|
+
ok: true,
|
|
1435
|
+
accepted: result.status === 202,
|
|
1436
|
+
pack: job.packId ?? pack,
|
|
1437
|
+
job,
|
|
1438
|
+
...job,
|
|
1439
|
+
warnings: job.warnings,
|
|
1440
|
+
},
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
if (name === 'select') {
|
|
1445
|
+
if (!pack) {
|
|
1446
|
+
return {
|
|
1447
|
+
status: 400,
|
|
1448
|
+
body: { ok: false, error: { code: 'invalid_request', message: '缺少 pack', retryable: false } },
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
const result = await memoryRuntimeSupervisor.activateModel(pack);
|
|
1452
|
+
if (!result.ok) return proxyFailure(result, '模型激活失败');
|
|
1453
|
+
const data = result.data ?? {};
|
|
1454
|
+
return {
|
|
1455
|
+
status: 200,
|
|
1456
|
+
body: {
|
|
1457
|
+
ok: true,
|
|
1458
|
+
selected: data.activated === true,
|
|
1459
|
+
selectedPack: data.packId ?? pack,
|
|
1460
|
+
activated: data.activated === true,
|
|
1461
|
+
active: data.active ?? 'heuristic',
|
|
1462
|
+
runtime: {
|
|
1463
|
+
source: data.active ?? 'heuristic',
|
|
1464
|
+
pack: data.active === 'local' ? (data.packId ?? pack) : null,
|
|
1465
|
+
selectionSource: 'sidecar',
|
|
1466
|
+
},
|
|
1467
|
+
requiresRestart: false,
|
|
1468
|
+
warnings: Array.isArray(data.warnings) ? data.warnings : [],
|
|
1469
|
+
},
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
if (name === 'cancel') {
|
|
1474
|
+
let jobId = typeof input?.jobId === 'string' ? input.jobId.trim() : '';
|
|
1475
|
+
if (jobId.length === 0) {
|
|
1476
|
+
const status = await memoryRuntimeSupervisor.inferenceStatus();
|
|
1477
|
+
if (status.ok && typeof status.data?.install?.jobId === 'string') {
|
|
1478
|
+
jobId = status.data.install.jobId;
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
if (jobId.length === 0) {
|
|
1482
|
+
return {
|
|
1483
|
+
status: 409,
|
|
1484
|
+
body: { ok: false, error: { code: 'install_not_running', message: '没有正在进行的安装任务', retryable: false } },
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
const result = await memoryRuntimeSupervisor.cancelInstall(jobId);
|
|
1488
|
+
if (!result.ok) return proxyFailure(result, '取消安装失败');
|
|
1489
|
+
return modelActionSuccess(result, {
|
|
1490
|
+
pack,
|
|
1491
|
+
cancelled: result.data?.state === 'cancelled',
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
if (name === 'test') {
|
|
1496
|
+
const inference = await memoryRuntimeSupervisor.inferenceStatus();
|
|
1497
|
+
if (!inference.ok) return proxyFailure(inference, '模型状态检查失败');
|
|
1498
|
+
let status = null;
|
|
1499
|
+
if (pack) {
|
|
1500
|
+
status = await memoryRuntimeSupervisor.modelStatus(pack);
|
|
1501
|
+
if (!status.ok) return proxyFailure(status, '模型状态检查失败');
|
|
1502
|
+
}
|
|
1503
|
+
return {
|
|
1504
|
+
status: 200,
|
|
1505
|
+
body: {
|
|
1506
|
+
ok: true,
|
|
1507
|
+
tested: true,
|
|
1508
|
+
pack: pack ?? inference.data?.active?.packId ?? null,
|
|
1509
|
+
state: status?.data?.state ?? null,
|
|
1510
|
+
installed: status?.data?.installed ?? null,
|
|
1511
|
+
engine: modelEngineView(inference.data?.engine),
|
|
1512
|
+
active: modelActiveView(inference.data?.active),
|
|
1513
|
+
warnings: uniqueStrings([
|
|
1514
|
+
...(Array.isArray(inference.warnings) ? inference.warnings : []),
|
|
1515
|
+
...(Array.isArray(status?.warnings) ? status.warnings : []),
|
|
1516
|
+
]),
|
|
1517
|
+
},
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
if (!pack) {
|
|
1522
|
+
return {
|
|
1523
|
+
status: 400,
|
|
1524
|
+
body: { ok: false, error: { code: 'invalid_request', message: '缺少 pack', retryable: false } },
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
const result = name === 'remove'
|
|
1528
|
+
? await memoryRuntimeSupervisor.removeModel(pack)
|
|
1529
|
+
: name === 'start'
|
|
1530
|
+
? await memoryRuntimeSupervisor.startEngine(pack)
|
|
1531
|
+
: await memoryRuntimeSupervisor.stopEngine(pack);
|
|
1532
|
+
if (!result.ok) return proxyFailure(result, `模型 ${name} 失败`);
|
|
1533
|
+
if (name === 'remove') {
|
|
1534
|
+
return modelActionSuccess(result, {
|
|
1535
|
+
pack: result.data?.packId ?? pack,
|
|
1536
|
+
removed: result.data?.removed === true,
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
return modelActionSuccess(result, { pack: result.data?.packId ?? pack });
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
function modelSourceModelView(data) {
|
|
1543
|
+
const active = data?.active ?? {};
|
|
1544
|
+
const providers = Array.isArray(data?.providers) ? data.providers : [];
|
|
1545
|
+
return {
|
|
1546
|
+
configured: data?.config?.source ?? active.source ?? null,
|
|
1547
|
+
active: active.source ?? null,
|
|
1548
|
+
degraded: data?.degraded === true,
|
|
1549
|
+
reason: null,
|
|
1550
|
+
sources: providers.map((provider) => provider.id).filter((id) => typeof id === 'string'),
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
function modelSourceSuccess(result, source) {
|
|
1555
|
+
const data = result.data ?? {};
|
|
1556
|
+
return {
|
|
1557
|
+
status: 200,
|
|
1558
|
+
body: {
|
|
1559
|
+
ok: true,
|
|
1560
|
+
source,
|
|
1561
|
+
defaultSource: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
|
|
1562
|
+
values: [...MEMORY_RUNTIME_MODEL_SOURCES],
|
|
1563
|
+
exists: true,
|
|
1564
|
+
enabled: true,
|
|
1565
|
+
available: true,
|
|
1566
|
+
state: result.state,
|
|
1567
|
+
degraded: result.degraded === true,
|
|
1568
|
+
reason: null,
|
|
1569
|
+
error: null,
|
|
1570
|
+
model: modelSourceModelView(data),
|
|
1571
|
+
applies: 'hot',
|
|
1572
|
+
},
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
async function readModelSourceResponse() {
|
|
1577
|
+
const enabled = memoryRuntimeSupervisor?.isEnabled() === true;
|
|
1578
|
+
if (enabled) {
|
|
1579
|
+
const result = await memoryRuntimeSupervisor.inferenceStatus();
|
|
1580
|
+
if (result.ok) {
|
|
1581
|
+
const data = result.data ?? {};
|
|
1582
|
+
const source = normalizeMemoryRuntimeModelSource(data?.config?.source)
|
|
1583
|
+
?? normalizeMemoryRuntimeModelSource(data?.active?.source)
|
|
1584
|
+
?? DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE;
|
|
1585
|
+
return modelSourceSuccess(result, source);
|
|
1586
|
+
}
|
|
1587
|
+
// 未就绪时仍返回可读视图;写入会返回结构化 unavailable。
|
|
1588
|
+
const fallback = await readMemoryRuntimeModelSource({ home }).catch(() => null);
|
|
1589
|
+
const snapshot = memoryRuntimeSupervisor.snapshot();
|
|
1590
|
+
return {
|
|
1591
|
+
status: 200,
|
|
1592
|
+
body: {
|
|
1593
|
+
ok: true,
|
|
1594
|
+
source: fallback?.source ?? DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
|
|
1595
|
+
defaultSource: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
|
|
1596
|
+
values: [...MEMORY_RUNTIME_MODEL_SOURCES],
|
|
1597
|
+
exists: fallback?.exists === true,
|
|
1598
|
+
enabled: true,
|
|
1599
|
+
available: false,
|
|
1600
|
+
state: snapshot.state,
|
|
1601
|
+
degraded: snapshot.state === 'degraded',
|
|
1602
|
+
reason: snapshot.reason ?? null,
|
|
1603
|
+
error: result.error,
|
|
1604
|
+
model: null,
|
|
1605
|
+
applies: 'next_start',
|
|
1606
|
+
},
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
let fallback;
|
|
1610
|
+
try {
|
|
1611
|
+
fallback = await readMemoryRuntimeModelSource({ home });
|
|
1612
|
+
} catch (error) {
|
|
1613
|
+
fallback = {
|
|
1614
|
+
source: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
|
|
1615
|
+
defaultSource: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
|
|
1616
|
+
values: [...MEMORY_RUNTIME_MODEL_SOURCES],
|
|
1617
|
+
exists: false,
|
|
1618
|
+
warnings: [error?.code ?? 'config_unreadable'],
|
|
1619
|
+
};
|
|
1620
|
+
}
|
|
1621
|
+
return {
|
|
1622
|
+
status: 200,
|
|
1623
|
+
body: {
|
|
1624
|
+
ok: true,
|
|
1625
|
+
...fallback,
|
|
1626
|
+
enabled: false,
|
|
1627
|
+
available: false,
|
|
1628
|
+
state: 'stopped',
|
|
1629
|
+
degraded: false,
|
|
1630
|
+
reason: 'disabled',
|
|
1631
|
+
error: null,
|
|
1632
|
+
model: null,
|
|
1633
|
+
applies: 'next_start',
|
|
1634
|
+
},
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
// model-source 保持既有 `error: '<code>'` 信封(Console 兼容);模型操作使用 error 对象。
|
|
1639
|
+
function modelSourceFailure(result, fallbackCode, fallbackMessage) {
|
|
1640
|
+
const code = typeof result?.error?.code === 'string' ? result.error.code : fallbackCode;
|
|
1641
|
+
const message = typeof result?.error?.message === 'string' ? result.error.message : fallbackMessage;
|
|
1642
|
+
const status = Number.isInteger(result?.status) ? result.status : 503;
|
|
1643
|
+
return {
|
|
1644
|
+
status,
|
|
1645
|
+
body: {
|
|
1646
|
+
ok: false,
|
|
1647
|
+
error: code,
|
|
1648
|
+
code,
|
|
1649
|
+
message,
|
|
1650
|
+
enabled: result?.enabled === true,
|
|
1651
|
+
state: result?.state ?? 'stopped',
|
|
1652
|
+
...(result?.disabled === true ? { disabled: true } : {}),
|
|
1653
|
+
},
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
async function writeModelSourceResponse(input) {
|
|
1658
|
+
const source = normalizeMemoryRuntimeModelSource(input?.source);
|
|
1659
|
+
if (!source) {
|
|
1660
|
+
return {
|
|
1661
|
+
status: 400,
|
|
1662
|
+
body: {
|
|
1663
|
+
ok: false,
|
|
1664
|
+
error: 'invalid_model_source',
|
|
1665
|
+
code: 'invalid_model_source',
|
|
1666
|
+
message: '模型来源不合法',
|
|
1667
|
+
},
|
|
1668
|
+
};
|
|
1669
|
+
}
|
|
1670
|
+
if (!memoryRuntimeSupervisor || memoryRuntimeSupervisor.isEnabled() !== true) {
|
|
1671
|
+
return modelSourceFailure({
|
|
1672
|
+
status: 409,
|
|
1673
|
+
enabled: false,
|
|
1674
|
+
disabled: true,
|
|
1675
|
+
state: 'stopped',
|
|
1676
|
+
error: { code: 'memory_runtime_disabled', message: '记忆模式为轻量 MCP:切换到沉浸式后才能调整模型来源', retryable: false },
|
|
1677
|
+
}, 'memory_runtime_disabled', '记忆模式为轻量 MCP');
|
|
1678
|
+
}
|
|
1679
|
+
if (source === 'local') {
|
|
1680
|
+
const pack = modelPackId(input);
|
|
1681
|
+
if (!pack) {
|
|
1682
|
+
return {
|
|
1683
|
+
status: 400,
|
|
1684
|
+
body: {
|
|
1685
|
+
ok: false,
|
|
1686
|
+
error: 'pack_required',
|
|
1687
|
+
code: 'pack_required',
|
|
1688
|
+
message: 'source=local 需要 pack,并通过模型包激活设置',
|
|
1689
|
+
},
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
const result = await memoryRuntimeSupervisor.activateModel(pack);
|
|
1693
|
+
if (!result.ok) return modelSourceFailure(result, 'model_activation_failed', '模型激活失败');
|
|
1694
|
+
const data = result.data ?? {};
|
|
1695
|
+
const response = modelSourceSuccess(result, normalizeMemoryRuntimeModelSource(data.active) ?? source);
|
|
1696
|
+
return {
|
|
1697
|
+
...response,
|
|
1698
|
+
body: {
|
|
1699
|
+
...response.body,
|
|
1700
|
+
selectedPack: data.packId ?? pack,
|
|
1701
|
+
activated: data.activated === true,
|
|
1702
|
+
requiresRestart: false,
|
|
1703
|
+
warnings: Array.isArray(data.warnings) ? data.warnings : [],
|
|
1704
|
+
},
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
const result = await memoryRuntimeSupervisor.updateInferenceSettings({ source });
|
|
1708
|
+
if (!result.ok) return modelSourceFailure(result, 'model_source_failed', '模型来源保存失败');
|
|
1709
|
+
return modelSourceSuccess(result, source);
|
|
1710
|
+
}
|
|
1711
|
+
|
|
958
1712
|
const mcpSessions = new Map(); // sessionId → { transport, server }
|
|
959
1713
|
async function transportFor(sessionId) {
|
|
960
1714
|
if (sessionId) return mcpSessions.get(sessionId)?.transport ?? null;
|
|
@@ -1162,7 +1916,17 @@ export async function startHttpServer({
|
|
|
1162
1916
|
|
|
1163
1917
|
async function handleAdminRead(req, res, path, url) {
|
|
1164
1918
|
const builder = READ_ROUTES[path];
|
|
1165
|
-
|
|
1919
|
+
const memoryRuntimeTrace = /^\/admin\/api\/memory-runtime\/traces\/([^/]+)$/.exec(path);
|
|
1920
|
+
const modelRead = path === '/admin/api/models'
|
|
1921
|
+
|| path === '/admin/api/models/status'
|
|
1922
|
+
|| path === '/admin/api/inference/models'
|
|
1923
|
+
|| path === '/admin/api/inference/status';
|
|
1924
|
+
const memoryRuntimeRead = modelRead
|
|
1925
|
+
|| path === '/admin/api/memory-runtime/status'
|
|
1926
|
+
|| path === '/admin/api/memory-runtime/model-source'
|
|
1927
|
+
|| path === '/admin/api/memory-runtime/traces'
|
|
1928
|
+
|| memoryRuntimeTrace !== null;
|
|
1929
|
+
if (!builder && !memoryRuntimeRead) return false;
|
|
1166
1930
|
// P2:助手列表只读本机配置,UNINITIALIZED 也开放;其余 admin 读数据面仍需 READY。
|
|
1167
1931
|
if ((!app || !service) && path !== '/admin/api/clients') {
|
|
1168
1932
|
return sendJson(res, 503, { error: 'console_unavailable', message: 'Mebular 尚未初始化' });
|
|
@@ -1173,6 +1937,84 @@ export async function startHttpServer({
|
|
|
1173
1937
|
if (check.challenge) res.setHeader('www-authenticate', check.challenge);
|
|
1174
1938
|
return sendJson(res, check.status, { error: 'unauthorized', message: check.message });
|
|
1175
1939
|
}
|
|
1940
|
+
if (memoryRuntimeRead) {
|
|
1941
|
+
// 只读薄代理:浏览器不接触 sidecar host token;轻量模式返回明确 disabled/stopped。
|
|
1942
|
+
if (modelRead) {
|
|
1943
|
+
const result = path.endsWith('/status')
|
|
1944
|
+
? await modelStatusResponse()
|
|
1945
|
+
: await modelListResponse();
|
|
1946
|
+
return sendJson(res, result.status, result.body);
|
|
1947
|
+
}
|
|
1948
|
+
if (path === '/admin/api/memory-runtime/status') {
|
|
1949
|
+
const status = memoryRuntimeSupervisor
|
|
1950
|
+
? await memoryRuntimeSupervisor.status().catch(() => memoryRuntimeSupervisor.snapshot())
|
|
1951
|
+
: disabledMemoryRuntimeStatus();
|
|
1952
|
+
const detail = memoryRuntimeSupervisor
|
|
1953
|
+
? await memoryRuntimeSupervisor.readStatus().catch(() => null)
|
|
1954
|
+
: null;
|
|
1955
|
+
// 进程、capability 与模型是独立观察;不得用进程存活伪造 capability ready。
|
|
1956
|
+
return sendJson(res, 200, {
|
|
1957
|
+
...status,
|
|
1958
|
+
mode: status.enabled ? (detail?.mode ?? (status.available ? 'immersive' : null)) : 'lightweight',
|
|
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,
|
|
1963
|
+
model: detail?.model ?? null,
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
if (path === '/admin/api/memory-runtime/model-source') {
|
|
1967
|
+
const result = await readModelSourceResponse();
|
|
1968
|
+
return sendJson(res, result.status, result.body);
|
|
1969
|
+
}
|
|
1970
|
+
if (!memoryRuntimeSupervisor) {
|
|
1971
|
+
if (memoryRuntimeTrace) {
|
|
1972
|
+
return sendJson(res, 200, {
|
|
1973
|
+
ok: true,
|
|
1974
|
+
enabled: false,
|
|
1975
|
+
available: false,
|
|
1976
|
+
disabled: true,
|
|
1977
|
+
state: 'stopped',
|
|
1978
|
+
reason: 'disabled',
|
|
1979
|
+
trace: null,
|
|
1980
|
+
error: null,
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
return sendJson(res, 200, {
|
|
1984
|
+
ok: true,
|
|
1985
|
+
enabled: false,
|
|
1986
|
+
available: false,
|
|
1987
|
+
disabled: true,
|
|
1988
|
+
state: 'stopped',
|
|
1989
|
+
reason: 'disabled',
|
|
1990
|
+
traces: [],
|
|
1991
|
+
total: 0,
|
|
1992
|
+
degraded: false,
|
|
1993
|
+
warnings: [],
|
|
1994
|
+
});
|
|
1995
|
+
}
|
|
1996
|
+
if (memoryRuntimeTrace) {
|
|
1997
|
+
const trace = await memoryRuntimeSupervisor.readTrace(decodeURIComponent(memoryRuntimeTrace[1]));
|
|
1998
|
+
return sendJson(res, 200, trace);
|
|
1999
|
+
}
|
|
2000
|
+
const traces = await memoryRuntimeSupervisor.readTraces({ limit: url.searchParams.get('limit') ?? 20 });
|
|
2001
|
+
return sendJson(res, 200, traces);
|
|
2002
|
+
}
|
|
2003
|
+
// 内部对象只在管理面显式调试时可见;includeInternal 不能由普通读 token 打开。
|
|
2004
|
+
if (path === '/admin/api/memories') {
|
|
2005
|
+
const includeInternal = url.searchParams.get('includeInternal');
|
|
2006
|
+
if (includeInternal === '1' || includeInternal === 'true') {
|
|
2007
|
+
const adminCheck = await authenticate(req, Buffer.alloc(0), 'memory.admin');
|
|
2008
|
+
if (!adminCheck.ok) {
|
|
2009
|
+
res.statusCode = adminCheck.status;
|
|
2010
|
+
if (adminCheck.challenge) res.setHeader('www-authenticate', adminCheck.challenge);
|
|
2011
|
+
return sendJson(res, adminCheck.status, {
|
|
2012
|
+
error: 'forbidden',
|
|
2013
|
+
message: 'includeInternal 需要 memory.admin scope',
|
|
2014
|
+
});
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
1176
2018
|
// 注意:CSRF token 只在 /console/ 页面加载时签发。若在 overview 轮询里重新签发,
|
|
1177
2019
|
// cookie 会被每次轮询改写,与并发的写请求竞争(读 cookie 后、发出写之前又来一次
|
|
1178
2020
|
// overview)→ header 与 cookie 不一致而 403。token 12h 有效,页面加载签发一次即可。
|
|
@@ -1193,6 +2035,10 @@ export async function startHttpServer({
|
|
|
1193
2035
|
}
|
|
1194
2036
|
if (path === '/admin/api/overview') {
|
|
1195
2037
|
payload.features = { writes: Boolean(writesEnabled) };
|
|
2038
|
+
// 只读状态;不包含 token/tokenFile。禁用/未安装/失败都明确呈现,失败开放。
|
|
2039
|
+
payload.memoryRuntime = memoryRuntimeSupervisor
|
|
2040
|
+
? await memoryRuntimeSupervisor.status().catch(() => memoryRuntimeSupervisor.snapshot())
|
|
2041
|
+
: disabledMemoryRuntimeStatus();
|
|
1196
2042
|
}
|
|
1197
2043
|
return sendJson(res, 200, payload);
|
|
1198
2044
|
}
|
|
@@ -1346,6 +2192,12 @@ export async function startHttpServer({
|
|
|
1346
2192
|
/^\/admin\/api\/assistants$/,
|
|
1347
2193
|
/^\/admin\/api\/assistants\/([^/]+)$/,
|
|
1348
2194
|
/^\/admin\/api\/assistants\/([^/]+)\/remove$/,
|
|
2195
|
+
// 0.3 本地模型:sidecar 薄代理;同走 Origin + CSRF + memory.admin。
|
|
2196
|
+
/^\/admin\/api\/(?:models|inference)\/(install|select|download|pause|resume|cancel|import|uninstall|remove|start|stop|test)$/,
|
|
2197
|
+
// 0.3 记忆运行时:召回反馈经 MCP 薄代理转发 sidecar;host token 不出服务端。
|
|
2198
|
+
/^\/admin\/api\/memory-runtime\/feedback$/,
|
|
2199
|
+
// 0.3 高级模型来源:经 sidecar `/inference/settings` 或 `/models/:pack/activate`。
|
|
2200
|
+
/^\/admin\/api\/memory-runtime\/model-source$/,
|
|
1349
2201
|
];
|
|
1350
2202
|
|
|
1351
2203
|
// P2:UNINITIALIZED 仅开放本机助手配置所需的读写动作(列表 / 预览 / 接入 / 验证 / 重探)。
|
|
@@ -1743,6 +2595,7 @@ export async function startHttpServer({
|
|
|
1743
2595
|
const attempt = applyAttempt;
|
|
1744
2596
|
await writeApplyPending(home, {
|
|
1745
2597
|
attempt,
|
|
2598
|
+
applyId: randomUUID(),
|
|
1746
2599
|
at: new Date().toISOString(),
|
|
1747
2600
|
fields,
|
|
1748
2601
|
attempts: 1,
|
|
@@ -1896,6 +2749,49 @@ export async function startHttpServer({
|
|
|
1896
2749
|
// 自动修复:客户端接入修复,**不**经 securityWriteGate(不写记忆/安全状态)。
|
|
1897
2750
|
if (path === '/admin/api/repair') return handleRepair(req, res);
|
|
1898
2751
|
|
|
2752
|
+
// 0.3 高级模型来源:sidecar 拥有 config.model.source;MCP 只做薄代理。
|
|
2753
|
+
// local 必须带 pack 并通过 sidecar activate;不直接写 config.json、不重启 sidecar。
|
|
2754
|
+
if (path === '/admin/api/memory-runtime/model-source') {
|
|
2755
|
+
const input = parseJsonBody(body);
|
|
2756
|
+
if (!input) {
|
|
2757
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 JSON 请求体' });
|
|
2758
|
+
}
|
|
2759
|
+
const result = await writeModelSourceResponse(input);
|
|
2760
|
+
return sendJson(res, result.status, result.body);
|
|
2761
|
+
}
|
|
2762
|
+
|
|
2763
|
+
// 0.3 记忆运行时:召回反馈经 MCP 薄代理转发 sidecar(host token 只在服务端使用)。
|
|
2764
|
+
if (path === '/admin/api/memory-runtime/feedback') {
|
|
2765
|
+
const input = parseJsonBody(body);
|
|
2766
|
+
if (!input) {
|
|
2767
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 JSON 请求体' });
|
|
2768
|
+
}
|
|
2769
|
+
const traceId = typeof input.traceId === 'string' ? input.traceId : '';
|
|
2770
|
+
const result = memoryRuntimeSupervisor
|
|
2771
|
+
? await memoryRuntimeSupervisor.submitRecallFeedback(traceId, input)
|
|
2772
|
+
: {
|
|
2773
|
+
statusCode: 409,
|
|
2774
|
+
body: {
|
|
2775
|
+
ok: false,
|
|
2776
|
+
error: 'memory_runtime_disabled',
|
|
2777
|
+
enabled: false,
|
|
2778
|
+
state: 'stopped',
|
|
2779
|
+
message: '记忆运行时未启用',
|
|
2780
|
+
},
|
|
2781
|
+
};
|
|
2782
|
+
return sendJson(res, result.statusCode, result.body);
|
|
2783
|
+
}
|
|
2784
|
+
|
|
2785
|
+
// 0.3 本地模型:只代理 sidecar;不经 securityWriteGate(不写记忆/安全状态)。
|
|
2786
|
+
const modelAction = path.match(/^\/admin\/api\/(?:models|inference)\/([^/]+)$/);
|
|
2787
|
+
if (modelAction) {
|
|
2788
|
+
const result = await handleModelAction(
|
|
2789
|
+
decodeURIComponent(modelAction[1]),
|
|
2790
|
+
parseJsonBody(body) ?? {},
|
|
2791
|
+
);
|
|
2792
|
+
return sendJson(res, result.status, result.body);
|
|
2793
|
+
}
|
|
2794
|
+
|
|
1899
2795
|
// S2:安全三档写端点门禁(medium 动态码 / high 会签或恢复码;low 放行)。
|
|
1900
2796
|
const gateInput = parseJsonBody(body) ?? {};
|
|
1901
2797
|
const gate = await securityWriteGate({ app, home, path, input: gateInput, namespace });
|
|
@@ -2345,6 +3241,33 @@ export async function startHttpServer({
|
|
|
2345
3241
|
|
|
2346
3242
|
// 控制台配置写入:curated 合并 + 原子写 + .bak 备份(全部需重启生效)
|
|
2347
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
|
+
}
|
|
2348
3271
|
const input = parseJsonBody(body);
|
|
2349
3272
|
if (!input || typeof input.patch !== 'object') {
|
|
2350
3273
|
return sendJson(res, 400, { error: 'bad_request', errorKey: 'config_patch_invalid', message: '需要 { patch: { ... } }' });
|
|
@@ -2353,10 +3276,11 @@ export async function startHttpServer({
|
|
|
2353
3276
|
if (errors.length > 0) {
|
|
2354
3277
|
return sendJson(res, 400, { error: 'bad_request', errorKey: 'config_patch_invalid', message: errors.join(';'), details: errors });
|
|
2355
3278
|
}
|
|
2356
|
-
const cfgFile = configPath(home);
|
|
2357
3279
|
let current = {};
|
|
3280
|
+
let originalRaw = null;
|
|
2358
3281
|
try {
|
|
2359
|
-
|
|
3282
|
+
originalRaw = await readFile(cfgFile, 'utf-8');
|
|
3283
|
+
current = JSON.parse(originalRaw);
|
|
2360
3284
|
} catch {
|
|
2361
3285
|
current = {};
|
|
2362
3286
|
}
|
|
@@ -2383,12 +3307,140 @@ export async function startHttpServer({
|
|
|
2383
3307
|
});
|
|
2384
3308
|
}
|
|
2385
3309
|
const tmp = `${cfgFile}.tmp-${process.pid}`;
|
|
2386
|
-
|
|
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
|
+
}
|
|
2387
3363
|
if (existsSync(cfgFile)) await copyFile(cfgFile, `${cfgFile}.bak`);
|
|
2388
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
|
+
}
|
|
2389
3381
|
const backup = existsSync(`${cfgFile}.bak`) ? `${cfgFile}.bak` : null;
|
|
2390
3382
|
const base = { ok: true, applied: changedPaths, backup, path: cfgFile, config: merged };
|
|
2391
3383
|
|
|
3384
|
+
// memoryRuntime.enabled 是热开关:同步内存配置,立即生成/撤销 capability token,
|
|
3385
|
+
// 并启动/停止 sidecar(sidecar 失败不影响配置写入与 MCP 本身)。
|
|
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
|
+
}
|
|
3401
|
+
if (merged?.memoryRuntime === undefined) {
|
|
3402
|
+
const next = { ...(config ?? {}) };
|
|
3403
|
+
delete next.memoryRuntime;
|
|
3404
|
+
config = next;
|
|
3405
|
+
} else {
|
|
3406
|
+
config = { ...(config ?? {}), memoryRuntime: merged.memoryRuntime };
|
|
3407
|
+
}
|
|
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
|
+
}
|
|
3424
|
+
} else {
|
|
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);
|
|
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
|
+
});
|
|
3439
|
+
}
|
|
3440
|
+
throw error;
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3443
|
+
|
|
2392
3444
|
// G1:全部即时生效项 → 不重启,就地生效(前端随即刷新 effective)
|
|
2393
3445
|
if (restartPaths.length === 0) {
|
|
2394
3446
|
return sendJson(res, 200, { ...base, restartRequired: false, effectiveImmediately: true, restart: { mode: 'none' }, immediatePaths });
|
|
@@ -2429,6 +3481,10 @@ export async function startHttpServer({
|
|
|
2429
3481
|
timeoutMs,
|
|
2430
3482
|
},
|
|
2431
3483
|
});
|
|
3484
|
+
} finally {
|
|
3485
|
+
if (releaseConfigFileLock) await releaseConfigFileLock();
|
|
3486
|
+
releaseConfigWrite();
|
|
3487
|
+
}
|
|
2432
3488
|
}
|
|
2433
3489
|
|
|
2434
3490
|
// G-ML-1:记忆生命周期(动作式,无开关)——归档/解除归档(可逆)+ 删除(墓碑)
|
|
@@ -2983,6 +4039,11 @@ export async function startHttpServer({
|
|
|
2983
4039
|
res.setHeader('cache-control', 'no-store');
|
|
2984
4040
|
return sendJson(res, 200, buildEmbedInfo({ origin, loopback: isLoopback }));
|
|
2985
4041
|
}
|
|
4042
|
+
// 0.3 Memory Capability API(内部):loopback + capability token,独立于 /mcp 鉴权。
|
|
4043
|
+
// 轻量模式(memoryRuntime.enabled=false)返回 404 capability_disabled,不创建 token/目录。
|
|
4044
|
+
if (isMemoryCapabilityPath(path)) {
|
|
4045
|
+
return memoryCapability({ req, res, url, body });
|
|
4046
|
+
}
|
|
2986
4047
|
if (auth === 'oauth') {
|
|
2987
4048
|
if (path === '/.well-known/oauth-protected-resource' && req.method === 'GET') {
|
|
2988
4049
|
return sendJson(res, 200, metadata.protectedResource);
|
|
@@ -3285,6 +4346,23 @@ export async function startHttpServer({
|
|
|
3285
4346
|
}
|
|
3286
4347
|
})
|
|
3287
4348
|
.catch((error) => console.error(`SKILL_ENSURE_FAILED ${error?.code ?? 'ERROR'}`));
|
|
4349
|
+
// 自动自愈(主路径):热初始化后实际端口已确定 → 只更新已存在的本机 loopback Mebular 条目。
|
|
4350
|
+
void import('./clients.mjs')
|
|
4351
|
+
.then(({ reconcileClientEndpoints, assistantUserHome, daemonMcpUrl }) => {
|
|
4352
|
+
const reconcileHost = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host;
|
|
4353
|
+
return reconcileClientEndpoints({
|
|
4354
|
+
home,
|
|
4355
|
+
userHome: assistantUserHome(),
|
|
4356
|
+
cwd: process.cwd(),
|
|
4357
|
+
mcpUrl: daemonMcpUrl({ host: `${reconcileHost}:${boundPort}`, encrypted: tls }),
|
|
4358
|
+
});
|
|
4359
|
+
})
|
|
4360
|
+
.then((result) => {
|
|
4361
|
+
if (result?.summary?.failed > 0) {
|
|
4362
|
+
console.error(`CLIENT_ENDPOINT_RECONCILE_PARTIAL ${result.summary.failed} client(s)`);
|
|
4363
|
+
}
|
|
4364
|
+
})
|
|
4365
|
+
.catch((error) => console.error(`CLIENT_ENDPOINT_RECONCILE_FAILED ${error?.code ?? 'ERROR'}`));
|
|
3288
4366
|
return sendJson(res, 200, {
|
|
3289
4367
|
ok: true,
|
|
3290
4368
|
...result,
|
|
@@ -3332,7 +4410,17 @@ export async function startHttpServer({
|
|
|
3332
4410
|
const out = await buildHandoffPlan({ app }, decodeURIComponent(planMatch[1]), successor);
|
|
3333
4411
|
return sendJson(res, out.status, out.body);
|
|
3334
4412
|
}
|
|
3335
|
-
if (req.method === 'GET' && READ_ROUTES[path]
|
|
4413
|
+
if (req.method === 'GET' && (READ_ROUTES[path]
|
|
4414
|
+
|| path === '/admin/api/models'
|
|
4415
|
+
|| path === '/admin/api/models/status'
|
|
4416
|
+
|| path === '/admin/api/inference/models'
|
|
4417
|
+
|| path === '/admin/api/inference/status'
|
|
4418
|
+
|| path === '/admin/api/memory-runtime/status'
|
|
4419
|
+
|| path === '/admin/api/memory-runtime/model-source'
|
|
4420
|
+
|| path === '/admin/api/memory-runtime/traces'
|
|
4421
|
+
|| /^\/admin\/api\/memory-runtime\/traces\/[^/]+$/.test(path))) {
|
|
4422
|
+
return handleAdminRead(req, res, path, url);
|
|
4423
|
+
}
|
|
3336
4424
|
// 写端点路径:任何方法都交给 handleAdminWrite(非 POST/PUT/PATCH → 405;Origin/CSRF/scope 同处校验)
|
|
3337
4425
|
if (WRITE_PATTERNS.some((re) => re.test(path))) {
|
|
3338
4426
|
const done = await handleAdminWrite(req, res, path, body);
|
|
@@ -3357,9 +4445,36 @@ export async function startHttpServer({
|
|
|
3357
4445
|
multiaddrs: app.node?.getLocalMultiaddrs?.() ?? [],
|
|
3358
4446
|
});
|
|
3359
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
|
+
}
|
|
3360
4473
|
if (path === '/app/namespaces' && req.method === 'GET') {
|
|
3361
|
-
const
|
|
3362
|
-
const namespaces =
|
|
4474
|
+
const stats = service && typeof service.stats === 'function' ? await service.stats() : null;
|
|
4475
|
+
const namespaces = stats
|
|
4476
|
+
? stats.domains.map((entry) => entry.domain).sort()
|
|
4477
|
+
: (await app.getNamespaceDirectory()).sort();
|
|
3363
4478
|
return sendJson(res, 200, { ok: true, namespaces, count: namespaces.length });
|
|
3364
4479
|
}
|
|
3365
4480
|
if (path === '/app/nodes' && req.method === 'POST') {
|
|
@@ -3371,14 +4486,47 @@ export async function startHttpServer({
|
|
|
3371
4486
|
}
|
|
3372
4487
|
const type = typeof payload.type === 'string' && payload.type.length > 0 ? payload.type : null;
|
|
3373
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
|
+
}
|
|
3374
4505
|
const node = await app.graph.createNode(
|
|
3375
4506
|
type,
|
|
3376
4507
|
typeof payload.content === 'object' && payload.content !== null ? payload.content : {},
|
|
3377
4508
|
Array.isArray(payload.edges) ? payload.edges : [],
|
|
3378
|
-
|
|
4509
|
+
{
|
|
4510
|
+
...(payload.namespace ? { namespace: payload.namespace } : {}),
|
|
4511
|
+
...(payload.metadata !== undefined ? { metadata: payload.metadata } : {}),
|
|
4512
|
+
},
|
|
3379
4513
|
);
|
|
3380
|
-
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
|
+
});
|
|
3381
4524
|
}
|
|
4525
|
+
// [raw-graph-debug] 原始图调试/接入端点(调试例外):不做内部对象、归档或
|
|
4526
|
+
// 墓碑过滤,仅供 daemon/fleet 原始图读写与排障。普通记忆列表与域统计必须走
|
|
4527
|
+
// MemoryService.listRecords()/namespaceStats()(Console 见 admin.mjs),
|
|
4528
|
+
// 不得把这里当作普通记忆读路径。
|
|
4529
|
+
// P5:即使 raw debug 也不返回角色卡原文;角色卡只能走 /app/role-cards。
|
|
3382
4530
|
if (path === '/app/nodes' && req.method === 'GET') {
|
|
3383
4531
|
const filter = {};
|
|
3384
4532
|
const ns = url.searchParams.get('namespace');
|
|
@@ -3387,11 +4535,331 @@ export async function startHttpServer({
|
|
|
3387
4535
|
if (ns) filter.namespace = ns;
|
|
3388
4536
|
if (type) filter.type = type;
|
|
3389
4537
|
const nodes = await app.graph.listNodes(filter);
|
|
3390
|
-
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;
|
|
3391
4541
|
return sendJson(res, 200, {
|
|
3392
4542
|
ok: true,
|
|
3393
4543
|
count: trimmed.length,
|
|
3394
|
-
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
|
+
})),
|
|
3395
4863
|
});
|
|
3396
4864
|
}
|
|
3397
4865
|
// W2 A4:join 邀请(守护用自身身份生成令牌)
|
|
@@ -3473,6 +4941,9 @@ export async function startHttpServer({
|
|
|
3473
4941
|
? await acquireActiveLock({ root: cloud.root, home, profileId: cloudId })
|
|
3474
4942
|
: null;
|
|
3475
4943
|
|
|
4944
|
+
// capability token 在监听前生成(sidecar 首次握手可读);监听失败由下方 catch 撤销。
|
|
4945
|
+
if (isMemoryRuntimeEnabled(config)) await memoryCapability.prepare();
|
|
4946
|
+
|
|
3476
4947
|
let server;
|
|
3477
4948
|
try {
|
|
3478
4949
|
if (tls) {
|
|
@@ -3485,6 +4956,7 @@ export async function startHttpServer({
|
|
|
3485
4956
|
server.listen(port, host, () => resolve());
|
|
3486
4957
|
});
|
|
3487
4958
|
} catch (error) {
|
|
4959
|
+
await memoryCapability.dispose().catch(() => undefined);
|
|
3488
4960
|
await activeLock?.release?.().catch(() => undefined);
|
|
3489
4961
|
throw error;
|
|
3490
4962
|
}
|
|
@@ -3503,12 +4975,31 @@ export async function startHttpServer({
|
|
|
3503
4975
|
}).catch((error) => {
|
|
3504
4976
|
console.error(`RUNTIME_FILE_WRITE_FAILED ${error?.code ?? 'ERROR'}`);
|
|
3505
4977
|
});
|
|
4978
|
+
// MCP 已就绪后再异步拉起 sidecar:失败只影响沉浸式记忆,不阻塞 READY/29 工具。
|
|
4979
|
+
if (memoryRuntimeSupervisor && isMemoryRuntimeEnabled(config)) {
|
|
4980
|
+
void enqueueMemoryRuntimeLifecycle(() => memoryRuntimeSupervisor.start()).catch((error) => {
|
|
4981
|
+
console.error(`MEMORY_RUNTIME_START_FAILED ${error?.code ?? 'ERROR'}`);
|
|
4982
|
+
});
|
|
4983
|
+
}
|
|
4984
|
+
// 详情保留维护同样在 listen 后异步启动:过期扫描失败只记录状态,不影响 MCP。
|
|
4985
|
+
detailMaintenance.start();
|
|
3506
4986
|
let closePromise = null;
|
|
3507
4987
|
const close = () => {
|
|
3508
4988
|
if (closePromise) return closePromise;
|
|
3509
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
|
+
}
|
|
3510
4998
|
// 优雅停止的顺序很重要:MCP/SSE/keep-alive 连接不会自己断,
|
|
3511
4999
|
// 先收 MCP sessions,再主动结束连接,最后才等 listener(带有限超时)。
|
|
5000
|
+
// 详情维护先停 timer;进行中的 prune 最多等一个 session 预算,不拖死关闭。
|
|
5001
|
+
detailMaintenance.stop();
|
|
5002
|
+
await settleWithin(detailMaintenance.idle(), SESSION_CLOSE_TIMEOUT_MS);
|
|
3512
5003
|
const deadline = Date.now() + CLOSE_TIMEOUT_MS;
|
|
3513
5004
|
try {
|
|
3514
5005
|
// 1) 先让每个 MCP session 的 transport/server 正常收尾。
|
|
@@ -3520,19 +5011,26 @@ export async function startHttpServer({
|
|
|
3520
5011
|
Promise.resolve().then(() => entry.server.close()),
|
|
3521
5012
|
sessionBudget,
|
|
3522
5013
|
)));
|
|
3523
|
-
// 2)
|
|
5014
|
+
// 2) 只结束空闲 keep-alive;仍活跃的请求需要机会完成响应。
|
|
5015
|
+
// 直接 closeAllConnections 会让已经进入 config rename 回滚的 PATCH
|
|
5016
|
+
// 在慢 CI 上只看到 socket closed,而不是契约要求的 409。
|
|
3524
5017
|
server.closeIdleConnections?.();
|
|
3525
|
-
|
|
3526
|
-
//
|
|
5018
|
+
// 3) 给已接受的请求一个很短的完成窗口,再强制断开 SSE/长连接;
|
|
5019
|
+
// 否则 server.close 会一直等到 5s 截止时间。
|
|
3527
5020
|
await new Promise((resolve) => {
|
|
3528
5021
|
let done = false;
|
|
3529
5022
|
let timer = null;
|
|
5023
|
+
let graceTimer = null;
|
|
3530
5024
|
const finish = () => {
|
|
3531
5025
|
if (done) return;
|
|
3532
5026
|
done = true;
|
|
3533
5027
|
clearTimeout(timer);
|
|
5028
|
+
clearTimeout(graceTimer);
|
|
3534
5029
|
resolve();
|
|
3535
5030
|
};
|
|
5031
|
+
graceTimer = setTimeout(() => {
|
|
5032
|
+
server.closeAllConnections?.();
|
|
5033
|
+
}, Math.min(500, Math.max(0, deadline - Date.now())));
|
|
3536
5034
|
timer = setTimeout(() => {
|
|
3537
5035
|
server.closeAllConnections?.();
|
|
3538
5036
|
finish();
|
|
@@ -3546,7 +5044,15 @@ export async function startHttpServer({
|
|
|
3546
5044
|
} finally {
|
|
3547
5045
|
// 4) 无论前面如何都要清理;pid 守卫保证不误删新实例的 runtime.json。
|
|
3548
5046
|
await clearRuntimeFile(home, { pid: process.pid }).catch(() => undefined);
|
|
3549
|
-
// 5)
|
|
5047
|
+
// 5) 本地模型进程由 sidecar 拥有;MCP 不持有推理引擎,无需本地清理。
|
|
5048
|
+
// 6) 保留最新 main 的生命周期收尾:root 单活锁 + 热初始化上下文(app/join/广播)。
|
|
5049
|
+
// capability 只有 drain clean 后才撤销;drain 失败时明确放弃,不声明已撤销。
|
|
5050
|
+
await memoryRuntimeSupervisor?.dispose().catch(() => undefined);
|
|
5051
|
+
if (capabilityDrain?.clean) {
|
|
5052
|
+
await memoryCapability.dispose().catch(() => undefined);
|
|
5053
|
+
} else {
|
|
5054
|
+
memoryCapability.abandon();
|
|
5055
|
+
}
|
|
3550
5056
|
await activeLock?.release?.().catch(() => undefined);
|
|
3551
5057
|
await onClose?.().catch(() => undefined);
|
|
3552
5058
|
}
|
|
@@ -3560,6 +5066,18 @@ export async function startHttpServer({
|
|
|
3560
5066
|
auth,
|
|
3561
5067
|
issuer,
|
|
3562
5068
|
close,
|
|
3563
|
-
getState: () => ({
|
|
5069
|
+
getState: () => ({
|
|
5070
|
+
phase,
|
|
5071
|
+
hotInitialized,
|
|
5072
|
+
closing: lifecycleClosing,
|
|
5073
|
+
capabilityDrain,
|
|
5074
|
+
capabilityDraining: memoryCapability.isDraining?.() === true,
|
|
5075
|
+
app,
|
|
5076
|
+
service,
|
|
5077
|
+
config,
|
|
5078
|
+
runtime,
|
|
5079
|
+
deviceId,
|
|
5080
|
+
detailMaintenance: detailMaintenance.status(),
|
|
5081
|
+
}),
|
|
3564
5082
|
};
|
|
3565
5083
|
}
|