@mebular/mcp 0.3.0 → 0.3.4

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';
@@ -28,14 +30,20 @@ export const MEMORY_RUNTIME_TOKEN_FILE = 'host-token';
28
30
  export const MEMORY_RUNTIME_CAPABILITY_TOKEN_FILE = 'capability-token';
29
31
  export const MEMORY_RUNTIME_DEFAULT_PORT = 7341;
30
32
  export const MEMORY_RUNTIME_DEFAULT_START_TIMEOUT_MS = 5000;
31
- export const MEMORY_RUNTIME_HEALTH_TIMEOUT_MS = 200;
33
+ // Local loopback health probes are cheap; allow a full second so a busy host
34
+ // (notably Windows CI) cannot turn one slow probe into a transient 503.
35
+ export const MEMORY_RUNTIME_HEALTH_TIMEOUT_MS = 1000;
32
36
  export const MEMORY_RUNTIME_HEALTH_CHECK_MS = 5000;
37
+ export const MEMORY_RUNTIME_DISCOVERY_STALE_MS = 15_000;
38
+ export const MEMORY_RUNTIME_DISCOVERY_DEAD_MS = 30_000;
33
39
  export const MEMORY_RUNTIME_RESTART_WINDOW_MS = 5 * 60 * 1000;
34
40
  export const MEMORY_RUNTIME_MAX_RESTARTS = 3;
35
41
  export const MEMORY_RUNTIME_RESTART_BACKOFF_MS = 500;
36
42
  export const MEMORY_RUNTIME_RESTART_BACKOFF_MAX_MS = 30_000;
37
43
  export const MEMORY_RUNTIME_RESTART_COOLDOWN_MS = 5 * 60 * 1000;
38
44
  export const MEMORY_RUNTIME_BIN = 'mebular-memory-runtime';
45
+ /** 默认 sidecar heartbeat 为 5s;禁用/停止必须覆盖至少一个完整心跳 + 有界收尾。 */
46
+ export const MEMORY_RUNTIME_ATTACHED_DORMANT_WAIT_MS = 12_000;
39
47
 
40
48
  const SIDECAR_KIND = 'mebular-memory-runtime';
41
49
  const CAPABILITY_API_VERSION = 1;
@@ -50,6 +58,41 @@ function stringOrNull(value) {
50
58
  return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
51
59
  }
52
60
 
61
+ function loopbackHostname(hostname) {
62
+ const normalized = String(hostname ?? '').replace(/^\[|\]$/g, '').toLowerCase();
63
+ return normalized === '127.0.0.1' || normalized === '::1' || normalized === 'localhost';
64
+ }
65
+
66
+ function validDiscoveryUrls(discovery) {
67
+ try {
68
+ const base = new URL(discovery.url);
69
+ const health = new URL(discovery.healthUrl);
70
+ const basePath = '/memory-runtime/v1';
71
+ return base.protocol === 'http:'
72
+ && health.protocol === 'http:'
73
+ && loopbackHostname(base.hostname)
74
+ && loopbackHostname(health.hostname)
75
+ && base.username === '' && base.password === ''
76
+ && health.username === '' && health.password === ''
77
+ && base.pathname === basePath
78
+ && health.pathname === `${basePath}/health`
79
+ && base.search === '' && base.hash === ''
80
+ && health.search === '' && health.hash === ''
81
+ && base.origin === health.origin
82
+ && Number(base.port) === discovery.port;
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ function sameDiscoveryInstance(left, right) {
89
+ return Boolean(left && right)
90
+ && left.pid === right.pid
91
+ && left.startedAt === right.startedAt
92
+ && left.url === right.url
93
+ && left.tokenFile === right.tokenFile;
94
+ }
95
+
53
96
  export function pidAlive(pid) {
54
97
  if (!Number.isInteger(pid) || pid <= 0) return false;
55
98
  try {
@@ -222,6 +265,7 @@ function makeDisabledStatus({ enabled = false, reason = 'disabled' } = {}) {
222
265
  apiVersion: null,
223
266
  capabilityApiVersion: null,
224
267
  commandSource: null,
268
+ discoveryMode: null,
225
269
  installed: enabled ? null : false,
226
270
  startedAt: null,
227
271
  lastOkAt: null,
@@ -252,7 +296,9 @@ function isSidecarDiscovery(value) {
252
296
 
253
297
  async function readDiscovery(path) {
254
298
  const value = await readJson(path, null);
255
- return isSidecarDiscovery(value) ? value : null;
299
+ if (!isSidecarDiscovery(value)) return null;
300
+ if (value.mode !== undefined && value.mode !== 'immersive' && value.mode !== 'mcp') return null;
301
+ return { ...value, mode: value.mode ?? 'immersive' };
256
302
  }
257
303
 
258
304
  async function readLock(path) {
@@ -288,6 +334,26 @@ const PROXY_SECRET_KEYS = new Set([
288
334
  'capability_token',
289
335
  'password',
290
336
  'secret',
337
+ 'keyref',
338
+ 'baseurl',
339
+ 'modelpath',
340
+ 'installedpath',
341
+ 'modelsdir',
342
+ 'apikey',
343
+ 'api_key',
344
+ 'api-key',
345
+ 'accesstoken',
346
+ 'refreshtoken',
347
+ 'secretref',
348
+ 'credentialref',
349
+ 'endpoint',
350
+ 'binarypath',
351
+ 'installpath',
352
+ 'enginepath',
353
+ 'path',
354
+ 'rootdir',
355
+ 'homedir',
356
+ 'debug',
291
357
  ]);
292
358
 
293
359
  /**
@@ -314,6 +380,114 @@ function scrubProxyValue(value, secrets) {
314
380
  return value;
315
381
  }
316
382
 
383
+ function traceText(value, max = 512) {
384
+ return typeof value === 'string' ? value.slice(0, max) : null;
385
+ }
386
+
387
+ function traceNumber(value) {
388
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
389
+ }
390
+
391
+ function traceStrings(value) {
392
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === 'string').slice(0, 100) : [];
393
+ }
394
+
395
+ function traceOwnerView(owner) {
396
+ return {
397
+ role: traceText(owner?.role, 64),
398
+ ownerId: traceText(owner?.ownerId, 256),
399
+ domain: traceText(owner?.domain, 256),
400
+ agentName: traceText(owner?.agentName, 128),
401
+ };
402
+ }
403
+
404
+ function traceProvenanceView(provenance) {
405
+ return {
406
+ source: traceText(provenance?.source, 64),
407
+ extractor: traceText(provenance?.extractor, 64),
408
+ hostId: traceText(provenance?.hostId, 128),
409
+ };
410
+ }
411
+
412
+ function traceSummaryView(trace) {
413
+ const feedback = trace?.feedback;
414
+ return {
415
+ id: traceText(trace?.id, 160),
416
+ recallId: traceText(trace?.recallId, 160),
417
+ schema: traceNumber(trace?.schema),
418
+ at: traceNumber(trace?.at),
419
+ agentId: traceText(trace?.agentId, 256),
420
+ threadId: traceText(trace?.threadId, 256),
421
+ queryHash: traceText(trace?.queryHash, 256),
422
+ queryPreview: traceText(trace?.queryPreview, 160),
423
+ domains: traceStrings(trace?.domains),
424
+ silenceReason: traceText(trace?.silenceReason, 128),
425
+ degraded: trace?.degraded === true,
426
+ feedback: feedback && typeof feedback === 'object' ? {
427
+ useful: feedback.useful === true,
428
+ reason: traceText(feedback.reason, 500),
429
+ at: traceNumber(feedback.at),
430
+ } : null,
431
+ counts: {
432
+ candidates: traceNumber(trace?.counts?.candidates),
433
+ expansions: traceNumber(trace?.counts?.expansions),
434
+ injected: traceNumber(trace?.counts?.injected),
435
+ tokens: traceNumber(trace?.counts?.tokens),
436
+ },
437
+ timing: { totalMs: traceNumber(trace?.timing?.totalMs) },
438
+ model: {
439
+ query: traceText(trace?.model?.query, 128),
440
+ embedding: traceText(trace?.model?.embedding, 128),
441
+ extractor: traceText(trace?.model?.extractor, 128),
442
+ tookMs: traceNumber(trace?.model?.tookMs),
443
+ },
444
+ };
445
+ }
446
+
447
+ function traceDetailView(trace) {
448
+ return {
449
+ ...traceSummaryView(trace),
450
+ hits: Array.isArray(trace?.hits) ? trace.hits.slice(0, 100).map((hit) => ({
451
+ id: traceText(hit?.id, 256),
452
+ type: traceText(hit?.type, 64),
453
+ score: traceNumber(hit?.score),
454
+ rank: traceNumber(hit?.rank),
455
+ })) : [],
456
+ cue: {
457
+ topics: traceStrings(trace?.cue?.topics),
458
+ entities: Array.isArray(trace?.cue?.entities) ? trace.cue.entities.slice(0, 100).map((entity) => ({
459
+ name: traceText(entity?.name, 256),
460
+ type: traceText(entity?.type, 64),
461
+ })) : [],
462
+ },
463
+ candidates: Array.isArray(trace?.candidates) ? trace.candidates.slice(0, 100).map((candidate) => ({
464
+ id: traceText(candidate?.id, 256),
465
+ type: traceText(candidate?.type, 64),
466
+ domain: traceText(candidate?.domain, 256),
467
+ owner: traceOwnerView(candidate?.owner),
468
+ provenance: traceProvenanceView(candidate?.provenance),
469
+ confidence: traceNumber(candidate?.confidence),
470
+ score: traceNumber(candidate?.score),
471
+ rank: traceNumber(candidate?.rank),
472
+ })) : [],
473
+ expansions: Array.isArray(trace?.expansions) ? trace.expansions.slice(0, 100).map((expansion) => ({
474
+ sourceId: traceText(expansion?.sourceId, 256),
475
+ reason: traceText(expansion?.reason, 128),
476
+ status: traceText(expansion?.status, 64),
477
+ })) : [],
478
+ injected: Array.isArray(trace?.injected) ? trace.injected.slice(0, 100).map((fragment) => ({
479
+ fragmentId: traceText(fragment?.fragmentId, 256),
480
+ sourceId: traceText(fragment?.sourceId, 256),
481
+ layer: traceText(fragment?.layer, 64),
482
+ tokens: traceNumber(fragment?.tokens),
483
+ citations: traceStrings(fragment?.citations),
484
+ confidence: traceNumber(fragment?.confidence),
485
+ owner: traceOwnerView(fragment?.owner),
486
+ provenance: traceProvenanceView(fragment?.provenance),
487
+ })) : [],
488
+ };
489
+ }
490
+
317
491
  function proxyErrorMessage(body, fallback) {
318
492
  const message = body?.error?.message ?? body?.message;
319
493
  return typeof message === 'string' && message.length > 0 ? message : fallback;
@@ -377,6 +551,9 @@ export class MemoryRuntimeSupervisor {
377
551
  this.child = null;
378
552
  this.childToken = null;
379
553
  this.childSecrets = [];
554
+ this.managedInstance = null;
555
+ this.dormantLock = null;
556
+ this.dormantLockInvalidated = false;
380
557
  this.startPromise = null;
381
558
  this.restartTimer = null;
382
559
  this.cooldownTimer = null;
@@ -438,7 +615,7 @@ export class MemoryRuntimeSupervisor {
438
615
  ...this.statusState,
439
616
  ...patch,
440
617
  enabled: this.isEnabled(),
441
- available: nextState === 'ready' || nextState === 'degraded',
618
+ available: this.isEnabled() && (patch.available ?? (nextState === 'ready' || nextState === 'degraded')),
442
619
  };
443
620
  return this.snapshot();
444
621
  }
@@ -450,14 +627,14 @@ export class MemoryRuntimeSupervisor {
450
627
  #profileMismatch(discovery) {
451
628
  const expectedProfile = this.#profileId();
452
629
  const actualProfile = discoveryProfileId(discovery);
453
- if (expectedProfile && actualProfile && expectedProfile !== actualProfile) return true;
630
+ if (expectedProfile && expectedProfile !== actualProfile) return true;
454
631
  const expectedCloud = this.#cloudId();
455
632
  const actualCloud = discoveryCloudId(discovery);
456
- return Boolean(expectedCloud && actualCloud && expectedCloud !== actualCloud);
633
+ return Boolean(expectedCloud && expectedCloud !== actualCloud);
457
634
  }
458
635
 
459
636
  #homeMismatch(discovery) {
460
- if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return false;
637
+ if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return true;
461
638
  return resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir;
462
639
  }
463
640
 
@@ -470,7 +647,14 @@ export class MemoryRuntimeSupervisor {
470
647
  );
471
648
  }
472
649
 
473
- async #fetchHealth(discovery) {
650
+ #healthIdentityMatches(discovery, body, { allowDormant = false } = {}) {
651
+ if (!isObject(body) || body.pid !== discovery.pid) return false;
652
+ if (stringOrNull(body.profileId) !== discoveryProfileId(discovery)) return false;
653
+ if (stringOrNull(body.cloudId) !== discoveryCloudId(discovery)) return false;
654
+ return body.mode === discovery.mode || (allowDormant && body.mode === 'mcp');
655
+ }
656
+
657
+ async #fetchHealth(discovery, { acceptDormant = false } = {}) {
474
658
  if (!this.fetchImpl || typeof discovery?.healthUrl !== 'string') return { ok: false };
475
659
  const controller = new AbortController();
476
660
  const timer = setTimeout(() => controller.abort(), Math.max(1, this.healthTimeoutMs));
@@ -483,8 +667,10 @@ export class MemoryRuntimeSupervisor {
483
667
  });
484
668
  if (!response || response.ok !== true) return { ok: false };
485
669
  const body = await response.json().catch(() => ({}));
670
+ const ready = body?.ready !== false;
671
+ const dormant = acceptDormant && body?.mode === 'mcp' && body?.state === 'stopped';
486
672
  return {
487
- ok: body?.ok !== false && body?.ready !== false,
673
+ ok: body?.ok !== false && (ready || dormant),
488
674
  degraded: body?.degraded === true || body?.state === 'degraded',
489
675
  body,
490
676
  };
@@ -509,14 +695,131 @@ export class MemoryRuntimeSupervisor {
509
695
  return lock;
510
696
  }
511
697
 
698
+ /** 从 start.lock 构造可验证候选;不写回 discovery,只用于显式 stop。 */
699
+ #discoveryFromLock(lock) {
700
+ if (!lock || lock.command !== 'serve' || !Number.isInteger(lock.port) || lock.port <= 0) return null;
701
+ const base = `http://127.0.0.1:${lock.port}/memory-runtime/v1`;
702
+ return {
703
+ schema: 1,
704
+ kind: SIDECAR_KIND,
705
+ pid: lock.pid,
706
+ host: '127.0.0.1',
707
+ port: lock.port,
708
+ url: base,
709
+ healthUrl: `${base}/health`,
710
+ tokenFile: this.paths.hostTokenPath,
711
+ cloudId: lock.cloudId,
712
+ profileId: lock.profileId,
713
+ runtimeVersion: APP_VERSION,
714
+ apiVersion: 1,
715
+ capabilityApiVersion: CAPABILITY_API_VERSION,
716
+ minMcpVersion: '0.3.0',
717
+ maxMcpVersion: '0.3.x',
718
+ state: 'ready',
719
+ mode: 'immersive',
720
+ degraded: false,
721
+ startedAt: lock.startedAt,
722
+ updatedAt: this.now(),
723
+ capabilities: {},
724
+ };
725
+ }
726
+
727
+ /** 当前实际 capability token(env 优先,其次生产文件)的指纹;null 表示没有可用凭据。 */
728
+ async #capabilityFingerprint() {
729
+ try {
730
+ const record = await readCapabilityToken({
731
+ home: this.paths.home,
732
+ env: this.env,
733
+ now: this.now(),
734
+ });
735
+ if (!record?.token) return null;
736
+ return createHash('sha256').update(record.token).digest('hex');
737
+ } catch {
738
+ return null;
739
+ }
740
+ }
741
+
742
+ get #dormantStatePath() {
743
+ return join(this.paths.dataDir, 'dormant.json');
744
+ }
745
+
746
+ async #readDormantState() {
747
+ try {
748
+ const info = await stat(this.#dormantStatePath);
749
+ if (process.platform !== 'win32' && (info.mode & 0o777) !== 0o600) return null;
750
+ const value = JSON.parse(await readFile(this.#dormantStatePath, 'utf-8'));
751
+ if (value?.version !== undefined && value.version !== 1) return null;
752
+ if (!Number.isInteger(value?.pid) || value.pid <= 0) return null;
753
+ if (!Number.isFinite(value?.startedAt)) return null;
754
+ if (!(typeof value?.credential === 'string' || value?.credential === null)) return null;
755
+ return {
756
+ pid: value.pid,
757
+ startedAt: value.startedAt,
758
+ credential: value.credential,
759
+ };
760
+ } catch {
761
+ return null;
762
+ }
763
+ }
764
+
765
+ async #writeDormantState(state) {
766
+ const tmp = `${this.#dormantStatePath}.tmp-${process.pid}`;
767
+ try {
768
+ await writeFile(tmp, JSON.stringify({ version: 1, ...state }, null, 2), { mode: 0o600 });
769
+ if (process.platform !== 'win32') await chmod(tmp, 0o600);
770
+ await rename(tmp, this.#dormantStatePath);
771
+ } catch (error) {
772
+ await unlink(tmp).catch(() => undefined);
773
+ throw error;
774
+ }
775
+ }
776
+
777
+ async #clearDormantState() {
778
+ await unlink(this.#dormantStatePath).catch(() => undefined);
779
+ }
780
+
512
781
  /**
513
782
  * 读取 discovery/health 并更新快照。
514
783
  * @returns {Promise<boolean>} 是否可接流量(ready 或 degraded)。
515
784
  */
516
785
  async #refreshDiscovery({ fetchHealth = true } = {}) {
786
+ if (!this.isEnabled()) {
787
+ if (this.statusState.error?.code !== 'disable_incomplete') {
788
+ this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
789
+ }
790
+ return false;
791
+ }
517
792
  await this.#readLockView();
518
793
  const discovery = await readDiscovery(this.paths.discoveryPath);
519
794
  if (!discovery) {
795
+ if (this.dormantLock) {
796
+ const lock = await readLock(this.paths.lockPath);
797
+ const credential = await this.#capabilityFingerprint();
798
+ if (!lock
799
+ || lock.pid !== this.dormantLock.pid
800
+ || lock.startedAt !== this.dormantLock.startedAt
801
+ || !pidAlive(lock.pid)
802
+ || credential !== this.dormantLock.credential) {
803
+ this.dormantLockInvalidated = true;
804
+ this.dormantLock = null;
805
+ // 保留持久化 baseline:跨进程启动仍能识别 credential 已换代。
806
+ } else {
807
+ this.#setState({
808
+ state: 'stopped',
809
+ available: false,
810
+ degraded: false,
811
+ managed: false,
812
+ attached: false,
813
+ pid: lock.pid,
814
+ url: null,
815
+ healthUrl: null,
816
+ reason: 'disabled',
817
+ error: null,
818
+ lock: this.lockView,
819
+ });
820
+ return false;
821
+ }
822
+ }
520
823
  if (this.child && this.child.exitCode === null) {
521
824
  const state = this.readySeen ? 'degraded' : 'starting';
522
825
  this.#setState({
@@ -527,13 +830,16 @@ export class MemoryRuntimeSupervisor {
527
830
  pid: this.child.pid ?? null,
528
831
  url: null,
529
832
  healthUrl: null,
833
+ discoveryMode: null,
530
834
  restarts: this.restarts,
531
835
  error: this.readySeen ? publicError('discovery_missing', 'sidecar discovery 缺失') : null,
532
836
  lock: this.lockView,
533
837
  });
534
838
  return false;
535
839
  }
536
- if (this.statusState.state !== 'failed') {
840
+ if (this.statusState.state !== 'failed'
841
+ || ['discovery_dead', 'discovery_stale', 'discovery_future', 'discovery_invalid', 'instance_mismatch']
842
+ .includes(this.statusState.error?.code)) {
537
843
  const startingByLock = this.isEnabled()
538
844
  && this.lockView !== null
539
845
  && this.lockView.stale !== true
@@ -546,6 +852,7 @@ export class MemoryRuntimeSupervisor {
546
852
  pid: this.lockView?.pid ?? null,
547
853
  url: null,
548
854
  healthUrl: null,
855
+ discoveryMode: null,
549
856
  restarts: this.restarts,
550
857
  error: null,
551
858
  lock: this.lockView,
@@ -559,23 +866,11 @@ export class MemoryRuntimeSupervisor {
559
866
  return false;
560
867
  }
561
868
 
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
869
  const managed = Boolean(this.child && this.child.pid === discovery.pid);
870
+ if (managed) {
871
+ // 记录本实例拥有的 pid/startedAt;child 被强杀后仍可确认 discovery/start.lock 归属。
872
+ this.managedInstance = { pid: discovery.pid, startedAt: discovery.startedAt };
873
+ }
579
874
  if (this.#homeMismatch(discovery)) {
580
875
  this.#setState({
581
876
  state: 'failed',
@@ -628,9 +923,90 @@ export class MemoryRuntimeSupervisor {
628
923
  return false;
629
924
  }
630
925
 
926
+ if (!pidAlive(discovery.pid)) {
927
+ // 只读 status/inspect 绝不 unlink;身份校验先于 dead 判定与后续清理。
928
+ this.#setState({
929
+ state: 'stopped',
930
+ available: false,
931
+ degraded: false,
932
+ managed: false,
933
+ attached: false,
934
+ pid: discovery.pid,
935
+ url: null,
936
+ healthUrl: null,
937
+ discoveryMode: discovery.mode,
938
+ error: publicError('discovery_dead', 'sidecar discovery 对应进程已退出'),
939
+ lock: this.lockView,
940
+ });
941
+ return false;
942
+ }
943
+
944
+ if (!validDiscoveryUrls(discovery)) {
945
+ this.#setState({
946
+ state: 'failed', available: false, degraded: false, managed, attached: !managed,
947
+ pid: discovery.pid, url: null, healthUrl: null,
948
+ error: publicError('discovery_invalid', 'sidecar discovery URL 非法:拒绝连接或转发凭据'),
949
+ lock: this.lockView,
950
+ });
951
+ return false;
952
+ }
953
+ const age = this.now() - discovery.updatedAt;
954
+ if (!Number.isFinite(age) || age < -1000 || age > MEMORY_RUNTIME_DISCOVERY_DEAD_MS) {
955
+ this.#setState({
956
+ state: 'failed', available: false, degraded: false, managed, attached: !managed,
957
+ pid: discovery.pid, url: null, healthUrl: null,
958
+ error: publicError(age < -1000 ? 'discovery_future' : 'discovery_dead', 'sidecar discovery 已失效'),
959
+ lock: this.lockView,
960
+ });
961
+ return false;
962
+ }
963
+ if (age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) {
964
+ this.#setState({
965
+ state: 'degraded', available: false, degraded: true, managed, attached: !managed,
966
+ pid: discovery.pid, url: null, healthUrl: null,
967
+ error: publicError('discovery_stale', 'sidecar discovery 已超过 15 秒未刷新'),
968
+ lock: this.lockView,
969
+ });
970
+ return false;
971
+ }
972
+ if (discovery.mode === 'mcp') {
973
+ const dormantClean = discovery.state === 'stopped';
974
+ this.#setState({
975
+ state: dormantClean ? 'stopped' : 'degraded',
976
+ available: false,
977
+ degraded: !dormantClean,
978
+ managed,
979
+ attached: !managed,
980
+ pid: discovery.pid,
981
+ url: null,
982
+ healthUrl: null,
983
+ discoveryMode: 'mcp',
984
+ reason: 'disabled',
985
+ error: dormantClean
986
+ ? null
987
+ : publicError('disable_incomplete', 'sidecar 尚未完成 dormant 收尾'),
988
+ lock: this.lockView,
989
+ });
990
+ return false;
991
+ }
992
+
631
993
  const health = fetchHealth ? await this.#fetchHealth(discovery) : { ok: true };
994
+ const healthBody = health.body ?? {};
995
+ const healthMismatch = health.ok && !this.#healthIdentityMatches(discovery, healthBody);
996
+ if (healthMismatch) {
997
+ this.#setState({
998
+ state: 'failed', available: false, degraded: false, managed, attached: !managed,
999
+ pid: discovery.pid, url: null, healthUrl: null,
1000
+ error: publicError('instance_mismatch', 'sidecar health 与 discovery 实例身份不一致'),
1001
+ lock: this.lockView,
1002
+ });
1003
+ return false;
1004
+ }
632
1005
  if (health.ok) {
633
1006
  this.readySeen = true;
1007
+ this.dormantLock = null;
1008
+ this.dormantLockInvalidated = false;
1009
+ await this.#clearDormantState();
634
1010
  const degraded = discovery.degraded === true || health.degraded === true;
635
1011
  this.#setState({
636
1012
  state: degraded ? 'degraded' : 'ready',
@@ -644,6 +1020,7 @@ export class MemoryRuntimeSupervisor {
644
1020
  apiVersion: discovery.apiVersion ?? null,
645
1021
  capabilityApiVersion: discovery.capabilityApiVersion ?? null,
646
1022
  startedAt: discovery.startedAt ?? null,
1023
+ discoveryMode: 'immersive',
647
1024
  lastOkAt: this.now(),
648
1025
  restarts: this.restarts,
649
1026
  reason: null,
@@ -656,6 +1033,7 @@ export class MemoryRuntimeSupervisor {
656
1033
  const starting = managed && !this.readySeen;
657
1034
  this.#setState({
658
1035
  state: starting ? 'starting' : 'degraded',
1036
+ available: false,
659
1037
  degraded: !starting,
660
1038
  managed,
661
1039
  attached: !managed,
@@ -666,6 +1044,7 @@ export class MemoryRuntimeSupervisor {
666
1044
  apiVersion: discovery.apiVersion ?? null,
667
1045
  capabilityApiVersion: discovery.capabilityApiVersion ?? null,
668
1046
  startedAt: discovery.startedAt ?? null,
1047
+ discoveryMode: discovery.mode,
669
1048
  restarts: this.restarts,
670
1049
  error: starting ? null : publicError('health_check_failed', 'sidecar 健康检查失败'),
671
1050
  lock: this.lockView,
@@ -674,7 +1053,8 @@ export class MemoryRuntimeSupervisor {
674
1053
  }
675
1054
 
676
1055
  async status() {
677
- if (!this.isEnabled() && !this.statusState.managed && !this.statusState.pid) {
1056
+ if (!this.isEnabled() && !this.statusState.managed && !this.statusState.pid
1057
+ && this.statusState.error?.code !== 'disable_incomplete') {
678
1058
  this.statusState = makeDisabledStatus({ enabled: false, reason: 'disabled' });
679
1059
  }
680
1060
  try {
@@ -700,9 +1080,10 @@ export class MemoryRuntimeSupervisor {
700
1080
  state: result.state,
701
1081
  reason: result.reason ?? null,
702
1082
  error: result.error ?? null,
703
- mode: null,
1083
+ mode: this.statusState.discoveryMode ?? null,
704
1084
  runtimeVersion: null,
705
1085
  degraded: result.state === 'degraded',
1086
+ capability: null,
706
1087
  model: null,
707
1088
  };
708
1089
  }
@@ -734,6 +1115,14 @@ export class MemoryRuntimeSupervisor {
734
1115
  mode: typeof data.mode === 'string' ? data.mode : null,
735
1116
  runtimeVersion: typeof data.runtimeVersion === 'string' ? data.runtimeVersion : null,
736
1117
  degraded: data.degraded === true || result.body?.degraded === true,
1118
+ capability: isObject(data.capability)
1119
+ ? {
1120
+ reachable: data.capability.reachable === true,
1121
+ version: Number.isInteger(data.capability.version) ? data.capability.version : null,
1122
+ lastOkAt: typeof data.capability.lastOkAt === 'number' ? data.capability.lastOkAt : null,
1123
+ error: typeof data.capability.error === 'string' ? data.capability.error : null,
1124
+ }
1125
+ : null,
737
1126
  model,
738
1127
  };
739
1128
  }
@@ -923,7 +1312,7 @@ export class MemoryRuntimeSupervisor {
923
1312
  };
924
1313
  }
925
1314
  const data = result.body?.data ?? result.body ?? {};
926
- const traces = Array.isArray(data.traces) ? data.traces : [];
1315
+ const traces = Array.isArray(data.traces) ? data.traces.slice(0, safeLimit).map(traceSummaryView) : [];
927
1316
  if (!result.ok) {
928
1317
  return {
929
1318
  ok: false,
@@ -1001,7 +1390,7 @@ export class MemoryRuntimeSupervisor {
1001
1390
  available: true,
1002
1391
  disabled: false,
1003
1392
  state: result.state,
1004
- trace: data,
1393
+ trace: traceDetailView(data),
1005
1394
  degraded: result.body?.degraded === true,
1006
1395
  };
1007
1396
  }
@@ -1051,35 +1440,132 @@ export class MemoryRuntimeSupervisor {
1051
1440
  }
1052
1441
 
1053
1442
  async #resolveHostToken(discovery) {
1054
- if (this.child && discovery?.pid === this.child.pid && typeof this.childToken === 'string') {
1055
- return this.childToken;
1056
- }
1057
1443
  const fromEnv = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN);
1058
- if (fromEnv) return fromEnv;
1444
+ if (fromEnv) return { token: fromEnv, source: 'override', refreshable: false };
1059
1445
  if (typeof discovery?.tokenFile !== 'string' || discovery.tokenFile.length === 0) return null;
1060
- // 只读当前 home 的 sidecar token;discovery 路径不匹配时拒绝读取。
1446
+ // 只读当前 home 的生产 JSON token;raw 文件不是隐式生产回退格式。
1061
1447
  if (resolve(dirname(discovery.tokenFile)) !== this.paths.dataDir) return null;
1062
1448
  try {
1063
- const token = (await readFile(discovery.tokenFile, 'utf-8')).trim();
1064
- return token.length > 0 ? token : null;
1449
+ if (process.platform !== 'win32' && ((await stat(discovery.tokenFile)).mode & 0o077) !== 0) return null;
1450
+ const record = JSON.parse(await readFile(discovery.tokenFile, 'utf-8'));
1451
+ if (record?.version !== 1 || typeof record?.token !== 'string' || record.token.length === 0) return null;
1452
+ if (typeof record.expiresAt === 'number' && record.expiresAt > 0 && this.now() >= record.expiresAt) return null;
1453
+ return { token: record.token, source: 'file', refreshable: true };
1454
+ } catch {
1455
+ // 显式测试/嵌入在文件尚未可见时仍可使用本子进程持有的凭据。
1456
+ if (this.child && discovery?.pid === this.child.pid && typeof this.childToken === 'string') {
1457
+ return { token: this.childToken, source: 'child', refreshable: true };
1458
+ }
1459
+ return null;
1460
+ }
1461
+ }
1462
+
1463
+ async #removeDiscoveryIfMatches(expected) {
1464
+ if (!expected || this.#homeMismatch(expected) || this.#profileMismatch(expected)) return false;
1465
+ const current = await readDiscovery(this.paths.discoveryPath);
1466
+ if (!sameDiscoveryInstance(current, expected)) return false;
1467
+ // 删除前再读一次,缩窄操作者重启/替换实例时的竞态窗口。
1468
+ const confirmed = await readDiscovery(this.paths.discoveryPath);
1469
+ if (!sameDiscoveryInstance(confirmed, expected)) return false;
1470
+ await unlink(this.paths.discoveryPath);
1471
+ return true;
1472
+ }
1473
+
1474
+ async #readSidecarMode(discovery) {
1475
+ const age = this.now() - discovery.updatedAt;
1476
+ if (!validDiscoveryUrls(discovery) || this.#homeMismatch(discovery)
1477
+ || this.#profileMismatch(discovery) || this.#versionMismatch(discovery)
1478
+ || !Number.isFinite(age) || age < -1000 || age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) {
1479
+ return null;
1480
+ }
1481
+ const health = await this.#fetchHealth(discovery, { acceptDormant: true });
1482
+ if (!this.#healthIdentityMatches(discovery, health.body, { allowDormant: true })) return null;
1483
+ const credential = await this.#resolveHostToken(discovery);
1484
+ if (!credential || !this.fetchImpl) return null;
1485
+ const controller = new AbortController();
1486
+ const timer = setTimeout(() => controller.abort(), Math.max(1, this.healthTimeoutMs));
1487
+ timer.unref?.();
1488
+ try {
1489
+ const response = await this.fetchImpl(`${discovery.url.replace(/\/+$/, '')}/status`, {
1490
+ method: 'GET',
1491
+ headers: { accept: 'application/json', authorization: `Bearer ${credential.token}` },
1492
+ signal: controller.signal,
1493
+ });
1494
+ if (!response?.ok) return null;
1495
+ const body = await response.json().catch(() => null);
1496
+ const data = body?.data;
1497
+ if (data?.pid !== discovery.pid) return null;
1498
+ if (typeof data.startedAt === 'number' && data.startedAt !== discovery.startedAt) return null;
1499
+ const mode = data?.mode;
1500
+ const state = data?.state;
1501
+ if ((mode !== 'mcp' && mode !== 'immersive') || typeof state !== 'string') return null;
1502
+ return { mode, state };
1065
1503
  } catch {
1066
1504
  return null;
1505
+ } finally {
1506
+ clearTimeout(timer);
1067
1507
  }
1068
1508
  }
1069
1509
 
1510
+ async #waitAttachedDormant(discovery, timeoutMs) {
1511
+ // 陈旧/非法 discovery 无法证明实例身份:不发送 HTTP,立即报告 incomplete。
1512
+ const age = this.now() - discovery.updatedAt;
1513
+ if (!validDiscoveryUrls(discovery)
1514
+ || this.#homeMismatch(discovery)
1515
+ || this.#profileMismatch(discovery)
1516
+ || this.#versionMismatch(discovery)
1517
+ || !Number.isFinite(age)
1518
+ || age < -1000
1519
+ || age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) {
1520
+ return false;
1521
+ }
1522
+ const deadline = Date.now() + Math.max(0, timeoutMs);
1523
+ for (;;) {
1524
+ if (!pidAlive(discovery.pid)) return true;
1525
+ const observed = await this.#readSidecarMode(discovery);
1526
+ if (observed?.mode === 'mcp' && observed.state === 'stopped') return true;
1527
+ if (Date.now() >= deadline) return false;
1528
+ await sleep(Math.min(50, Math.max(1, deadline - Date.now())));
1529
+ }
1530
+ }
1531
+
1532
+ /**
1533
+ * 显式 stop 前的实例校验:与 attach 使用同一套 freshness/URL/home/profile/version、
1534
+ * health 身份和 token 鉴权的 /status 校验;任何一项无法确认都不得发送信号。
1535
+ */
1536
+ async #verifyLiveInstance(discovery, { requireDiscovery = true } = {}) {
1537
+ if (!discovery || !Number.isInteger(discovery.pid) || !pidAlive(discovery.pid)) return false;
1538
+ if (this.#homeMismatch(discovery) || this.#profileMismatch(discovery) || this.#versionMismatch(discovery)) {
1539
+ return false;
1540
+ }
1541
+ if (!validDiscoveryUrls(discovery)) return false;
1542
+ const age = this.now() - discovery.updatedAt;
1543
+ if (!Number.isFinite(age) || age < -1000 || age > MEMORY_RUNTIME_DISCOVERY_STALE_MS) return false;
1544
+ const health = await this.#fetchHealth(discovery, { acceptDormant: true });
1545
+ if (!health.ok || !this.#healthIdentityMatches(discovery, health.body, { allowDormant: true })) {
1546
+ return false;
1547
+ }
1548
+ // 需要 host token 的 /status:确认 pid(以及新实例提供的 startedAt)仍属于同一实例。
1549
+ const observed = await this.#readSidecarMode(discovery);
1550
+ if (!observed) return false;
1551
+ if (health.body?.ready === false
1552
+ && !(observed.mode === 'mcp' && observed.state === 'stopped')) {
1553
+ return false;
1554
+ }
1555
+ if (!requireDiscovery) return true;
1556
+ // 探测期间实例可能被替换;确认 discovery 仍是同一 pid/startedAt/url/tokenFile。
1557
+ return sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), discovery);
1558
+ }
1559
+
1070
1560
  async #proxyHostApi(pathname, { method = 'GET', body = null, timeoutMs = 2500 } = {}) {
1071
1561
  await this.status().catch(() => undefined);
1072
1562
  if (!this.isEnabled()) {
1073
1563
  return {
1074
- enabled: false,
1075
- available: false,
1076
- disabled: true,
1077
- state: 'stopped',
1078
- reason: 'disabled',
1079
- error: null,
1564
+ enabled: false, available: false, disabled: true, state: 'stopped', reason: 'disabled', error: null,
1080
1565
  };
1081
1566
  }
1082
- if (!['ready', 'degraded'].includes(this.statusState.state) || typeof this.statusState.url !== 'string') {
1567
+ if (!this.statusState.available || !['ready', 'degraded'].includes(this.statusState.state)
1568
+ || typeof this.statusState.url !== 'string') {
1083
1569
  return {
1084
1570
  enabled: true,
1085
1571
  available: false,
@@ -1089,73 +1575,97 @@ export class MemoryRuntimeSupervisor {
1089
1575
  error: this.statusState.error ?? publicError('sidecar_unavailable', 'Memory Runtime sidecar 未就绪'),
1090
1576
  };
1091
1577
  }
1578
+ const validatedDiscovery = (candidate) => {
1579
+ const age = candidate ? this.now() - candidate.updatedAt : Number.POSITIVE_INFINITY;
1580
+ return candidate
1581
+ && candidate.pid === this.statusState.pid
1582
+ && candidate.startedAt === this.statusState.startedAt
1583
+ && candidate.url === this.statusState.url
1584
+ && candidate.mode === 'immersive'
1585
+ && age >= -1000 && age <= MEMORY_RUNTIME_DISCOVERY_STALE_MS
1586
+ && validDiscoveryUrls(candidate)
1587
+ && !this.#homeMismatch(candidate)
1588
+ && !this.#profileMismatch(candidate)
1589
+ && !this.#versionMismatch(candidate);
1590
+ };
1092
1591
  const discovery = await readDiscovery(this.paths.discoveryPath);
1093
- if (!discovery) {
1592
+ if (!validatedDiscovery(discovery)) {
1094
1593
  return {
1095
1594
  enabled: true,
1096
1595
  available: false,
1097
1596
  disabled: false,
1098
1597
  state: this.statusState.state,
1099
1598
  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'),
1599
+ error: publicError(discovery ? 'instance_mismatch' : 'discovery_missing', 'sidecar discovery 已变化或失效'),
1112
1600
  };
1113
1601
  }
1114
1602
  if (!this.fetchImpl) {
1115
1603
  return {
1116
- enabled: true,
1117
- available: false,
1118
- disabled: false,
1119
- state: this.statusState.state,
1120
- reason: null,
1604
+ enabled: true, available: false, disabled: false, state: this.statusState.state, reason: null,
1121
1605
  error: publicError('fetch_unavailable', '当前运行环境不支持 HTTP 代理'),
1122
1606
  };
1123
1607
  }
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;
1608
+
1609
+ const requestId = `proxy_${randomBytes(16).toString('hex')}`;
1610
+ const attemptedSecrets = new Set();
1611
+ const execute = async (instance, token) => {
1612
+ attemptedSecrets.add(token);
1613
+ const controller = new AbortController();
1614
+ const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs));
1615
+ timer.unref?.();
1142
1616
  try {
1143
- parsed = text.length > 0 ? JSON.parse(text) : null;
1144
- } catch {
1145
- parsed = null;
1617
+ const base = instance.url.replace(/\/+$/, '');
1618
+ const url = new URL(`${base}/${String(pathname).replace(/^\/+/, '')}`);
1619
+ const headers = {
1620
+ accept: 'application/json',
1621
+ authorization: `Bearer ${token}`,
1622
+ 'x-request-id': requestId,
1623
+ };
1624
+ const init = { method, headers, signal: controller.signal };
1625
+ if (body !== null && body !== undefined) {
1626
+ headers['content-type'] = 'application/json';
1627
+ init.body = JSON.stringify(body);
1628
+ }
1629
+ const response = await this.fetchImpl(url.toString(), init);
1630
+ const text = await response.text().catch(() => '');
1631
+ let parsed = null;
1632
+ try {
1633
+ parsed = text.length > 0 ? JSON.parse(text) : null;
1634
+ } catch {
1635
+ parsed = null;
1636
+ }
1637
+ return { response, text, parsed };
1638
+ } catch (error) {
1639
+ return { transportError: error };
1640
+ } finally {
1641
+ clearTimeout(timer);
1146
1642
  }
1147
- const scrubbed = scrubProxyValue(parsed, [token, this.childToken]);
1643
+ };
1644
+
1645
+ let credential = await this.#resolveHostToken(discovery);
1646
+ if (!credential) {
1148
1647
  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]) } : {}),
1648
+ enabled: true, available: false, disabled: false, state: this.statusState.state, reason: null,
1649
+ error: publicError('host_token_missing', '无法读取 sidecar host token'),
1157
1650
  };
1158
- } catch (error) {
1651
+ }
1652
+ let attemptedDiscovery = discovery;
1653
+ let attempt = await execute(attemptedDiscovery, credential.token);
1654
+ if (attempt.response?.status === 401 && credential.refreshable) {
1655
+ // 操作者可能已在 401 前后重启 sidecar;新实例也必须重新通过完整校验。
1656
+ await this.status().catch(() => undefined);
1657
+ const current = await readDiscovery(this.paths.discoveryPath);
1658
+ if (validatedDiscovery(current)) {
1659
+ const refreshed = await this.#resolveHostToken(current);
1660
+ if (refreshed?.refreshable) {
1661
+ attemptedDiscovery = current;
1662
+ credential = refreshed;
1663
+ attempt = await execute(attemptedDiscovery, credential.token);
1664
+ }
1665
+ }
1666
+ }
1667
+ if (attempt.transportError) {
1668
+ const error = attempt.transportError;
1159
1669
  return {
1160
1670
  enabled: true,
1161
1671
  available: false,
@@ -1167,9 +1677,20 @@ export class MemoryRuntimeSupervisor {
1167
1677
  error?.name === 'AbortError' ? 'sidecar 请求超时' : '无法连接 Memory Runtime sidecar',
1168
1678
  ),
1169
1679
  };
1170
- } finally {
1171
- clearTimeout(timer);
1172
1680
  }
1681
+ const secrets = [...attemptedSecrets, this.childToken];
1682
+ return {
1683
+ enabled: true,
1684
+ available: true,
1685
+ disabled: false,
1686
+ state: this.statusState.state,
1687
+ statusCode: attempt.response.status,
1688
+ ok: attempt.response.ok === true,
1689
+ body: scrubProxyValue(attempt.parsed, secrets),
1690
+ ...(attempt.parsed === null && attempt.text.length > 0
1691
+ ? { message: redact(attempt.text, secrets) }
1692
+ : {}),
1693
+ };
1173
1694
  }
1174
1695
 
1175
1696
  #resolveCommand() {
@@ -1200,7 +1721,9 @@ export class MemoryRuntimeSupervisor {
1200
1721
  const fromEnv = stringOrNull(this.env?.MEBULAR_CAPABILITY_TOKEN);
1201
1722
  if (fromEnv) return fromEnv;
1202
1723
  const record = await readJson(this.paths.capabilityTokenPath, null);
1203
- return typeof record?.token === 'string' && record.token.length > 0 ? record.token : null;
1724
+ if (record?.version !== 1 || typeof record?.token !== 'string' || record.token.length === 0) return null;
1725
+ if (typeof record.expiresAt === 'number' && record.expiresAt > 0 && this.now() >= record.expiresAt) return null;
1726
+ return record.token;
1204
1727
  }
1205
1728
 
1206
1729
  async #waitForDiscovery(deadline) {
@@ -1387,6 +1910,15 @@ export class MemoryRuntimeSupervisor {
1387
1910
  ),
1388
1911
  lock: this.lockView,
1389
1912
  });
1913
+ appendMemoryRuntimeLogSync(this.paths.dataDir, {
1914
+ level: 'error',
1915
+ event: 'supervisor_restart',
1916
+ reason: 'child_exit',
1917
+ code: 'sidecar_crashed',
1918
+ exitCode: typeof code === 'number' ? code : null,
1919
+ signal: typeof signal === 'string' ? signal : null,
1920
+ restarts: this.restarts,
1921
+ }, { now: this.now });
1390
1922
  this.#scheduleRestart();
1391
1923
  }
1392
1924
 
@@ -1542,10 +2074,40 @@ export class MemoryRuntimeSupervisor {
1542
2074
  return false;
1543
2075
  }
1544
2076
 
2077
+ async #waitForOrphanedManagedExit(discovery) {
2078
+ const deadline = Date.now() + Math.max(100, this.configuredStartTimeout());
2079
+ this.#setState({
2080
+ state: 'starting', available: false, degraded: false, managed: false, attached: true,
2081
+ pid: discovery.pid, url: null, healthUrl: null, error: null,
2082
+ });
2083
+ for (;;) {
2084
+ const current = await readDiscovery(this.paths.discoveryPath);
2085
+ if (!sameDiscoveryInstance(current, discovery) || !pidAlive(discovery.pid)) return true;
2086
+ if (Date.now() >= deadline || this.stopping || this.disposed) return false;
2087
+ await sleep(Math.min(this.healthPollMs, 50));
2088
+ }
2089
+ }
2090
+
1545
2091
  async #startOnce({ force = false, manual = false, isRestart = false } = {}) {
1546
2092
  if (this.disposed) return this.snapshot();
1547
2093
  this.stopping = false;
1548
2094
 
2095
+ const beforeStart = await readDiscovery(this.paths.discoveryPath);
2096
+ if (beforeStart && Number.isInteger(beforeStart.parentPid)
2097
+ && beforeStart.parentPid !== process.pid && !pidAlive(beforeStart.parentPid)) {
2098
+ // 只等待旧 parent supervision 收尾;绝不替父进程杀 attached/manual 或旧 child。
2099
+ if (!await this.#waitForOrphanedManagedExit(beforeStart)) {
2100
+ if (!this.stopping && !this.disposed) {
2101
+ this.#setState({
2102
+ state: 'degraded', available: false, degraded: true, managed: false, attached: true,
2103
+ pid: beforeStart.pid,
2104
+ error: publicError('orphaned_sidecar_alive', '旧 managed sidecar 尚未按父监督退出:不终止、不替换'),
2105
+ });
2106
+ }
2107
+ return this.snapshot();
2108
+ }
2109
+ }
2110
+
1549
2111
  const discovered = await this.#refreshDiscovery({ fetchHealth: true });
1550
2112
  if (discovered && ['ready', 'degraded'].includes(this.statusState.state)) {
1551
2113
  this.#startWatchdog();
@@ -1588,7 +2150,17 @@ export class MemoryRuntimeSupervisor {
1588
2150
  });
1589
2151
  return this.snapshot();
1590
2152
  }
1591
- if (existing) await unlink(this.paths.discoveryPath).catch(() => undefined);
2153
+ if (existing) {
2154
+ const removed = await this.#removeDiscoveryIfMatches(existing).catch(() => false);
2155
+ const remaining = removed ? null : await readDiscovery(this.paths.discoveryPath);
2156
+ if (sameDiscoveryInstance(remaining, existing)) {
2157
+ this.#setState({
2158
+ state: 'failed', available: false, degraded: false,
2159
+ error: publicError('discovery_cleanup_failed', '无法安全清理旧 discovery:不启动替换实例'),
2160
+ });
2161
+ return this.snapshot();
2162
+ }
2163
+ }
1592
2164
 
1593
2165
  const lock = await this.#readLockView();
1594
2166
  if (lock && pidAlive(lock.pid)) {
@@ -1604,6 +2176,76 @@ export class MemoryRuntimeSupervisor {
1604
2176
  });
1605
2177
  return this.snapshot();
1606
2178
  }
2179
+ // 已验证的 dormant 外部/manual 实例不是“正在启动”:不要卡在 sidecar_starting。
2180
+ const dormantCandidate = this.#discoveryFromLock(lock);
2181
+ if (dormantCandidate && await this.#verifyLiveInstance(dormantCandidate, { requireDiscovery: false })) {
2182
+ const observed = await this.#readSidecarMode(dormantCandidate);
2183
+ if (observed?.mode === 'mcp' && observed.state === 'stopped') {
2184
+ const persisted = await this.#readDormantState();
2185
+ const persistedMatches = persisted
2186
+ && persisted.pid === lock.pid
2187
+ && persisted.startedAt === lock.startedAt
2188
+ ? persisted
2189
+ : null;
2190
+ if (persisted && !persistedMatches) await this.#clearDormantState();
2191
+ const inMemoryBaseline = this.dormantLock
2192
+ && this.dormantLock.pid === lock.pid
2193
+ && this.dormantLock.startedAt === lock.startedAt
2194
+ ? this.dormantLock.credential
2195
+ : undefined;
2196
+ const baseline = inMemoryBaseline !== undefined
2197
+ ? inMemoryBaseline
2198
+ : (persistedMatches ? persistedMatches.credential : undefined);
2199
+ const credential = await this.#capabilityFingerprint();
2200
+ if (!this.dormantLockInvalidated) {
2201
+ if (baseline === undefined) {
2202
+ // 没有可信 baseline(文件缺失/损坏/权限异常/写失败):不能证明仍是同一代 dormant 实例,
2203
+ // 保守进入 starting,绝不报告 clean stopped。
2204
+ this.dormantLockInvalidated = true;
2205
+ } else if (baseline !== credential) {
2206
+ // 保留旧 baseline:同一进程重启后仍据此判定凭据已换代,不得回退 stopped。
2207
+ this.dormantLock = null;
2208
+ this.dormantLockInvalidated = true;
2209
+ }
2210
+ }
2211
+ const resumeDeadline = this.now() + Math.min(500, this.configuredStartTimeout());
2212
+ while (this.now() < resumeDeadline) {
2213
+ const discovery = await readDiscovery(this.paths.discoveryPath);
2214
+ if (discovery) {
2215
+ const ready = await this.#refreshDiscovery({ fetchHealth: true });
2216
+ if (ready) return this.snapshot();
2217
+ break;
2218
+ }
2219
+ await sleep(50);
2220
+ }
2221
+ if (!this.dormantLockInvalidated) {
2222
+ this.#setState({
2223
+ state: 'stopped',
2224
+ available: false,
2225
+ degraded: false,
2226
+ managed: false,
2227
+ attached: false,
2228
+ pid: lock.pid,
2229
+ url: null,
2230
+ healthUrl: null,
2231
+ reason: 'disabled',
2232
+ error: null,
2233
+ lock: this.lockView,
2234
+ });
2235
+ this.dormantLock = {
2236
+ pid: lock.pid,
2237
+ startedAt: lock.startedAt,
2238
+ credential,
2239
+ };
2240
+ await this.#writeDormantState({
2241
+ pid: lock.pid,
2242
+ startedAt: lock.startedAt,
2243
+ credential,
2244
+ });
2245
+ return this.snapshot();
2246
+ }
2247
+ }
2248
+ }
1607
2249
  const deadline = this.now() + Math.max(100, this.configuredStartTimeout());
1608
2250
  const ready = await this.#waitForDiscovery(deadline);
1609
2251
  if (ready) {
@@ -1614,6 +2256,26 @@ export class MemoryRuntimeSupervisor {
1614
2256
  if (this.statusState.error && ['profile_mismatch', 'home_mismatch', 'version_incompatible'].includes(this.statusState.error.code)) {
1615
2257
  return this.snapshot();
1616
2258
  }
2259
+ if (this.dormantLockInvalidated
2260
+ && this.lockView
2261
+ && Number.isInteger(this.lockView.pid)
2262
+ && pidAlive(this.lockView.pid)) {
2263
+ this.#setState({
2264
+ state: 'starting',
2265
+ available: false,
2266
+ degraded: false,
2267
+ managed: false,
2268
+ attached: false,
2269
+ pid: this.lockView.pid,
2270
+ url: null,
2271
+ healthUrl: null,
2272
+ discoveryMode: 'mcp',
2273
+ reason: null,
2274
+ error: null,
2275
+ lock: this.lockView,
2276
+ });
2277
+ return this.snapshot();
2278
+ }
1617
2279
  this.#setState({
1618
2280
  state: 'failed',
1619
2281
  degraded: false,
@@ -1667,15 +2329,19 @@ export class MemoryRuntimeSupervisor {
1667
2329
 
1668
2330
  async stop({ includeAttached = false, timeoutMs = 5000 } = {}) {
1669
2331
  this.stopping = true;
2332
+ let dormantBaseline = null;
1670
2333
  this.#clearRestartTimer();
1671
2334
  this.#clearCooldownTimer();
1672
2335
  this.#stopWatchdog();
1673
2336
 
1674
- // 让正在启动的流程看到 stopping 并退出,避免它在本函数返回后又拉起子进程。
1675
- if (this.startPromise) {
1676
- await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1677
- }
2337
+ if (this.startPromise) await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
2338
+ const discoveredAtStop = await readDiscovery(this.paths.discoveryPath);
1678
2339
  const child = this.child;
2340
+ const attachedDiscovery = discoveredAtStop
2341
+ && discoveredAtStop.pid !== child?.pid
2342
+ && discoveredAtStop.pid !== this.managedInstance?.pid
2343
+ ? discoveredAtStop
2344
+ : null;
1679
2345
  if (child) {
1680
2346
  this.#killChild('SIGTERM');
1681
2347
  await this.#waitChildExit(child, timeoutMs);
@@ -1685,9 +2351,7 @@ export class MemoryRuntimeSupervisor {
1685
2351
  }
1686
2352
  if (this.child === child) this.child = null;
1687
2353
  }
1688
- if (this.startPromise) {
1689
- await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1690
- }
2354
+ if (this.startPromise) await Promise.race([this.startPromise.catch(() => undefined), sleep(250)]);
1691
2355
  const lateChild = this.child;
1692
2356
  if (lateChild && lateChild !== child) {
1693
2357
  this.#killChild('SIGTERM');
@@ -1696,55 +2360,259 @@ export class MemoryRuntimeSupervisor {
1696
2360
  if (this.child === lateChild) this.child = null;
1697
2361
  }
1698
2362
 
1699
- // Windows 的 SIGTERM 是强制终止,sidecar 可能来不及清理 discovery/lock。
1700
- // 只清理确实属于本 supervisor 已停止子进程的残留,不碰 attach 实例。
1701
- const stoppedPids = new Set([child?.pid, lateChild?.pid].filter((pid) => Number.isInteger(pid)));
2363
+ let clean = true;
2364
+ const stoppedPids = new Set([child?.pid, lateChild?.pid, this.managedInstance?.pid]
2365
+ .filter((pid) => Number.isInteger(pid)));
1702
2366
  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);
2367
+ if (pidAlive(pid)) {
2368
+ clean = false;
2369
+ continue;
2370
+ }
2371
+ const current = await readDiscovery(this.paths.discoveryPath);
2372
+ const knownStartedAt = discoveredAtStop?.pid === pid
2373
+ ? discoveredAtStop.startedAt
2374
+ : this.managedInstance?.pid === pid
2375
+ ? this.managedInstance.startedAt
2376
+ : this.statusState.pid === pid ? this.statusState.startedAt : null;
2377
+ if (current?.pid === pid && knownStartedAt !== null && current.startedAt === knownStartedAt) {
2378
+ const expected = current;
2379
+ const removed = await this.#removeDiscoveryIfMatches(expected).catch(() => false);
2380
+ if (!removed && sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), expected)) {
2381
+ clean = false;
2382
+ }
2383
+ } else if (current?.pid === pid) {
2384
+ // 身份不明的残留不得删除,也不得静默当作已清理。
2385
+ clean = false;
1707
2386
  }
1708
2387
  const lock = await this.#readLockView();
1709
2388
  if (lock?.pid === pid) {
1710
- await unlink(this.paths.lockPath).catch(() => undefined);
2389
+ if (knownStartedAt === null || lock.startedAt !== knownStartedAt) {
2390
+ clean = false;
2391
+ } else {
2392
+ await unlink(this.paths.lockPath).catch(() => {
2393
+ clean = false;
2394
+ });
2395
+ }
1711
2396
  }
1712
2397
  }
1713
2398
 
1714
2399
  if (includeAttached) {
1715
- await this.#readLockView();
1716
2400
  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);
2401
+ const verified = discovery && await this.#verifyLiveInstance(discovery)
2402
+ ? discovery
2403
+ : null;
2404
+ if (verified) {
2405
+ // 信号前二次读取,缩窄操作者重启/替换实例的竞态窗口。
2406
+ const confirmed = await readDiscovery(this.paths.discoveryPath);
2407
+ if (!sameDiscoveryInstance(confirmed, verified)) {
2408
+ clean = false;
2409
+ } else {
2410
+ if (pidAlive(verified.pid) && !await this.#stopPid(verified.pid, timeoutMs)) clean = false;
2411
+ if (!pidAlive(verified.pid)) {
2412
+ const removed = await this.#removeDiscoveryIfMatches(verified).catch(() => false);
2413
+ if (!removed && sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), verified)) {
2414
+ clean = false;
2415
+ }
2416
+ }
2417
+ }
2418
+ } else if (discovery) {
2419
+ // 不可验证的 live PID 绝不 kill;只允许清理已退出实例的匹配 discovery。
2420
+ if (!pidAlive(discovery.pid)) {
2421
+ const removed = await this.#removeDiscoveryIfMatches(discovery).catch(() => false);
2422
+ if (!removed && sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), discovery)) {
2423
+ clean = false;
2424
+ }
2425
+ } else {
2426
+ clean = false;
2427
+ }
2428
+ }
2429
+ const lock = await this.#readLockView();
2430
+ if (lock && lock.command === 'serve') {
2431
+ if (!pidAlive(lock.pid)) {
2432
+ await unlink(this.paths.lockPath).catch(() => {
2433
+ clean = false;
2434
+ });
2435
+ } else {
2436
+ // 只有 lock 与已验证 discovery 的 pid/startedAt 完全一致时才允许信号;
2437
+ // 否则可能是复用 PID 或陈旧锁,必须留给操作者处理并报告 incomplete。
2438
+ const matchesVerified = Boolean(verified)
2439
+ && verified.pid === lock.pid
2440
+ && verified.startedAt === lock.startedAt;
2441
+ if (!matchesVerified) {
2442
+ // discovery 已被 stop 删除时,从 start.lock + health/status identity + pid/startedAt 验证;
2443
+ // 不重建 discovery,也不对不可验证的复用 PID 发信号。
2444
+ const candidate = this.#discoveryFromLock(lock);
2445
+ const verifiedFromLock = candidate
2446
+ && await this.#verifyLiveInstance(candidate, { requireDiscovery: false });
2447
+ if (!verifiedFromLock) {
2448
+ clean = false;
2449
+ } else {
2450
+ const confirmedLock = await this.#readLockView();
2451
+ if (!confirmedLock
2452
+ || confirmedLock.pid !== lock.pid
2453
+ || confirmedLock.startedAt !== lock.startedAt
2454
+ || !pidAlive(lock.pid)) {
2455
+ clean = false;
2456
+ } else if (!await this.#stopPid(lock.pid, timeoutMs)) {
2457
+ clean = false;
2458
+ }
2459
+ }
2460
+ } else {
2461
+ const confirmedLock = await this.#readLockView();
2462
+ const confirmedDiscovery = await readDiscovery(this.paths.discoveryPath);
2463
+ if (!confirmedLock
2464
+ || confirmedLock.pid !== lock.pid
2465
+ || confirmedLock.startedAt !== lock.startedAt
2466
+ || !sameDiscoveryInstance(confirmedDiscovery, verified)
2467
+ || !pidAlive(lock.pid)) {
2468
+ clean = false;
2469
+ } else if (!await this.#stopPid(lock.pid, timeoutMs)) {
2470
+ clean = false;
2471
+ }
2472
+ }
1722
2473
  }
1723
2474
  }
2475
+ const remainingLock = await this.#readLockView();
2476
+ if (remainingLock && !pidAlive(remainingLock.pid)) {
2477
+ await unlink(this.paths.lockPath).catch(() => {
2478
+ clean = false;
2479
+ });
2480
+ }
2481
+ } else if (attachedDiscovery && !this.#homeMismatch(attachedDiscovery)
2482
+ && !this.#profileMismatch(attachedDiscovery)) {
2483
+ // D1:外部 PID 归操作者;仅撤销匹配 discovery,再验证旧凭据也无法工作。
2484
+ const capabilityBefore = await this.#capabilityFingerprint();
2485
+ await this.#removeDiscoveryIfMatches(attachedDiscovery).catch(() => false);
2486
+ if (pidAlive(attachedDiscovery.pid)
2487
+ && !await this.#waitAttachedDormant(
2488
+ attachedDiscovery,
2489
+ Math.max(timeoutMs, MEMORY_RUNTIME_ATTACHED_DORMANT_WAIT_MS),
2490
+ )) {
2491
+ clean = false;
2492
+ }
2493
+ let remaining = await readDiscovery(this.paths.discoveryPath);
2494
+ const needsDormant = (candidate) => candidate
2495
+ && !this.#homeMismatch(candidate)
2496
+ && !this.#profileMismatch(candidate)
2497
+ && !this.#versionMismatch(candidate)
2498
+ && (candidate.mode !== 'mcp' || candidate.state !== 'stopped');
2499
+ if (needsDormant(remaining)) {
2500
+ // 操作者可能在禁用期间替换实例;新实例同样必须撤销并验证,不能漏过。
2501
+ await this.#removeDiscoveryIfMatches(remaining).catch(() => false);
2502
+ if (pidAlive(remaining.pid)
2503
+ && !await this.#waitAttachedDormant(
2504
+ remaining,
2505
+ Math.max(timeoutMs, MEMORY_RUNTIME_ATTACHED_DORMANT_WAIT_MS),
2506
+ )) {
2507
+ clean = false;
2508
+ }
2509
+ remaining = await readDiscovery(this.paths.discoveryPath);
2510
+ }
2511
+ if (needsDormant(remaining)) clean = false;
2512
+ // 能力仍有效且凭据未撤销/未换代:不能把“可能被同一 token 唤醒”的实例报告为 clean stopped。
2513
+ const capabilityAfter = await this.#capabilityFingerprint();
2514
+ const credentialUnchanged = capabilityBefore === null
2515
+ ? capabilityAfter !== null
2516
+ : capabilityAfter === capabilityBefore;
2517
+ if (credentialUnchanged) clean = false;
2518
+ // 外部进程仍存活:记录停止时的 credential baseline(可能是 null=已撤销)。
2519
+ // 下一次 start 只有在当前凭据仍等于 baseline 时才允许报告 stopped。
2520
+ if (pidAlive(attachedDiscovery.pid)) {
2521
+ dormantBaseline = {
2522
+ pid: attachedDiscovery.pid,
2523
+ startedAt: attachedDiscovery.startedAt,
2524
+ credential: capabilityBefore,
2525
+ };
2526
+ }
2527
+ } else {
2528
+ // discovery 缺失时仍可能存活 manual/attached 实例:从 start.lock 验证 identity/token/status。
1724
2529
  const lock = await this.#readLockView();
1725
- if (lock && lock.command === 'serve' && pidAlive(lock.pid)) {
1726
- await this.#stopPid(lock.pid, timeoutMs);
2530
+ if (lock && lock.command === 'serve' && !pidAlive(lock.pid)) {
2531
+ await unlink(this.paths.lockPath).catch(() => {
2532
+ clean = false;
2533
+ });
2534
+ } else if (lock && lock.command === 'serve' && pidAlive(lock.pid)) {
2535
+ const capabilityBefore = await this.#capabilityFingerprint();
2536
+ const candidate = this.#discoveryFromLock(lock);
2537
+ const verified = candidate
2538
+ && await this.#verifyLiveInstance(candidate, { requireDiscovery: false });
2539
+ if (!verified) {
2540
+ clean = false;
2541
+ } else {
2542
+ const observed = await this.#readSidecarMode(candidate);
2543
+ if (!(observed?.mode === 'mcp' && observed.state === 'stopped')) {
2544
+ // 仍然 immersive/starting/degraded:没有确认 dormant,不能 clean。
2545
+ clean = false;
2546
+ } else {
2547
+ if (lock.pid !== this.child?.pid && lock.pid !== this.managedInstance?.pid) {
2548
+ dormantBaseline = {
2549
+ pid: lock.pid,
2550
+ startedAt: lock.startedAt,
2551
+ credential: capabilityBefore,
2552
+ };
2553
+ }
2554
+ const capabilityAfter = await this.#capabilityFingerprint();
2555
+ const credentialUnchanged = capabilityBefore === null
2556
+ ? capabilityAfter !== null
2557
+ : capabilityAfter === capabilityBefore;
2558
+ if (credentialUnchanged) clean = false;
2559
+ }
2560
+ }
1727
2561
  }
1728
- await unlink(this.paths.lockPath).catch(() => undefined);
1729
2562
  }
1730
2563
 
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
- });
2564
+ let dormantPersistError = null;
2565
+ if (dormantBaseline) {
2566
+ try {
2567
+ await this.#writeDormantState(dormantBaseline);
2568
+ } catch (error) {
2569
+ dormantPersistError = error;
2570
+ clean = false;
2571
+ }
2572
+ } else {
2573
+ await this.#clearDormantState();
2574
+ }
2575
+
2576
+ if (clean) {
2577
+ this.managedInstance = null;
2578
+ this.dormantLock = null;
2579
+ this.dormantLockInvalidated = false;
2580
+ this.#setState({
2581
+ state: 'stopped', available: false, degraded: false, managed: false, attached: false,
2582
+ pid: null, url: null, healthUrl: null, error: null,
2583
+ reason: this.isEnabled() ? null : 'disabled', lock: null,
2584
+ });
2585
+ } else {
2586
+ this.#setState({
2587
+ state: 'degraded', available: false, degraded: true, managed: false,
2588
+ attached: Boolean(attachedDiscovery && pidAlive(attachedDiscovery.pid)),
2589
+ pid: attachedDiscovery && pidAlive(attachedDiscovery.pid) ? attachedDiscovery.pid : null,
2590
+ url: null, healthUrl: null,
2591
+ error: dormantPersistError
2592
+ ? publicError(includeAttached ? 'stop_incomplete' : 'disable_incomplete',
2593
+ `sidecar 休眠凭据基线写入失败(${dormantPersistError?.code ?? 'ERROR'})`)
2594
+ : publicError(includeAttached ? 'stop_incomplete' : 'disable_incomplete',
2595
+ includeAttached ? 'sidecar 未能完整停止' : 'sidecar 未确认 dormant:禁用不完整'),
2596
+ reason: this.isEnabled() ? null : 'disabled', lock: this.lockView,
2597
+ });
2598
+ }
1743
2599
  this.stopping = false;
1744
2600
  return this.snapshot();
1745
2601
  }
1746
2602
 
1747
2603
  async restart({ includeAttached = false, timeoutMs = 5000, manual = false, force = true } = {}) {
2604
+ if (!includeAttached && !this.child) {
2605
+ const external = await readDiscovery(this.paths.discoveryPath);
2606
+ if (external && pidAlive(external.pid)) {
2607
+ // 配置变化不是操作者 restart:不撤销/替换 attached/manual 实例。
2608
+ return this.start({ force: false, manual: false });
2609
+ }
2610
+ }
2611
+ appendMemoryRuntimeLogSync(this.paths.dataDir, {
2612
+ level: 'info',
2613
+ event: 'supervisor_restart',
2614
+ reason: manual ? 'operator_restart' : 'config_restart',
2615
+ }, { now: this.now });
1748
2616
  await this.stop({ includeAttached, timeoutMs });
1749
2617
  this.crashTimes = [];
1750
2618
  this.restarts = 0;
@@ -1754,49 +2622,9 @@ export class MemoryRuntimeSupervisor {
1754
2622
 
1755
2623
  async dispose() {
1756
2624
  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
- });
2625
+ const status = await this.stop({ includeAttached: false, timeoutMs: 3000 });
2626
+ this.disposed = true;
2627
+ if (!status.error) this.#setState({ reason: 'disposed', available: false });
1800
2628
  }
1801
2629
  }
1802
2630