@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.
@@ -0,0 +1,2670 @@
1
+ // Memory Runtime sidecar 生命周期适配(MCP daemon 侧)。
2
+ //
3
+ // 边界(contract v2 §2.3 / §9.3,sidecar §5):
4
+ // - 只做进程 spawn/stop/restart、discovery 读取、health HTTP;
5
+ // - 不 import `@mebular/memory-runtime` 的抽取/召回/模型/存储实现;
6
+ // - 轻量模式(memoryRuntime.enabled=false)不创建目录/token/进程/端口;
7
+ // - 自动启动失败不阻塞 MCP;状态以 failed/degraded 明确呈现;
8
+ // - 一个 home/profile 一个实例:已有健康 sidecar attach,不重复启动;
9
+ // profile/home 不匹配时拒绝接管。
10
+ //
11
+ // 状态文件:`<home>/memory-runtime.json`(sidecar discovery)、
12
+ // `<home>/memory-runtime/start.lock`(sidecar 启动锁)。
13
+ // 本模块不读取/返回 host token 或 capability token 明文。
14
+
15
+ import { spawn as defaultSpawn } from 'node:child_process';
16
+ import { randomBytes, createHash } from 'node:crypto';
17
+ import { statSync } from 'node:fs';
18
+ import { chmod, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
19
+ import { homedir } from 'node:os';
20
+ import { delimiter, dirname, join, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { APP_VERSION } from './version.mjs';
23
+ import { readCapabilityToken } from './memory-runtime-token.mjs';
24
+ import { appendMemoryRuntimeLogSync } from './memory-runtime-diagnostics.mjs';
25
+
26
+ export const MEMORY_RUNTIME_DISCOVERY_FILE = 'memory-runtime.json';
27
+ export const MEMORY_RUNTIME_DATA_DIR = 'memory-runtime';
28
+ export const MEMORY_RUNTIME_START_LOCK_FILE = 'start.lock';
29
+ export const MEMORY_RUNTIME_TOKEN_FILE = 'host-token';
30
+ export const MEMORY_RUNTIME_CAPABILITY_TOKEN_FILE = 'capability-token';
31
+ export const MEMORY_RUNTIME_DEFAULT_PORT = 7341;
32
+ export const MEMORY_RUNTIME_DEFAULT_START_TIMEOUT_MS = 5000;
33
+ export const MEMORY_RUNTIME_HEALTH_TIMEOUT_MS = 200;
34
+ export const MEMORY_RUNTIME_HEALTH_CHECK_MS = 5000;
35
+ export const MEMORY_RUNTIME_DISCOVERY_STALE_MS = 15_000;
36
+ export const MEMORY_RUNTIME_DISCOVERY_DEAD_MS = 30_000;
37
+ export const MEMORY_RUNTIME_RESTART_WINDOW_MS = 5 * 60 * 1000;
38
+ export const MEMORY_RUNTIME_MAX_RESTARTS = 3;
39
+ export const MEMORY_RUNTIME_RESTART_BACKOFF_MS = 500;
40
+ export const MEMORY_RUNTIME_RESTART_BACKOFF_MAX_MS = 30_000;
41
+ export const MEMORY_RUNTIME_RESTART_COOLDOWN_MS = 5 * 60 * 1000;
42
+ export const MEMORY_RUNTIME_BIN = 'mebular-memory-runtime';
43
+ /** 默认 sidecar heartbeat 为 5s;禁用/停止必须覆盖至少一个完整心跳 + 有界收尾。 */
44
+ export const MEMORY_RUNTIME_ATTACHED_DORMANT_WAIT_MS = 12_000;
45
+
46
+ const SIDECAR_KIND = 'mebular-memory-runtime';
47
+ const CAPABILITY_API_VERSION = 1;
48
+
49
+ const sleep = (ms) => new Promise((resolvePromise) => setTimeout(resolvePromise, Math.max(0, ms)));
50
+
51
+ function isObject(value) {
52
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
53
+ }
54
+
55
+ function stringOrNull(value) {
56
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
57
+ }
58
+
59
+ function loopbackHostname(hostname) {
60
+ const normalized = String(hostname ?? '').replace(/^\[|\]$/g, '').toLowerCase();
61
+ return normalized === '127.0.0.1' || normalized === '::1' || normalized === 'localhost';
62
+ }
63
+
64
+ function validDiscoveryUrls(discovery) {
65
+ try {
66
+ const base = new URL(discovery.url);
67
+ const health = new URL(discovery.healthUrl);
68
+ const basePath = '/memory-runtime/v1';
69
+ return base.protocol === 'http:'
70
+ && health.protocol === 'http:'
71
+ && loopbackHostname(base.hostname)
72
+ && loopbackHostname(health.hostname)
73
+ && base.username === '' && base.password === ''
74
+ && health.username === '' && health.password === ''
75
+ && base.pathname === basePath
76
+ && health.pathname === `${basePath}/health`
77
+ && base.search === '' && base.hash === ''
78
+ && health.search === '' && health.hash === ''
79
+ && base.origin === health.origin
80
+ && Number(base.port) === discovery.port;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ function sameDiscoveryInstance(left, right) {
87
+ return Boolean(left && right)
88
+ && left.pid === right.pid
89
+ && left.startedAt === right.startedAt
90
+ && left.url === right.url
91
+ && left.tokenFile === right.tokenFile;
92
+ }
93
+
94
+ export function pidAlive(pid) {
95
+ if (!Number.isInteger(pid) || pid <= 0) return false;
96
+ try {
97
+ process.kill(pid, 0);
98
+ return true;
99
+ } catch (error) {
100
+ return error?.code === 'EPERM';
101
+ }
102
+ }
103
+
104
+ export function resolveMemoryRuntimeHome({ home, env = process.env } = {}) {
105
+ const raw = typeof home === 'string' && home.length > 0
106
+ ? home
107
+ : (typeof env?.MEBULAR_HOME === 'string' && env.MEBULAR_HOME.trim().length > 0
108
+ ? env.MEBULAR_HOME
109
+ : join(homedir(), '.mebular'));
110
+ return resolve(raw);
111
+ }
112
+
113
+ export function resolveMemoryRuntimePaths({ home, env = process.env } = {}) {
114
+ const resolvedHome = resolveMemoryRuntimeHome({ home, env });
115
+ const override = typeof env?.MEBULAR_MEMORY_RUNTIME_HOME === 'string'
116
+ && env.MEBULAR_MEMORY_RUNTIME_HOME.trim().length > 0
117
+ ? env.MEBULAR_MEMORY_RUNTIME_HOME
118
+ : null;
119
+ const dataDir = override ? resolve(override) : join(resolvedHome, MEMORY_RUNTIME_DATA_DIR);
120
+ return {
121
+ home: resolvedHome,
122
+ dataDir,
123
+ discoveryPath: join(resolvedHome, MEMORY_RUNTIME_DISCOVERY_FILE),
124
+ lockPath: join(dataDir, MEMORY_RUNTIME_START_LOCK_FILE),
125
+ hostTokenPath: join(dataDir, MEMORY_RUNTIME_TOKEN_FILE),
126
+ capabilityTokenPath: join(dataDir, MEMORY_RUNTIME_CAPABILITY_TOKEN_FILE),
127
+ };
128
+ }
129
+
130
+ async function readJson(path, fallback = null) {
131
+ try {
132
+ return JSON.parse(await readFile(path, 'utf-8'));
133
+ } catch {
134
+ return fallback;
135
+ }
136
+ }
137
+
138
+ function executableExists(path) {
139
+ try {
140
+ return statSync(path).isFile();
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+
146
+ function bundledBinCandidates() {
147
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
148
+ return [
149
+ join(moduleDir, '..', '..', 'memory-runtime', 'bin', 'mebular-memory-runtime.mjs'),
150
+ join(moduleDir, '..', 'node_modules', '@mebular', 'memory-runtime', 'bin', 'mebular-memory-runtime.mjs'),
151
+ join(moduleDir, '..', '..', '..', '@mebular', 'memory-runtime', 'bin', 'mebular-memory-runtime.mjs'),
152
+ ].map((entry) => resolve(entry));
153
+ }
154
+
155
+ function findOnPath(name, env) {
156
+ const pathValue = typeof env?.PATH === 'string' ? env.PATH : process.env.PATH;
157
+ if (typeof pathValue !== 'string' || pathValue.length === 0) return null;
158
+ const names = process.platform === 'win32' ? [`${name}.cmd`, `${name}.exe`, name] : [name];
159
+ for (const dir of pathValue.split(delimiter)) {
160
+ if (!dir) continue;
161
+ for (const candidate of names) {
162
+ const full = join(dir, candidate);
163
+ if (executableExists(full)) return full;
164
+ }
165
+ }
166
+ return null;
167
+ }
168
+
169
+ /**
170
+ * 解析 sidecar 可执行文件。
171
+ *
172
+ * 优先级:`memoryRuntime.command` > `MEBULAR_MEMORY_RUNTIME_BIN` > 包内 bin > PATH。
173
+ * 显式配置/环境变量指向不存在文件时直接失败,不静默回退。
174
+ */
175
+ export function resolveMemoryRuntimeCommand({ config, env = process.env } = {}) {
176
+ const configured = stringOrNull(config?.memoryRuntime?.command);
177
+ if (configured) {
178
+ const command = resolve(configured);
179
+ return executableExists(command)
180
+ ? { ok: true, command, source: 'config' }
181
+ : { ok: false, command, source: 'config', reason: 'not_installed' };
182
+ }
183
+
184
+ const fromEnv = stringOrNull(env?.MEBULAR_MEMORY_RUNTIME_BIN);
185
+ if (fromEnv) {
186
+ const command = resolve(fromEnv);
187
+ return executableExists(command)
188
+ ? { ok: true, command, source: 'env' }
189
+ : { ok: false, command, source: 'env', reason: 'not_installed' };
190
+ }
191
+
192
+ for (const candidate of bundledBinCandidates()) {
193
+ if (executableExists(candidate)) {
194
+ return { ok: true, command: candidate, source: 'bundled' };
195
+ }
196
+ }
197
+
198
+ const onPath = findOnPath(MEMORY_RUNTIME_BIN, env);
199
+ if (onPath) return { ok: true, command: onPath, source: 'path' };
200
+
201
+ return { ok: false, command: null, source: 'missing', reason: 'not_installed' };
202
+ }
203
+
204
+ function commandSpec(command) {
205
+ if (/\.(?:mjs|cjs|js)$/i.test(command)) {
206
+ return { execPath: process.execPath, args: [command] };
207
+ }
208
+ if (process.platform === 'win32' && /\.cmd$/i.test(command)) {
209
+ return { execPath: process.env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', command] };
210
+ }
211
+ return { execPath: command, args: [] };
212
+ }
213
+
214
+ function parseVersion(value) {
215
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(String(value ?? '').trim());
216
+ if (!match) return null;
217
+ return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
218
+ }
219
+
220
+ function compareVersion(a, b) {
221
+ if (a.major !== b.major) return a.major - b.major;
222
+ if (a.minor !== b.minor) return a.minor - b.minor;
223
+ return a.patch - b.patch;
224
+ }
225
+
226
+ function mcpVersionCompatible(version, minVersion, maxVersion) {
227
+ const parsed = parseVersion(version);
228
+ const min = parseVersion(minVersion);
229
+ if (!parsed || !min) return false;
230
+ if (compareVersion(parsed, min) < 0) return false;
231
+ const wildcard = /^(\d+)\.(\d+)\.x$/.exec(String(maxVersion ?? '').trim());
232
+ if (wildcard) {
233
+ return parsed.major === Number(wildcard[1]) && parsed.minor <= Number(wildcard[2]);
234
+ }
235
+ const max = parseVersion(maxVersion);
236
+ return max ? compareVersion(parsed, max) <= 0 : false;
237
+ }
238
+
239
+ function discoveryProfileId(discovery) {
240
+ return stringOrNull(discovery?.profileId);
241
+ }
242
+
243
+ function discoveryCloudId(discovery) {
244
+ return stringOrNull(discovery?.cloudId);
245
+ }
246
+
247
+ function publicError(code, message) {
248
+ return code ? { code, message } : null;
249
+ }
250
+
251
+ function makeDisabledStatus({ enabled = false, reason = 'disabled' } = {}) {
252
+ return {
253
+ enabled,
254
+ state: 'stopped',
255
+ available: false,
256
+ degraded: false,
257
+ managed: false,
258
+ attached: false,
259
+ pid: null,
260
+ url: null,
261
+ healthUrl: null,
262
+ runtimeVersion: null,
263
+ apiVersion: null,
264
+ capabilityApiVersion: null,
265
+ commandSource: null,
266
+ discoveryMode: null,
267
+ installed: enabled ? null : false,
268
+ startedAt: null,
269
+ lastOkAt: null,
270
+ restarts: 0,
271
+ reason,
272
+ error: null,
273
+ lock: null,
274
+ };
275
+ }
276
+
277
+ export function disabledMemoryRuntimeStatus() {
278
+ return makeDisabledStatus();
279
+ }
280
+
281
+ function isSidecarDiscovery(value) {
282
+ return isObject(value)
283
+ && value.schema === 1
284
+ && value.kind === SIDECAR_KIND
285
+ && Number.isInteger(value.pid)
286
+ && value.pid > 0
287
+ && typeof value.host === 'string'
288
+ && Number.isInteger(value.port)
289
+ && typeof value.url === 'string'
290
+ && typeof value.healthUrl === 'string'
291
+ && typeof value.tokenFile === 'string'
292
+ && typeof value.updatedAt === 'number';
293
+ }
294
+
295
+ async function readDiscovery(path) {
296
+ const value = await readJson(path, null);
297
+ if (!isSidecarDiscovery(value)) return null;
298
+ if (value.mode !== undefined && value.mode !== 'immersive' && value.mode !== 'mcp') return null;
299
+ return { ...value, mode: value.mode ?? 'immersive' };
300
+ }
301
+
302
+ async function readLock(path) {
303
+ const value = await readJson(path, null);
304
+ if (!isObject(value) || !Number.isInteger(value.pid) || value.pid <= 0) return null;
305
+ return {
306
+ pid: value.pid,
307
+ port: Number.isInteger(value.port) ? value.port : null,
308
+ startedAt: typeof value.startedAt === 'number' ? value.startedAt : 0,
309
+ updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,
310
+ cloudId: stringOrNull(value.cloudId),
311
+ profileId: stringOrNull(value.profileId),
312
+ command: typeof value.command === 'string' ? value.command : 'serve',
313
+ };
314
+ }
315
+
316
+ function redact(text, secrets) {
317
+ let out = String(text ?? '');
318
+ for (const secret of secrets) {
319
+ if (typeof secret === 'string' && secret.length > 0) out = out.split(secret).join('[redacted]');
320
+ }
321
+ return out.slice(-1000);
322
+ }
323
+
324
+ const PROXY_SECRET_KEYS = new Set([
325
+ 'authorization',
326
+ 'cookie',
327
+ 'token',
328
+ 'tokenfile',
329
+ 'hosttoken',
330
+ 'host_token',
331
+ 'capabilitytoken',
332
+ 'capability_token',
333
+ 'password',
334
+ 'secret',
335
+ 'keyref',
336
+ 'baseurl',
337
+ 'modelpath',
338
+ 'installedpath',
339
+ 'modelsdir',
340
+ 'apikey',
341
+ 'api_key',
342
+ 'api-key',
343
+ 'accesstoken',
344
+ 'refreshtoken',
345
+ 'secretref',
346
+ 'credentialref',
347
+ 'endpoint',
348
+ 'binarypath',
349
+ 'installpath',
350
+ 'enginepath',
351
+ 'path',
352
+ 'rootdir',
353
+ 'homedir',
354
+ 'debug',
355
+ ]);
356
+
357
+ /**
358
+ * 管理面代理只返回 sidecar 的公开视图:递归去掉令牌类字段,并把已知密钥从字符串里抹掉。
359
+ * sidecar 本身不应返回这些字段;这里多做一层,避免未来回归把 host token 带到浏览器。
360
+ */
361
+ function scrubProxyValue(value, secrets) {
362
+ if (Array.isArray(value)) return value.map((entry) => scrubProxyValue(entry, secrets));
363
+ if (isObject(value)) {
364
+ const out = {};
365
+ for (const [key, entry] of Object.entries(value)) {
366
+ if (PROXY_SECRET_KEYS.has(String(key).toLowerCase())) continue;
367
+ out[key] = scrubProxyValue(entry, secrets);
368
+ }
369
+ return out;
370
+ }
371
+ if (typeof value === 'string') {
372
+ let text = value;
373
+ for (const secret of secrets) {
374
+ if (typeof secret === 'string' && secret.length > 0) text = text.split(secret).join('[redacted]');
375
+ }
376
+ return text;
377
+ }
378
+ return value;
379
+ }
380
+
381
+ function traceText(value, max = 512) {
382
+ return typeof value === 'string' ? value.slice(0, max) : null;
383
+ }
384
+
385
+ function traceNumber(value) {
386
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
387
+ }
388
+
389
+ function traceStrings(value) {
390
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === 'string').slice(0, 100) : [];
391
+ }
392
+
393
+ function traceOwnerView(owner) {
394
+ return {
395
+ role: traceText(owner?.role, 64),
396
+ ownerId: traceText(owner?.ownerId, 256),
397
+ domain: traceText(owner?.domain, 256),
398
+ agentName: traceText(owner?.agentName, 128),
399
+ };
400
+ }
401
+
402
+ function traceProvenanceView(provenance) {
403
+ return {
404
+ source: traceText(provenance?.source, 64),
405
+ extractor: traceText(provenance?.extractor, 64),
406
+ hostId: traceText(provenance?.hostId, 128),
407
+ };
408
+ }
409
+
410
+ function traceSummaryView(trace) {
411
+ const feedback = trace?.feedback;
412
+ return {
413
+ id: traceText(trace?.id, 160),
414
+ recallId: traceText(trace?.recallId, 160),
415
+ schema: traceNumber(trace?.schema),
416
+ at: traceNumber(trace?.at),
417
+ agentId: traceText(trace?.agentId, 256),
418
+ threadId: traceText(trace?.threadId, 256),
419
+ queryHash: traceText(trace?.queryHash, 256),
420
+ queryPreview: traceText(trace?.queryPreview, 160),
421
+ domains: traceStrings(trace?.domains),
422
+ silenceReason: traceText(trace?.silenceReason, 128),
423
+ degraded: trace?.degraded === true,
424
+ feedback: feedback && typeof feedback === 'object' ? {
425
+ useful: feedback.useful === true,
426
+ reason: traceText(feedback.reason, 500),
427
+ at: traceNumber(feedback.at),
428
+ } : null,
429
+ counts: {
430
+ candidates: traceNumber(trace?.counts?.candidates),
431
+ expansions: traceNumber(trace?.counts?.expansions),
432
+ injected: traceNumber(trace?.counts?.injected),
433
+ tokens: traceNumber(trace?.counts?.tokens),
434
+ },
435
+ timing: { totalMs: traceNumber(trace?.timing?.totalMs) },
436
+ model: {
437
+ query: traceText(trace?.model?.query, 128),
438
+ embedding: traceText(trace?.model?.embedding, 128),
439
+ extractor: traceText(trace?.model?.extractor, 128),
440
+ tookMs: traceNumber(trace?.model?.tookMs),
441
+ },
442
+ };
443
+ }
444
+
445
+ function traceDetailView(trace) {
446
+ return {
447
+ ...traceSummaryView(trace),
448
+ hits: Array.isArray(trace?.hits) ? trace.hits.slice(0, 100).map((hit) => ({
449
+ id: traceText(hit?.id, 256),
450
+ type: traceText(hit?.type, 64),
451
+ score: traceNumber(hit?.score),
452
+ rank: traceNumber(hit?.rank),
453
+ })) : [],
454
+ cue: {
455
+ topics: traceStrings(trace?.cue?.topics),
456
+ entities: Array.isArray(trace?.cue?.entities) ? trace.cue.entities.slice(0, 100).map((entity) => ({
457
+ name: traceText(entity?.name, 256),
458
+ type: traceText(entity?.type, 64),
459
+ })) : [],
460
+ },
461
+ candidates: Array.isArray(trace?.candidates) ? trace.candidates.slice(0, 100).map((candidate) => ({
462
+ id: traceText(candidate?.id, 256),
463
+ type: traceText(candidate?.type, 64),
464
+ domain: traceText(candidate?.domain, 256),
465
+ owner: traceOwnerView(candidate?.owner),
466
+ provenance: traceProvenanceView(candidate?.provenance),
467
+ confidence: traceNumber(candidate?.confidence),
468
+ score: traceNumber(candidate?.score),
469
+ rank: traceNumber(candidate?.rank),
470
+ })) : [],
471
+ expansions: Array.isArray(trace?.expansions) ? trace.expansions.slice(0, 100).map((expansion) => ({
472
+ sourceId: traceText(expansion?.sourceId, 256),
473
+ reason: traceText(expansion?.reason, 128),
474
+ status: traceText(expansion?.status, 64),
475
+ })) : [],
476
+ injected: Array.isArray(trace?.injected) ? trace.injected.slice(0, 100).map((fragment) => ({
477
+ fragmentId: traceText(fragment?.fragmentId, 256),
478
+ sourceId: traceText(fragment?.sourceId, 256),
479
+ layer: traceText(fragment?.layer, 64),
480
+ tokens: traceNumber(fragment?.tokens),
481
+ citations: traceStrings(fragment?.citations),
482
+ confidence: traceNumber(fragment?.confidence),
483
+ owner: traceOwnerView(fragment?.owner),
484
+ provenance: traceProvenanceView(fragment?.provenance),
485
+ })) : [],
486
+ };
487
+ }
488
+
489
+ function proxyErrorMessage(body, fallback) {
490
+ const message = body?.error?.message ?? body?.message;
491
+ return typeof message === 'string' && message.length > 0 ? message : fallback;
492
+ }
493
+
494
+ /**
495
+ * Memory Runtime sidecar supervisor。
496
+ *
497
+ * 仅管理当前 `<home>` 的 sidecar;不启动 MCP daemon、不读写图、不 import sidecar 业务。
498
+ */
499
+ export class MemoryRuntimeSupervisor {
500
+ constructor({
501
+ home,
502
+ config = () => ({}),
503
+ env = process.env,
504
+ profileId = () => null,
505
+ cloudId = () => null,
506
+ mcpUrl = () => null,
507
+ getCapabilityToken = null,
508
+ command = null,
509
+ spawnImpl = defaultSpawn,
510
+ fetchImpl = globalThis.fetch,
511
+ now = Date.now,
512
+ startTimeoutMs = null,
513
+ healthTimeoutMs = MEMORY_RUNTIME_HEALTH_TIMEOUT_MS,
514
+ healthCheckIntervalMs = MEMORY_RUNTIME_HEALTH_CHECK_MS,
515
+ healthPollMs = 100,
516
+ restartWindowMs = MEMORY_RUNTIME_RESTART_WINDOW_MS,
517
+ maxRestartsInWindow = MEMORY_RUNTIME_MAX_RESTARTS,
518
+ restartBackoffMs = MEMORY_RUNTIME_RESTART_BACKOFF_MS,
519
+ restartBackoffMaxMs = MEMORY_RUNTIME_RESTART_BACKOFF_MAX_MS,
520
+ restartCooldownMs = MEMORY_RUNTIME_RESTART_COOLDOWN_MS,
521
+ restartOnFailure = true,
522
+ } = {}) {
523
+ this.home = resolveMemoryRuntimeHome({ home, env });
524
+ this.env = env ?? process.env;
525
+ this.paths = resolveMemoryRuntimePaths({ home: this.home, env: this.env });
526
+ this.getConfig = typeof config === 'function' ? config : () => config;
527
+ this.getProfileId = typeof profileId === 'function' ? profileId : () => profileId;
528
+ this.getCloudId = typeof cloudId === 'function' ? cloudId : () => cloudId;
529
+ this.getMcpUrl = typeof mcpUrl === 'function' ? mcpUrl : () => mcpUrl;
530
+ this.getCapabilityToken = getCapabilityToken;
531
+ this.explicitCommand = stringOrNull(command);
532
+ this.spawnImpl = spawnImpl;
533
+ this.fetchImpl = fetchImpl;
534
+ this.now = now;
535
+ this.startTimeoutMs = startTimeoutMs
536
+ ?? (typeof this.getConfig()?.memoryRuntime?.startTimeoutMs === 'number'
537
+ ? this.getConfig().memoryRuntime.startTimeoutMs
538
+ : MEMORY_RUNTIME_DEFAULT_START_TIMEOUT_MS);
539
+ this.healthTimeoutMs = healthTimeoutMs;
540
+ this.healthCheckIntervalMs = healthCheckIntervalMs;
541
+ this.healthPollMs = healthPollMs;
542
+ this.restartWindowMs = restartWindowMs;
543
+ this.maxRestartsInWindow = Math.max(0, maxRestartsInWindow);
544
+ this.restartBackoffMs = restartBackoffMs;
545
+ this.restartBackoffMaxMs = restartBackoffMaxMs;
546
+ this.restartCooldownMs = restartCooldownMs;
547
+ this.restartOnFailure = restartOnFailure;
548
+
549
+ this.child = null;
550
+ this.childToken = null;
551
+ this.childSecrets = [];
552
+ this.managedInstance = null;
553
+ this.dormantLock = null;
554
+ this.dormantLockInvalidated = false;
555
+ this.startPromise = null;
556
+ this.restartTimer = null;
557
+ this.cooldownTimer = null;
558
+ this.watchdogTimer = null;
559
+ this.healthFailures = 0;
560
+ this.crashTimes = [];
561
+ this.restarts = 0;
562
+ this.stopping = false;
563
+ this.disposed = false;
564
+ this.readySeen = false;
565
+ this.manualStart = false;
566
+ this.commandSource = null;
567
+ this.installed = null;
568
+ this.lockView = null;
569
+ this.statusState = makeDisabledStatus({
570
+ enabled: this.isEnabled(),
571
+ reason: this.isEnabled() ? null : 'disabled',
572
+ });
573
+ }
574
+
575
+ isEnabled() {
576
+ try {
577
+ return this.getConfig()?.memoryRuntime?.enabled === true;
578
+ } catch {
579
+ return false;
580
+ }
581
+ }
582
+
583
+ configuredStartTimeout() {
584
+ const configured = this.getConfig()?.memoryRuntime?.startTimeoutMs;
585
+ return Number.isInteger(configured) && configured >= 100
586
+ ? configured
587
+ : Math.max(100, this.startTimeoutMs);
588
+ }
589
+
590
+ snapshot() {
591
+ return JSON.parse(JSON.stringify(this.statusState));
592
+ }
593
+
594
+ #profileId() {
595
+ try {
596
+ return stringOrNull(this.getProfileId());
597
+ } catch {
598
+ return null;
599
+ }
600
+ }
601
+
602
+ #cloudId() {
603
+ try {
604
+ return stringOrNull(this.getCloudId());
605
+ } catch {
606
+ return null;
607
+ }
608
+ }
609
+
610
+ #setState(patch) {
611
+ const nextState = patch.state ?? this.statusState.state;
612
+ this.statusState = {
613
+ ...this.statusState,
614
+ ...patch,
615
+ enabled: this.isEnabled(),
616
+ available: this.isEnabled() && (patch.available ?? (nextState === 'ready' || nextState === 'degraded')),
617
+ };
618
+ return this.snapshot();
619
+ }
620
+
621
+ #degradedError(code = 'sidecar_degraded') {
622
+ return publicError(code, 'Memory Runtime sidecar 处于降级状态');
623
+ }
624
+
625
+ #profileMismatch(discovery) {
626
+ const expectedProfile = this.#profileId();
627
+ const actualProfile = discoveryProfileId(discovery);
628
+ if (expectedProfile && expectedProfile !== actualProfile) return true;
629
+ const expectedCloud = this.#cloudId();
630
+ const actualCloud = discoveryCloudId(discovery);
631
+ return Boolean(expectedCloud && expectedCloud !== actualCloud);
632
+ }
633
+
634
+ #homeMismatch(discovery) {
635
+ if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return true;
636
+ return resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir;
637
+ }
638
+
639
+ #versionMismatch(discovery) {
640
+ if (discovery?.capabilityApiVersion !== CAPABILITY_API_VERSION) return true;
641
+ return !mcpVersionCompatible(
642
+ APP_VERSION,
643
+ discovery.minMcpVersion ?? '0.3.0',
644
+ discovery.maxMcpVersion ?? '0.3.x',
645
+ );
646
+ }
647
+
648
+ #healthIdentityMatches(discovery, body, { allowDormant = false } = {}) {
649
+ if (!isObject(body) || body.pid !== discovery.pid) return false;
650
+ if (stringOrNull(body.profileId) !== discoveryProfileId(discovery)) return false;
651
+ if (stringOrNull(body.cloudId) !== discoveryCloudId(discovery)) return false;
652
+ return body.mode === discovery.mode || (allowDormant && body.mode === 'mcp');
653
+ }
654
+
655
+ async #fetchHealth(discovery, { acceptDormant = false } = {}) {
656
+ if (!this.fetchImpl || typeof discovery?.healthUrl !== 'string') return { ok: false };
657
+ const controller = new AbortController();
658
+ const timer = setTimeout(() => controller.abort(), Math.max(1, this.healthTimeoutMs));
659
+ timer.unref?.();
660
+ try {
661
+ const response = await this.fetchImpl(discovery.healthUrl, {
662
+ method: 'GET',
663
+ headers: { accept: 'application/json' },
664
+ signal: controller.signal,
665
+ });
666
+ if (!response || response.ok !== true) return { ok: false };
667
+ const body = await response.json().catch(() => ({}));
668
+ const ready = body?.ready !== false;
669
+ const dormant = acceptDormant && body?.mode === 'mcp' && body?.state === 'stopped';
670
+ return {
671
+ ok: body?.ok !== false && (ready || dormant),
672
+ degraded: body?.degraded === true || body?.state === 'degraded',
673
+ body,
674
+ };
675
+ } catch {
676
+ return { ok: false };
677
+ } finally {
678
+ clearTimeout(timer);
679
+ }
680
+ }
681
+
682
+ async #readLockView() {
683
+ const lock = await readLock(this.paths.lockPath);
684
+ this.lockView = lock === null
685
+ ? null
686
+ : {
687
+ pid: lock.pid,
688
+ port: lock.port,
689
+ cloudId: lock.cloudId,
690
+ profileId: lock.profileId,
691
+ stale: !pidAlive(lock.pid),
692
+ };
693
+ return lock;
694
+ }
695
+
696
+ /** 从 start.lock 构造可验证候选;不写回 discovery,只用于显式 stop。 */
697
+ #discoveryFromLock(lock) {
698
+ if (!lock || lock.command !== 'serve' || !Number.isInteger(lock.port) || lock.port <= 0) return null;
699
+ const base = `http://127.0.0.1:${lock.port}/memory-runtime/v1`;
700
+ return {
701
+ schema: 1,
702
+ kind: SIDECAR_KIND,
703
+ pid: lock.pid,
704
+ host: '127.0.0.1',
705
+ port: lock.port,
706
+ url: base,
707
+ healthUrl: `${base}/health`,
708
+ tokenFile: this.paths.hostTokenPath,
709
+ cloudId: lock.cloudId,
710
+ profileId: lock.profileId,
711
+ runtimeVersion: APP_VERSION,
712
+ apiVersion: 1,
713
+ capabilityApiVersion: CAPABILITY_API_VERSION,
714
+ minMcpVersion: '0.3.0',
715
+ maxMcpVersion: '0.3.x',
716
+ state: 'ready',
717
+ mode: 'immersive',
718
+ degraded: false,
719
+ startedAt: lock.startedAt,
720
+ updatedAt: this.now(),
721
+ capabilities: {},
722
+ };
723
+ }
724
+
725
+ /** 当前实际 capability token(env 优先,其次生产文件)的指纹;null 表示没有可用凭据。 */
726
+ async #capabilityFingerprint() {
727
+ try {
728
+ const record = await readCapabilityToken({
729
+ home: this.paths.home,
730
+ env: this.env,
731
+ now: this.now(),
732
+ });
733
+ if (!record?.token) return null;
734
+ return createHash('sha256').update(record.token).digest('hex');
735
+ } catch {
736
+ return null;
737
+ }
738
+ }
739
+
740
+ get #dormantStatePath() {
741
+ return join(this.paths.dataDir, 'dormant.json');
742
+ }
743
+
744
+ async #readDormantState() {
745
+ try {
746
+ const info = await stat(this.#dormantStatePath);
747
+ if (process.platform !== 'win32' && (info.mode & 0o777) !== 0o600) return null;
748
+ const value = JSON.parse(await readFile(this.#dormantStatePath, 'utf-8'));
749
+ if (value?.version !== undefined && value.version !== 1) return null;
750
+ if (!Number.isInteger(value?.pid) || value.pid <= 0) return null;
751
+ if (!Number.isFinite(value?.startedAt)) return null;
752
+ if (!(typeof value?.credential === 'string' || value?.credential === null)) return null;
753
+ return {
754
+ pid: value.pid,
755
+ startedAt: value.startedAt,
756
+ credential: value.credential,
757
+ };
758
+ } catch {
759
+ return null;
760
+ }
761
+ }
762
+
763
+ async #writeDormantState(state) {
764
+ const tmp = `${this.#dormantStatePath}.tmp-${process.pid}`;
765
+ try {
766
+ await writeFile(tmp, JSON.stringify({ version: 1, ...state }, null, 2), { mode: 0o600 });
767
+ if (process.platform !== 'win32') await chmod(tmp, 0o600);
768
+ await rename(tmp, this.#dormantStatePath);
769
+ } catch (error) {
770
+ await unlink(tmp).catch(() => undefined);
771
+ throw error;
772
+ }
773
+ }
774
+
775
+ async #clearDormantState() {
776
+ await unlink(this.#dormantStatePath).catch(() => undefined);
777
+ }
778
+
779
+ /**
780
+ * 读取 discovery/health 并更新快照。
781
+ * @returns {Promise<boolean>} 是否可接流量(ready 或 degraded)。
782
+ */
783
+ async #refreshDiscovery({ fetchHealth = true } = {}) {
784
+ if (!this.isEnabled()) {
785
+ if (this.statusState.error?.code !== 'disable_incomplete') {
786
+ this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
787
+ }
788
+ return false;
789
+ }
790
+ await this.#readLockView();
791
+ const discovery = await readDiscovery(this.paths.discoveryPath);
792
+ if (!discovery) {
793
+ if (this.dormantLock) {
794
+ const lock = await readLock(this.paths.lockPath);
795
+ const credential = await this.#capabilityFingerprint();
796
+ if (!lock
797
+ || lock.pid !== this.dormantLock.pid
798
+ || lock.startedAt !== this.dormantLock.startedAt
799
+ || !pidAlive(lock.pid)
800
+ || credential !== this.dormantLock.credential) {
801
+ this.dormantLockInvalidated = true;
802
+ this.dormantLock = null;
803
+ // 保留持久化 baseline:跨进程启动仍能识别 credential 已换代。
804
+ } else {
805
+ this.#setState({
806
+ state: 'stopped',
807
+ available: false,
808
+ degraded: false,
809
+ managed: false,
810
+ attached: false,
811
+ pid: lock.pid,
812
+ url: null,
813
+ healthUrl: null,
814
+ reason: 'disabled',
815
+ error: null,
816
+ lock: this.lockView,
817
+ });
818
+ return false;
819
+ }
820
+ }
821
+ if (this.child && this.child.exitCode === null) {
822
+ const state = this.readySeen ? 'degraded' : 'starting';
823
+ this.#setState({
824
+ state,
825
+ degraded: this.readySeen,
826
+ managed: true,
827
+ attached: false,
828
+ pid: this.child.pid ?? null,
829
+ url: null,
830
+ healthUrl: null,
831
+ discoveryMode: null,
832
+ restarts: this.restarts,
833
+ error: this.readySeen ? publicError('discovery_missing', 'sidecar discovery 缺失') : null,
834
+ lock: this.lockView,
835
+ });
836
+ return false;
837
+ }
838
+ if (this.statusState.state !== 'failed'
839
+ || ['discovery_dead', 'discovery_stale', 'discovery_future', 'discovery_invalid', 'instance_mismatch']
840
+ .includes(this.statusState.error?.code)) {
841
+ const startingByLock = this.isEnabled()
842
+ && this.lockView !== null
843
+ && this.lockView.stale !== true
844
+ && this.env?.MEBULAR_MEMORY_RUNTIME_DISABLE !== '1';
845
+ this.#setState({
846
+ state: startingByLock ? 'starting' : 'stopped',
847
+ degraded: false,
848
+ managed: false,
849
+ attached: false,
850
+ pid: this.lockView?.pid ?? null,
851
+ url: null,
852
+ healthUrl: null,
853
+ discoveryMode: null,
854
+ restarts: this.restarts,
855
+ error: null,
856
+ lock: this.lockView,
857
+ reason: !this.isEnabled() || this.env?.MEBULAR_MEMORY_RUNTIME_DISABLE === '1'
858
+ ? 'disabled'
859
+ : this.statusState.reason ?? null,
860
+ });
861
+ } else {
862
+ this.#setState({ restarts: this.restarts, lock: this.lockView });
863
+ }
864
+ return false;
865
+ }
866
+
867
+ const managed = Boolean(this.child && this.child.pid === discovery.pid);
868
+ if (managed) {
869
+ // 记录本实例拥有的 pid/startedAt;child 被强杀后仍可确认 discovery/start.lock 归属。
870
+ this.managedInstance = { pid: discovery.pid, startedAt: discovery.startedAt };
871
+ }
872
+ if (this.#homeMismatch(discovery)) {
873
+ this.#setState({
874
+ state: 'failed',
875
+ degraded: false,
876
+ managed,
877
+ attached: !managed,
878
+ pid: discovery.pid,
879
+ url: discovery.url,
880
+ healthUrl: discovery.healthUrl,
881
+ runtimeVersion: discovery.runtimeVersion ?? null,
882
+ apiVersion: discovery.apiVersion ?? null,
883
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
884
+ error: publicError('home_mismatch', '已有 sidecar 使用不同的数据目录:拒绝接管'),
885
+ lock: this.lockView,
886
+ });
887
+ return false;
888
+ }
889
+ if (this.#profileMismatch(discovery)) {
890
+ this.#setState({
891
+ state: 'failed',
892
+ degraded: false,
893
+ managed,
894
+ attached: !managed,
895
+ pid: discovery.pid,
896
+ url: discovery.url,
897
+ healthUrl: discovery.healthUrl,
898
+ runtimeVersion: discovery.runtimeVersion ?? null,
899
+ apiVersion: discovery.apiVersion ?? null,
900
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
901
+ error: publicError('profile_mismatch', '已有 sidecar 属于其他 profile/忆云:拒绝接管'),
902
+ lock: this.lockView,
903
+ });
904
+ return false;
905
+ }
906
+ if (this.#versionMismatch(discovery)) {
907
+ this.#setState({
908
+ state: 'failed',
909
+ degraded: false,
910
+ managed,
911
+ attached: !managed,
912
+ pid: discovery.pid,
913
+ url: discovery.url,
914
+ healthUrl: discovery.healthUrl,
915
+ runtimeVersion: discovery.runtimeVersion ?? null,
916
+ apiVersion: discovery.apiVersion ?? null,
917
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
918
+ error: publicError('version_incompatible', 'sidecar 版本与 MCP capability 不兼容'),
919
+ lock: this.lockView,
920
+ });
921
+ return false;
922
+ }
923
+
924
+ if (!pidAlive(discovery.pid)) {
925
+ // 只读 status/inspect 绝不 unlink;身份校验先于 dead 判定与后续清理。
926
+ this.#setState({
927
+ state: 'stopped',
928
+ available: false,
929
+ degraded: false,
930
+ managed: false,
931
+ attached: false,
932
+ pid: discovery.pid,
933
+ url: null,
934
+ healthUrl: null,
935
+ discoveryMode: discovery.mode,
936
+ error: publicError('discovery_dead', 'sidecar discovery 对应进程已退出'),
937
+ lock: this.lockView,
938
+ });
939
+ return false;
940
+ }
941
+
942
+ if (!validDiscoveryUrls(discovery)) {
943
+ this.#setState({
944
+ state: 'failed', available: false, degraded: false, managed, attached: !managed,
945
+ pid: discovery.pid, url: null, healthUrl: null,
946
+ error: publicError('discovery_invalid', 'sidecar discovery URL 非法:拒绝连接或转发凭据'),
947
+ lock: this.lockView,
948
+ });
949
+ return false;
950
+ }
951
+ const age = this.now() - discovery.updatedAt;
952
+ if (!Number.isFinite(age) || age < -1000 || age > MEMORY_RUNTIME_DISCOVERY_DEAD_MS) {
953
+ this.#setState({
954
+ state: 'failed', available: false, degraded: false, managed, attached: !managed,
955
+ pid: discovery.pid, url: null, healthUrl: null,
956
+ error: publicError(age < -1000 ? 'discovery_future' : 'discovery_dead', 'sidecar discovery 已失效'),
957
+ lock: this.lockView,
958
+ });
959
+ return false;
960
+ }
961
+ if (age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) {
962
+ this.#setState({
963
+ state: 'degraded', available: false, degraded: true, managed, attached: !managed,
964
+ pid: discovery.pid, url: null, healthUrl: null,
965
+ error: publicError('discovery_stale', 'sidecar discovery 已超过 15 秒未刷新'),
966
+ lock: this.lockView,
967
+ });
968
+ return false;
969
+ }
970
+ if (discovery.mode === 'mcp') {
971
+ const dormantClean = discovery.state === 'stopped';
972
+ this.#setState({
973
+ state: dormantClean ? 'stopped' : 'degraded',
974
+ available: false,
975
+ degraded: !dormantClean,
976
+ managed,
977
+ attached: !managed,
978
+ pid: discovery.pid,
979
+ url: null,
980
+ healthUrl: null,
981
+ discoveryMode: 'mcp',
982
+ reason: 'disabled',
983
+ error: dormantClean
984
+ ? null
985
+ : publicError('disable_incomplete', 'sidecar 尚未完成 dormant 收尾'),
986
+ lock: this.lockView,
987
+ });
988
+ return false;
989
+ }
990
+
991
+ const health = fetchHealth ? await this.#fetchHealth(discovery) : { ok: true };
992
+ const healthBody = health.body ?? {};
993
+ const healthMismatch = health.ok && !this.#healthIdentityMatches(discovery, healthBody);
994
+ if (healthMismatch) {
995
+ this.#setState({
996
+ state: 'failed', available: false, degraded: false, managed, attached: !managed,
997
+ pid: discovery.pid, url: null, healthUrl: null,
998
+ error: publicError('instance_mismatch', 'sidecar health 与 discovery 实例身份不一致'),
999
+ lock: this.lockView,
1000
+ });
1001
+ return false;
1002
+ }
1003
+ if (health.ok) {
1004
+ this.readySeen = true;
1005
+ this.dormantLock = null;
1006
+ this.dormantLockInvalidated = false;
1007
+ await this.#clearDormantState();
1008
+ const degraded = discovery.degraded === true || health.degraded === true;
1009
+ this.#setState({
1010
+ state: degraded ? 'degraded' : 'ready',
1011
+ degraded,
1012
+ managed,
1013
+ attached: !managed,
1014
+ pid: discovery.pid,
1015
+ url: discovery.url,
1016
+ healthUrl: discovery.healthUrl,
1017
+ runtimeVersion: discovery.runtimeVersion ?? null,
1018
+ apiVersion: discovery.apiVersion ?? null,
1019
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
1020
+ startedAt: discovery.startedAt ?? null,
1021
+ discoveryMode: 'immersive',
1022
+ lastOkAt: this.now(),
1023
+ restarts: this.restarts,
1024
+ reason: null,
1025
+ error: degraded ? this.#degradedError() : null,
1026
+ lock: this.lockView,
1027
+ });
1028
+ return true;
1029
+ }
1030
+
1031
+ const starting = managed && !this.readySeen;
1032
+ this.#setState({
1033
+ state: starting ? 'starting' : 'degraded',
1034
+ available: false,
1035
+ degraded: !starting,
1036
+ managed,
1037
+ attached: !managed,
1038
+ pid: discovery.pid,
1039
+ url: discovery.url,
1040
+ healthUrl: discovery.healthUrl,
1041
+ runtimeVersion: discovery.runtimeVersion ?? null,
1042
+ apiVersion: discovery.apiVersion ?? null,
1043
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
1044
+ startedAt: discovery.startedAt ?? null,
1045
+ discoveryMode: discovery.mode,
1046
+ restarts: this.restarts,
1047
+ error: starting ? null : publicError('health_check_failed', 'sidecar 健康检查失败'),
1048
+ lock: this.lockView,
1049
+ });
1050
+ return false;
1051
+ }
1052
+
1053
+ async status() {
1054
+ if (!this.isEnabled() && !this.statusState.managed && !this.statusState.pid
1055
+ && this.statusState.error?.code !== 'disable_incomplete') {
1056
+ this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
1057
+ }
1058
+ try {
1059
+ await this.#refreshDiscovery({ fetchHealth: true });
1060
+ } catch {
1061
+ this.#setState({ error: publicError('status_failed', '无法读取 sidecar 状态') });
1062
+ }
1063
+ return this.snapshot();
1064
+ }
1065
+
1066
+ /**
1067
+ * 只读 sidecar `/status` 的最小视图:模式、版本、模型来源/降级。
1068
+ * 不返回 host token、keyRef、endpoint、模型路径或配置正文。
1069
+ */
1070
+ async readStatus() {
1071
+ const result = await this.#proxyHostApi('status');
1072
+ if (!result.available) {
1073
+ return {
1074
+ ok: !result.error,
1075
+ enabled: result.enabled,
1076
+ available: false,
1077
+ disabled: result.disabled === true,
1078
+ state: result.state,
1079
+ reason: result.reason ?? null,
1080
+ error: result.error ?? null,
1081
+ mode: this.statusState.discoveryMode ?? null,
1082
+ runtimeVersion: null,
1083
+ degraded: result.state === 'degraded',
1084
+ capability: null,
1085
+ model: null,
1086
+ };
1087
+ }
1088
+ const data = result.body?.data ?? result.body ?? {};
1089
+ const model = isObject(data.model)
1090
+ ? {
1091
+ configured: typeof data.model.configured === 'string' ? data.model.configured : null,
1092
+ active: typeof data.model.active === 'string' ? data.model.active : null,
1093
+ degraded: data.model.degraded === true,
1094
+ reason: typeof data.model.reason === 'string' ? data.model.reason : null,
1095
+ sources: Array.isArray(data.model.sources)
1096
+ ? data.model.sources.filter((source) => typeof source === 'string')
1097
+ : [],
1098
+ }
1099
+ : null;
1100
+ return {
1101
+ ok: result.ok !== false,
1102
+ enabled: true,
1103
+ available: true,
1104
+ disabled: false,
1105
+ state: result.state,
1106
+ reason: null,
1107
+ error: result.ok === false
1108
+ ? publicError(
1109
+ data?.error?.code ?? result.body?.error?.code ?? 'sidecar_request_failed',
1110
+ proxyErrorMessage(data, proxyErrorMessage(result.body, '读取记忆运行时状态失败')),
1111
+ )
1112
+ : null,
1113
+ mode: typeof data.mode === 'string' ? data.mode : null,
1114
+ runtimeVersion: typeof data.runtimeVersion === 'string' ? data.runtimeVersion : null,
1115
+ degraded: data.degraded === true || result.body?.degraded === true,
1116
+ capability: isObject(data.capability)
1117
+ ? {
1118
+ reachable: data.capability.reachable === true,
1119
+ version: Number.isInteger(data.capability.version) ? data.capability.version : null,
1120
+ lastOkAt: typeof data.capability.lastOkAt === 'number' ? data.capability.lastOkAt : null,
1121
+ error: typeof data.capability.error === 'string' ? data.capability.error : null,
1122
+ }
1123
+ : null,
1124
+ model,
1125
+ };
1126
+ }
1127
+
1128
+ /**
1129
+ * 统一 host API 代理:服务端读取 host token,调用方只拿到脱敏数据。
1130
+ *
1131
+ * 返回扁平结果,不抛异常:
1132
+ * { ok, status, enabled, available, disabled, state, data, warnings, degraded, error }
1133
+ * 轻量模式 → memory_runtime_disabled;未就绪 → memory_runtime_unavailable。
1134
+ */
1135
+ async request(path, { method = 'GET', body = null, timeoutMs = 5000 } = {}) {
1136
+ const relative = typeof path === 'string' ? path.replace(/^\/+/, '') : '';
1137
+ if (relative.length === 0 || relative.includes('..') || relative.includes('\\')) {
1138
+ return {
1139
+ ok: false,
1140
+ status: 400,
1141
+ enabled: this.isEnabled(),
1142
+ available: false,
1143
+ disabled: false,
1144
+ state: this.statusState.state,
1145
+ data: null,
1146
+ warnings: [],
1147
+ degraded: false,
1148
+ error: { code: 'invalid_request', message: 'sidecar 请求路径非法', retryable: false },
1149
+ };
1150
+ }
1151
+ const result = await this.#proxyHostApi(relative, {
1152
+ method: String(method).toUpperCase(),
1153
+ body,
1154
+ timeoutMs,
1155
+ });
1156
+ if (!result.available) {
1157
+ const disabled = result.disabled === true;
1158
+ return {
1159
+ ok: false,
1160
+ status: disabled ? 409 : 503,
1161
+ enabled: result.enabled === true,
1162
+ available: false,
1163
+ disabled,
1164
+ state: result.state,
1165
+ data: null,
1166
+ warnings: [],
1167
+ degraded: result.state === 'degraded',
1168
+ error: {
1169
+ code: disabled ? 'memory_runtime_disabled' : 'memory_runtime_unavailable',
1170
+ message: disabled ? '记忆运行时未启用' : 'Memory Runtime sidecar 未就绪',
1171
+ retryable: !disabled,
1172
+ ...(result.reason ? { reason: result.reason } : {}),
1173
+ },
1174
+ };
1175
+ }
1176
+ if (!result.ok) {
1177
+ const envelope = isObject(result.body) ? result.body : {};
1178
+ const rawError = isObject(envelope.error) ? envelope.error : {};
1179
+ const code = typeof rawError.code === 'string'
1180
+ ? rawError.code
1181
+ : typeof envelope.error === 'string' ? envelope.error : 'sidecar_request_failed';
1182
+ const statusCode = Number.isInteger(result.statusCode) ? result.statusCode : 502;
1183
+ return {
1184
+ ok: false,
1185
+ status: statusCode >= 400 && statusCode < 500 ? statusCode : 502,
1186
+ enabled: true,
1187
+ available: true,
1188
+ disabled: false,
1189
+ state: result.state,
1190
+ data: null,
1191
+ warnings: Array.isArray(envelope.warnings) ? envelope.warnings : [],
1192
+ degraded: envelope.degraded === true || result.state === 'degraded',
1193
+ error: {
1194
+ code,
1195
+ message: proxyErrorMessage(envelope, 'sidecar 请求失败'),
1196
+ retryable: rawError.retryable === true,
1197
+ ...(isObject(rawError.details) ? { details: rawError.details } : {}),
1198
+ },
1199
+ };
1200
+ }
1201
+ const envelope = isObject(result.body) ? result.body : {};
1202
+ const data = envelope.data ?? result.body ?? null;
1203
+ return {
1204
+ ok: true,
1205
+ status: Number.isInteger(result.statusCode) ? result.statusCode : 200,
1206
+ enabled: true,
1207
+ available: true,
1208
+ disabled: false,
1209
+ state: result.state,
1210
+ data,
1211
+ warnings: Array.isArray(envelope.warnings) ? envelope.warnings : [],
1212
+ degraded: envelope.degraded === true || result.state === 'degraded',
1213
+ error: null,
1214
+ };
1215
+ }
1216
+
1217
+ async listModels() {
1218
+ return this.request('models');
1219
+ }
1220
+
1221
+ async modelStatus(packId) {
1222
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/status`);
1223
+ }
1224
+
1225
+ async installModel(packId, { force = false } = {}) {
1226
+ const suffix = force === true ? '?force=true' : '';
1227
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/install${suffix}`, {
1228
+ method: 'POST',
1229
+ timeoutMs: 10_000,
1230
+ });
1231
+ }
1232
+
1233
+ async getInstall(jobId) {
1234
+ return this.request(`installs/${encodeURIComponent(String(jobId ?? ''))}`);
1235
+ }
1236
+
1237
+ async cancelInstall(jobId) {
1238
+ return this.request(`installs/${encodeURIComponent(String(jobId ?? ''))}/cancel`, {
1239
+ method: 'POST',
1240
+ });
1241
+ }
1242
+
1243
+ async activateModel(packId) {
1244
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/activate`, {
1245
+ method: 'POST',
1246
+ timeoutMs: 30_000,
1247
+ });
1248
+ }
1249
+
1250
+ async deactivateModel(packId) {
1251
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/deactivate`, {
1252
+ method: 'POST',
1253
+ timeoutMs: 15_000,
1254
+ });
1255
+ }
1256
+
1257
+ async startEngine(packId) {
1258
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/start`, {
1259
+ method: 'POST',
1260
+ timeoutMs: 30_000,
1261
+ });
1262
+ }
1263
+
1264
+ async stopEngine(packId) {
1265
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/stop`, {
1266
+ method: 'POST',
1267
+ timeoutMs: 15_000,
1268
+ });
1269
+ }
1270
+
1271
+ async removeModel(packId) {
1272
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/remove`, {
1273
+ method: 'POST',
1274
+ timeoutMs: 15_000,
1275
+ });
1276
+ }
1277
+
1278
+ async inferenceStatus() {
1279
+ return this.request('inference');
1280
+ }
1281
+
1282
+ async updateInferenceSettings(input) {
1283
+ return this.request('inference/settings', {
1284
+ method: 'POST',
1285
+ body: isObject(input) ? input : {},
1286
+ });
1287
+ }
1288
+
1289
+ /**
1290
+ * Console 只读代理:服务端读取 host token,浏览器只拿到脱敏后的 sidecar 视图。
1291
+ * 轻量模式/未就绪时返回明确状态,不启动进程、不创建 token。
1292
+ */
1293
+ async readTraces({ limit = 20 } = {}) {
1294
+ const requested = Number(limit);
1295
+ const safeLimit = Number.isFinite(requested) ? Math.min(Math.max(Math.trunc(requested), 1), 100) : 20;
1296
+ const result = await this.#proxyHostApi(`traces?limit=${safeLimit}`);
1297
+ if (!result.available) {
1298
+ return {
1299
+ ok: !result.error,
1300
+ enabled: result.enabled,
1301
+ available: false,
1302
+ disabled: result.disabled === true,
1303
+ state: result.state,
1304
+ reason: result.reason ?? null,
1305
+ error: result.error ?? null,
1306
+ traces: [],
1307
+ total: 0,
1308
+ degraded: result.state === 'degraded',
1309
+ warnings: [],
1310
+ };
1311
+ }
1312
+ const data = result.body?.data ?? result.body ?? {};
1313
+ const traces = Array.isArray(data.traces) ? data.traces.slice(0, safeLimit).map(traceSummaryView) : [];
1314
+ if (!result.ok) {
1315
+ return {
1316
+ ok: false,
1317
+ enabled: true,
1318
+ available: true,
1319
+ disabled: false,
1320
+ state: result.state,
1321
+ error: publicError(
1322
+ data?.error?.code ?? result.body?.error?.code ?? 'sidecar_request_failed',
1323
+ proxyErrorMessage(data, proxyErrorMessage(result.body, '读取召回轨迹失败')),
1324
+ ),
1325
+ traces: [],
1326
+ total: 0,
1327
+ degraded: true,
1328
+ warnings: [],
1329
+ };
1330
+ }
1331
+ return {
1332
+ ok: true,
1333
+ enabled: true,
1334
+ available: true,
1335
+ disabled: false,
1336
+ state: result.state,
1337
+ degraded: data.degraded === true || result.body?.degraded === true,
1338
+ traces,
1339
+ total: Number.isInteger(data.total) ? data.total : traces.length,
1340
+ warnings: Array.isArray(result.body?.warnings) ? result.body.warnings : [],
1341
+ };
1342
+ }
1343
+
1344
+ async readTrace(id) {
1345
+ const traceId = typeof id === 'string' ? id.trim() : '';
1346
+ if (!/^tr_[A-Za-z0-9._:-]{1,128}$/.test(traceId)) {
1347
+ return {
1348
+ ok: false,
1349
+ enabled: this.isEnabled(),
1350
+ available: false,
1351
+ disabled: !this.isEnabled(),
1352
+ state: this.statusState.state,
1353
+ trace: null,
1354
+ error: publicError('invalid_trace_id', 'trace id 格式非法'),
1355
+ };
1356
+ }
1357
+ const result = await this.#proxyHostApi(`traces/${encodeURIComponent(traceId)}`);
1358
+ if (!result.available) {
1359
+ return {
1360
+ ok: !result.error,
1361
+ enabled: result.enabled,
1362
+ available: false,
1363
+ disabled: result.disabled === true,
1364
+ state: result.state,
1365
+ reason: result.reason ?? null,
1366
+ error: result.error ?? null,
1367
+ trace: null,
1368
+ };
1369
+ }
1370
+ const data = result.body?.data ?? result.body ?? null;
1371
+ if (!result.ok || !data) {
1372
+ return {
1373
+ ok: false,
1374
+ enabled: true,
1375
+ available: true,
1376
+ disabled: false,
1377
+ state: result.state,
1378
+ trace: null,
1379
+ error: publicError(
1380
+ data?.error?.code ?? result.body?.error?.code ?? (result.statusCode === 404 ? 'trace_not_found' : 'sidecar_request_failed'),
1381
+ proxyErrorMessage(data, proxyErrorMessage(result.body, '读取召回轨迹详情失败')),
1382
+ ),
1383
+ };
1384
+ }
1385
+ return {
1386
+ ok: true,
1387
+ enabled: true,
1388
+ available: true,
1389
+ disabled: false,
1390
+ state: result.state,
1391
+ trace: traceDetailView(data),
1392
+ degraded: result.body?.degraded === true,
1393
+ };
1394
+ }
1395
+
1396
+ async submitRecallFeedback(traceId, feedback) {
1397
+ const id = typeof traceId === 'string' ? traceId.trim() : '';
1398
+ if (!/^tr_[A-Za-z0-9._:-]{1,128}$/.test(id)) {
1399
+ return { statusCode: 400, body: { ok: false, error: 'invalid_trace_id', message: 'trace id 格式非法' } };
1400
+ }
1401
+ if (!isObject(feedback) || typeof feedback.useful !== 'boolean') {
1402
+ return { statusCode: 400, body: { ok: false, error: 'invalid_feedback', message: 'feedback.useful 必须是布尔值' } };
1403
+ }
1404
+ const body = {
1405
+ useful: feedback.useful,
1406
+ ...(typeof feedback.reason === 'string' && feedback.reason.length > 0
1407
+ ? { reason: feedback.reason.slice(0, 200) }
1408
+ : {}),
1409
+ };
1410
+ const result = await this.#proxyHostApi(`recall/${encodeURIComponent(id)}/feedback`, { method: 'POST', body });
1411
+ if (!result.available) {
1412
+ return {
1413
+ statusCode: result.disabled === true ? 409 : 503,
1414
+ body: {
1415
+ ok: false,
1416
+ error: result.disabled === true ? 'memory_runtime_disabled' : 'sidecar_unavailable',
1417
+ enabled: result.enabled,
1418
+ state: result.state,
1419
+ message: result.disabled === true
1420
+ ? '记忆运行时未启用'
1421
+ : 'Memory Runtime sidecar 未就绪',
1422
+ ...(result.error ? { details: result.error } : {}),
1423
+ },
1424
+ };
1425
+ }
1426
+ const data = result.body?.data ?? result.body ?? null;
1427
+ if (!result.ok) {
1428
+ return {
1429
+ statusCode: result.statusCode ?? 502,
1430
+ body: {
1431
+ ok: false,
1432
+ error: data?.error?.code ?? result.body?.error?.code ?? 'feedback_failed',
1433
+ message: proxyErrorMessage(data, proxyErrorMessage(result.body, '召回反馈失败')),
1434
+ },
1435
+ };
1436
+ }
1437
+ return { statusCode: 200, body: result.body ?? { ok: true, data } };
1438
+ }
1439
+
1440
+ async #resolveHostToken(discovery) {
1441
+ const fromEnv = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN);
1442
+ if (fromEnv) return { token: fromEnv, source: 'override', refreshable: false };
1443
+ if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return null;
1444
+ // 只读当前 home 的生产 JSON token;raw 文件不是隐式生产回退格式。
1445
+ if (resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir) return null;
1446
+ try {
1447
+ if (process.platform !== 'win32' && ((await stat(discovery.tokenFile)).mode & 0o077) !== 0) return null;
1448
+ const record = JSON.parse(await readFile(discovery.tokenFile, 'utf-8'));
1449
+ if (record?.version !== 1 || typeof record?.token !== 'string' || record.token.length === 0) return null;
1450
+ if (typeof record.expiresAt === 'number' && record.expiresAt > 0 && this.now() >= record.expiresAt) return null;
1451
+ return { token: record.token, source: 'file', refreshable: true };
1452
+ } catch {
1453
+ // 显式测试/嵌入在文件尚未可见时仍可使用本子进程持有的凭据。
1454
+ if (this.child && discovery?.pid === this.child.pid && typeof this.childToken === 'string') {
1455
+ return { token: this.childToken, source: 'child', refreshable: true };
1456
+ }
1457
+ return null;
1458
+ }
1459
+ }
1460
+
1461
+ async #removeDiscoveryIfMatches(expected) {
1462
+ if (!expected || this.#homeMismatch(expected) || this.#profileMismatch(expected)) return false;
1463
+ const current = await readDiscovery(this.paths.discoveryPath);
1464
+ if (!sameDiscoveryInstance(current, expected)) return false;
1465
+ // 删除前再读一次,缩窄操作者重启/替换实例时的竞态窗口。
1466
+ const confirmed = await readDiscovery(this.paths.discoveryPath);
1467
+ if (!sameDiscoveryInstance(confirmed, expected)) return false;
1468
+ await unlink(this.paths.discoveryPath);
1469
+ return true;
1470
+ }
1471
+
1472
+ async #readSidecarMode(discovery) {
1473
+ const age = this.now() - discovery.updatedAt;
1474
+ if (!validDiscoveryUrls(discovery) || this.#homeMismatch(discovery)
1475
+ || this.#profileMismatch(discovery) || this.#versionMismatch(discovery)
1476
+ || !Number.isFinite(age) || age < -1000 || age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) {
1477
+ return null;
1478
+ }
1479
+ const health = await this.#fetchHealth(discovery, { acceptDormant: true });
1480
+ if (!this.#healthIdentityMatches(discovery, health.body, { allowDormant: true })) return null;
1481
+ const credential = await this.#resolveHostToken(discovery);
1482
+ if (!credential || !this.fetchImpl) return null;
1483
+ const controller = new AbortController();
1484
+ const timer = setTimeout(() => controller.abort(), Math.max(1, this.healthTimeoutMs));
1485
+ timer.unref?.();
1486
+ try {
1487
+ const response = await this.fetchImpl(`${discovery.url.replace(/\/+$/, '')}/status`, {
1488
+ method: 'GET',
1489
+ headers: { accept: 'application/json', authorization: `Bearer ${credential.token}` },
1490
+ signal: controller.signal,
1491
+ });
1492
+ if (!response?.ok) return null;
1493
+ const body = await response.json().catch(() => null);
1494
+ const data = body?.data;
1495
+ if (data?.pid !== discovery.pid) return null;
1496
+ if (typeof data.startedAt === 'number' && data.startedAt !== discovery.startedAt) return null;
1497
+ const mode = data?.mode;
1498
+ const state = data?.state;
1499
+ if ((mode !== 'mcp' && mode !== 'immersive') || typeof state !== 'string') return null;
1500
+ return { mode, state };
1501
+ } catch {
1502
+ return null;
1503
+ } finally {
1504
+ clearTimeout(timer);
1505
+ }
1506
+ }
1507
+
1508
+ async #waitAttachedDormant(discovery, timeoutMs) {
1509
+ // 陈旧/非法 discovery 无法证明实例身份:不发送 HTTP,立即报告 incomplete。
1510
+ const age = this.now() - discovery.updatedAt;
1511
+ if (!validDiscoveryUrls(discovery)
1512
+ || this.#homeMismatch(discovery)
1513
+ || this.#profileMismatch(discovery)
1514
+ || this.#versionMismatch(discovery)
1515
+ || !Number.isFinite(age)
1516
+ || age < -1000
1517
+ || age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) {
1518
+ return false;
1519
+ }
1520
+ const deadline = Date.now() + Math.max(0, timeoutMs);
1521
+ for (;;) {
1522
+ if (!pidAlive(discovery.pid)) return true;
1523
+ const observed = await this.#readSidecarMode(discovery);
1524
+ if (observed?.mode === 'mcp' && observed.state === 'stopped') return true;
1525
+ if (Date.now() >= deadline) return false;
1526
+ await sleep(Math.min(50, Math.max(1, deadline - Date.now())));
1527
+ }
1528
+ }
1529
+
1530
+ /**
1531
+ * 显式 stop 前的实例校验:与 attach 使用同一套 freshness/URL/home/profile/version、
1532
+ * health 身份和 token 鉴权的 /status 校验;任何一项无法确认都不得发送信号。
1533
+ */
1534
+ async #verifyLiveInstance(discovery, { requireDiscovery = true } = {}) {
1535
+ if (!discovery || !Number.isInteger(discovery.pid) || !pidAlive(discovery.pid)) return false;
1536
+ if (this.#homeMismatch(discovery) || this.#profileMismatch(discovery) || this.#versionMismatch(discovery)) {
1537
+ return false;
1538
+ }
1539
+ if (!validDiscoveryUrls(discovery)) return false;
1540
+ const age = this.now() - discovery.updatedAt;
1541
+ if (!Number.isFinite(age) || age < -1000 || age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) return false;
1542
+ const health = await this.#fetchHealth(discovery, { acceptDormant: true });
1543
+ if (!health.ok || !this.#healthIdentityMatches(discovery, health.body, { allowDormant: true })) {
1544
+ return false;
1545
+ }
1546
+ // 需要 host token 的 /status:确认 pid(以及新实例提供的 startedAt)仍属于同一实例。
1547
+ const observed = await this.#readSidecarMode(discovery);
1548
+ if (!observed) return false;
1549
+ if (health.body?.ready === false
1550
+ && !(observed.mode === 'mcp' && observed.state === 'stopped')) {
1551
+ return false;
1552
+ }
1553
+ if (!requireDiscovery) return true;
1554
+ // 探测期间实例可能被替换;确认 discovery 仍是同一 pid/startedAt/url/tokenFile。
1555
+ return sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), discovery);
1556
+ }
1557
+
1558
+ async #proxyHostApi(pathname, { method = 'GET', body = null, timeoutMs = 2500 } = {}) {
1559
+ await this.status().catch(() => undefined);
1560
+ if (!this.isEnabled()) {
1561
+ return {
1562
+ enabled: false, available: false, disabled: true, state: 'stopped', reason: 'disabled', error: null,
1563
+ };
1564
+ }
1565
+ if (!this.statusState.available || !['ready', 'degraded'].includes(this.statusState.state)
1566
+ || typeof this.statusState.url !== 'string') {
1567
+ return {
1568
+ enabled: true,
1569
+ available: false,
1570
+ disabled: false,
1571
+ state: this.statusState.state,
1572
+ reason: this.statusState.reason ?? null,
1573
+ error: this.statusState.error ?? publicError('sidecar_unavailable', 'Memory Runtime sidecar 未就绪'),
1574
+ };
1575
+ }
1576
+ const validatedDiscovery = (candidate) => {
1577
+ const age = candidate ? this.now() - candidate.updatedAt : Number.POSITIVE_INFINITY;
1578
+ return candidate
1579
+ && candidate.pid === this.statusState.pid
1580
+ && candidate.startedAt === this.statusState.startedAt
1581
+ && candidate.url === this.statusState.url
1582
+ && candidate.mode === 'immersive'
1583
+ && age >= -1000 && age <= MEMORY_RUNTIME_DISCOVERY_STALE_MS
1584
+ && validDiscoveryUrls(candidate)
1585
+ && !this.#homeMismatch(candidate)
1586
+ && !this.#profileMismatch(candidate)
1587
+ && !this.#versionMismatch(candidate);
1588
+ };
1589
+ const discovery = await readDiscovery(this.paths.discoveryPath);
1590
+ if (!validatedDiscovery(discovery)) {
1591
+ return {
1592
+ enabled: true,
1593
+ available: false,
1594
+ disabled: false,
1595
+ state: this.statusState.state,
1596
+ reason: null,
1597
+ error: publicError(discovery ? 'instance_mismatch' : 'discovery_missing', 'sidecar discovery 已变化或失效'),
1598
+ };
1599
+ }
1600
+ if (!this.fetchImpl) {
1601
+ return {
1602
+ enabled: true, available: false, disabled: false, state: this.statusState.state, reason: null,
1603
+ error: publicError('fetch_unavailable', '当前运行环境不支持 HTTP 代理'),
1604
+ };
1605
+ }
1606
+
1607
+ const requestId = `proxy_${randomBytes(16).toString('hex')}`;
1608
+ const attemptedSecrets = new Set();
1609
+ const execute = async (instance, token) => {
1610
+ attemptedSecrets.add(token);
1611
+ const controller = new AbortController();
1612
+ const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs));
1613
+ timer.unref?.();
1614
+ try {
1615
+ const base = instance.url.replace(/\/+$/, '');
1616
+ const url = new URL(`${base}/${String(pathname).replace(/^\/+/, '')}`);
1617
+ const headers = {
1618
+ accept: 'application/json',
1619
+ authorization: `Bearer ${token}`,
1620
+ 'x-request-id': requestId,
1621
+ };
1622
+ const init = { method, headers, signal: controller.signal };
1623
+ if (body !== null && body !== undefined) {
1624
+ headers['content-type'] = 'application/json';
1625
+ init.body = JSON.stringify(body);
1626
+ }
1627
+ const response = await this.fetchImpl(url.toString(), init);
1628
+ const text = await response.text().catch(() => '');
1629
+ let parsed = null;
1630
+ try {
1631
+ parsed = text.length > 0 ? JSON.parse(text) : null;
1632
+ } catch {
1633
+ parsed = null;
1634
+ }
1635
+ return { response, text, parsed };
1636
+ } catch (error) {
1637
+ return { transportError: error };
1638
+ } finally {
1639
+ clearTimeout(timer);
1640
+ }
1641
+ };
1642
+
1643
+ let credential = await this.#resolveHostToken(discovery);
1644
+ if (!credential) {
1645
+ return {
1646
+ enabled: true, available: false, disabled: false, state: this.statusState.state, reason: null,
1647
+ error: publicError('host_token_missing', '无法读取 sidecar host token'),
1648
+ };
1649
+ }
1650
+ let attemptedDiscovery = discovery;
1651
+ let attempt = await execute(attemptedDiscovery, credential.token);
1652
+ if (attempt.response?.status === 401 && credential.refreshable) {
1653
+ // 操作者可能已在 401 前后重启 sidecar;新实例也必须重新通过完整校验。
1654
+ await this.status().catch(() => undefined);
1655
+ const current = await readDiscovery(this.paths.discoveryPath);
1656
+ if (validatedDiscovery(current)) {
1657
+ const refreshed = await this.#resolveHostToken(current);
1658
+ if (refreshed?.refreshable) {
1659
+ attemptedDiscovery = current;
1660
+ credential = refreshed;
1661
+ attempt = await execute(attemptedDiscovery, credential.token);
1662
+ }
1663
+ }
1664
+ }
1665
+ if (attempt.transportError) {
1666
+ const error = attempt.transportError;
1667
+ return {
1668
+ enabled: true,
1669
+ available: false,
1670
+ disabled: false,
1671
+ state: this.statusState.state,
1672
+ reason: null,
1673
+ error: publicError(
1674
+ error?.name === 'AbortError' ? 'sidecar_timeout' : 'sidecar_unreachable',
1675
+ error?.name === 'AbortError' ? 'sidecar 请求超时' : '无法连接 Memory Runtime sidecar',
1676
+ ),
1677
+ };
1678
+ }
1679
+ const secrets = [...attemptedSecrets, this.childToken];
1680
+ return {
1681
+ enabled: true,
1682
+ available: true,
1683
+ disabled: false,
1684
+ state: this.statusState.state,
1685
+ statusCode: attempt.response.status,
1686
+ ok: attempt.response.ok === true,
1687
+ body: scrubProxyValue(attempt.parsed, secrets),
1688
+ ...(attempt.parsed === null && attempt.text.length > 0
1689
+ ? { message: redact(attempt.text, secrets) }
1690
+ : {}),
1691
+ };
1692
+ }
1693
+
1694
+ #resolveCommand() {
1695
+ if (this.explicitCommand) {
1696
+ const command = resolve(this.explicitCommand);
1697
+ this.installed = executableExists(command);
1698
+ this.commandSource = 'explicit';
1699
+ return this.installed
1700
+ ? { ok: true, command, source: 'explicit' }
1701
+ : { ok: false, command, source: 'explicit', reason: 'not_installed' };
1702
+ }
1703
+ const resolved = resolveMemoryRuntimeCommand({ config: this.getConfig(), env: this.env });
1704
+ this.installed = resolved.ok === true;
1705
+ this.commandSource = resolved.source;
1706
+ return resolved;
1707
+ }
1708
+
1709
+ async #resolveCapabilityToken() {
1710
+ if (typeof this.getCapabilityToken === 'function') {
1711
+ try {
1712
+ const value = await this.getCapabilityToken();
1713
+ const token = typeof value === 'string' ? value : value?.token;
1714
+ if (typeof token === 'string' && token.length > 0) return token;
1715
+ } catch {
1716
+ // fall through to env/file
1717
+ }
1718
+ }
1719
+ const fromEnv = stringOrNull(this.env?.MEBULAR_CAPABILITY_TOKEN);
1720
+ if (fromEnv) return fromEnv;
1721
+ const record = await readJson(this.paths.capabilityTokenPath, null);
1722
+ if (record?.version !== 1 || typeof record?.token !== 'string' || record.token.length === 0) return null;
1723
+ if (typeof record.expiresAt === 'number' && record.expiresAt > 0 && this.now() >= record.expiresAt) return null;
1724
+ return record.token;
1725
+ }
1726
+
1727
+ async #waitForDiscovery(deadline) {
1728
+ for (;;) {
1729
+ if (this.stopping || this.disposed) return false;
1730
+ const ready = await this.#refreshDiscovery({ fetchHealth: true });
1731
+ if (ready) return true;
1732
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1733
+ return false;
1734
+ }
1735
+ const lock = await readLock(this.paths.lockPath);
1736
+ if (!lock || !pidAlive(lock.pid)) {
1737
+ this.lockView = null;
1738
+ return false;
1739
+ }
1740
+ if (this.now() >= deadline) return false;
1741
+ await sleep(Math.min(this.healthPollMs, Math.max(1, deadline - this.now())));
1742
+ }
1743
+ }
1744
+
1745
+ async #waitForReady(deadline, child) {
1746
+ while (this.child === child && child.exitCode === null) {
1747
+ if (this.stopping || this.disposed) return false;
1748
+ const ready = await this.#refreshDiscovery({ fetchHealth: true });
1749
+ if (ready && this.statusState.pid === child.pid) return true;
1750
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1751
+ return false;
1752
+ }
1753
+ if (this.now() >= deadline) return false;
1754
+ await sleep(Math.min(this.healthPollMs, Math.max(1, deadline - this.now())));
1755
+ }
1756
+ return false;
1757
+ }
1758
+
1759
+ #clearRestartTimer() {
1760
+ if (this.restartTimer) {
1761
+ clearTimeout(this.restartTimer);
1762
+ this.restartTimer = null;
1763
+ }
1764
+ }
1765
+
1766
+ #clearCooldownTimer() {
1767
+ if (this.cooldownTimer) {
1768
+ clearTimeout(this.cooldownTimer);
1769
+ this.cooldownTimer = null;
1770
+ }
1771
+ }
1772
+
1773
+ #stopWatchdog() {
1774
+ if (this.watchdogTimer) {
1775
+ clearInterval(this.watchdogTimer);
1776
+ this.watchdogTimer = null;
1777
+ }
1778
+ }
1779
+
1780
+ #startWatchdog() {
1781
+ this.#stopWatchdog();
1782
+ if (!this.healthCheckIntervalMs || this.healthCheckIntervalMs <= 0) return;
1783
+ this.watchdogTimer = setInterval(() => {
1784
+ if (this.disposed || this.stopping) return;
1785
+ void (async () => {
1786
+ const healthy = await this.#refreshDiscovery({ fetchHealth: true });
1787
+ if (healthy) {
1788
+ this.healthFailures = 0;
1789
+ return;
1790
+ }
1791
+ if (this.statusState.error?.code !== 'health_check_failed') return;
1792
+ this.healthFailures += 1;
1793
+ if (this.healthFailures < 3) return;
1794
+ this.healthFailures = 0;
1795
+ if (this.child && this.child.exitCode === null) {
1796
+ this.#setState({ error: publicError('health_check_failed', 'sidecar 连续健康检查失败') });
1797
+ this.#killChild('SIGTERM');
1798
+ } else {
1799
+ this.#setState({
1800
+ state: 'degraded',
1801
+ degraded: true,
1802
+ error: publicError('health_check_failed', 'sidecar 连续健康检查失败'),
1803
+ });
1804
+ }
1805
+ })().catch(() => undefined);
1806
+ }, this.healthCheckIntervalMs);
1807
+ this.watchdogTimer.unref?.();
1808
+ }
1809
+
1810
+ #pruneCrashTimes() {
1811
+ const cutoff = this.now() - this.restartWindowMs;
1812
+ this.crashTimes = this.crashTimes.filter((at) => at >= cutoff);
1813
+ }
1814
+
1815
+ #scheduleRestart() {
1816
+ this.#clearRestartTimer();
1817
+ if (this.disposed || this.stopping || this.manualStart) return;
1818
+ if (!this.restartOnFailure || this.maxRestartsInWindow <= 0) return;
1819
+ if (!this.isEnabled()) return;
1820
+ this.#pruneCrashTimes();
1821
+ if (this.crashTimes.length > this.maxRestartsInWindow) {
1822
+ this.#setState({
1823
+ state: 'failed',
1824
+ degraded: false,
1825
+ error: publicError('restart_limit', 'sidecar 崩溃次数超过上限:已暂停自动重启'),
1826
+ });
1827
+ this.#clearCooldownTimer();
1828
+ this.cooldownTimer = setTimeout(() => {
1829
+ this.crashTimes = [];
1830
+ this.restarts = 0;
1831
+ this.#clearCooldownTimer();
1832
+ }, Math.max(1000, this.restartCooldownMs));
1833
+ this.cooldownTimer.unref?.();
1834
+ return;
1835
+ }
1836
+ const exponent = Math.max(0, this.crashTimes.length - 1);
1837
+ const delay = Math.min(this.restartBackoffMs * (2 ** exponent), this.restartBackoffMaxMs);
1838
+ this.restartTimer = setTimeout(() => {
1839
+ this.restartTimer = null;
1840
+ if (this.disposed || this.stopping || !this.isEnabled()) return;
1841
+ void this.#startOnce({ force: false, isRestart: true }).catch(() => undefined);
1842
+ }, Math.max(10, delay));
1843
+ this.restartTimer.unref?.();
1844
+ }
1845
+
1846
+ #killChild(signal) {
1847
+ const child = this.child;
1848
+ if (!child || child.exitCode !== null) return false;
1849
+ try {
1850
+ child.kill(signal);
1851
+ return true;
1852
+ } catch {
1853
+ return false;
1854
+ }
1855
+ }
1856
+
1857
+ async #waitChildExit(child, timeoutMs) {
1858
+ if (!child || child.exitCode !== null) return true;
1859
+ return new Promise((resolvePromise) => {
1860
+ let done = false;
1861
+ const finish = () => {
1862
+ if (done) return;
1863
+ done = true;
1864
+ clearTimeout(timer);
1865
+ child.removeListener?.('exit', finish);
1866
+ resolvePromise(child.exitCode !== null);
1867
+ };
1868
+ const timer = setTimeout(finish, Math.max(0, timeoutMs));
1869
+ timer.unref?.();
1870
+ child.once?.('exit', finish);
1871
+ if (child.exitCode !== null) finish();
1872
+ });
1873
+ }
1874
+
1875
+ #onChildExit(child, code, signal) {
1876
+ if (this.child !== child) return;
1877
+ this.child = null;
1878
+ this.#stopWatchdog();
1879
+ if (this.stopping || this.disposed) {
1880
+ this.#setState({
1881
+ state: 'stopped',
1882
+ degraded: false,
1883
+ managed: false,
1884
+ attached: false,
1885
+ pid: null,
1886
+ url: null,
1887
+ healthUrl: null,
1888
+ error: null,
1889
+ lock: this.lockView,
1890
+ });
1891
+ return;
1892
+ }
1893
+
1894
+ this.restarts += 1;
1895
+ this.crashTimes.push(this.now());
1896
+ this.#setState({
1897
+ state: 'failed',
1898
+ degraded: false,
1899
+ managed: false,
1900
+ attached: false,
1901
+ pid: null,
1902
+ url: null,
1903
+ healthUrl: null,
1904
+ restarts: this.restarts,
1905
+ error: publicError(
1906
+ 'sidecar_crashed',
1907
+ `sidecar 已退出(${signal ?? code ?? 'unknown'})`,
1908
+ ),
1909
+ lock: this.lockView,
1910
+ });
1911
+ appendMemoryRuntimeLogSync(this.paths.dataDir, {
1912
+ level: 'error',
1913
+ event: 'supervisor_restart',
1914
+ reason: 'child_exit',
1915
+ code: 'sidecar_crashed',
1916
+ exitCode: typeof code === 'number' ? code : null,
1917
+ signal: typeof signal === 'string' ? signal : null,
1918
+ restarts: this.restarts,
1919
+ }, { now: this.now });
1920
+ this.#scheduleRestart();
1921
+ }
1922
+
1923
+ async #spawnSidecar({ manual }) {
1924
+ const resolved = this.#resolveCommand();
1925
+ if (!resolved.ok) {
1926
+ this.#setState({
1927
+ state: 'not_installed',
1928
+ degraded: false,
1929
+ installed: false,
1930
+ commandSource: resolved.source,
1931
+ error: publicError(resolved.reason ?? 'not_installed', '未找到 mebular-memory-runtime 可执行文件'),
1932
+ });
1933
+ return false;
1934
+ }
1935
+
1936
+ if (this.stopping || this.disposed) return false;
1937
+ const token = await this.#resolveCapabilityToken();
1938
+ if (this.stopping || this.disposed) return false;
1939
+ if (!token) {
1940
+ this.#setState({
1941
+ state: 'failed',
1942
+ degraded: false,
1943
+ installed: true,
1944
+ commandSource: resolved.source,
1945
+ error: publicError('capability_token_missing', '找不到 capability token:MCP 未启用或未启动 sidecar'),
1946
+ });
1947
+ return false;
1948
+ }
1949
+
1950
+ const hostToken = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN)
1951
+ ?? randomBytes(32).toString('base64url');
1952
+ this.childSecrets = [token, hostToken];
1953
+ const spec = commandSpec(resolved.command);
1954
+ const args = [
1955
+ ...spec.args,
1956
+ 'serve',
1957
+ ...(manual ? [] : ['--parent-pid', String(process.pid)]),
1958
+ ];
1959
+ const env = {
1960
+ ...process.env,
1961
+ ...this.env,
1962
+ MEBULAR_HOME: this.paths.home,
1963
+ MEBULAR_MEMORY_RUNTIME_HOME: this.paths.dataDir,
1964
+ MEBULAR_CAPABILITY_TOKEN: token,
1965
+ MEBULAR_MEMORY_RUNTIME_TOKEN: hostToken,
1966
+ ...(stringOrNull(this.getMcpUrl()) ? { MEBULAR_MCP_URL: stringOrNull(this.getMcpUrl()) } : {}),
1967
+ };
1968
+
1969
+ let child;
1970
+ try {
1971
+ child = this.spawnImpl(spec.execPath, args, {
1972
+ cwd: this.paths.home,
1973
+ env,
1974
+ detached: manual,
1975
+ windowsHide: true,
1976
+ stdio: manual ? 'ignore' : ['ignore', 'ignore', 'pipe'],
1977
+ });
1978
+ } catch (error) {
1979
+ this.#setState({
1980
+ state: 'failed',
1981
+ degraded: false,
1982
+ error: publicError('spawn_failed', `sidecar 启动失败(${error?.code ?? 'spawn_failed'})`),
1983
+ });
1984
+ return false;
1985
+ }
1986
+
1987
+ this.child = child;
1988
+ this.childToken = hostToken;
1989
+ this.manualStart = manual;
1990
+ this.readySeen = false;
1991
+ this.healthFailures = 0;
1992
+ this.commandSource = resolved.source;
1993
+ this.installed = true;
1994
+ this.#setState({
1995
+ state: 'starting',
1996
+ degraded: false,
1997
+ managed: true,
1998
+ attached: false,
1999
+ pid: child.pid ?? null,
2000
+ url: null,
2001
+ healthUrl: null,
2002
+ runtimeVersion: null,
2003
+ apiVersion: null,
2004
+ capabilityApiVersion: null,
2005
+ commandSource: resolved.source,
2006
+ installed: true,
2007
+ startedAt: this.now(),
2008
+ lastOkAt: null,
2009
+ restarts: this.restarts,
2010
+ reason: null,
2011
+ error: null,
2012
+ });
2013
+
2014
+ child.once?.('error', (error) => {
2015
+ if (this.child !== child) return;
2016
+ this.#setState({
2017
+ state: 'failed',
2018
+ degraded: false,
2019
+ error: publicError('spawn_failed', `sidecar 启动失败(${error?.code ?? 'spawn_failed'})`),
2020
+ });
2021
+ });
2022
+ child.once?.('exit', (code, signal) => this.#onChildExit(child, code, signal));
2023
+ if (child.stderr) {
2024
+ child.stderr.on('data', (chunk) => {
2025
+ const text = redact(chunk?.toString?.('utf-8') ?? '', this.childSecrets);
2026
+ if (text.trim().length > 0) this.lastStderr = text;
2027
+ });
2028
+ }
2029
+
2030
+ const deadline = this.now() + Math.max(100, this.configuredStartTimeout());
2031
+ const ready = await this.#waitForReady(deadline, child);
2032
+ if (ready) {
2033
+ this.#startWatchdog();
2034
+ if (manual) child.unref?.();
2035
+ return true;
2036
+ }
2037
+ if (this.stopping || this.disposed) return false;
2038
+
2039
+ if (this.child === child) {
2040
+ // 先解除归属,避免 SIGTERM 触发的 exit handler 把超时当成一次崩溃并重复排程。
2041
+ this.child = null;
2042
+ this.#stopWatchdog();
2043
+ try {
2044
+ child.kill('SIGTERM');
2045
+ } catch {
2046
+ // already gone
2047
+ }
2048
+ await this.#waitChildExit(child, 500);
2049
+ if (child.exitCode === null) {
2050
+ try {
2051
+ child.kill('SIGKILL');
2052
+ } catch {
2053
+ // already gone
2054
+ }
2055
+ await this.#waitChildExit(child, 500);
2056
+ }
2057
+ this.restarts += 1;
2058
+ this.crashTimes.push(this.now());
2059
+ this.#setState({
2060
+ state: 'failed',
2061
+ degraded: false,
2062
+ managed: false,
2063
+ attached: false,
2064
+ pid: null,
2065
+ url: null,
2066
+ healthUrl: null,
2067
+ restarts: this.restarts,
2068
+ error: publicError('start_timeout', 'sidecar 启动超时'),
2069
+ });
2070
+ this.#scheduleRestart();
2071
+ }
2072
+ return false;
2073
+ }
2074
+
2075
+ async #waitForOrphanedManagedExit(discovery) {
2076
+ const deadline = Date.now() + Math.max(100, this.configuredStartTimeout());
2077
+ this.#setState({
2078
+ state: 'starting', available: false, degraded: false, managed: false, attached: true,
2079
+ pid: discovery.pid, url: null, healthUrl: null, error: null,
2080
+ });
2081
+ for (;;) {
2082
+ const current = await readDiscovery(this.paths.discoveryPath);
2083
+ if (!sameDiscoveryInstance(current, discovery) || !pidAlive(discovery.pid)) return true;
2084
+ if (Date.now() >= deadline || this.stopping || this.disposed) return false;
2085
+ await sleep(Math.min(this.healthPollMs, 50));
2086
+ }
2087
+ }
2088
+
2089
+ async #startOnce({ force = false, manual = false, isRestart = false } = {}) {
2090
+ if (this.disposed) return this.snapshot();
2091
+ this.stopping = false;
2092
+
2093
+ const beforeStart = await readDiscovery(this.paths.discoveryPath);
2094
+ if (beforeStart && Number.isInteger(beforeStart.parentPid)
2095
+ && beforeStart.parentPid !== process.pid && !pidAlive(beforeStart.parentPid)) {
2096
+ // 只等待旧 parent supervision 收尾;绝不替父进程杀 attached/manual 或旧 child。
2097
+ if (!await this.#waitForOrphanedManagedExit(beforeStart)) {
2098
+ if (!this.stopping && !this.disposed) {
2099
+ this.#setState({
2100
+ state: 'degraded', available: false, degraded: true, managed: false, attached: true,
2101
+ pid: beforeStart.pid,
2102
+ error: publicError('orphaned_sidecar_alive', '旧 managed sidecar 尚未按父监督退出:不终止、不替换'),
2103
+ });
2104
+ }
2105
+ return this.snapshot();
2106
+ }
2107
+ }
2108
+
2109
+ const discovered = await this.#refreshDiscovery({ fetchHealth: true });
2110
+ if (discovered && ['ready', 'degraded'].includes(this.statusState.state)) {
2111
+ this.#startWatchdog();
2112
+ return this.snapshot();
2113
+ }
2114
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
2115
+ return this.snapshot();
2116
+ }
2117
+ if (this.stopping || this.disposed) return this.snapshot();
2118
+
2119
+ if (!force && !this.isEnabled()) {
2120
+ this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
2121
+ return this.snapshot();
2122
+ }
2123
+ if (!force && this.env?.MEBULAR_MEMORY_RUNTIME_DISABLE === '1') {
2124
+ this.#setState({
2125
+ state: 'stopped',
2126
+ degraded: false,
2127
+ managed: false,
2128
+ attached: false,
2129
+ pid: null,
2130
+ reason: 'disabled',
2131
+ error: null,
2132
+ });
2133
+ return this.snapshot();
2134
+ }
2135
+
2136
+ const existing = await readDiscovery(this.paths.discoveryPath);
2137
+ if (existing && pidAlive(existing.pid)) {
2138
+ // 存活但未通过 health/版本校验:不启动第二个实例。
2139
+ this.#setState({
2140
+ state: 'degraded',
2141
+ degraded: true,
2142
+ managed: false,
2143
+ attached: true,
2144
+ pid: existing.pid,
2145
+ url: existing.url,
2146
+ healthUrl: existing.healthUrl,
2147
+ error: publicError('sidecar_unhealthy', '已有 sidecar 未就绪:不重复启动'),
2148
+ });
2149
+ return this.snapshot();
2150
+ }
2151
+ if (existing) {
2152
+ const removed = await this.#removeDiscoveryIfMatches(existing).catch(() => false);
2153
+ const remaining = removed ? null : await readDiscovery(this.paths.discoveryPath);
2154
+ if (sameDiscoveryInstance(remaining, existing)) {
2155
+ this.#setState({
2156
+ state: 'failed', available: false, degraded: false,
2157
+ error: publicError('discovery_cleanup_failed', '无法安全清理旧 discovery:不启动替换实例'),
2158
+ });
2159
+ return this.snapshot();
2160
+ }
2161
+ }
2162
+
2163
+ const lock = await this.#readLockView();
2164
+ if (lock && pidAlive(lock.pid)) {
2165
+ const expectedProfile = this.#profileId();
2166
+ const expectedCloud = this.#cloudId();
2167
+ if ((expectedProfile && lock.profileId && expectedProfile !== lock.profileId)
2168
+ || (expectedCloud && lock.cloudId && expectedCloud !== lock.cloudId)) {
2169
+ this.#setState({
2170
+ state: 'failed',
2171
+ degraded: false,
2172
+ error: publicError('profile_mismatch', '已有 sidecar 启动锁属于其他 profile/忆云:拒绝接管'),
2173
+ lock: this.lockView,
2174
+ });
2175
+ return this.snapshot();
2176
+ }
2177
+ // 已验证的 dormant 外部/manual 实例不是“正在启动”:不要卡在 sidecar_starting。
2178
+ const dormantCandidate = this.#discoveryFromLock(lock);
2179
+ if (dormantCandidate && await this.#verifyLiveInstance(dormantCandidate, { requireDiscovery: false })) {
2180
+ const observed = await this.#readSidecarMode(dormantCandidate);
2181
+ if (observed?.mode === 'mcp' && observed.state === 'stopped') {
2182
+ const persisted = await this.#readDormantState();
2183
+ const persistedMatches = persisted
2184
+ && persisted.pid === lock.pid
2185
+ && persisted.startedAt === lock.startedAt
2186
+ ? persisted
2187
+ : null;
2188
+ if (persisted && !persistedMatches) await this.#clearDormantState();
2189
+ const inMemoryBaseline = this.dormantLock
2190
+ && this.dormantLock.pid === lock.pid
2191
+ && this.dormantLock.startedAt === lock.startedAt
2192
+ ? this.dormantLock.credential
2193
+ : undefined;
2194
+ const baseline = inMemoryBaseline !== undefined
2195
+ ? inMemoryBaseline
2196
+ : (persistedMatches ? persistedMatches.credential : undefined);
2197
+ const credential = await this.#capabilityFingerprint();
2198
+ if (!this.dormantLockInvalidated) {
2199
+ if (baseline === undefined) {
2200
+ // 没有可信 baseline(文件缺失/损坏/权限异常/写失败):不能证明仍是同一代 dormant 实例,
2201
+ // 保守进入 starting,绝不报告 clean stopped。
2202
+ this.dormantLockInvalidated = true;
2203
+ } else if (baseline !== credential) {
2204
+ // 保留旧 baseline:同一进程重启后仍据此判定凭据已换代,不得回退 stopped。
2205
+ this.dormantLock = null;
2206
+ this.dormantLockInvalidated = true;
2207
+ }
2208
+ }
2209
+ const resumeDeadline = this.now() + Math.min(500, this.configuredStartTimeout());
2210
+ while (this.now() < resumeDeadline) {
2211
+ const discovery = await readDiscovery(this.paths.discoveryPath);
2212
+ if (discovery) {
2213
+ const ready = await this.#refreshDiscovery({ fetchHealth: true });
2214
+ if (ready) return this.snapshot();
2215
+ break;
2216
+ }
2217
+ await sleep(50);
2218
+ }
2219
+ if (!this.dormantLockInvalidated) {
2220
+ this.#setState({
2221
+ state: 'stopped',
2222
+ available: false,
2223
+ degraded: false,
2224
+ managed: false,
2225
+ attached: false,
2226
+ pid: lock.pid,
2227
+ url: null,
2228
+ healthUrl: null,
2229
+ reason: 'disabled',
2230
+ error: null,
2231
+ lock: this.lockView,
2232
+ });
2233
+ this.dormantLock = {
2234
+ pid: lock.pid,
2235
+ startedAt: lock.startedAt,
2236
+ credential,
2237
+ };
2238
+ await this.#writeDormantState({
2239
+ pid: lock.pid,
2240
+ startedAt: lock.startedAt,
2241
+ credential,
2242
+ });
2243
+ return this.snapshot();
2244
+ }
2245
+ }
2246
+ }
2247
+ const deadline = this.now() + Math.max(100, this.configuredStartTimeout());
2248
+ const ready = await this.#waitForDiscovery(deadline);
2249
+ if (ready) {
2250
+ this.#startWatchdog();
2251
+ return this.snapshot();
2252
+ }
2253
+ if (this.stopping || this.disposed) return this.snapshot();
2254
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
2255
+ return this.snapshot();
2256
+ }
2257
+ if (this.dormantLockInvalidated
2258
+ && this.lockView
2259
+ && Number.isInteger(this.lockView.pid)
2260
+ && pidAlive(this.lockView.pid)) {
2261
+ this.#setState({
2262
+ state: 'starting',
2263
+ available: false,
2264
+ degraded: false,
2265
+ managed: false,
2266
+ attached: false,
2267
+ pid: this.lockView.pid,
2268
+ url: null,
2269
+ healthUrl: null,
2270
+ discoveryMode: 'mcp',
2271
+ reason: null,
2272
+ error: null,
2273
+ lock: this.lockView,
2274
+ });
2275
+ return this.snapshot();
2276
+ }
2277
+ this.#setState({
2278
+ state: 'failed',
2279
+ degraded: false,
2280
+ error: publicError('sidecar_starting', '已有 sidecar 正在启动但未在超时内就绪'),
2281
+ lock: this.lockView,
2282
+ });
2283
+ return this.snapshot();
2284
+ }
2285
+ // 陈旧/损坏锁交给 sidecar 自己原子接管;supervisor 不删除 start.lock,避免误删并发新实例。
2286
+ if (this.stopping || this.disposed) return this.snapshot();
2287
+ if (isRestart) this.#pruneCrashTimes();
2288
+ await this.#spawnSidecar({ manual });
2289
+ return this.snapshot();
2290
+ }
2291
+
2292
+ async start({ force = false, manual = false } = {}) {
2293
+ if (this.disposed) return this.snapshot();
2294
+ if (this.startPromise) return this.startPromise;
2295
+ this.startPromise = this.#startOnce({ force, manual })
2296
+ .catch((error) => this.#setState({
2297
+ state: 'failed',
2298
+ degraded: false,
2299
+ error: publicError(error?.code ?? 'supervisor_error', 'sidecar supervisor 异常'),
2300
+ }))
2301
+ .finally(() => {
2302
+ this.startPromise = null;
2303
+ });
2304
+ return this.startPromise;
2305
+ }
2306
+
2307
+ async #stopPid(pid, timeoutMs) {
2308
+ if (!pidAlive(pid)) return true;
2309
+ try {
2310
+ process.kill(pid, 'SIGTERM');
2311
+ } catch {
2312
+ return !pidAlive(pid);
2313
+ }
2314
+ const deadline = this.now() + Math.max(0, timeoutMs);
2315
+ while (pidAlive(pid) && this.now() < deadline) await sleep(25);
2316
+ if (pidAlive(pid)) {
2317
+ try {
2318
+ process.kill(pid, 'SIGKILL');
2319
+ } catch {
2320
+ // already gone
2321
+ }
2322
+ const killDeadline = this.now() + 500;
2323
+ while (pidAlive(pid) && this.now() < killDeadline) await sleep(25);
2324
+ }
2325
+ return !pidAlive(pid);
2326
+ }
2327
+
2328
+ async stop({ includeAttached = false, timeoutMs = 5000 } = {}) {
2329
+ this.stopping = true;
2330
+ let dormantBaseline = null;
2331
+ this.#clearRestartTimer();
2332
+ this.#clearCooldownTimer();
2333
+ this.#stopWatchdog();
2334
+
2335
+ if (this.startPromise) await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
2336
+ const discoveredAtStop = await readDiscovery(this.paths.discoveryPath);
2337
+ const child = this.child;
2338
+ const attachedDiscovery = discoveredAtStop
2339
+ && discoveredAtStop.pid !== child?.pid
2340
+ && discoveredAtStop.pid !== this.managedInstance?.pid
2341
+ ? discoveredAtStop
2342
+ : null;
2343
+ if (child) {
2344
+ this.#killChild('SIGTERM');
2345
+ await this.#waitChildExit(child, timeoutMs);
2346
+ if (child.exitCode === null) {
2347
+ this.#killChild('SIGKILL');
2348
+ await this.#waitChildExit(child, 500);
2349
+ }
2350
+ if (this.child === child) this.child = null;
2351
+ }
2352
+ if (this.startPromise) await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
2353
+ const lateChild = this.child;
2354
+ if (lateChild && lateChild !== child) {
2355
+ this.#killChild('SIGTERM');
2356
+ await this.#waitChildExit(lateChild, Math.min(timeoutMs, 1000));
2357
+ if (lateChild.exitCode === null) this.#killChild('SIGKILL');
2358
+ if (this.child === lateChild) this.child = null;
2359
+ }
2360
+
2361
+ let clean = true;
2362
+ const stoppedPids = new Set([child?.pid, lateChild?.pid, this.managedInstance?.pid]
2363
+ .filter((pid) => Number.isInteger(pid)));
2364
+ for (const pid of stoppedPids) {
2365
+ if (pidAlive(pid)) {
2366
+ clean = false;
2367
+ continue;
2368
+ }
2369
+ const current = await readDiscovery(this.paths.discoveryPath);
2370
+ const knownStartedAt = discoveredAtStop?.pid === pid
2371
+ ? discoveredAtStop.startedAt
2372
+ : this.managedInstance?.pid === pid
2373
+ ? this.managedInstance.startedAt
2374
+ : this.statusState.pid === pid ? this.statusState.startedAt : null;
2375
+ if (current?.pid === pid && knownStartedAt !== null && current.startedAt === knownStartedAt) {
2376
+ const expected = current;
2377
+ const removed = await this.#removeDiscoveryIfMatches(expected).catch(() => false);
2378
+ if (!removed && sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), expected)) {
2379
+ clean = false;
2380
+ }
2381
+ } else if (current?.pid === pid) {
2382
+ // 身份不明的残留不得删除,也不得静默当作已清理。
2383
+ clean = false;
2384
+ }
2385
+ const lock = await this.#readLockView();
2386
+ if (lock?.pid === pid) {
2387
+ if (knownStartedAt === null || lock.startedAt !== knownStartedAt) {
2388
+ clean = false;
2389
+ } else {
2390
+ await unlink(this.paths.lockPath).catch(() => {
2391
+ clean = false;
2392
+ });
2393
+ }
2394
+ }
2395
+ }
2396
+
2397
+ if (includeAttached) {
2398
+ const discovery = await readDiscovery(this.paths.discoveryPath);
2399
+ const verified = discovery && await this.#verifyLiveInstance(discovery)
2400
+ ? discovery
2401
+ : null;
2402
+ if (verified) {
2403
+ // 信号前二次读取,缩窄操作者重启/替换实例的竞态窗口。
2404
+ const confirmed = await readDiscovery(this.paths.discoveryPath);
2405
+ if (!sameDiscoveryInstance(confirmed, verified)) {
2406
+ clean = false;
2407
+ } else {
2408
+ if (pidAlive(verified.pid) && !await this.#stopPid(verified.pid, timeoutMs)) clean = false;
2409
+ if (!pidAlive(verified.pid)) {
2410
+ const removed = await this.#removeDiscoveryIfMatches(verified).catch(() => false);
2411
+ if (!removed && sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), verified)) {
2412
+ clean = false;
2413
+ }
2414
+ }
2415
+ }
2416
+ } else if (discovery) {
2417
+ // 不可验证的 live PID 绝不 kill;只允许清理已退出实例的匹配 discovery。
2418
+ if (!pidAlive(discovery.pid)) {
2419
+ const removed = await this.#removeDiscoveryIfMatches(discovery).catch(() => false);
2420
+ if (!removed && sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), discovery)) {
2421
+ clean = false;
2422
+ }
2423
+ } else {
2424
+ clean = false;
2425
+ }
2426
+ }
2427
+ const lock = await this.#readLockView();
2428
+ if (lock && lock.command === 'serve') {
2429
+ if (!pidAlive(lock.pid)) {
2430
+ await unlink(this.paths.lockPath).catch(() => {
2431
+ clean = false;
2432
+ });
2433
+ } else {
2434
+ // 只有 lock 与已验证 discovery 的 pid/startedAt 完全一致时才允许信号;
2435
+ // 否则可能是复用 PID 或陈旧锁,必须留给操作者处理并报告 incomplete。
2436
+ const matchesVerified = Boolean(verified)
2437
+ && verified.pid === lock.pid
2438
+ && verified.startedAt === lock.startedAt;
2439
+ if (!matchesVerified) {
2440
+ // discovery 已被 stop 删除时,从 start.lock + health/status identity + pid/startedAt 验证;
2441
+ // 不重建 discovery,也不对不可验证的复用 PID 发信号。
2442
+ const candidate = this.#discoveryFromLock(lock);
2443
+ const verifiedFromLock = candidate
2444
+ && await this.#verifyLiveInstance(candidate, { requireDiscovery: false });
2445
+ if (!verifiedFromLock) {
2446
+ clean = false;
2447
+ } else {
2448
+ const confirmedLock = await this.#readLockView();
2449
+ if (!confirmedLock
2450
+ || confirmedLock.pid !== lock.pid
2451
+ || confirmedLock.startedAt !== lock.startedAt
2452
+ || !pidAlive(lock.pid)) {
2453
+ clean = false;
2454
+ } else if (!await this.#stopPid(lock.pid, timeoutMs)) {
2455
+ clean = false;
2456
+ }
2457
+ }
2458
+ } else {
2459
+ const confirmedLock = await this.#readLockView();
2460
+ const confirmedDiscovery = await readDiscovery(this.paths.discoveryPath);
2461
+ if (!confirmedLock
2462
+ || confirmedLock.pid !== lock.pid
2463
+ || confirmedLock.startedAt !== lock.startedAt
2464
+ || !sameDiscoveryInstance(confirmedDiscovery, verified)
2465
+ || !pidAlive(lock.pid)) {
2466
+ clean = false;
2467
+ } else if (!await this.#stopPid(lock.pid, timeoutMs)) {
2468
+ clean = false;
2469
+ }
2470
+ }
2471
+ }
2472
+ }
2473
+ const remainingLock = await this.#readLockView();
2474
+ if (remainingLock && !pidAlive(remainingLock.pid)) {
2475
+ await unlink(this.paths.lockPath).catch(() => {
2476
+ clean = false;
2477
+ });
2478
+ }
2479
+ } else if (attachedDiscovery && !this.#homeMismatch(attachedDiscovery)
2480
+ && !this.#profileMismatch(attachedDiscovery)) {
2481
+ // D1:外部 PID 归操作者;仅撤销匹配 discovery,再验证旧凭据也无法工作。
2482
+ const capabilityBefore = await this.#capabilityFingerprint();
2483
+ await this.#removeDiscoveryIfMatches(attachedDiscovery).catch(() => false);
2484
+ if (pidAlive(attachedDiscovery.pid)
2485
+ && !await this.#waitAttachedDormant(
2486
+ attachedDiscovery,
2487
+ Math.max(timeoutMs, MEMORY_RUNTIME_ATTACHED_DORMANT_WAIT_MS),
2488
+ )) {
2489
+ clean = false;
2490
+ }
2491
+ let remaining = await readDiscovery(this.paths.discoveryPath);
2492
+ const needsDormant = (candidate) => candidate
2493
+ && !this.#homeMismatch(candidate)
2494
+ && !this.#profileMismatch(candidate)
2495
+ && !this.#versionMismatch(candidate)
2496
+ && (candidate.mode !== 'mcp' || candidate.state !== 'stopped');
2497
+ if (needsDormant(remaining)) {
2498
+ // 操作者可能在禁用期间替换实例;新实例同样必须撤销并验证,不能漏过。
2499
+ await this.#removeDiscoveryIfMatches(remaining).catch(() => false);
2500
+ if (pidAlive(remaining.pid)
2501
+ && !await this.#waitAttachedDormant(
2502
+ remaining,
2503
+ Math.max(timeoutMs, MEMORY_RUNTIME_ATTACHED_DORMANT_WAIT_MS),
2504
+ )) {
2505
+ clean = false;
2506
+ }
2507
+ remaining = await readDiscovery(this.paths.discoveryPath);
2508
+ }
2509
+ if (needsDormant(remaining)) clean = false;
2510
+ // 能力仍有效且凭据未撤销/未换代:不能把“可能被同一 token 唤醒”的实例报告为 clean stopped。
2511
+ const capabilityAfter = await this.#capabilityFingerprint();
2512
+ const credentialUnchanged = capabilityBefore === null
2513
+ ? capabilityAfter !== null
2514
+ : capabilityAfter === capabilityBefore;
2515
+ if (credentialUnchanged) clean = false;
2516
+ // 外部进程仍存活:记录停止时的 credential baseline(可能是 null=已撤销)。
2517
+ // 下一次 start 只有在当前凭据仍等于 baseline 时才允许报告 stopped。
2518
+ if (pidAlive(attachedDiscovery.pid)) {
2519
+ dormantBaseline = {
2520
+ pid: attachedDiscovery.pid,
2521
+ startedAt: attachedDiscovery.startedAt,
2522
+ credential: capabilityBefore,
2523
+ };
2524
+ }
2525
+ } else {
2526
+ // discovery 缺失时仍可能存活 manual/attached 实例:从 start.lock 验证 identity/token/status。
2527
+ const lock = await this.#readLockView();
2528
+ if (lock && lock.command === 'serve' && !pidAlive(lock.pid)) {
2529
+ await unlink(this.paths.lockPath).catch(() => {
2530
+ clean = false;
2531
+ });
2532
+ } else if (lock && lock.command === 'serve' && pidAlive(lock.pid)) {
2533
+ const capabilityBefore = await this.#capabilityFingerprint();
2534
+ const candidate = this.#discoveryFromLock(lock);
2535
+ const verified = candidate
2536
+ && await this.#verifyLiveInstance(candidate, { requireDiscovery: false });
2537
+ if (!verified) {
2538
+ clean = false;
2539
+ } else {
2540
+ const observed = await this.#readSidecarMode(candidate);
2541
+ if (!(observed?.mode === 'mcp' && observed.state === 'stopped')) {
2542
+ // 仍然 immersive/starting/degraded:没有确认 dormant,不能 clean。
2543
+ clean = false;
2544
+ } else {
2545
+ if (lock.pid !== this.child?.pid && lock.pid !== this.managedInstance?.pid) {
2546
+ dormantBaseline = {
2547
+ pid: lock.pid,
2548
+ startedAt: lock.startedAt,
2549
+ credential: capabilityBefore,
2550
+ };
2551
+ }
2552
+ const capabilityAfter = await this.#capabilityFingerprint();
2553
+ const credentialUnchanged = capabilityBefore === null
2554
+ ? capabilityAfter !== null
2555
+ : capabilityAfter === capabilityBefore;
2556
+ if (credentialUnchanged) clean = false;
2557
+ }
2558
+ }
2559
+ }
2560
+ }
2561
+
2562
+ let dormantPersistError = null;
2563
+ if (dormantBaseline) {
2564
+ try {
2565
+ await this.#writeDormantState(dormantBaseline);
2566
+ } catch (error) {
2567
+ dormantPersistError = error;
2568
+ clean = false;
2569
+ }
2570
+ } else {
2571
+ await this.#clearDormantState();
2572
+ }
2573
+
2574
+ if (clean) {
2575
+ this.managedInstance = null;
2576
+ this.dormantLock = null;
2577
+ this.dormantLockInvalidated = false;
2578
+ this.#setState({
2579
+ state: 'stopped', available: false, degraded: false, managed: false, attached: false,
2580
+ pid: null, url: null, healthUrl: null, error: null,
2581
+ reason: this.isEnabled() ? null : 'disabled', lock: null,
2582
+ });
2583
+ } else {
2584
+ this.#setState({
2585
+ state: 'degraded', available: false, degraded: true, managed: false,
2586
+ attached: Boolean(attachedDiscovery && pidAlive(attachedDiscovery.pid)),
2587
+ pid: attachedDiscovery && pidAlive(attachedDiscovery.pid) ? attachedDiscovery.pid : null,
2588
+ url: null, healthUrl: null,
2589
+ error: dormantPersistError
2590
+ ? publicError(includeAttached ? 'stop_incomplete' : 'disable_incomplete',
2591
+ `sidecar 休眠凭据基线写入失败(${dormantPersistError?.code ?? 'ERROR'})`)
2592
+ : publicError(includeAttached ? 'stop_incomplete' : 'disable_incomplete',
2593
+ includeAttached ? 'sidecar 未能完整停止' : 'sidecar 未确认 dormant:禁用不完整'),
2594
+ reason: this.isEnabled() ? null : 'disabled', lock: this.lockView,
2595
+ });
2596
+ }
2597
+ this.stopping = false;
2598
+ return this.snapshot();
2599
+ }
2600
+
2601
+ async restart({ includeAttached = false, timeoutMs = 5000, manual = false, force = true } = {}) {
2602
+ if (!includeAttached && !this.child) {
2603
+ const external = await readDiscovery(this.paths.discoveryPath);
2604
+ if (external && pidAlive(external.pid)) {
2605
+ // 配置变化不是操作者 restart:不撤销/替换 attached/manual 实例。
2606
+ return this.start({ force: false, manual: false });
2607
+ }
2608
+ }
2609
+ appendMemoryRuntimeLogSync(this.paths.dataDir, {
2610
+ level: 'info',
2611
+ event: 'supervisor_restart',
2612
+ reason: manual ? 'operator_restart' : 'config_restart',
2613
+ }, { now: this.now });
2614
+ await this.stop({ includeAttached, timeoutMs });
2615
+ this.crashTimes = [];
2616
+ this.restarts = 0;
2617
+ this.healthFailures = 0;
2618
+ return this.start({ force, manual });
2619
+ }
2620
+
2621
+ async dispose() {
2622
+ this.disposed = true;
2623
+ const status = await this.stop({ includeAttached: false, timeoutMs: 3000 });
2624
+ this.disposed = true;
2625
+ if (!status.error) this.#setState({ reason: 'disposed', available: false });
2626
+ }
2627
+ }
2628
+
2629
+ /** 只读检查:不 spawn、不创建目录/token;供 CLI status 与 admin 使用。 */
2630
+ export async function inspectMemoryRuntimeStatus({
2631
+ home,
2632
+ env = process.env,
2633
+ config = {},
2634
+ expectedProfileId = null,
2635
+ expectedCloudId = null,
2636
+ now = Date.now,
2637
+ fetchImpl = globalThis.fetch,
2638
+ } = {}) {
2639
+ const supervisor = new MemoryRuntimeSupervisor({
2640
+ home,
2641
+ env,
2642
+ config,
2643
+ profileId: () => expectedProfileId,
2644
+ cloudId: () => expectedCloudId,
2645
+ now,
2646
+ fetchImpl,
2647
+ restartOnFailure: false,
2648
+ });
2649
+ const status = await supervisor.status();
2650
+ const resolved = resolveMemoryRuntimeCommand({ config, env });
2651
+ return {
2652
+ ...status,
2653
+ installed: resolved.ok === true,
2654
+ commandSource: resolved.source,
2655
+ };
2656
+ }
2657
+
2658
+ /** 稳定 CLI 退出码(sidecar §11.2 + MCP CLI 包装约定)。 */
2659
+ export function memoryRuntimeStatusExitCode(status) {
2660
+ const code = status?.error?.code ?? null;
2661
+ if (code === 'not_installed') return 3;
2662
+ if (code === 'capability_token_missing' || code === 'capability_token_invalid') return 5;
2663
+ if (code === 'storage_unavailable' || code === 'token_permissions_insecure') return 6;
2664
+ if (code === 'bind_failed' || code === 'bind_not_loopback') return 4;
2665
+ if (code === 'version_incompatible' || code === 'capability_disabled') return 2;
2666
+ if (code === 'profile_mismatch' || code === 'home_mismatch' || code === 'lock_conflict'
2667
+ || code === 'already_running' || code === 'sidecar_starting') return 7;
2668
+ if (status?.state === 'ready' || status?.state === 'degraded' || status?.state === 'stopped') return 0;
2669
+ return 1;
2670
+ }