@mebular/mcp 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1844 @@
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 } from 'node:crypto';
17
+ import { statSync } from 'node:fs';
18
+ import { readFile, unlink } 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
+
24
+ export const MEMORY_RUNTIME_DISCOVERY_FILE = 'memory-runtime.json';
25
+ export const MEMORY_RUNTIME_DATA_DIR = 'memory-runtime';
26
+ export const MEMORY_RUNTIME_START_LOCK_FILE = 'start.lock';
27
+ export const MEMORY_RUNTIME_TOKEN_FILE = 'host-token';
28
+ export const MEMORY_RUNTIME_CAPABILITY_TOKEN_FILE = 'capability-token';
29
+ export const MEMORY_RUNTIME_DEFAULT_PORT = 7341;
30
+ export const MEMORY_RUNTIME_DEFAULT_START_TIMEOUT_MS = 5000;
31
+ export const MEMORY_RUNTIME_HEALTH_TIMEOUT_MS = 200;
32
+ export const MEMORY_RUNTIME_HEALTH_CHECK_MS = 5000;
33
+ export const MEMORY_RUNTIME_RESTART_WINDOW_MS = 5 * 60 * 1000;
34
+ export const MEMORY_RUNTIME_MAX_RESTARTS = 3;
35
+ export const MEMORY_RUNTIME_RESTART_BACKOFF_MS = 500;
36
+ export const MEMORY_RUNTIME_RESTART_BACKOFF_MAX_MS = 30_000;
37
+ export const MEMORY_RUNTIME_RESTART_COOLDOWN_MS = 5 * 60 * 1000;
38
+ export const MEMORY_RUNTIME_BIN = 'mebular-memory-runtime';
39
+
40
+ const SIDECAR_KIND = 'mebular-memory-runtime';
41
+ const CAPABILITY_API_VERSION = 1;
42
+
43
+ const sleep = (ms) => new Promise((resolvePromise) => setTimeout(resolvePromise, Math.max(0, ms)));
44
+
45
+ function isObject(value) {
46
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
47
+ }
48
+
49
+ function stringOrNull(value) {
50
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
51
+ }
52
+
53
+ export function pidAlive(pid) {
54
+ if (!Number.isInteger(pid) || pid <= 0) return false;
55
+ try {
56
+ process.kill(pid, 0);
57
+ return true;
58
+ } catch (error) {
59
+ return error?.code === 'EPERM';
60
+ }
61
+ }
62
+
63
+ export function resolveMemoryRuntimeHome({ home, env = process.env } = {}) {
64
+ const raw = typeof home === 'string' && home.length > 0
65
+ ? home
66
+ : (typeof env?.MEBULAR_HOME === 'string' && env.MEBULAR_HOME.trim().length > 0
67
+ ? env.MEBULAR_HOME
68
+ : join(homedir(), '.mebular'));
69
+ return resolve(raw);
70
+ }
71
+
72
+ export function resolveMemoryRuntimePaths({ home, env = process.env } = {}) {
73
+ const resolvedHome = resolveMemoryRuntimeHome({ home, env });
74
+ const override = typeof env?.MEBULAR_MEMORY_RUNTIME_HOME === 'string'
75
+ && env.MEBULAR_MEMORY_RUNTIME_HOME.trim().length > 0
76
+ ? env.MEBULAR_MEMORY_RUNTIME_HOME
77
+ : null;
78
+ const dataDir = override ? resolve(override) : join(resolvedHome, MEMORY_RUNTIME_DATA_DIR);
79
+ return {
80
+ home: resolvedHome,
81
+ dataDir,
82
+ discoveryPath: join(resolvedHome, MEMORY_RUNTIME_DISCOVERY_FILE),
83
+ lockPath: join(dataDir, MEMORY_RUNTIME_START_LOCK_FILE),
84
+ hostTokenPath: join(dataDir, MEMORY_RUNTIME_TOKEN_FILE),
85
+ capabilityTokenPath: join(dataDir, MEMORY_RUNTIME_CAPABILITY_TOKEN_FILE),
86
+ };
87
+ }
88
+
89
+ async function readJson(path, fallback = null) {
90
+ try {
91
+ return JSON.parse(await readFile(path, 'utf-8'));
92
+ } catch {
93
+ return fallback;
94
+ }
95
+ }
96
+
97
+ function executableExists(path) {
98
+ try {
99
+ return statSync(path).isFile();
100
+ } catch {
101
+ return false;
102
+ }
103
+ }
104
+
105
+ function bundledBinCandidates() {
106
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
107
+ return [
108
+ join(moduleDir, '..', '..', 'memory-runtime', 'bin', 'mebular-memory-runtime.mjs'),
109
+ join(moduleDir, '..', 'node_modules', '@mebular', 'memory-runtime', 'bin', 'mebular-memory-runtime.mjs'),
110
+ join(moduleDir, '..', '..', '..', '@mebular', 'memory-runtime', 'bin', 'mebular-memory-runtime.mjs'),
111
+ ].map((entry) => resolve(entry));
112
+ }
113
+
114
+ function findOnPath(name, env) {
115
+ const pathValue = typeof env?.PATH === 'string' ? env.PATH : process.env.PATH;
116
+ if (typeof pathValue !== 'string' || pathValue.length === 0) return null;
117
+ const names = process.platform === 'win32' ? [`${name}.cmd`, `${name}.exe`, name] : [name];
118
+ for (const dir of pathValue.split(delimiter)) {
119
+ if (!dir) continue;
120
+ for (const candidate of names) {
121
+ const full = join(dir, candidate);
122
+ if (executableExists(full)) return full;
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+
128
+ /**
129
+ * 解析 sidecar 可执行文件。
130
+ *
131
+ * 优先级:`memoryRuntime.command` > `MEBULAR_MEMORY_RUNTIME_BIN` > 包内 bin > PATH。
132
+ * 显式配置/环境变量指向不存在文件时直接失败,不静默回退。
133
+ */
134
+ export function resolveMemoryRuntimeCommand({ config, env = process.env } = {}) {
135
+ const configured = stringOrNull(config?.memoryRuntime?.command);
136
+ if (configured) {
137
+ const command = resolve(configured);
138
+ return executableExists(command)
139
+ ? { ok: true, command, source: 'config' }
140
+ : { ok: false, command, source: 'config', reason: 'not_installed' };
141
+ }
142
+
143
+ const fromEnv = stringOrNull(env?.MEBULAR_MEMORY_RUNTIME_BIN);
144
+ if (fromEnv) {
145
+ const command = resolve(fromEnv);
146
+ return executableExists(command)
147
+ ? { ok: true, command, source: 'env' }
148
+ : { ok: false, command, source: 'env', reason: 'not_installed' };
149
+ }
150
+
151
+ for (const candidate of bundledBinCandidates()) {
152
+ if (executableExists(candidate)) {
153
+ return { ok: true, command: candidate, source: 'bundled' };
154
+ }
155
+ }
156
+
157
+ const onPath = findOnPath(MEMORY_RUNTIME_BIN, env);
158
+ if (onPath) return { ok: true, command: onPath, source: 'path' };
159
+
160
+ return { ok: false, command: null, source: 'missing', reason: 'not_installed' };
161
+ }
162
+
163
+ function commandSpec(command) {
164
+ if (/\.(?:mjs|cjs|js)$/i.test(command)) {
165
+ return { execPath: process.execPath, args: [command] };
166
+ }
167
+ if (process.platform === 'win32' && /\.cmd$/i.test(command)) {
168
+ return { execPath: process.env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', command] };
169
+ }
170
+ return { execPath: command, args: [] };
171
+ }
172
+
173
+ function parseVersion(value) {
174
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(String(value ?? '').trim());
175
+ if (!match) return null;
176
+ return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
177
+ }
178
+
179
+ function compareVersion(a, b) {
180
+ if (a.major !== b.major) return a.major - b.major;
181
+ if (a.minor !== b.minor) return a.minor - b.minor;
182
+ return a.patch - b.patch;
183
+ }
184
+
185
+ function mcpVersionCompatible(version, minVersion, maxVersion) {
186
+ const parsed = parseVersion(version);
187
+ const min = parseVersion(minVersion);
188
+ if (!parsed || !min) return false;
189
+ if (compareVersion(parsed, min) < 0) return false;
190
+ const wildcard = /^(\d+)\.(\d+)\.x$/.exec(String(maxVersion ?? '').trim());
191
+ if (wildcard) {
192
+ return parsed.major === Number(wildcard[1]) && parsed.minor <= Number(wildcard[2]);
193
+ }
194
+ const max = parseVersion(maxVersion);
195
+ return max ? compareVersion(parsed, max) <= 0 : false;
196
+ }
197
+
198
+ function discoveryProfileId(discovery) {
199
+ return stringOrNull(discovery?.profileId);
200
+ }
201
+
202
+ function discoveryCloudId(discovery) {
203
+ return stringOrNull(discovery?.cloudId);
204
+ }
205
+
206
+ function publicError(code, message) {
207
+ return code ? { code, message } : null;
208
+ }
209
+
210
+ function makeDisabledStatus({ enabled = false, reason = 'disabled' } = {}) {
211
+ return {
212
+ enabled,
213
+ state: 'stopped',
214
+ available: false,
215
+ degraded: false,
216
+ managed: false,
217
+ attached: false,
218
+ pid: null,
219
+ url: null,
220
+ healthUrl: null,
221
+ runtimeVersion: null,
222
+ apiVersion: null,
223
+ capabilityApiVersion: null,
224
+ commandSource: null,
225
+ installed: enabled ? null : false,
226
+ startedAt: null,
227
+ lastOkAt: null,
228
+ restarts: 0,
229
+ reason,
230
+ error: null,
231
+ lock: null,
232
+ };
233
+ }
234
+
235
+ export function disabledMemoryRuntimeStatus() {
236
+ return makeDisabledStatus();
237
+ }
238
+
239
+ function isSidecarDiscovery(value) {
240
+ return isObject(value)
241
+ && value.schema === 1
242
+ && value.kind === SIDECAR_KIND
243
+ && Number.isInteger(value.pid)
244
+ && value.pid > 0
245
+ && typeof value.host === 'string'
246
+ && Number.isInteger(value.port)
247
+ && typeof value.url === 'string'
248
+ && typeof value.healthUrl === 'string'
249
+ && typeof value.tokenFile === 'string'
250
+ && typeof value.updatedAt === 'number';
251
+ }
252
+
253
+ async function readDiscovery(path) {
254
+ const value = await readJson(path, null);
255
+ return isSidecarDiscovery(value) ? value : null;
256
+ }
257
+
258
+ async function readLock(path) {
259
+ const value = await readJson(path, null);
260
+ if (!isObject(value) || !Number.isInteger(value.pid) || value.pid <= 0) return null;
261
+ return {
262
+ pid: value.pid,
263
+ port: Number.isInteger(value.port) ? value.port : null,
264
+ startedAt: typeof value.startedAt === 'number' ? value.startedAt : 0,
265
+ updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,
266
+ cloudId: stringOrNull(value.cloudId),
267
+ profileId: stringOrNull(value.profileId),
268
+ command: typeof value.command === 'string' ? value.command : 'serve',
269
+ };
270
+ }
271
+
272
+ function redact(text, secrets) {
273
+ let out = String(text ?? '');
274
+ for (const secret of secrets) {
275
+ if (typeof secret === 'string' && secret.length > 0) out = out.split(secret).join('[redacted]');
276
+ }
277
+ return out.slice(-1000);
278
+ }
279
+
280
+ const PROXY_SECRET_KEYS = new Set([
281
+ 'authorization',
282
+ 'cookie',
283
+ 'token',
284
+ 'tokenfile',
285
+ 'hosttoken',
286
+ 'host_token',
287
+ 'capabilitytoken',
288
+ 'capability_token',
289
+ 'password',
290
+ 'secret',
291
+ ]);
292
+
293
+ /**
294
+ * 管理面代理只返回 sidecar 的公开视图:递归去掉令牌类字段,并把已知密钥从字符串里抹掉。
295
+ * sidecar 本身不应返回这些字段;这里多做一层,避免未来回归把 host token 带到浏览器。
296
+ */
297
+ function scrubProxyValue(value, secrets) {
298
+ if (Array.isArray(value)) return value.map((entry) => scrubProxyValue(entry, secrets));
299
+ if (isObject(value)) {
300
+ const out = {};
301
+ for (const [key, entry] of Object.entries(value)) {
302
+ if (PROXY_SECRET_KEYS.has(String(key).toLowerCase())) continue;
303
+ out[key] = scrubProxyValue(entry, secrets);
304
+ }
305
+ return out;
306
+ }
307
+ if (typeof value === 'string') {
308
+ let text = value;
309
+ for (const secret of secrets) {
310
+ if (typeof secret === 'string' && secret.length > 0) text = text.split(secret).join('[redacted]');
311
+ }
312
+ return text;
313
+ }
314
+ return value;
315
+ }
316
+
317
+ function proxyErrorMessage(body, fallback) {
318
+ const message = body?.error?.message ?? body?.message;
319
+ return typeof message === 'string' && message.length > 0 ? message : fallback;
320
+ }
321
+
322
+ /**
323
+ * Memory Runtime sidecar supervisor。
324
+ *
325
+ * 仅管理当前 `<home>` 的 sidecar;不启动 MCP daemon、不读写图、不 import sidecar 业务。
326
+ */
327
+ export class MemoryRuntimeSupervisor {
328
+ constructor({
329
+ home,
330
+ config = () => ({}),
331
+ env = process.env,
332
+ profileId = () => null,
333
+ cloudId = () => null,
334
+ mcpUrl = () => null,
335
+ getCapabilityToken = null,
336
+ command = null,
337
+ spawnImpl = defaultSpawn,
338
+ fetchImpl = globalThis.fetch,
339
+ now = Date.now,
340
+ startTimeoutMs = null,
341
+ healthTimeoutMs = MEMORY_RUNTIME_HEALTH_TIMEOUT_MS,
342
+ healthCheckIntervalMs = MEMORY_RUNTIME_HEALTH_CHECK_MS,
343
+ healthPollMs = 100,
344
+ restartWindowMs = MEMORY_RUNTIME_RESTART_WINDOW_MS,
345
+ maxRestartsInWindow = MEMORY_RUNTIME_MAX_RESTARTS,
346
+ restartBackoffMs = MEMORY_RUNTIME_RESTART_BACKOFF_MS,
347
+ restartBackoffMaxMs = MEMORY_RUNTIME_RESTART_BACKOFF_MAX_MS,
348
+ restartCooldownMs = MEMORY_RUNTIME_RESTART_COOLDOWN_MS,
349
+ restartOnFailure = true,
350
+ } = {}) {
351
+ this.home = resolveMemoryRuntimeHome({ home, env });
352
+ this.env = env ?? process.env;
353
+ this.paths = resolveMemoryRuntimePaths({ home: this.home, env: this.env });
354
+ this.getConfig = typeof config === 'function' ? config : () => config;
355
+ this.getProfileId = typeof profileId === 'function' ? profileId : () => profileId;
356
+ this.getCloudId = typeof cloudId === 'function' ? cloudId : () => cloudId;
357
+ this.getMcpUrl = typeof mcpUrl === 'function' ? mcpUrl : () => mcpUrl;
358
+ this.getCapabilityToken = getCapabilityToken;
359
+ this.explicitCommand = stringOrNull(command);
360
+ this.spawnImpl = spawnImpl;
361
+ this.fetchImpl = fetchImpl;
362
+ this.now = now;
363
+ this.startTimeoutMs = startTimeoutMs
364
+ ?? (typeof this.getConfig()?.memoryRuntime?.startTimeoutMs === 'number'
365
+ ? this.getConfig().memoryRuntime.startTimeoutMs
366
+ : MEMORY_RUNTIME_DEFAULT_START_TIMEOUT_MS);
367
+ this.healthTimeoutMs = healthTimeoutMs;
368
+ this.healthCheckIntervalMs = healthCheckIntervalMs;
369
+ this.healthPollMs = healthPollMs;
370
+ this.restartWindowMs = restartWindowMs;
371
+ this.maxRestartsInWindow = Math.max(0, maxRestartsInWindow);
372
+ this.restartBackoffMs = restartBackoffMs;
373
+ this.restartBackoffMaxMs = restartBackoffMaxMs;
374
+ this.restartCooldownMs = restartCooldownMs;
375
+ this.restartOnFailure = restartOnFailure;
376
+
377
+ this.child = null;
378
+ this.childToken = null;
379
+ this.childSecrets = [];
380
+ this.startPromise = null;
381
+ this.restartTimer = null;
382
+ this.cooldownTimer = null;
383
+ this.watchdogTimer = null;
384
+ this.healthFailures = 0;
385
+ this.crashTimes = [];
386
+ this.restarts = 0;
387
+ this.stopping = false;
388
+ this.disposed = false;
389
+ this.readySeen = false;
390
+ this.manualStart = false;
391
+ this.commandSource = null;
392
+ this.installed = null;
393
+ this.lockView = null;
394
+ this.statusState = makeDisabledStatus({
395
+ enabled: this.isEnabled(),
396
+ reason: this.isEnabled() ? null : 'disabled',
397
+ });
398
+ }
399
+
400
+ isEnabled() {
401
+ try {
402
+ return this.getConfig()?.memoryRuntime?.enabled === true;
403
+ } catch {
404
+ return false;
405
+ }
406
+ }
407
+
408
+ configuredStartTimeout() {
409
+ const configured = this.getConfig()?.memoryRuntime?.startTimeoutMs;
410
+ return Number.isInteger(configured) && configured >= 100
411
+ ? configured
412
+ : Math.max(100, this.startTimeoutMs);
413
+ }
414
+
415
+ snapshot() {
416
+ return JSON.parse(JSON.stringify(this.statusState));
417
+ }
418
+
419
+ #profileId() {
420
+ try {
421
+ return stringOrNull(this.getProfileId());
422
+ } catch {
423
+ return null;
424
+ }
425
+ }
426
+
427
+ #cloudId() {
428
+ try {
429
+ return stringOrNull(this.getCloudId());
430
+ } catch {
431
+ return null;
432
+ }
433
+ }
434
+
435
+ #setState(patch) {
436
+ const nextState = patch.state ?? this.statusState.state;
437
+ this.statusState = {
438
+ ...this.statusState,
439
+ ...patch,
440
+ enabled: this.isEnabled(),
441
+ available: nextState === 'ready' || nextState === 'degraded',
442
+ };
443
+ return this.snapshot();
444
+ }
445
+
446
+ #degradedError(code = 'sidecar_degraded') {
447
+ return publicError(code, 'Memory Runtime sidecar 处于降级状态');
448
+ }
449
+
450
+ #profileMismatch(discovery) {
451
+ const expectedProfile = this.#profileId();
452
+ const actualProfile = discoveryProfileId(discovery);
453
+ if (expectedProfile && actualProfile && expectedProfile !== actualProfile) return true;
454
+ const expectedCloud = this.#cloudId();
455
+ const actualCloud = discoveryCloudId(discovery);
456
+ return Boolean(expectedCloud && actualCloud && expectedCloud !== actualCloud);
457
+ }
458
+
459
+ #homeMismatch(discovery) {
460
+ if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return false;
461
+ return resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir;
462
+ }
463
+
464
+ #versionMismatch(discovery) {
465
+ if (discovery?.capabilityApiVersion !== CAPABILITY_API_VERSION) return true;
466
+ return !mcpVersionCompatible(
467
+ APP_VERSION,
468
+ discovery.minMcpVersion ?? '0.3.0',
469
+ discovery.maxMcpVersion ?? '0.3.x',
470
+ );
471
+ }
472
+
473
+ async #fetchHealth(discovery) {
474
+ if (!this.fetchImpl || typeof discovery?.healthUrl !== 'string') return { ok: false };
475
+ const controller = new AbortController();
476
+ const timer = setTimeout(() => controller.abort(), Math.max(1, this.healthTimeoutMs));
477
+ timer.unref?.();
478
+ try {
479
+ const response = await this.fetchImpl(discovery.healthUrl, {
480
+ method: 'GET',
481
+ headers: { accept: 'application/json' },
482
+ signal: controller.signal,
483
+ });
484
+ if (!response || response.ok !== true) return { ok: false };
485
+ const body = await response.json().catch(() => ({}));
486
+ return {
487
+ ok: body?.ok !== false && body?.ready !== false,
488
+ degraded: body?.degraded === true || body?.state === 'degraded',
489
+ body,
490
+ };
491
+ } catch {
492
+ return { ok: false };
493
+ } finally {
494
+ clearTimeout(timer);
495
+ }
496
+ }
497
+
498
+ async #readLockView() {
499
+ const lock = await readLock(this.paths.lockPath);
500
+ this.lockView = lock === null
501
+ ? null
502
+ : {
503
+ pid: lock.pid,
504
+ port: lock.port,
505
+ cloudId: lock.cloudId,
506
+ profileId: lock.profileId,
507
+ stale: !pidAlive(lock.pid),
508
+ };
509
+ return lock;
510
+ }
511
+
512
+ /**
513
+ * 读取 discovery/health 并更新快照。
514
+ * @returns {Promise<boolean>} 是否可接流量(ready 或 degraded)。
515
+ */
516
+ async #refreshDiscovery({ fetchHealth = true } = {}) {
517
+ await this.#readLockView();
518
+ const discovery = await readDiscovery(this.paths.discoveryPath);
519
+ if (!discovery) {
520
+ if (this.child && this.child.exitCode === null) {
521
+ const state = this.readySeen ? 'degraded' : 'starting';
522
+ this.#setState({
523
+ state,
524
+ degraded: this.readySeen,
525
+ managed: true,
526
+ attached: false,
527
+ pid: this.child.pid ?? null,
528
+ url: null,
529
+ healthUrl: null,
530
+ restarts: this.restarts,
531
+ error: this.readySeen ? publicError('discovery_missing', 'sidecar discovery 缺失') : null,
532
+ lock: this.lockView,
533
+ });
534
+ return false;
535
+ }
536
+ if (this.statusState.state !== 'failed') {
537
+ const startingByLock = this.isEnabled()
538
+ && this.lockView !== null
539
+ && this.lockView.stale !== true
540
+ && this.env?.MEBULAR_MEMORY_RUNTIME_DISABLE !== '1';
541
+ this.#setState({
542
+ state: startingByLock ? 'starting' : 'stopped',
543
+ degraded: false,
544
+ managed: false,
545
+ attached: false,
546
+ pid: this.lockView?.pid ?? null,
547
+ url: null,
548
+ healthUrl: null,
549
+ restarts: this.restarts,
550
+ error: null,
551
+ lock: this.lockView,
552
+ reason: !this.isEnabled() || this.env?.MEBULAR_MEMORY_RUNTIME_DISABLE === '1'
553
+ ? 'disabled'
554
+ : this.statusState.reason ?? null,
555
+ });
556
+ } else {
557
+ this.#setState({ restarts: this.restarts, lock: this.lockView });
558
+ }
559
+ return false;
560
+ }
561
+
562
+ if (!pidAlive(discovery.pid)) {
563
+ await unlink(this.paths.discoveryPath).catch(() => undefined);
564
+ this.#setState({
565
+ state: 'stopped',
566
+ degraded: false,
567
+ managed: false,
568
+ attached: false,
569
+ pid: null,
570
+ url: null,
571
+ healthUrl: null,
572
+ error: null,
573
+ lock: this.lockView,
574
+ });
575
+ return false;
576
+ }
577
+
578
+ const managed = Boolean(this.child && this.child.pid === discovery.pid);
579
+ if (this.#homeMismatch(discovery)) {
580
+ this.#setState({
581
+ state: 'failed',
582
+ degraded: false,
583
+ managed,
584
+ attached: !managed,
585
+ pid: discovery.pid,
586
+ url: discovery.url,
587
+ healthUrl: discovery.healthUrl,
588
+ runtimeVersion: discovery.runtimeVersion ?? null,
589
+ apiVersion: discovery.apiVersion ?? null,
590
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
591
+ error: publicError('home_mismatch', '已有 sidecar 使用不同的数据目录:拒绝接管'),
592
+ lock: this.lockView,
593
+ });
594
+ return false;
595
+ }
596
+ if (this.#profileMismatch(discovery)) {
597
+ this.#setState({
598
+ state: 'failed',
599
+ degraded: false,
600
+ managed,
601
+ attached: !managed,
602
+ pid: discovery.pid,
603
+ url: discovery.url,
604
+ healthUrl: discovery.healthUrl,
605
+ runtimeVersion: discovery.runtimeVersion ?? null,
606
+ apiVersion: discovery.apiVersion ?? null,
607
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
608
+ error: publicError('profile_mismatch', '已有 sidecar 属于其他 profile/忆云:拒绝接管'),
609
+ lock: this.lockView,
610
+ });
611
+ return false;
612
+ }
613
+ if (this.#versionMismatch(discovery)) {
614
+ this.#setState({
615
+ state: 'failed',
616
+ degraded: false,
617
+ managed,
618
+ attached: !managed,
619
+ pid: discovery.pid,
620
+ url: discovery.url,
621
+ healthUrl: discovery.healthUrl,
622
+ runtimeVersion: discovery.runtimeVersion ?? null,
623
+ apiVersion: discovery.apiVersion ?? null,
624
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
625
+ error: publicError('version_incompatible', 'sidecar 版本与 MCP capability 不兼容'),
626
+ lock: this.lockView,
627
+ });
628
+ return false;
629
+ }
630
+
631
+ const health = fetchHealth ? await this.#fetchHealth(discovery) : { ok: true };
632
+ if (health.ok) {
633
+ this.readySeen = true;
634
+ const degraded = discovery.degraded === true || health.degraded === true;
635
+ this.#setState({
636
+ state: degraded ? 'degraded' : 'ready',
637
+ degraded,
638
+ managed,
639
+ attached: !managed,
640
+ pid: discovery.pid,
641
+ url: discovery.url,
642
+ healthUrl: discovery.healthUrl,
643
+ runtimeVersion: discovery.runtimeVersion ?? null,
644
+ apiVersion: discovery.apiVersion ?? null,
645
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
646
+ startedAt: discovery.startedAt ?? null,
647
+ lastOkAt: this.now(),
648
+ restarts: this.restarts,
649
+ reason: null,
650
+ error: degraded ? this.#degradedError() : null,
651
+ lock: this.lockView,
652
+ });
653
+ return true;
654
+ }
655
+
656
+ const starting = managed && !this.readySeen;
657
+ this.#setState({
658
+ state: starting ? 'starting' : 'degraded',
659
+ degraded: !starting,
660
+ managed,
661
+ attached: !managed,
662
+ pid: discovery.pid,
663
+ url: discovery.url,
664
+ healthUrl: discovery.healthUrl,
665
+ runtimeVersion: discovery.runtimeVersion ?? null,
666
+ apiVersion: discovery.apiVersion ?? null,
667
+ capabilityApiVersion: discovery.capabilityApiVersion ?? null,
668
+ startedAt: discovery.startedAt ?? null,
669
+ restarts: this.restarts,
670
+ error: starting ? null : publicError('health_check_failed', 'sidecar 健康检查失败'),
671
+ lock: this.lockView,
672
+ });
673
+ return false;
674
+ }
675
+
676
+ async status() {
677
+ if (!this.isEnabled() && !this.statusState.managed && !this.statusState.pid) {
678
+ this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
679
+ }
680
+ try {
681
+ await this.#refreshDiscovery({ fetchHealth: true });
682
+ } catch {
683
+ this.#setState({ error: publicError('status_failed', '无法读取 sidecar 状态') });
684
+ }
685
+ return this.snapshot();
686
+ }
687
+
688
+ /**
689
+ * 只读 sidecar `/status` 的最小视图:模式、版本、模型来源/降级。
690
+ * 不返回 host token、keyRef、endpoint、模型路径或配置正文。
691
+ */
692
+ async readStatus() {
693
+ const result = await this.#proxyHostApi('status');
694
+ if (!result.available) {
695
+ return {
696
+ ok: !result.error,
697
+ enabled: result.enabled,
698
+ available: false,
699
+ disabled: result.disabled === true,
700
+ state: result.state,
701
+ reason: result.reason ?? null,
702
+ error: result.error ?? null,
703
+ mode: null,
704
+ runtimeVersion: null,
705
+ degraded: result.state === 'degraded',
706
+ model: null,
707
+ };
708
+ }
709
+ const data = result.body?.data ?? result.body ?? {};
710
+ const model = isObject(data.model)
711
+ ? {
712
+ configured: typeof data.model.configured === 'string' ? data.model.configured : null,
713
+ active: typeof data.model.active === 'string' ? data.model.active : null,
714
+ degraded: data.model.degraded === true,
715
+ reason: typeof data.model.reason === 'string' ? data.model.reason : null,
716
+ sources: Array.isArray(data.model.sources)
717
+ ? data.model.sources.filter((source) => typeof source === 'string')
718
+ : [],
719
+ }
720
+ : null;
721
+ return {
722
+ ok: result.ok !== false,
723
+ enabled: true,
724
+ available: true,
725
+ disabled: false,
726
+ state: result.state,
727
+ reason: null,
728
+ error: result.ok === false
729
+ ? publicError(
730
+ data?.error?.code ?? result.body?.error?.code ?? 'sidecar_request_failed',
731
+ proxyErrorMessage(data, proxyErrorMessage(result.body, '读取记忆运行时状态失败')),
732
+ )
733
+ : null,
734
+ mode: typeof data.mode === 'string' ? data.mode : null,
735
+ runtimeVersion: typeof data.runtimeVersion === 'string' ? data.runtimeVersion : null,
736
+ degraded: data.degraded === true || result.body?.degraded === true,
737
+ model,
738
+ };
739
+ }
740
+
741
+ /**
742
+ * 统一 host API 代理:服务端读取 host token,调用方只拿到脱敏数据。
743
+ *
744
+ * 返回扁平结果,不抛异常:
745
+ * { ok, status, enabled, available, disabled, state, data, warnings, degraded, error }
746
+ * 轻量模式 → memory_runtime_disabled;未就绪 → memory_runtime_unavailable。
747
+ */
748
+ async request(path, { method = 'GET', body = null, timeoutMs = 5000 } = {}) {
749
+ const relative = typeof path === 'string' ? path.replace(/^\/+/, '') : '';
750
+ if (relative.length === 0 || relative.includes('..') || relative.includes('\\')) {
751
+ return {
752
+ ok: false,
753
+ status: 400,
754
+ enabled: this.isEnabled(),
755
+ available: false,
756
+ disabled: false,
757
+ state: this.statusState.state,
758
+ data: null,
759
+ warnings: [],
760
+ degraded: false,
761
+ error: { code: 'invalid_request', message: 'sidecar 请求路径非法', retryable: false },
762
+ };
763
+ }
764
+ const result = await this.#proxyHostApi(relative, {
765
+ method: String(method).toUpperCase(),
766
+ body,
767
+ timeoutMs,
768
+ });
769
+ if (!result.available) {
770
+ const disabled = result.disabled === true;
771
+ return {
772
+ ok: false,
773
+ status: disabled ? 409 : 503,
774
+ enabled: result.enabled === true,
775
+ available: false,
776
+ disabled,
777
+ state: result.state,
778
+ data: null,
779
+ warnings: [],
780
+ degraded: result.state === 'degraded',
781
+ error: {
782
+ code: disabled ? 'memory_runtime_disabled' : 'memory_runtime_unavailable',
783
+ message: disabled ? '记忆运行时未启用' : 'Memory Runtime sidecar 未就绪',
784
+ retryable: !disabled,
785
+ ...(result.reason ? { reason: result.reason } : {}),
786
+ },
787
+ };
788
+ }
789
+ if (!result.ok) {
790
+ const envelope = isObject(result.body) ? result.body : {};
791
+ const rawError = isObject(envelope.error) ? envelope.error : {};
792
+ const code = typeof rawError.code === 'string'
793
+ ? rawError.code
794
+ : typeof envelope.error === 'string' ? envelope.error : 'sidecar_request_failed';
795
+ const statusCode = Number.isInteger(result.statusCode) ? result.statusCode : 502;
796
+ return {
797
+ ok: false,
798
+ status: statusCode >= 400 && statusCode < 500 ? statusCode : 502,
799
+ enabled: true,
800
+ available: true,
801
+ disabled: false,
802
+ state: result.state,
803
+ data: null,
804
+ warnings: Array.isArray(envelope.warnings) ? envelope.warnings : [],
805
+ degraded: envelope.degraded === true || result.state === 'degraded',
806
+ error: {
807
+ code,
808
+ message: proxyErrorMessage(envelope, 'sidecar 请求失败'),
809
+ retryable: rawError.retryable === true,
810
+ ...(isObject(rawError.details) ? { details: rawError.details } : {}),
811
+ },
812
+ };
813
+ }
814
+ const envelope = isObject(result.body) ? result.body : {};
815
+ const data = envelope.data ?? result.body ?? null;
816
+ return {
817
+ ok: true,
818
+ status: Number.isInteger(result.statusCode) ? result.statusCode : 200,
819
+ enabled: true,
820
+ available: true,
821
+ disabled: false,
822
+ state: result.state,
823
+ data,
824
+ warnings: Array.isArray(envelope.warnings) ? envelope.warnings : [],
825
+ degraded: envelope.degraded === true || result.state === 'degraded',
826
+ error: null,
827
+ };
828
+ }
829
+
830
+ async listModels() {
831
+ return this.request('models');
832
+ }
833
+
834
+ async modelStatus(packId) {
835
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/status`);
836
+ }
837
+
838
+ async installModel(packId, { force = false } = {}) {
839
+ const suffix = force === true ? '?force=true' : '';
840
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/install${suffix}`, {
841
+ method: 'POST',
842
+ timeoutMs: 10_000,
843
+ });
844
+ }
845
+
846
+ async getInstall(jobId) {
847
+ return this.request(`installs/${encodeURIComponent(String(jobId ?? ''))}`);
848
+ }
849
+
850
+ async cancelInstall(jobId) {
851
+ return this.request(`installs/${encodeURIComponent(String(jobId ?? ''))}/cancel`, {
852
+ method: 'POST',
853
+ });
854
+ }
855
+
856
+ async activateModel(packId) {
857
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/activate`, {
858
+ method: 'POST',
859
+ timeoutMs: 30_000,
860
+ });
861
+ }
862
+
863
+ async deactivateModel(packId) {
864
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/deactivate`, {
865
+ method: 'POST',
866
+ timeoutMs: 15_000,
867
+ });
868
+ }
869
+
870
+ async startEngine(packId) {
871
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/start`, {
872
+ method: 'POST',
873
+ timeoutMs: 30_000,
874
+ });
875
+ }
876
+
877
+ async stopEngine(packId) {
878
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/stop`, {
879
+ method: 'POST',
880
+ timeoutMs: 15_000,
881
+ });
882
+ }
883
+
884
+ async removeModel(packId) {
885
+ return this.request(`models/${encodeURIComponent(String(packId ?? ''))}/remove`, {
886
+ method: 'POST',
887
+ timeoutMs: 15_000,
888
+ });
889
+ }
890
+
891
+ async inferenceStatus() {
892
+ return this.request('inference');
893
+ }
894
+
895
+ async updateInferenceSettings(input) {
896
+ return this.request('inference/settings', {
897
+ method: 'POST',
898
+ body: isObject(input) ? input : {},
899
+ });
900
+ }
901
+
902
+ /**
903
+ * Console 只读代理:服务端读取 host token,浏览器只拿到脱敏后的 sidecar 视图。
904
+ * 轻量模式/未就绪时返回明确状态,不启动进程、不创建 token。
905
+ */
906
+ async readTraces({ limit = 20 } = {}) {
907
+ const requested = Number(limit);
908
+ const safeLimit = Number.isFinite(requested) ? Math.min(Math.max(Math.trunc(requested), 1), 100) : 20;
909
+ const result = await this.#proxyHostApi(`traces?limit=${safeLimit}`);
910
+ if (!result.available) {
911
+ return {
912
+ ok: !result.error,
913
+ enabled: result.enabled,
914
+ available: false,
915
+ disabled: result.disabled === true,
916
+ state: result.state,
917
+ reason: result.reason ?? null,
918
+ error: result.error ?? null,
919
+ traces: [],
920
+ total: 0,
921
+ degraded: result.state === 'degraded',
922
+ warnings: [],
923
+ };
924
+ }
925
+ const data = result.body?.data ?? result.body ?? {};
926
+ const traces = Array.isArray(data.traces) ? data.traces : [];
927
+ if (!result.ok) {
928
+ return {
929
+ ok: false,
930
+ enabled: true,
931
+ available: true,
932
+ disabled: false,
933
+ state: result.state,
934
+ error: publicError(
935
+ data?.error?.code ?? result.body?.error?.code ?? 'sidecar_request_failed',
936
+ proxyErrorMessage(data, proxyErrorMessage(result.body, '读取召回轨迹失败')),
937
+ ),
938
+ traces: [],
939
+ total: 0,
940
+ degraded: true,
941
+ warnings: [],
942
+ };
943
+ }
944
+ return {
945
+ ok: true,
946
+ enabled: true,
947
+ available: true,
948
+ disabled: false,
949
+ state: result.state,
950
+ degraded: data.degraded === true || result.body?.degraded === true,
951
+ traces,
952
+ total: Number.isInteger(data.total) ? data.total : traces.length,
953
+ warnings: Array.isArray(result.body?.warnings) ? result.body.warnings : [],
954
+ };
955
+ }
956
+
957
+ async readTrace(id) {
958
+ const traceId = typeof id === 'string' ? id.trim() : '';
959
+ if (!/^tr_[A-Za-z0-9._:-]{1,128}$/.test(traceId)) {
960
+ return {
961
+ ok: false,
962
+ enabled: this.isEnabled(),
963
+ available: false,
964
+ disabled: !this.isEnabled(),
965
+ state: this.statusState.state,
966
+ trace: null,
967
+ error: publicError('invalid_trace_id', 'trace id 格式非法'),
968
+ };
969
+ }
970
+ const result = await this.#proxyHostApi(`traces/${encodeURIComponent(traceId)}`);
971
+ if (!result.available) {
972
+ return {
973
+ ok: !result.error,
974
+ enabled: result.enabled,
975
+ available: false,
976
+ disabled: result.disabled === true,
977
+ state: result.state,
978
+ reason: result.reason ?? null,
979
+ error: result.error ?? null,
980
+ trace: null,
981
+ };
982
+ }
983
+ const data = result.body?.data ?? result.body ?? null;
984
+ if (!result.ok || !data) {
985
+ return {
986
+ ok: false,
987
+ enabled: true,
988
+ available: true,
989
+ disabled: false,
990
+ state: result.state,
991
+ trace: null,
992
+ error: publicError(
993
+ data?.error?.code ?? result.body?.error?.code ?? (result.statusCode === 404 ? 'trace_not_found' : 'sidecar_request_failed'),
994
+ proxyErrorMessage(data, proxyErrorMessage(result.body, '读取召回轨迹详情失败')),
995
+ ),
996
+ };
997
+ }
998
+ return {
999
+ ok: true,
1000
+ enabled: true,
1001
+ available: true,
1002
+ disabled: false,
1003
+ state: result.state,
1004
+ trace: data,
1005
+ degraded: result.body?.degraded === true,
1006
+ };
1007
+ }
1008
+
1009
+ async submitRecallFeedback(traceId, feedback) {
1010
+ const id = typeof traceId === 'string' ? traceId.trim() : '';
1011
+ if (!/^tr_[A-Za-z0-9._:-]{1,128}$/.test(id)) {
1012
+ return { statusCode: 400, body: { ok: false, error: 'invalid_trace_id', message: 'trace id 格式非法' } };
1013
+ }
1014
+ if (!isObject(feedback) || typeof feedback.useful !== 'boolean') {
1015
+ return { statusCode: 400, body: { ok: false, error: 'invalid_feedback', message: 'feedback.useful 必须是布尔值' } };
1016
+ }
1017
+ const body = {
1018
+ useful: feedback.useful,
1019
+ ...(typeof feedback.reason === 'string' && feedback.reason.length > 0
1020
+ ? { reason: feedback.reason.slice(0, 200) }
1021
+ : {}),
1022
+ };
1023
+ const result = await this.#proxyHostApi(`recall/${encodeURIComponent(id)}/feedback`, { method: 'POST', body });
1024
+ if (!result.available) {
1025
+ return {
1026
+ statusCode: result.disabled === true ? 409 : 503,
1027
+ body: {
1028
+ ok: false,
1029
+ error: result.disabled === true ? 'memory_runtime_disabled' : 'sidecar_unavailable',
1030
+ enabled: result.enabled,
1031
+ state: result.state,
1032
+ message: result.disabled === true
1033
+ ? '记忆运行时未启用'
1034
+ : 'Memory Runtime sidecar 未就绪',
1035
+ ...(result.error ? { details: result.error } : {}),
1036
+ },
1037
+ };
1038
+ }
1039
+ const data = result.body?.data ?? result.body ?? null;
1040
+ if (!result.ok) {
1041
+ return {
1042
+ statusCode: result.statusCode ?? 502,
1043
+ body: {
1044
+ ok: false,
1045
+ error: data?.error?.code ?? result.body?.error?.code ?? 'feedback_failed',
1046
+ message: proxyErrorMessage(data, proxyErrorMessage(result.body, '召回反馈失败')),
1047
+ },
1048
+ };
1049
+ }
1050
+ return { statusCode: 200, body: result.body ?? { ok: true, data } };
1051
+ }
1052
+
1053
+ async #resolveHostToken(discovery) {
1054
+ if (this.child && discovery?.pid === this.child.pid && typeof this.childToken === 'string') {
1055
+ return this.childToken;
1056
+ }
1057
+ const fromEnv = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN);
1058
+ if (fromEnv) return fromEnv;
1059
+ if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return null;
1060
+ // 只读当前 home 的 sidecar token;discovery 路径不匹配时拒绝读取。
1061
+ if (resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir) return null;
1062
+ try {
1063
+ const token = (await readFile(discovery.tokenFile, 'utf-8')).trim();
1064
+ return token.length > 0 ? token : null;
1065
+ } catch {
1066
+ return null;
1067
+ }
1068
+ }
1069
+
1070
+ async #proxyHostApi(pathname, { method = 'GET', body = null, timeoutMs = 2500 } = {}) {
1071
+ await this.status().catch(() => undefined);
1072
+ if (!this.isEnabled()) {
1073
+ return {
1074
+ enabled: false,
1075
+ available: false,
1076
+ disabled: true,
1077
+ state: 'stopped',
1078
+ reason: 'disabled',
1079
+ error: null,
1080
+ };
1081
+ }
1082
+ if (!['ready', 'degraded'].includes(this.statusState.state) || typeof this.statusState.url !== 'string') {
1083
+ return {
1084
+ enabled: true,
1085
+ available: false,
1086
+ disabled: false,
1087
+ state: this.statusState.state,
1088
+ reason: this.statusState.reason ?? null,
1089
+ error: this.statusState.error ?? publicError('sidecar_unavailable', 'Memory Runtime sidecar 未就绪'),
1090
+ };
1091
+ }
1092
+ const discovery = await readDiscovery(this.paths.discoveryPath);
1093
+ if (!discovery) {
1094
+ return {
1095
+ enabled: true,
1096
+ available: false,
1097
+ disabled: false,
1098
+ state: this.statusState.state,
1099
+ reason: null,
1100
+ error: publicError('discovery_missing', 'sidecar discovery 缺失'),
1101
+ };
1102
+ }
1103
+ const token = await this.#resolveHostToken(discovery);
1104
+ if (!token) {
1105
+ return {
1106
+ enabled: true,
1107
+ available: false,
1108
+ disabled: false,
1109
+ state: this.statusState.state,
1110
+ reason: null,
1111
+ error: publicError('host_token_missing', '无法读取 sidecar host token'),
1112
+ };
1113
+ }
1114
+ if (!this.fetchImpl) {
1115
+ return {
1116
+ enabled: true,
1117
+ available: false,
1118
+ disabled: false,
1119
+ state: this.statusState.state,
1120
+ reason: null,
1121
+ error: publicError('fetch_unavailable', '当前运行环境不支持 HTTP 代理'),
1122
+ };
1123
+ }
1124
+ const controller = new AbortController();
1125
+ const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs));
1126
+ timer.unref?.();
1127
+ try {
1128
+ const base = discovery.url.replace(/\/+$/, '');
1129
+ const url = new URL(`${base}/${String(pathname).replace(/^\/+/, '')}`);
1130
+ const headers = {
1131
+ accept: 'application/json',
1132
+ authorization: `Bearer ${token}`,
1133
+ };
1134
+ const init = { method, headers, signal: controller.signal };
1135
+ if (body !== null && body !== undefined) {
1136
+ headers['content-type'] = 'application/json';
1137
+ init.body = JSON.stringify(body);
1138
+ }
1139
+ const response = await this.fetchImpl(url.toString(), init);
1140
+ const text = await response.text().catch(() => '');
1141
+ let parsed = null;
1142
+ try {
1143
+ parsed = text.length > 0 ? JSON.parse(text) : null;
1144
+ } catch {
1145
+ parsed = null;
1146
+ }
1147
+ const scrubbed = scrubProxyValue(parsed, [token, this.childToken]);
1148
+ return {
1149
+ enabled: true,
1150
+ available: true,
1151
+ disabled: false,
1152
+ state: this.statusState.state,
1153
+ statusCode: response.status,
1154
+ ok: response.ok === true,
1155
+ body: scrubbed,
1156
+ ...(parsed === null && text.length > 0 ? { message: redact(text, [token]) } : {}),
1157
+ };
1158
+ } catch (error) {
1159
+ return {
1160
+ enabled: true,
1161
+ available: false,
1162
+ disabled: false,
1163
+ state: this.statusState.state,
1164
+ reason: null,
1165
+ error: publicError(
1166
+ error?.name === 'AbortError' ? 'sidecar_timeout' : 'sidecar_unreachable',
1167
+ error?.name === 'AbortError' ? 'sidecar 请求超时' : '无法连接 Memory Runtime sidecar',
1168
+ ),
1169
+ };
1170
+ } finally {
1171
+ clearTimeout(timer);
1172
+ }
1173
+ }
1174
+
1175
+ #resolveCommand() {
1176
+ if (this.explicitCommand) {
1177
+ const command = resolve(this.explicitCommand);
1178
+ this.installed = executableExists(command);
1179
+ this.commandSource = 'explicit';
1180
+ return this.installed
1181
+ ? { ok: true, command, source: 'explicit' }
1182
+ : { ok: false, command, source: 'explicit', reason: 'not_installed' };
1183
+ }
1184
+ const resolved = resolveMemoryRuntimeCommand({ config: this.getConfig(), env: this.env });
1185
+ this.installed = resolved.ok === true;
1186
+ this.commandSource = resolved.source;
1187
+ return resolved;
1188
+ }
1189
+
1190
+ async #resolveCapabilityToken() {
1191
+ if (typeof this.getCapabilityToken === 'function') {
1192
+ try {
1193
+ const value = await this.getCapabilityToken();
1194
+ const token = typeof value === 'string' ? value : value?.token;
1195
+ if (typeof token === 'string' && token.length > 0) return token;
1196
+ } catch {
1197
+ // fall through to env/file
1198
+ }
1199
+ }
1200
+ const fromEnv = stringOrNull(this.env?.MEBULAR_CAPABILITY_TOKEN);
1201
+ if (fromEnv) return fromEnv;
1202
+ const record = await readJson(this.paths.capabilityTokenPath, null);
1203
+ return typeof record?.token === 'string' && record.token.length > 0 ? record.token : null;
1204
+ }
1205
+
1206
+ async #waitForDiscovery(deadline) {
1207
+ for (;;) {
1208
+ if (this.stopping || this.disposed) return false;
1209
+ const ready = await this.#refreshDiscovery({ fetchHealth: true });
1210
+ if (ready) return true;
1211
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1212
+ return false;
1213
+ }
1214
+ const lock = await readLock(this.paths.lockPath);
1215
+ if (!lock || !pidAlive(lock.pid)) {
1216
+ this.lockView = null;
1217
+ return false;
1218
+ }
1219
+ if (this.now() >= deadline) return false;
1220
+ await sleep(Math.min(this.healthPollMs, Math.max(1, deadline - this.now())));
1221
+ }
1222
+ }
1223
+
1224
+ async #waitForReady(deadline, child) {
1225
+ while (this.child === child && child.exitCode === null) {
1226
+ if (this.stopping || this.disposed) return false;
1227
+ const ready = await this.#refreshDiscovery({ fetchHealth: true });
1228
+ if (ready && this.statusState.pid === child.pid) return true;
1229
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1230
+ return false;
1231
+ }
1232
+ if (this.now() >= deadline) return false;
1233
+ await sleep(Math.min(this.healthPollMs, Math.max(1, deadline - this.now())));
1234
+ }
1235
+ return false;
1236
+ }
1237
+
1238
+ #clearRestartTimer() {
1239
+ if (this.restartTimer) {
1240
+ clearTimeout(this.restartTimer);
1241
+ this.restartTimer = null;
1242
+ }
1243
+ }
1244
+
1245
+ #clearCooldownTimer() {
1246
+ if (this.cooldownTimer) {
1247
+ clearTimeout(this.cooldownTimer);
1248
+ this.cooldownTimer = null;
1249
+ }
1250
+ }
1251
+
1252
+ #stopWatchdog() {
1253
+ if (this.watchdogTimer) {
1254
+ clearInterval(this.watchdogTimer);
1255
+ this.watchdogTimer = null;
1256
+ }
1257
+ }
1258
+
1259
+ #startWatchdog() {
1260
+ this.#stopWatchdog();
1261
+ if (!this.healthCheckIntervalMs || this.healthCheckIntervalMs <= 0) return;
1262
+ this.watchdogTimer = setInterval(() => {
1263
+ if (this.disposed || this.stopping) return;
1264
+ void (async () => {
1265
+ const healthy = await this.#refreshDiscovery({ fetchHealth: true });
1266
+ if (healthy) {
1267
+ this.healthFailures = 0;
1268
+ return;
1269
+ }
1270
+ if (this.statusState.error?.code !== 'health_check_failed') return;
1271
+ this.healthFailures += 1;
1272
+ if (this.healthFailures < 3) return;
1273
+ this.healthFailures = 0;
1274
+ if (this.child && this.child.exitCode === null) {
1275
+ this.#setState({ error: publicError('health_check_failed', 'sidecar 连续健康检查失败') });
1276
+ this.#killChild('SIGTERM');
1277
+ } else {
1278
+ this.#setState({
1279
+ state: 'degraded',
1280
+ degraded: true,
1281
+ error: publicError('health_check_failed', 'sidecar 连续健康检查失败'),
1282
+ });
1283
+ }
1284
+ })().catch(() => undefined);
1285
+ }, this.healthCheckIntervalMs);
1286
+ this.watchdogTimer.unref?.();
1287
+ }
1288
+
1289
+ #pruneCrashTimes() {
1290
+ const cutoff = this.now() - this.restartWindowMs;
1291
+ this.crashTimes = this.crashTimes.filter((at) => at >= cutoff);
1292
+ }
1293
+
1294
+ #scheduleRestart() {
1295
+ this.#clearRestartTimer();
1296
+ if (this.disposed || this.stopping || this.manualStart) return;
1297
+ if (!this.restartOnFailure || this.maxRestartsInWindow <= 0) return;
1298
+ if (!this.isEnabled()) return;
1299
+ this.#pruneCrashTimes();
1300
+ if (this.crashTimes.length > this.maxRestartsInWindow) {
1301
+ this.#setState({
1302
+ state: 'failed',
1303
+ degraded: false,
1304
+ error: publicError('restart_limit', 'sidecar 崩溃次数超过上限:已暂停自动重启'),
1305
+ });
1306
+ this.#clearCooldownTimer();
1307
+ this.cooldownTimer = setTimeout(() => {
1308
+ this.crashTimes = [];
1309
+ this.restarts = 0;
1310
+ this.#clearCooldownTimer();
1311
+ }, Math.max(1000, this.restartCooldownMs));
1312
+ this.cooldownTimer.unref?.();
1313
+ return;
1314
+ }
1315
+ const exponent = Math.max(0, this.crashTimes.length - 1);
1316
+ const delay = Math.min(this.restartBackoffMs * (2 ** exponent), this.restartBackoffMaxMs);
1317
+ this.restartTimer = setTimeout(() => {
1318
+ this.restartTimer = null;
1319
+ if (this.disposed || this.stopping || !this.isEnabled()) return;
1320
+ void this.#startOnce({ force: false, isRestart: true }).catch(() => undefined);
1321
+ }, Math.max(10, delay));
1322
+ this.restartTimer.unref?.();
1323
+ }
1324
+
1325
+ #killChild(signal) {
1326
+ const child = this.child;
1327
+ if (!child || child.exitCode !== null) return false;
1328
+ try {
1329
+ child.kill(signal);
1330
+ return true;
1331
+ } catch {
1332
+ return false;
1333
+ }
1334
+ }
1335
+
1336
+ async #waitChildExit(child, timeoutMs) {
1337
+ if (!child || child.exitCode !== null) return true;
1338
+ return new Promise((resolvePromise) => {
1339
+ let done = false;
1340
+ const finish = () => {
1341
+ if (done) return;
1342
+ done = true;
1343
+ clearTimeout(timer);
1344
+ child.removeListener?.('exit', finish);
1345
+ resolvePromise(child.exitCode !== null);
1346
+ };
1347
+ const timer = setTimeout(finish, Math.max(0, timeoutMs));
1348
+ timer.unref?.();
1349
+ child.once?.('exit', finish);
1350
+ if (child.exitCode !== null) finish();
1351
+ });
1352
+ }
1353
+
1354
+ #onChildExit(child, code, signal) {
1355
+ if (this.child !== child) return;
1356
+ this.child = null;
1357
+ this.#stopWatchdog();
1358
+ if (this.stopping || this.disposed) {
1359
+ this.#setState({
1360
+ state: 'stopped',
1361
+ degraded: false,
1362
+ managed: false,
1363
+ attached: false,
1364
+ pid: null,
1365
+ url: null,
1366
+ healthUrl: null,
1367
+ error: null,
1368
+ lock: this.lockView,
1369
+ });
1370
+ return;
1371
+ }
1372
+
1373
+ this.restarts += 1;
1374
+ this.crashTimes.push(this.now());
1375
+ this.#setState({
1376
+ state: 'failed',
1377
+ degraded: false,
1378
+ managed: false,
1379
+ attached: false,
1380
+ pid: null,
1381
+ url: null,
1382
+ healthUrl: null,
1383
+ restarts: this.restarts,
1384
+ error: publicError(
1385
+ 'sidecar_crashed',
1386
+ `sidecar 已退出(${signal ?? code ?? 'unknown'})`,
1387
+ ),
1388
+ lock: this.lockView,
1389
+ });
1390
+ this.#scheduleRestart();
1391
+ }
1392
+
1393
+ async #spawnSidecar({ manual }) {
1394
+ const resolved = this.#resolveCommand();
1395
+ if (!resolved.ok) {
1396
+ this.#setState({
1397
+ state: 'not_installed',
1398
+ degraded: false,
1399
+ installed: false,
1400
+ commandSource: resolved.source,
1401
+ error: publicError(resolved.reason ?? 'not_installed', '未找到 mebular-memory-runtime 可执行文件'),
1402
+ });
1403
+ return false;
1404
+ }
1405
+
1406
+ if (this.stopping || this.disposed) return false;
1407
+ const token = await this.#resolveCapabilityToken();
1408
+ if (this.stopping || this.disposed) return false;
1409
+ if (!token) {
1410
+ this.#setState({
1411
+ state: 'failed',
1412
+ degraded: false,
1413
+ installed: true,
1414
+ commandSource: resolved.source,
1415
+ error: publicError('capability_token_missing', '找不到 capability token:MCP 未启用或未启动 sidecar'),
1416
+ });
1417
+ return false;
1418
+ }
1419
+
1420
+ const hostToken = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN)
1421
+ ?? randomBytes(32).toString('base64url');
1422
+ this.childSecrets = [token, hostToken];
1423
+ const spec = commandSpec(resolved.command);
1424
+ const args = [
1425
+ ...spec.args,
1426
+ 'serve',
1427
+ ...(manual ? [] : ['--parent-pid', String(process.pid)]),
1428
+ ];
1429
+ const env = {
1430
+ ...process.env,
1431
+ ...this.env,
1432
+ MEBULAR_HOME: this.paths.home,
1433
+ MEBULAR_MEMORY_RUNTIME_HOME: this.paths.dataDir,
1434
+ MEBULAR_CAPABILITY_TOKEN: token,
1435
+ MEBULAR_MEMORY_RUNTIME_TOKEN: hostToken,
1436
+ ...(stringOrNull(this.getMcpUrl()) ? { MEBULAR_MCP_URL: stringOrNull(this.getMcpUrl()) } : {}),
1437
+ };
1438
+
1439
+ let child;
1440
+ try {
1441
+ child = this.spawnImpl(spec.execPath, args, {
1442
+ cwd: this.paths.home,
1443
+ env,
1444
+ detached: manual,
1445
+ windowsHide: true,
1446
+ stdio: manual ? 'ignore' : ['ignore', 'ignore', 'pipe'],
1447
+ });
1448
+ } catch (error) {
1449
+ this.#setState({
1450
+ state: 'failed',
1451
+ degraded: false,
1452
+ error: publicError('spawn_failed', `sidecar 启动失败(${error?.code ?? 'spawn_failed'})`),
1453
+ });
1454
+ return false;
1455
+ }
1456
+
1457
+ this.child = child;
1458
+ this.childToken = hostToken;
1459
+ this.manualStart = manual;
1460
+ this.readySeen = false;
1461
+ this.healthFailures = 0;
1462
+ this.commandSource = resolved.source;
1463
+ this.installed = true;
1464
+ this.#setState({
1465
+ state: 'starting',
1466
+ degraded: false,
1467
+ managed: true,
1468
+ attached: false,
1469
+ pid: child.pid ?? null,
1470
+ url: null,
1471
+ healthUrl: null,
1472
+ runtimeVersion: null,
1473
+ apiVersion: null,
1474
+ capabilityApiVersion: null,
1475
+ commandSource: resolved.source,
1476
+ installed: true,
1477
+ startedAt: this.now(),
1478
+ lastOkAt: null,
1479
+ restarts: this.restarts,
1480
+ reason: null,
1481
+ error: null,
1482
+ });
1483
+
1484
+ child.once?.('error', (error) => {
1485
+ if (this.child !== child) return;
1486
+ this.#setState({
1487
+ state: 'failed',
1488
+ degraded: false,
1489
+ error: publicError('spawn_failed', `sidecar 启动失败(${error?.code ?? 'spawn_failed'})`),
1490
+ });
1491
+ });
1492
+ child.once?.('exit', (code, signal) => this.#onChildExit(child, code, signal));
1493
+ if (child.stderr) {
1494
+ child.stderr.on('data', (chunk) => {
1495
+ const text = redact(chunk?.toString?.('utf-8') ?? '', this.childSecrets);
1496
+ if (text.trim().length > 0) this.lastStderr = text;
1497
+ });
1498
+ }
1499
+
1500
+ const deadline = this.now() + Math.max(100, this.configuredStartTimeout());
1501
+ const ready = await this.#waitForReady(deadline, child);
1502
+ if (ready) {
1503
+ this.#startWatchdog();
1504
+ if (manual) child.unref?.();
1505
+ return true;
1506
+ }
1507
+ if (this.stopping || this.disposed) return false;
1508
+
1509
+ if (this.child === child) {
1510
+ // 先解除归属,避免 SIGTERM 触发的 exit handler 把超时当成一次崩溃并重复排程。
1511
+ this.child = null;
1512
+ this.#stopWatchdog();
1513
+ try {
1514
+ child.kill('SIGTERM');
1515
+ } catch {
1516
+ // already gone
1517
+ }
1518
+ await this.#waitChildExit(child, 500);
1519
+ if (child.exitCode === null) {
1520
+ try {
1521
+ child.kill('SIGKILL');
1522
+ } catch {
1523
+ // already gone
1524
+ }
1525
+ await this.#waitChildExit(child, 500);
1526
+ }
1527
+ this.restarts += 1;
1528
+ this.crashTimes.push(this.now());
1529
+ this.#setState({
1530
+ state: 'failed',
1531
+ degraded: false,
1532
+ managed: false,
1533
+ attached: false,
1534
+ pid: null,
1535
+ url: null,
1536
+ healthUrl: null,
1537
+ restarts: this.restarts,
1538
+ error: publicError('start_timeout', 'sidecar 启动超时'),
1539
+ });
1540
+ this.#scheduleRestart();
1541
+ }
1542
+ return false;
1543
+ }
1544
+
1545
+ async #startOnce({ force = false, manual = false, isRestart = false } = {}) {
1546
+ if (this.disposed) return this.snapshot();
1547
+ this.stopping = false;
1548
+
1549
+ const discovered = await this.#refreshDiscovery({ fetchHealth: true });
1550
+ if (discovered && ['ready', 'degraded'].includes(this.statusState.state)) {
1551
+ this.#startWatchdog();
1552
+ return this.snapshot();
1553
+ }
1554
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1555
+ return this.snapshot();
1556
+ }
1557
+ if (this.stopping || this.disposed) return this.snapshot();
1558
+
1559
+ if (!force && !this.isEnabled()) {
1560
+ this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
1561
+ return this.snapshot();
1562
+ }
1563
+ if (!force && this.env?.MEBULAR_MEMORY_RUNTIME_DISABLE === '1') {
1564
+ this.#setState({
1565
+ state: 'stopped',
1566
+ degraded: false,
1567
+ managed: false,
1568
+ attached: false,
1569
+ pid: null,
1570
+ reason: 'disabled',
1571
+ error: null,
1572
+ });
1573
+ return this.snapshot();
1574
+ }
1575
+
1576
+ const existing = await readDiscovery(this.paths.discoveryPath);
1577
+ if (existing && pidAlive(existing.pid)) {
1578
+ // 存活但未通过 health/版本校验:不启动第二个实例。
1579
+ this.#setState({
1580
+ state: 'degraded',
1581
+ degraded: true,
1582
+ managed: false,
1583
+ attached: true,
1584
+ pid: existing.pid,
1585
+ url: existing.url,
1586
+ healthUrl: existing.healthUrl,
1587
+ error: publicError('sidecar_unhealthy', '已有 sidecar 未就绪:不重复启动'),
1588
+ });
1589
+ return this.snapshot();
1590
+ }
1591
+ if (existing) await unlink(this.paths.discoveryPath).catch(() => undefined);
1592
+
1593
+ const lock = await this.#readLockView();
1594
+ if (lock && pidAlive(lock.pid)) {
1595
+ const expectedProfile = this.#profileId();
1596
+ const expectedCloud = this.#cloudId();
1597
+ if ((expectedProfile && lock.profileId && expectedProfile !== lock.profileId)
1598
+ || (expectedCloud && lock.cloudId && expectedCloud !== lock.cloudId)) {
1599
+ this.#setState({
1600
+ state: 'failed',
1601
+ degraded: false,
1602
+ error: publicError('profile_mismatch', '已有 sidecar 启动锁属于其他 profile/忆云:拒绝接管'),
1603
+ lock: this.lockView,
1604
+ });
1605
+ return this.snapshot();
1606
+ }
1607
+ const deadline = this.now() + Math.max(100, this.configuredStartTimeout());
1608
+ const ready = await this.#waitForDiscovery(deadline);
1609
+ if (ready) {
1610
+ this.#startWatchdog();
1611
+ return this.snapshot();
1612
+ }
1613
+ if (this.stopping || this.disposed) return this.snapshot();
1614
+ if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1615
+ return this.snapshot();
1616
+ }
1617
+ this.#setState({
1618
+ state: 'failed',
1619
+ degraded: false,
1620
+ error: publicError('sidecar_starting', '已有 sidecar 正在启动但未在超时内就绪'),
1621
+ lock: this.lockView,
1622
+ });
1623
+ return this.snapshot();
1624
+ }
1625
+ // 陈旧/损坏锁交给 sidecar 自己原子接管;supervisor 不删除 start.lock,避免误删并发新实例。
1626
+ if (this.stopping || this.disposed) return this.snapshot();
1627
+ if (isRestart) this.#pruneCrashTimes();
1628
+ await this.#spawnSidecar({ manual });
1629
+ return this.snapshot();
1630
+ }
1631
+
1632
+ async start({ force = false, manual = false } = {}) {
1633
+ if (this.disposed) return this.snapshot();
1634
+ if (this.startPromise) return this.startPromise;
1635
+ this.startPromise = this.#startOnce({ force, manual })
1636
+ .catch((error) => this.#setState({
1637
+ state: 'failed',
1638
+ degraded: false,
1639
+ error: publicError(error?.code ?? 'supervisor_error', 'sidecar supervisor 异常'),
1640
+ }))
1641
+ .finally(() => {
1642
+ this.startPromise = null;
1643
+ });
1644
+ return this.startPromise;
1645
+ }
1646
+
1647
+ async #stopPid(pid, timeoutMs) {
1648
+ if (!pidAlive(pid)) return true;
1649
+ try {
1650
+ process.kill(pid, 'SIGTERM');
1651
+ } catch {
1652
+ return !pidAlive(pid);
1653
+ }
1654
+ const deadline = this.now() + Math.max(0, timeoutMs);
1655
+ while (pidAlive(pid) && this.now() < deadline) await sleep(25);
1656
+ if (pidAlive(pid)) {
1657
+ try {
1658
+ process.kill(pid, 'SIGKILL');
1659
+ } catch {
1660
+ // already gone
1661
+ }
1662
+ const killDeadline = this.now() + 500;
1663
+ while (pidAlive(pid) && this.now() < killDeadline) await sleep(25);
1664
+ }
1665
+ return !pidAlive(pid);
1666
+ }
1667
+
1668
+ async stop({ includeAttached = false, timeoutMs = 5000 } = {}) {
1669
+ this.stopping = true;
1670
+ this.#clearRestartTimer();
1671
+ this.#clearCooldownTimer();
1672
+ this.#stopWatchdog();
1673
+
1674
+ // 让正在启动的流程看到 stopping 并退出,避免它在本函数返回后又拉起子进程。
1675
+ if (this.startPromise) {
1676
+ await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1677
+ }
1678
+ const child = this.child;
1679
+ if (child) {
1680
+ this.#killChild('SIGTERM');
1681
+ await this.#waitChildExit(child, timeoutMs);
1682
+ if (child.exitCode === null) {
1683
+ this.#killChild('SIGKILL');
1684
+ await this.#waitChildExit(child, 500);
1685
+ }
1686
+ if (this.child === child) this.child = null;
1687
+ }
1688
+ if (this.startPromise) {
1689
+ await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1690
+ }
1691
+ const lateChild = this.child;
1692
+ if (lateChild && lateChild !== child) {
1693
+ this.#killChild('SIGTERM');
1694
+ await this.#waitChildExit(lateChild, Math.min(timeoutMs, 1000));
1695
+ if (lateChild.exitCode === null) this.#killChild('SIGKILL');
1696
+ if (this.child === lateChild) this.child = null;
1697
+ }
1698
+
1699
+ // Windows 的 SIGTERM 是强制终止,sidecar 可能来不及清理 discovery/lock。
1700
+ // 只清理确实属于本 supervisor 已停止子进程的残留,不碰 attach 实例。
1701
+ const stoppedPids = new Set([child?.pid, lateChild?.pid].filter((pid) => Number.isInteger(pid)));
1702
+ for (const pid of stoppedPids) {
1703
+ if (pidAlive(pid)) continue;
1704
+ const discovery = await readDiscovery(this.paths.discoveryPath);
1705
+ if (discovery?.pid === pid) {
1706
+ await unlink(this.paths.discoveryPath).catch(() => undefined);
1707
+ }
1708
+ const lock = await this.#readLockView();
1709
+ if (lock?.pid === pid) {
1710
+ await unlink(this.paths.lockPath).catch(() => undefined);
1711
+ }
1712
+ }
1713
+
1714
+ if (includeAttached) {
1715
+ await this.#readLockView();
1716
+ const discovery = await readDiscovery(this.paths.discoveryPath);
1717
+ if (discovery && !this.#homeMismatch(discovery) && pidAlive(discovery.pid)) {
1718
+ await this.#stopPid(discovery.pid, timeoutMs);
1719
+ const current = await readDiscovery(this.paths.discoveryPath);
1720
+ if (current?.pid === discovery.pid && !pidAlive(discovery.pid)) {
1721
+ await unlink(this.paths.discoveryPath).catch(() => undefined);
1722
+ }
1723
+ }
1724
+ const lock = await this.#readLockView();
1725
+ if (lock && lock.command === 'serve' && pidAlive(lock.pid)) {
1726
+ await this.#stopPid(lock.pid, timeoutMs);
1727
+ }
1728
+ await unlink(this.paths.lockPath).catch(() => undefined);
1729
+ }
1730
+
1731
+ this.#setState({
1732
+ state: 'stopped',
1733
+ degraded: false,
1734
+ managed: false,
1735
+ attached: false,
1736
+ pid: null,
1737
+ url: null,
1738
+ healthUrl: null,
1739
+ error: null,
1740
+ reason: this.isEnabled() ? null : 'disabled',
1741
+ lock: null,
1742
+ });
1743
+ this.stopping = false;
1744
+ return this.snapshot();
1745
+ }
1746
+
1747
+ async restart({ includeAttached = false, timeoutMs = 5000, manual = false, force = true } = {}) {
1748
+ await this.stop({ includeAttached, timeoutMs });
1749
+ this.crashTimes = [];
1750
+ this.restarts = 0;
1751
+ this.healthFailures = 0;
1752
+ return this.start({ force, manual });
1753
+ }
1754
+
1755
+ async dispose() {
1756
+ this.disposed = true;
1757
+ this.#clearRestartTimer();
1758
+ this.#clearCooldownTimer();
1759
+ this.#stopWatchdog();
1760
+ if (this.startPromise) {
1761
+ await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1762
+ }
1763
+ const child = this.child;
1764
+ if (child) {
1765
+ this.#killChild('SIGTERM');
1766
+ await this.#waitChildExit(child, 3000);
1767
+ if (child.exitCode === null) this.#killChild('SIGKILL');
1768
+ if (this.child === child) this.child = null;
1769
+ }
1770
+ const lateChild = this.child;
1771
+ if (lateChild && lateChild !== child) {
1772
+ this.#killChild('SIGTERM');
1773
+ await this.#waitChildExit(lateChild, 1000);
1774
+ if (lateChild.exitCode === null) this.#killChild('SIGKILL');
1775
+ if (this.child === lateChild) this.child = null;
1776
+ }
1777
+ // Windows 强制终止不会执行 sidecar 自己的清理;只清理本 supervisor
1778
+ // 确实停止的子进程残留,attach 的实例不动。
1779
+ const stoppedPids = new Set([child?.pid, lateChild?.pid].filter((pid) => Number.isInteger(pid)));
1780
+ for (const pid of stoppedPids) {
1781
+ if (pidAlive(pid)) continue;
1782
+ const discovery = await readDiscovery(this.paths.discoveryPath);
1783
+ if (discovery?.pid === pid) {
1784
+ await unlink(this.paths.discoveryPath).catch(() => undefined);
1785
+ }
1786
+ const lock = await this.#readLockView();
1787
+ if (lock?.pid === pid) {
1788
+ await unlink(this.paths.lockPath).catch(() => undefined);
1789
+ }
1790
+ }
1791
+ this.#setState({
1792
+ state: 'stopped',
1793
+ managed: false,
1794
+ attached: false,
1795
+ pid: null,
1796
+ url: null,
1797
+ healthUrl: null,
1798
+ error: null,
1799
+ });
1800
+ }
1801
+ }
1802
+
1803
+ /** 只读检查:不 spawn、不创建目录/token;供 CLI status 与 admin 使用。 */
1804
+ export async function inspectMemoryRuntimeStatus({
1805
+ home,
1806
+ env = process.env,
1807
+ config = {},
1808
+ expectedProfileId = null,
1809
+ expectedCloudId = null,
1810
+ now = Date.now,
1811
+ fetchImpl = globalThis.fetch,
1812
+ } = {}) {
1813
+ const supervisor = new MemoryRuntimeSupervisor({
1814
+ home,
1815
+ env,
1816
+ config,
1817
+ profileId: () => expectedProfileId,
1818
+ cloudId: () => expectedCloudId,
1819
+ now,
1820
+ fetchImpl,
1821
+ restartOnFailure: false,
1822
+ });
1823
+ const status = await supervisor.status();
1824
+ const resolved = resolveMemoryRuntimeCommand({ config, env });
1825
+ return {
1826
+ ...status,
1827
+ installed: resolved.ok === true,
1828
+ commandSource: resolved.source,
1829
+ };
1830
+ }
1831
+
1832
+ /** 稳定 CLI 退出码(sidecar §11.2 + MCP CLI 包装约定)。 */
1833
+ export function memoryRuntimeStatusExitCode(status) {
1834
+ const code = status?.error?.code ?? null;
1835
+ if (code === 'not_installed') return 3;
1836
+ if (code === 'capability_token_missing' || code === 'capability_token_invalid') return 5;
1837
+ if (code === 'storage_unavailable' || code === 'token_permissions_insecure') return 6;
1838
+ if (code === 'bind_failed' || code === 'bind_not_loopback') return 4;
1839
+ if (code === 'version_incompatible' || code === 'capability_disabled') return 2;
1840
+ if (code === 'profile_mismatch' || code === 'home_mismatch' || code === 'lock_conflict'
1841
+ || code === 'already_running' || code === 'sidecar_starting') return 7;
1842
+ if (status?.state === 'ready' || status?.state === 'degraded' || status?.state === 'stopped') return 0;
1843
+ return 1;
1844
+ }