@mebular/mcp 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,13 +13,15 @@
13
13
  // 本模块不读取/返回 host token 或 capability token 明文。
14
14
 
15
15
  import { spawn as defaultSpawn } from 'node:child_process';
16
- import { randomBytes } from 'node:crypto';
16
+ import { randomBytes, createHash } from 'node:crypto';
17
17
  import { statSync } from 'node:fs';
18
- import { readFile, unlink } from 'node:fs/promises';
18
+ import { chmod, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
19
19
  import { homedir } from 'node:os';
20
20
  import { delimiter, dirname, join, resolve } from 'node:path';
21
21
  import { fileURLToPath } from 'node:url';
22
22
  import { APP_VERSION } from './version.mjs';
23
+ import { readCapabilityToken } from './memory-runtime-token.mjs';
24
+ import { appendMemoryRuntimeLogSync } from './memory-runtime-diagnostics.mjs';
23
25
 
24
26
  export const MEMORY_RUNTIME_DISCOVERY_FILE = 'memory-runtime.json';
25
27
  export const MEMORY_RUNTIME_DATA_DIR = 'memory-runtime';
@@ -30,12 +32,16 @@ export const MEMORY_RUNTIME_DEFAULT_PORT = 7341;
30
32
  export const MEMORY_RUNTIME_DEFAULT_START_TIMEOUT_MS = 5000;
31
33
  export const MEMORY_RUNTIME_HEALTH_TIMEOUT_MS = 200;
32
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;
33
37
  export const MEMORY_RUNTIME_RESTART_WINDOW_MS = 5 * 60 * 1000;
34
38
  export const MEMORY_RUNTIME_MAX_RESTARTS = 3;
35
39
  export const MEMORY_RUNTIME_RESTART_BACKOFF_MS = 500;
36
40
  export const MEMORY_RUNTIME_RESTART_BACKOFF_MAX_MS = 30_000;
37
41
  export const MEMORY_RUNTIME_RESTART_COOLDOWN_MS = 5 * 60 * 1000;
38
42
  export const MEMORY_RUNTIME_BIN = 'mebular-memory-runtime';
43
+ /** 默认 sidecar heartbeat 为 5s;禁用/停止必须覆盖至少一个完整心跳 + 有界收尾。 */
44
+ export const MEMORY_RUNTIME_ATTACHED_DORMANT_WAIT_MS = 12_000;
39
45
 
40
46
  const SIDECAR_KIND = 'mebular-memory-runtime';
41
47
  const CAPABILITY_API_VERSION = 1;
@@ -50,6 +56,41 @@ function stringOrNull(value) {
50
56
  return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
51
57
  }
52
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
+
53
94
  export function pidAlive(pid) {
54
95
  if (!Number.isInteger(pid) || pid <= 0) return false;
55
96
  try {
@@ -222,6 +263,7 @@ function makeDisabledStatus({ enabled = false, reason = 'disabled' } = {}) {
222
263
  apiVersion: null,
223
264
  capabilityApiVersion: null,
224
265
  commandSource: null,
266
+ discoveryMode: null,
225
267
  installed: enabled ? null : false,
226
268
  startedAt: null,
227
269
  lastOkAt: null,
@@ -252,7 +294,9 @@ function isSidecarDiscovery(value) {
252
294
 
253
295
  async function readDiscovery(path) {
254
296
  const value = await readJson(path, null);
255
- return isSidecarDiscovery(value) ? value : 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' };
256
300
  }
257
301
 
258
302
  async function readLock(path) {
@@ -288,6 +332,26 @@ const PROXY_SECRET_KEYS = new Set([
288
332
  'capability_token',
289
333
  'password',
290
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',
291
355
  ]);
292
356
 
293
357
  /**
@@ -314,6 +378,114 @@ function scrubProxyValue(value, secrets) {
314
378
  return value;
315
379
  }
316
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
+
317
489
  function proxyErrorMessage(body, fallback) {
318
490
  const message = body?.error?.message ?? body?.message;
319
491
  return typeof message === 'string' && message.length > 0 ? message : fallback;
@@ -377,6 +549,9 @@ export class MemoryRuntimeSupervisor {
377
549
  this.child = null;
378
550
  this.childToken = null;
379
551
  this.childSecrets = [];
552
+ this.managedInstance = null;
553
+ this.dormantLock = null;
554
+ this.dormantLockInvalidated = false;
380
555
  this.startPromise = null;
381
556
  this.restartTimer = null;
382
557
  this.cooldownTimer = null;
@@ -438,7 +613,7 @@ export class MemoryRuntimeSupervisor {
438
613
  ...this.statusState,
439
614
  ...patch,
440
615
  enabled: this.isEnabled(),
441
- available: nextState === 'ready' || nextState === 'degraded',
616
+ available: this.isEnabled() && (patch.available ?? (nextState === 'ready' || nextState === 'degraded')),
442
617
  };
443
618
  return this.snapshot();
444
619
  }
@@ -450,14 +625,14 @@ export class MemoryRuntimeSupervisor {
450
625
  #profileMismatch(discovery) {
451
626
  const expectedProfile = this.#profileId();
452
627
  const actualProfile = discoveryProfileId(discovery);
453
- if (expectedProfile && actualProfile && expectedProfile !== actualProfile) return true;
628
+ if (expectedProfile && expectedProfile !== actualProfile) return true;
454
629
  const expectedCloud = this.#cloudId();
455
630
  const actualCloud = discoveryCloudId(discovery);
456
- return Boolean(expectedCloud && actualCloud && expectedCloud !== actualCloud);
631
+ return Boolean(expectedCloud && expectedCloud !== actualCloud);
457
632
  }
458
633
 
459
634
  #homeMismatch(discovery) {
460
- if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return false;
635
+ if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return true;
461
636
  return resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir;
462
637
  }
463
638
 
@@ -470,7 +645,14 @@ export class MemoryRuntimeSupervisor {
470
645
  );
471
646
  }
472
647
 
473
- async #fetchHealth(discovery) {
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 } = {}) {
474
656
  if (!this.fetchImpl || typeof discovery?.healthUrl !== 'string') return { ok: false };
475
657
  const controller = new AbortController();
476
658
  const timer = setTimeout(() => controller.abort(), Math.max(1, this.healthTimeoutMs));
@@ -483,8 +665,10 @@ export class MemoryRuntimeSupervisor {
483
665
  });
484
666
  if (!response || response.ok !== true) return { ok: false };
485
667
  const body = await response.json().catch(() => ({}));
668
+ const ready = body?.ready !== false;
669
+ const dormant = acceptDormant && body?.mode === 'mcp' && body?.state === 'stopped';
486
670
  return {
487
- ok: body?.ok !== false && body?.ready !== false,
671
+ ok: body?.ok !== false && (ready || dormant),
488
672
  degraded: body?.degraded === true || body?.state === 'degraded',
489
673
  body,
490
674
  };
@@ -509,14 +693,131 @@ export class MemoryRuntimeSupervisor {
509
693
  return lock;
510
694
  }
511
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
+
512
779
  /**
513
780
  * 读取 discovery/health 并更新快照。
514
781
  * @returns {Promise<boolean>} 是否可接流量(ready 或 degraded)。
515
782
  */
516
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
+ }
517
790
  await this.#readLockView();
518
791
  const discovery = await readDiscovery(this.paths.discoveryPath);
519
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
+ }
520
821
  if (this.child && this.child.exitCode === null) {
521
822
  const state = this.readySeen ? 'degraded' : 'starting';
522
823
  this.#setState({
@@ -527,13 +828,16 @@ export class MemoryRuntimeSupervisor {
527
828
  pid: this.child.pid ?? null,
528
829
  url: null,
529
830
  healthUrl: null,
831
+ discoveryMode: null,
530
832
  restarts: this.restarts,
531
833
  error: this.readySeen ? publicError('discovery_missing', 'sidecar discovery 缺失') : null,
532
834
  lock: this.lockView,
533
835
  });
534
836
  return false;
535
837
  }
536
- if (this.statusState.state !== 'failed') {
838
+ if (this.statusState.state !== 'failed'
839
+ || ['discovery_dead', 'discovery_stale', 'discovery_future', 'discovery_invalid', 'instance_mismatch']
840
+ .includes(this.statusState.error?.code)) {
537
841
  const startingByLock = this.isEnabled()
538
842
  && this.lockView !== null
539
843
  && this.lockView.stale !== true
@@ -546,6 +850,7 @@ export class MemoryRuntimeSupervisor {
546
850
  pid: this.lockView?.pid ?? null,
547
851
  url: null,
548
852
  healthUrl: null,
853
+ discoveryMode: null,
549
854
  restarts: this.restarts,
550
855
  error: null,
551
856
  lock: this.lockView,
@@ -559,23 +864,11 @@ export class MemoryRuntimeSupervisor {
559
864
  return false;
560
865
  }
561
866
 
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
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
+ }
579
872
  if (this.#homeMismatch(discovery)) {
580
873
  this.#setState({
581
874
  state: 'failed',
@@ -628,9 +921,90 @@ export class MemoryRuntimeSupervisor {
628
921
  return false;
629
922
  }
630
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
+
631
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
+ }
632
1003
  if (health.ok) {
633
1004
  this.readySeen = true;
1005
+ this.dormantLock = null;
1006
+ this.dormantLockInvalidated = false;
1007
+ await this.#clearDormantState();
634
1008
  const degraded = discovery.degraded === true || health.degraded === true;
635
1009
  this.#setState({
636
1010
  state: degraded ? 'degraded' : 'ready',
@@ -644,6 +1018,7 @@ export class MemoryRuntimeSupervisor {
644
1018
  apiVersion: discovery.apiVersion ?? null,
645
1019
  capabilityApiVersion: discovery.capabilityApiVersion ?? null,
646
1020
  startedAt: discovery.startedAt ?? null,
1021
+ discoveryMode: 'immersive',
647
1022
  lastOkAt: this.now(),
648
1023
  restarts: this.restarts,
649
1024
  reason: null,
@@ -656,6 +1031,7 @@ export class MemoryRuntimeSupervisor {
656
1031
  const starting = managed && !this.readySeen;
657
1032
  this.#setState({
658
1033
  state: starting ? 'starting' : 'degraded',
1034
+ available: false,
659
1035
  degraded: !starting,
660
1036
  managed,
661
1037
  attached: !managed,
@@ -666,6 +1042,7 @@ export class MemoryRuntimeSupervisor {
666
1042
  apiVersion: discovery.apiVersion ?? null,
667
1043
  capabilityApiVersion: discovery.capabilityApiVersion ?? null,
668
1044
  startedAt: discovery.startedAt ?? null,
1045
+ discoveryMode: discovery.mode,
669
1046
  restarts: this.restarts,
670
1047
  error: starting ? null : publicError('health_check_failed', 'sidecar 健康检查失败'),
671
1048
  lock: this.lockView,
@@ -674,7 +1051,8 @@ export class MemoryRuntimeSupervisor {
674
1051
  }
675
1052
 
676
1053
  async status() {
677
- if (!this.isEnabled() && !this.statusState.managed && !this.statusState.pid) {
1054
+ if (!this.isEnabled() && !this.statusState.managed && !this.statusState.pid
1055
+ && this.statusState.error?.code !== 'disable_incomplete') {
678
1056
  this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
679
1057
  }
680
1058
  try {
@@ -700,9 +1078,10 @@ export class MemoryRuntimeSupervisor {
700
1078
  state: result.state,
701
1079
  reason: result.reason ?? null,
702
1080
  error: result.error ?? null,
703
- mode: null,
1081
+ mode: this.statusState.discoveryMode ?? null,
704
1082
  runtimeVersion: null,
705
1083
  degraded: result.state === 'degraded',
1084
+ capability: null,
706
1085
  model: null,
707
1086
  };
708
1087
  }
@@ -734,6 +1113,14 @@ export class MemoryRuntimeSupervisor {
734
1113
  mode: typeof data.mode === 'string' ? data.mode : null,
735
1114
  runtimeVersion: typeof data.runtimeVersion === 'string' ? data.runtimeVersion : null,
736
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,
737
1124
  model,
738
1125
  };
739
1126
  }
@@ -923,7 +1310,7 @@ export class MemoryRuntimeSupervisor {
923
1310
  };
924
1311
  }
925
1312
  const data = result.body?.data ?? result.body ?? {};
926
- const traces = Array.isArray(data.traces) ? data.traces : [];
1313
+ const traces = Array.isArray(data.traces) ? data.traces.slice(0, safeLimit).map(traceSummaryView) : [];
927
1314
  if (!result.ok) {
928
1315
  return {
929
1316
  ok: false,
@@ -1001,7 +1388,7 @@ export class MemoryRuntimeSupervisor {
1001
1388
  available: true,
1002
1389
  disabled: false,
1003
1390
  state: result.state,
1004
- trace: data,
1391
+ trace: traceDetailView(data),
1005
1392
  degraded: result.body?.degraded === true,
1006
1393
  };
1007
1394
  }
@@ -1051,35 +1438,132 @@ export class MemoryRuntimeSupervisor {
1051
1438
  }
1052
1439
 
1053
1440
  async #resolveHostToken(discovery) {
1054
- if (this.child && discovery?.pid === this.child.pid && typeof this.childToken === 'string') {
1055
- return this.childToken;
1056
- }
1057
1441
  const fromEnv = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN);
1058
- if (fromEnv) return fromEnv;
1442
+ if (fromEnv) return { token: fromEnv, source: 'override', refreshable: false };
1059
1443
  if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return null;
1060
- // 只读当前 home 的 sidecar token;discovery 路径不匹配时拒绝读取。
1444
+ // 只读当前 home 的生产 JSON token;raw 文件不是隐式生产回退格式。
1061
1445
  if (resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir) return null;
1062
1446
  try {
1063
- const token = (await readFile(discovery.tokenFile, 'utf-8')).trim();
1064
- return token.length > 0 ? token : null;
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 };
1065
1501
  } catch {
1066
1502
  return null;
1503
+ } finally {
1504
+ clearTimeout(timer);
1067
1505
  }
1068
1506
  }
1069
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
+
1070
1558
  async #proxyHostApi(pathname, { method = 'GET', body = null, timeoutMs = 2500 } = {}) {
1071
1559
  await this.status().catch(() => undefined);
1072
1560
  if (!this.isEnabled()) {
1073
1561
  return {
1074
- enabled: false,
1075
- available: false,
1076
- disabled: true,
1077
- state: 'stopped',
1078
- reason: 'disabled',
1079
- error: null,
1562
+ enabled: false, available: false, disabled: true, state: 'stopped', reason: 'disabled', error: null,
1080
1563
  };
1081
1564
  }
1082
- if (!['ready', 'degraded'].includes(this.statusState.state) || typeof this.statusState.url !== 'string') {
1565
+ if (!this.statusState.available || !['ready', 'degraded'].includes(this.statusState.state)
1566
+ || typeof this.statusState.url !== 'string') {
1083
1567
  return {
1084
1568
  enabled: true,
1085
1569
  available: false,
@@ -1089,73 +1573,97 @@ export class MemoryRuntimeSupervisor {
1089
1573
  error: this.statusState.error ?? publicError('sidecar_unavailable', 'Memory Runtime sidecar 未就绪'),
1090
1574
  };
1091
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
+ };
1092
1589
  const discovery = await readDiscovery(this.paths.discoveryPath);
1093
- if (!discovery) {
1590
+ if (!validatedDiscovery(discovery)) {
1094
1591
  return {
1095
1592
  enabled: true,
1096
1593
  available: false,
1097
1594
  disabled: false,
1098
1595
  state: this.statusState.state,
1099
1596
  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'),
1597
+ error: publicError(discovery ? 'instance_mismatch' : 'discovery_missing', 'sidecar discovery 已变化或失效'),
1112
1598
  };
1113
1599
  }
1114
1600
  if (!this.fetchImpl) {
1115
1601
  return {
1116
- enabled: true,
1117
- available: false,
1118
- disabled: false,
1119
- state: this.statusState.state,
1120
- reason: null,
1602
+ enabled: true, available: false, disabled: false, state: this.statusState.state, reason: null,
1121
1603
  error: publicError('fetch_unavailable', '当前运行环境不支持 HTTP 代理'),
1122
1604
  };
1123
1605
  }
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;
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?.();
1142
1614
  try {
1143
- parsed = text.length > 0 ? JSON.parse(text) : null;
1144
- } catch {
1145
- parsed = null;
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);
1146
1640
  }
1147
- const scrubbed = scrubProxyValue(parsed, [token, this.childToken]);
1641
+ };
1642
+
1643
+ let credential = await this.#resolveHostToken(discovery);
1644
+ if (!credential) {
1148
1645
  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]) } : {}),
1646
+ enabled: true, available: false, disabled: false, state: this.statusState.state, reason: null,
1647
+ error: publicError('host_token_missing', '无法读取 sidecar host token'),
1157
1648
  };
1158
- } catch (error) {
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;
1159
1667
  return {
1160
1668
  enabled: true,
1161
1669
  available: false,
@@ -1167,9 +1675,20 @@ export class MemoryRuntimeSupervisor {
1167
1675
  error?.name === 'AbortError' ? 'sidecar 请求超时' : '无法连接 Memory Runtime sidecar',
1168
1676
  ),
1169
1677
  };
1170
- } finally {
1171
- clearTimeout(timer);
1172
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
+ };
1173
1692
  }
1174
1693
 
1175
1694
  #resolveCommand() {
@@ -1200,7 +1719,9 @@ export class MemoryRuntimeSupervisor {
1200
1719
  const fromEnv = stringOrNull(this.env?.MEBULAR_CAPABILITY_TOKEN);
1201
1720
  if (fromEnv) return fromEnv;
1202
1721
  const record = await readJson(this.paths.capabilityTokenPath, null);
1203
- return typeof record?.token === 'string' && record.token.length > 0 ? record.token : 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;
1204
1725
  }
1205
1726
 
1206
1727
  async #waitForDiscovery(deadline) {
@@ -1387,6 +1908,15 @@ export class MemoryRuntimeSupervisor {
1387
1908
  ),
1388
1909
  lock: this.lockView,
1389
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 });
1390
1920
  this.#scheduleRestart();
1391
1921
  }
1392
1922
 
@@ -1542,10 +2072,40 @@ export class MemoryRuntimeSupervisor {
1542
2072
  return false;
1543
2073
  }
1544
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
+
1545
2089
  async #startOnce({ force = false, manual = false, isRestart = false } = {}) {
1546
2090
  if (this.disposed) return this.snapshot();
1547
2091
  this.stopping = false;
1548
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
+
1549
2109
  const discovered = await this.#refreshDiscovery({ fetchHealth: true });
1550
2110
  if (discovered && ['ready', 'degraded'].includes(this.statusState.state)) {
1551
2111
  this.#startWatchdog();
@@ -1588,7 +2148,17 @@ export class MemoryRuntimeSupervisor {
1588
2148
  });
1589
2149
  return this.snapshot();
1590
2150
  }
1591
- if (existing) await unlink(this.paths.discoveryPath).catch(() => undefined);
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
+ }
1592
2162
 
1593
2163
  const lock = await this.#readLockView();
1594
2164
  if (lock && pidAlive(lock.pid)) {
@@ -1604,6 +2174,76 @@ export class MemoryRuntimeSupervisor {
1604
2174
  });
1605
2175
  return this.snapshot();
1606
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
+ }
1607
2247
  const deadline = this.now() + Math.max(100, this.configuredStartTimeout());
1608
2248
  const ready = await this.#waitForDiscovery(deadline);
1609
2249
  if (ready) {
@@ -1614,6 +2254,26 @@ export class MemoryRuntimeSupervisor {
1614
2254
  if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1615
2255
  return this.snapshot();
1616
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
+ }
1617
2277
  this.#setState({
1618
2278
  state: 'failed',
1619
2279
  degraded: false,
@@ -1667,15 +2327,19 @@ export class MemoryRuntimeSupervisor {
1667
2327
 
1668
2328
  async stop({ includeAttached = false, timeoutMs = 5000 } = {}) {
1669
2329
  this.stopping = true;
2330
+ let dormantBaseline = null;
1670
2331
  this.#clearRestartTimer();
1671
2332
  this.#clearCooldownTimer();
1672
2333
  this.#stopWatchdog();
1673
2334
 
1674
- // 让正在启动的流程看到 stopping 并退出,避免它在本函数返回后又拉起子进程。
1675
- if (this.startPromise) {
1676
- await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1677
- }
2335
+ if (this.startPromise) await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
2336
+ const discoveredAtStop = await readDiscovery(this.paths.discoveryPath);
1678
2337
  const child = this.child;
2338
+ const attachedDiscovery = discoveredAtStop
2339
+ && discoveredAtStop.pid !== child?.pid
2340
+ && discoveredAtStop.pid !== this.managedInstance?.pid
2341
+ ? discoveredAtStop
2342
+ : null;
1679
2343
  if (child) {
1680
2344
  this.#killChild('SIGTERM');
1681
2345
  await this.#waitChildExit(child, timeoutMs);
@@ -1685,9 +2349,7 @@ export class MemoryRuntimeSupervisor {
1685
2349
  }
1686
2350
  if (this.child === child) this.child = null;
1687
2351
  }
1688
- if (this.startPromise) {
1689
- await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1690
- }
2352
+ if (this.startPromise) await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1691
2353
  const lateChild = this.child;
1692
2354
  if (lateChild && lateChild !== child) {
1693
2355
  this.#killChild('SIGTERM');
@@ -1696,55 +2358,259 @@ export class MemoryRuntimeSupervisor {
1696
2358
  if (this.child === lateChild) this.child = null;
1697
2359
  }
1698
2360
 
1699
- // Windows 的 SIGTERM 是强制终止,sidecar 可能来不及清理 discovery/lock。
1700
- // 只清理确实属于本 supervisor 已停止子进程的残留,不碰 attach 实例。
1701
- const stoppedPids = new Set([child?.pid, lateChild?.pid].filter((pid) => Number.isInteger(pid)));
2361
+ let clean = true;
2362
+ const stoppedPids = new Set([child?.pid, lateChild?.pid, this.managedInstance?.pid]
2363
+ .filter((pid) => Number.isInteger(pid)));
1702
2364
  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);
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;
1707
2384
  }
1708
2385
  const lock = await this.#readLockView();
1709
2386
  if (lock?.pid === pid) {
1710
- await unlink(this.paths.lockPath).catch(() => undefined);
2387
+ if (knownStartedAt === null || lock.startedAt !== knownStartedAt) {
2388
+ clean = false;
2389
+ } else {
2390
+ await unlink(this.paths.lockPath).catch(() => {
2391
+ clean = false;
2392
+ });
2393
+ }
1711
2394
  }
1712
2395
  }
1713
2396
 
1714
2397
  if (includeAttached) {
1715
- await this.#readLockView();
1716
2398
  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);
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
+ }
1722
2471
  }
1723
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。
1724
2527
  const lock = await this.#readLockView();
1725
- if (lock && lock.command === 'serve' && pidAlive(lock.pid)) {
1726
- await this.#stopPid(lock.pid, timeoutMs);
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
+ }
1727
2559
  }
1728
- await unlink(this.paths.lockPath).catch(() => undefined);
1729
2560
  }
1730
2561
 
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
- });
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
+ }
1743
2597
  this.stopping = false;
1744
2598
  return this.snapshot();
1745
2599
  }
1746
2600
 
1747
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 });
1748
2614
  await this.stop({ includeAttached, timeoutMs });
1749
2615
  this.crashTimes = [];
1750
2616
  this.restarts = 0;
@@ -1754,49 +2620,9 @@ export class MemoryRuntimeSupervisor {
1754
2620
 
1755
2621
  async dispose() {
1756
2622
  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
- });
2623
+ const status = await this.stop({ includeAttached: false, timeoutMs: 3000 });
2624
+ this.disposed = true;
2625
+ if (!status.error) this.#setState({ reason: 'disposed', available: false });
1800
2626
  }
1801
2627
  }
1802
2628