@mebular/mcp 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1673 @@
1
+ // 共享 Runtime Supervisor(Phase 1):profile/cloudRoot 解析、provider 发现、ensure/status。
2
+ //
3
+ // 目标边界:
4
+ // - App 与 DSH Plugin 只 attach/ensure 同一个 runtime/daemon/service;
5
+ // - 本模块放在 @mebular/mcp 内,不 import apps/desktop,也不复制 App 的业务状态机;
6
+ // - 健康 daemon → attach;已注册 service → 启动/复用;provider → 启动;否则
7
+ // `download_required`。Phase 1 **绝不下载、不安装、不升级**。
8
+ //
9
+ // 返回对象只含非敏感发现信息(profile/home/http/instance/version/provider/service),
10
+ // 不含令牌、主密钥或身份文件内容。CLI 用 `toPublicRuntimeResult` 去掉进程句柄。
11
+
12
+ import { accessSync, existsSync, readFileSync, statSync } from 'node:fs';
13
+ import { constants as fsConstants } from 'node:fs';
14
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
15
+ import { spawn } from 'node:child_process';
16
+ import { connect } from 'node:net';
17
+ import { homedir } from 'node:os';
18
+ import { delimiter, join, resolve } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { APP_VERSION } from './version.mjs';
21
+ import {
22
+ cloudError,
23
+ displayPath,
24
+ homeKey,
25
+ isHomeInRoot,
26
+ pidAlive,
27
+ profileHomeForEntry,
28
+ profileIdForHome,
29
+ readRegistry,
30
+ resolveCloudRoot,
31
+ } from './profiles.mjs';
32
+ import { readRuntimeFile, runtimePath } from './runtime-file.mjs';
33
+ import {
34
+ readRuntimeProviders,
35
+ runtimeProviderId,
36
+ } from './runtime-providers.mjs';
37
+ import {
38
+ publicRuntimeCurrent,
39
+ readRuntimeCurrent,
40
+ } from './runtime-current.mjs';
41
+ import {
42
+ RUNTIME_SERVICE_KIND,
43
+ resolveRuntimeServiceSource,
44
+ restartRuntimeService,
45
+ runtimeServiceDescriptor,
46
+ runtimeServiceStatus,
47
+ } from './runtime-service.mjs';
48
+
49
+ export const RUNTIME_DEFAULT_HOST = '127.0.0.1';
50
+ export const RUNTIME_DEFAULT_PORT = 7331;
51
+ export const RUNTIME_START_LOCK_FILE = 'runtime-start.lock';
52
+ export { RUNTIME_SERVICE_KIND };
53
+ export const RUNTIME_SERVICE_KIND_NAME = RUNTIME_SERVICE_KIND;
54
+ export const RUNTIME_PROVIDER_SOURCE_ORDER = Object.freeze({ current: -1, registry: 0, standard: 1, path: 2, self: 2 });
55
+ export const RUNTIME_PROVIDER_KIND_ORDER = Object.freeze({ app: 0, cli: 1, shared: 2 });
56
+
57
+ const HEALTH_TERMINAL_REASONS = new Set(['instance_mismatch', 'instance_missing', 'cloud_mismatch']);
58
+ const HEALTH_STATUS_TERMINAL_REASONS = new Set([...HEALTH_TERMINAL_REASONS, 'status']);
59
+
60
+ const sleep = (ms) => new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
61
+
62
+ export function runtimeStartLockPath(root) {
63
+ return join(root, RUNTIME_START_LOCK_FILE);
64
+ }
65
+
66
+ export function resolveRuntimeServiceHome({ serviceHome, env = process.env } = {}) {
67
+ return serviceHome ?? env.MEBULAR_SERVICE_UNIT_HOME ?? homedir();
68
+ }
69
+
70
+ /** 本 CLI 入口(provider 自身;不依赖 cwd)。 */
71
+ export function defaultSelfCliPath() {
72
+ return fileURLToPath(new URL('../bin/mebular.mjs', import.meta.url));
73
+ }
74
+
75
+ async function readHomeConfig(home) {
76
+ try {
77
+ return JSON.parse(await readFile(join(home, 'config.json'), 'utf-8'));
78
+ } catch {
79
+ return {};
80
+ }
81
+ }
82
+
83
+ function pickPort(value) {
84
+ const port = Number(value);
85
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
86
+ }
87
+
88
+ /** 守护 HTTP 目标:env > runtime.json(实际监听)> config.json > 默认。 */
89
+ export async function resolveRuntimeHttp(home, { env = process.env, runtime = null } = {}) {
90
+ const config = await readHomeConfig(home);
91
+ const configHttp = config?.mcp?.http ?? {};
92
+ const runtimeHttp = runtime?.http ?? {};
93
+ const rawHost = env.MEBULAR_HTTP_HOST
94
+ ?? (typeof runtimeHttp.host === 'string' && runtimeHttp.host.length > 0 ? runtimeHttp.host : null)
95
+ ?? (typeof configHttp.host === 'string' && configHttp.host.length > 0 ? configHttp.host : null)
96
+ ?? RUNTIME_DEFAULT_HOST;
97
+ const host = rawHost === '0.0.0.0' || rawHost === '::' ? RUNTIME_DEFAULT_HOST : rawHost;
98
+ const port = pickPort(env.MEBULAR_HTTP_PORT)
99
+ ?? pickPort(runtimeHttp.port)
100
+ ?? pickPort(configHttp.port)
101
+ ?? RUNTIME_DEFAULT_PORT;
102
+ const tls = configHttp.tls === true || Boolean(configHttp.tlsKey && configHttp.tlsCert);
103
+ const scheme = tls ? 'https' : 'http';
104
+ return { host, port, scheme, url: `${scheme}://${host}:${port}/healthz` };
105
+ }
106
+
107
+ /**
108
+ * 解析 runtime 所属的 cloudRoot/profile/home。
109
+ *
110
+ * 显式 home(App 传入 / 用户设置 MEBULAR_HOME)优先;未显式指定时跟随注册表 current,
111
+ * 这样 Plugin/CLI 在默认 `~/.mebular` 下也能 attach 到 App 当前的非默认 profile。
112
+ */
113
+ export async function resolveRuntimeContext({ home, env = process.env, userHome = homedir() } = {}) {
114
+ const cloud = resolveCloudRoot({ home, env, userHome });
115
+ if (!cloud.available) {
116
+ return {
117
+ ok: false,
118
+ reason: cloud.reason ?? 'cloud_unavailable',
119
+ cloudRoot: cloud.root,
120
+ home: cloud.home,
121
+ defaultHome: cloud.defaultHome,
122
+ };
123
+ }
124
+
125
+ const state = await readRegistry(cloud.root);
126
+ const explicitHome = home !== undefined
127
+ || (typeof env.MEBULAR_HOME === 'string' && env.MEBULAR_HOME.trim().length > 0);
128
+ const current = state.registry.current === null
129
+ ? null
130
+ : state.registry.profiles.find((entry) => entry.id === state.registry.current) ?? null;
131
+
132
+ let profileId = null;
133
+ let profile = null;
134
+ if (explicitHome) {
135
+ const candidateId = await profileIdForHome(cloud.root, cloud.home);
136
+ const candidate = candidateId === null
137
+ ? null
138
+ : state.registry.profiles.find((entry) => entry.id === candidateId) ?? null;
139
+ const explicitIsRoot = resolve(cloud.home) === resolve(cloud.root);
140
+ // 显式 home 是默认 root 时仍跟随 current profile:Plugin/CLI 常继承 MEBULAR_HOME=~/.mebular,
141
+ // 不能因此落到 default 而另起一张忆云。App 传入的是当前 profile home,不受影响。
142
+ if (candidate !== null && !(explicitIsRoot && current !== null && current.id !== candidate.id)) {
143
+ profileId = candidate.id;
144
+ profile = candidate;
145
+ } else if (explicitIsRoot && current !== null) {
146
+ profileId = current.id;
147
+ profile = current;
148
+ } else if (candidate !== null) {
149
+ profileId = candidate.id;
150
+ profile = candidate;
151
+ }
152
+ } else {
153
+ profileId = current?.id ?? null;
154
+ profile = current;
155
+ }
156
+
157
+ const homePath = profile !== null
158
+ ? profileHomeForEntry(cloud.root, profile)
159
+ : (isHomeInRoot(cloud.root, cloud.home) ? cloud.home : cloud.root);
160
+ const runtime = await readRuntimeFile(homePath);
161
+ const http = await resolveRuntimeHttp(homePath, { env, runtime });
162
+
163
+ return {
164
+ ok: true,
165
+ cloudRoot: cloud.root,
166
+ cloudRootDisplay: displayPath(cloud.root, { userHome }),
167
+ profileId,
168
+ profile: profile === null
169
+ ? null
170
+ : { id: profile.id, name: profile.name, home: profile.home, kind: profile.kind },
171
+ home: homePath,
172
+ homeKey: homeKey(homePath),
173
+ defaultHome: cloud.defaultHome,
174
+ registrySource: state.source,
175
+ warning: state.warning ?? null,
176
+ runtime,
177
+ runtimePath: runtime === null ? null : runtimePath(homePath),
178
+ http,
179
+ };
180
+ }
181
+
182
+ /** `<root>/active.lock`:root 级单活锁;损坏/不存在返回 null。 */
183
+ export function readActiveRuntimeLock(root) {
184
+ if (typeof root !== 'string' || root.length === 0) return null;
185
+ try {
186
+ return JSON.parse(readFileSync(join(root, 'active.lock'), 'utf-8'));
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+
192
+ export function activeLockConflict(active, home) {
193
+ if (!active || !Number.isInteger(active.pid) || !pidAlive(active.pid)) return null;
194
+ const heldHome = typeof active.home === 'string' && active.home.length > 0 ? resolve(active.home) : null;
195
+ if (heldHome === null) return null;
196
+ if (heldHome === resolve(home)) return null;
197
+ return active;
198
+ }
199
+
200
+ /**
201
+ * `/healthz` 探测详情(注入 fetch,便于单测):
202
+ * 200 但 instance/cloudId 不符 → 返回原因,调用方不得 reused / 不得继续启动。
203
+ */
204
+ export async function probeRuntimeHealth(fetchImpl, http = { url: null }, options = {}) {
205
+ const { timeoutMs = 1200, expectedInstance = null, cloudId = null } = options ?? {};
206
+ const url = http.url ?? `${http.scheme ?? 'http'}://${http.host ?? RUNTIME_DEFAULT_HOST}:${http.port ?? RUNTIME_DEFAULT_PORT}/healthz`;
207
+ let res;
208
+ try {
209
+ res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
210
+ } catch (error) {
211
+ return { ok: false, reason: 'unreachable', http, url, error: String(error?.message ?? error) };
212
+ }
213
+ if (!res?.ok) {
214
+ return { ok: false, reason: 'status', http, url, status: res?.status ?? null };
215
+ }
216
+ let body = null;
217
+ try {
218
+ body = typeof res.json === 'function' ? await res.json() : null;
219
+ } catch {
220
+ body = null;
221
+ }
222
+ const instance = typeof body?.instance === 'string' ? body.instance : null;
223
+ if (typeof expectedInstance === 'string' && expectedInstance.length > 0) {
224
+ if (instance === null) return { ok: false, reason: 'instance_missing', http, url, body };
225
+ if (instance !== expectedInstance) {
226
+ return { ok: false, reason: 'instance_mismatch', http, url, instance, body };
227
+ }
228
+ }
229
+ if (typeof cloudId === 'string' && cloudId.length > 0
230
+ && typeof body?.cloudId === 'string' && body.cloudId !== cloudId) {
231
+ return { ok: false, reason: 'cloud_mismatch', http, url, cloudId: body.cloudId, body };
232
+ }
233
+ return { ok: true, http, url, body, instance };
234
+ }
235
+
236
+ /** 等待守护就绪;instance/cloudId 不匹配与 HTTP 非 200 是终态(重试无意义)。 */
237
+ export async function waitForRuntime({
238
+ fetchImpl,
239
+ http,
240
+ attempts = 40,
241
+ intervalMs = 500,
242
+ onTick,
243
+ expectedInstance = null,
244
+ cloudId = null,
245
+ timeoutMs = 1200,
246
+ } = {}) {
247
+ let last = null;
248
+ for (let index = 0; index < attempts; index += 1) {
249
+ last = await probeRuntimeHealth(fetchImpl, http, { timeoutMs, expectedInstance, cloudId });
250
+ if (last.ok) return last;
251
+ if (HEALTH_STATUS_TERMINAL_REASONS.has(last.reason)) return last;
252
+ onTick?.(index);
253
+ if (index + 1 < attempts) await sleep(intervalMs);
254
+ }
255
+ return last ?? { ok: false, reason: 'timeout', http };
256
+ }
257
+
258
+ /** 端口是否有进程监听(只做 connect 探测,不发数据)。 */
259
+ export function isPortOpen({ host = RUNTIME_DEFAULT_HOST, port } = {}, timeoutMs = 800) {
260
+ return new Promise((resolvePromise) => {
261
+ if (!Number.isInteger(port) || port <= 0) return resolvePromise(false);
262
+ const socket = connect({ host, port });
263
+ let settled = false;
264
+ const done = (open) => {
265
+ if (settled) return;
266
+ settled = true;
267
+ socket.destroy();
268
+ resolvePromise(open);
269
+ };
270
+ socket.setTimeout(timeoutMs, () => done(false));
271
+ socket.once('connect', () => done(true));
272
+ socket.once('error', () => done(false));
273
+ });
274
+ }
275
+
276
+ function standardAppProviderPaths({ platform = process.platform, env = process.env, userHome = homedir() } = {}) {
277
+ const tail = ['node_modules', '@mebular', 'core', 'packages', 'mcp', 'bin', 'mebular.mjs'];
278
+ if (platform === 'darwin') {
279
+ return [
280
+ join('/Applications', 'Mebular.app', 'Contents', 'Resources', ...tail),
281
+ join(userHome, 'Applications', 'Mebular.app', 'Contents', 'Resources', ...tail),
282
+ ];
283
+ }
284
+ if (platform === 'win32') {
285
+ const local = env.LOCALAPPDATA ?? join(userHome, 'AppData', 'Local');
286
+ return [
287
+ join(local, 'Programs', 'Mebular', 'resources', ...tail),
288
+ join(local, 'Mebular', 'resources', ...tail),
289
+ ];
290
+ }
291
+ return [
292
+ join('/opt', 'Mebular', 'resources', ...tail),
293
+ join(userHome, '.local', 'share', 'Mebular', 'resources', ...tail),
294
+ ];
295
+ }
296
+
297
+ function findExecutableOnPath(name, { env = process.env, platform = process.platform } = {}) {
298
+ const pathEnv = env.PATH ?? env.Path ?? '';
299
+ const dirs = pathEnv.split(delimiter).filter((dir) => dir.length > 0);
300
+ const suffixes = platform === 'win32'
301
+ ? ['', '.exe', '.cmd', '.bat', '.com']
302
+ : [''];
303
+ for (const dir of dirs) {
304
+ for (const suffix of suffixes) {
305
+ const candidate = join(dir, `${name}${suffix}`);
306
+ if (!existsSync(candidate)) continue;
307
+ try {
308
+ if (!statSync(candidate).isFile()) continue;
309
+ if (platform !== 'win32') accessSync(candidate, fsConstants.X_OK);
310
+ return candidate;
311
+ } catch {
312
+ // 不可执行/无权限:继续找下一个
313
+ }
314
+ }
315
+ }
316
+ return null;
317
+ }
318
+
319
+ function providerPriority(provider) {
320
+ return [
321
+ RUNTIME_PROVIDER_KIND_ORDER[provider.kind] ?? 9,
322
+ RUNTIME_PROVIDER_SOURCE_ORDER[provider.source] ?? 9,
323
+ provider.path,
324
+ ];
325
+ }
326
+
327
+ function compareProviders(a, b) {
328
+ const left = providerPriority(a);
329
+ const right = providerPriority(b);
330
+ for (let index = 0; index < left.length; index += 1) {
331
+ if (left[index] < right[index]) return -1;
332
+ if (left[index] > right[index]) return 1;
333
+ }
334
+ return 0;
335
+ }
336
+
337
+ /**
338
+ * 发现 provider:
339
+ * 1. 注册表(App 注册的 kind:app / CLI kind:cli / shared);
340
+ * 2. 标准 App 安装路径(扩展点:打包布局变化只改这里);
341
+ * 3. PATH 上的 `mebular`;
342
+ * 4. 当前 CLI 自身(调用 `mebular runtime` 时一定可用)。
343
+ * 只返回已存在路径的 `available`;缺失路径留在 `entries` 供诊断,不参与启动。
344
+ */
345
+ export async function discoverRuntimeProviders({
346
+ root,
347
+ env = process.env,
348
+ platform = process.platform,
349
+ userHome = homedir(),
350
+ includeSelf = true,
351
+ includeStandardApp = true,
352
+ registryProviders = null,
353
+ currentState: providedCurrentState = null,
354
+ selfPath = defaultSelfCliPath(),
355
+ } = {}) {
356
+ const warnings = [];
357
+ let registry = [];
358
+ if (Array.isArray(registryProviders)) {
359
+ registry = registryProviders;
360
+ } else if (typeof root === 'string' && root.length > 0) {
361
+ const state = await readRuntimeProviders(root);
362
+ registry = state.registry.providers;
363
+ warnings.push(...state.warnings);
364
+ }
365
+
366
+ const currentState = providedCurrentState ?? (typeof root === 'string' && root.length > 0
367
+ ? await readRuntimeCurrent(root, { userHome })
368
+ : { current: null, usable: false, source: 'missing', warnings: [] });
369
+ if (currentState?.source === 'invalid') {
370
+ warnings.push(...(currentState.warnings ?? []));
371
+ }
372
+
373
+ const entries = [];
374
+ if (currentState?.usable === true && currentState.current) {
375
+ entries.push({
376
+ id: runtimeProviderId('shared', currentState.current.cliPath),
377
+ kind: 'shared',
378
+ path: currentState.current.cliPath,
379
+ version: currentState.current.version,
380
+ runtimePath: currentState.current.runtimePath,
381
+ capabilities: ['serve'],
382
+ registeredAt: currentState.current.installedAt ?? null,
383
+ updatedAt: currentState.current.installedAt ?? null,
384
+ source: 'current',
385
+ available: true,
386
+ });
387
+ }
388
+ const invalidCurrentPath = currentState?.usable !== true && currentState?.current?.cliPath
389
+ ? resolve(currentState.current.cliPath)
390
+ : null;
391
+ for (const provider of registry) {
392
+ const unavailableCurrentTarget = provider.kind === 'shared'
393
+ && invalidCurrentPath !== null
394
+ && resolve(provider.path) === invalidCurrentPath;
395
+ entries.push({
396
+ ...provider,
397
+ source: 'registry',
398
+ available: !unavailableCurrentTarget && existsSync(provider.path),
399
+ });
400
+ }
401
+
402
+ if (includeStandardApp) {
403
+ for (const path of standardAppProviderPaths({ platform, env, userHome })) {
404
+ if (!existsSync(path)) continue;
405
+ entries.push({
406
+ id: runtimeProviderId('app', path),
407
+ kind: 'app',
408
+ path,
409
+ version: null,
410
+ capabilities: ['serve'],
411
+ registeredAt: null,
412
+ updatedAt: null,
413
+ source: 'standard',
414
+ available: true,
415
+ });
416
+ }
417
+ }
418
+
419
+ const pathCli = findExecutableOnPath('mebular', { env, platform });
420
+ if (pathCli !== null) {
421
+ entries.push({
422
+ id: runtimeProviderId('cli', pathCli),
423
+ kind: 'cli',
424
+ path: pathCli,
425
+ version: null,
426
+ capabilities: ['serve'],
427
+ registeredAt: null,
428
+ updatedAt: null,
429
+ source: 'path',
430
+ available: true,
431
+ });
432
+ }
433
+
434
+ if (includeSelf && existsSync(selfPath)) {
435
+ entries.push({
436
+ id: runtimeProviderId('cli', selfPath),
437
+ kind: 'cli',
438
+ path: selfPath,
439
+ version: APP_VERSION,
440
+ capabilities: ['serve'],
441
+ registeredAt: null,
442
+ updatedAt: null,
443
+ source: 'self',
444
+ available: true,
445
+ });
446
+ }
447
+
448
+ const deduped = new Map();
449
+ for (const entry of entries) {
450
+ const key = `${entry.kind}\n${entry.path}`;
451
+ if (!deduped.has(key)) deduped.set(key, entry);
452
+ }
453
+ const sorted = [...deduped.values()].sort(compareProviders);
454
+ const available = sorted.filter((entry) => entry.available);
455
+ if (currentState?.usable !== true) {
456
+ const shared = available.filter((entry) => entry.kind === 'shared');
457
+ if (shared.length > 1) {
458
+ warnings.push('存在多个 shared runtime,但 current 不可用:按现有 provider 路径/版本规则选择(建议运行 runtime status 修复 current)');
459
+ }
460
+ }
461
+ return {
462
+ root: typeof root === 'string' ? root : null,
463
+ entries: sorted,
464
+ available,
465
+ selected: available[0] ?? null,
466
+ current: publicRuntimeCurrent(currentState?.current ?? null),
467
+ currentUsable: currentState?.usable === true,
468
+ currentSource: currentState?.source ?? 'missing',
469
+ warnings,
470
+ };
471
+ }
472
+
473
+ /** provider 启动命令:JS 入口用当前 Node 运行时;可执行文件直接执行。 */
474
+ export function runtimeCommandForProvider(provider, { execPath = process.execPath } = {}) {
475
+ if (!provider || typeof provider.path !== 'string' || provider.path.length === 0) {
476
+ throw cloudError('RUNTIME_PROVIDER_INVALID', '缺少可启动的 runtime provider');
477
+ }
478
+ if (/\.(mjs|cjs|js)$/i.test(provider.path)) {
479
+ return { execPath, args: [provider.path, 'serve'] };
480
+ }
481
+ return { execPath: provider.path, args: ['serve'] };
482
+ }
483
+
484
+ /** 默认 service 适配器:复用共享 service 层(current 优先);状态失败不阻塞 attach/provider 兜底。 */
485
+ export function createRuntimeServiceAdapter({
486
+ root,
487
+ home,
488
+ cliBin = defaultSelfCliPath(),
489
+ serviceHome,
490
+ env = process.env,
491
+ currentState = null,
492
+ fallbackProvider = null,
493
+ } = {}) {
494
+ const resolvedServiceHome = resolveRuntimeServiceHome({ serviceHome, env });
495
+ const fallback = fallbackProvider ?? {
496
+ path: cliBin,
497
+ kind: 'cli',
498
+ owner: 'cli',
499
+ version: APP_VERSION,
500
+ execPath: process.execPath,
501
+ };
502
+ const source = resolveRuntimeServiceSource({ currentState, fallbackProvider: fallback });
503
+ const descriptor = source.ok === true
504
+ ? runtimeServiceDescriptor({ root, home, source })
505
+ : null;
506
+ return {
507
+ descriptor,
508
+ serviceHome: resolvedServiceHome,
509
+ async status() {
510
+ const status = await runtimeServiceStatus({
511
+ root,
512
+ home,
513
+ serviceHome: resolvedServiceHome,
514
+ currentState,
515
+ fallbackProvider: fallback,
516
+ });
517
+ if (status.ok !== true) {
518
+ return {
519
+ ok: false,
520
+ registered: false,
521
+ running: false,
522
+ label: null,
523
+ autostart: null,
524
+ foreign: false,
525
+ unitPath: null,
526
+ error: status.message ?? status.reason ?? 'service_unknown',
527
+ };
528
+ }
529
+ return {
530
+ ok: true,
531
+ registered: status.registered === true,
532
+ running: status.running === true,
533
+ label: status.label ?? null,
534
+ autostart: status.autostart ?? null,
535
+ foreign: status.foreign === true,
536
+ unitPath: status.unitPath ?? null,
537
+ version: status.version ?? null,
538
+ runtimePath: status.runtimePath ?? null,
539
+ provider: status.provider ?? null,
540
+ owner: status.owner ?? null,
541
+ runtime: status.runtime ?? null,
542
+ current: status.current ?? null,
543
+ currentUsable: status.currentUsable === true,
544
+ };
545
+ },
546
+ async restart() {
547
+ const result = await restartRuntimeService({
548
+ root,
549
+ home,
550
+ serviceHome: resolvedServiceHome,
551
+ currentState,
552
+ fallbackProvider: fallback,
553
+ });
554
+ if (result?.ok !== true) {
555
+ throw cloudError(
556
+ 'RUNTIME_SERVICE_RESTART_FAILED',
557
+ `常驻服务重启失败:${result?.manual ?? result?.message ?? '未知原因'}`,
558
+ { result },
559
+ );
560
+ }
561
+ return result;
562
+ },
563
+ };
564
+ }
565
+
566
+ /**
567
+ * `<root>/runtime-start.lock`:跨入口启动互斥。
568
+ * 持有者活着的 PID → 返回 acquired:false(调用方等待健康或返回 start_locked);
569
+ * 陈旧锁 → 回收后重试一次。
570
+ */
571
+ export async function tryAcquireRuntimeStartLock({
572
+ root,
573
+ home,
574
+ startedAt = new Date().toISOString(),
575
+ pidAliveFn = pidAlive,
576
+ } = {}) {
577
+ if (typeof root !== 'string' || root.length === 0) {
578
+ return { acquired: false, holder: null, path: null, reason: 'cloud_root_unavailable' };
579
+ }
580
+ await mkdir(root, { recursive: true });
581
+ const path = runtimeStartLockPath(root);
582
+ const payload = JSON.stringify({ pid: process.pid, home: resolve(home), startedAt });
583
+ const acquire = () => writeFile(path, payload, { mode: 0o600, flag: 'wx' });
584
+ for (let attempt = 0; attempt < 2; attempt += 1) {
585
+ try {
586
+ await acquire();
587
+ return {
588
+ acquired: true,
589
+ holder: null,
590
+ path,
591
+ async release() {
592
+ try {
593
+ const held = JSON.parse(await readFile(path, 'utf-8'));
594
+ if (held?.pid === process.pid && held?.startedAt === startedAt) {
595
+ await rm(path, { force: true });
596
+ }
597
+ } catch {
598
+ // 已被回收/删除:无需处理
599
+ }
600
+ },
601
+ };
602
+ } catch (error) {
603
+ if (error?.code !== 'EEXIST') throw error;
604
+ let held = null;
605
+ try {
606
+ held = JSON.parse(await readFile(path, 'utf-8'));
607
+ } catch {
608
+ held = null;
609
+ }
610
+ if (held?.pid && pidAliveFn(held.pid)) {
611
+ return { acquired: false, holder: held, path, reason: 'start_locked' };
612
+ }
613
+ await rm(path, { force: true }).catch(() => undefined);
614
+ }
615
+ }
616
+ return { acquired: false, holder: null, path, reason: 'start_locked' };
617
+ }
618
+
619
+ /** child 是否仍由本进程托管且存活。 */
620
+ export function isRuntimeChildAlive(child) {
621
+ if (!child || child.killed === true) return false;
622
+ const exitedBySignal = typeof child.signalCode === 'string' && child.signalCode.length > 0;
623
+ return child.exitCode === null && !exitedBySignal;
624
+ }
625
+
626
+ /** 只停止本 supervisor 拉起的 child(不碰外部 daemon/service)。 */
627
+ export function stopRuntimeChild(child, { signal = 'SIGTERM' } = {}) {
628
+ if (!isRuntimeChildAlive(child) || typeof child.kill !== 'function') return false;
629
+ try {
630
+ return child.kill(signal);
631
+ } catch {
632
+ return false;
633
+ }
634
+ }
635
+
636
+ function childExited(child) {
637
+ if (!child) return true;
638
+ if (typeof child.exitCode === 'number') return true;
639
+ return typeof child.signalCode === 'string' && child.signalCode.length > 0;
640
+ }
641
+
642
+ function signalChild(child, signal) {
643
+ if (!child || typeof child.kill !== 'function' || childExited(child)) return false;
644
+ try {
645
+ return child.kill(signal) !== false;
646
+ } catch {
647
+ return false;
648
+ }
649
+ }
650
+
651
+ /** 等待 child 退出事件;无事件接口/超时返回 false。timeoutMs=null 表示无限等待。 */
652
+ function waitForChildExit(child, timeoutMs) {
653
+ if (childExited(child)) return Promise.resolve(true);
654
+ if (!child || typeof child.once !== 'function') return Promise.resolve(false);
655
+ return new Promise((resolvePromise) => {
656
+ let timer = null;
657
+ const remove = typeof child.removeListener === 'function'
658
+ ? (event, listener) => child.removeListener(event, listener)
659
+ : (event, listener) => child.off?.(event, listener);
660
+ const done = (exited) => {
661
+ if (timer !== null) clearTimeout(timer);
662
+ remove('exit', onExit);
663
+ resolvePromise(exited);
664
+ };
665
+ const onExit = () => done(true);
666
+ child.once('exit', onExit);
667
+ // 事件注册与退出可能竞态:注册后再检查一次。
668
+ if (childExited(child)) {
669
+ done(true);
670
+ return;
671
+ }
672
+ if (Number.isFinite(timeoutMs)) {
673
+ timer = setTimeout(() => done(false), Math.max(0, timeoutMs));
674
+ }
675
+ });
676
+ }
677
+
678
+ /**
679
+ * 优雅停止本 supervisor 拉起的 child:SIGTERM → graceMs → SIGKILL → 等待退出。
680
+ * 返回 `{stopped, escalated, signal, termSent, killSent}`;只作用于传入的 child 句柄。
681
+ */
682
+ export async function stopRuntimeChildGracefully(child, {
683
+ graceMs = 2000,
684
+ killWaitMs = 5000,
685
+ graceSignal = 'SIGTERM',
686
+ killSignal = 'SIGKILL',
687
+ } = {}) {
688
+ if (!child || childExited(child)) {
689
+ return { stopped: false, escalated: false, signal: null, termSent: false, killSent: false, reason: 'not_running' };
690
+ }
691
+ const termWait = waitForChildExit(child, graceMs);
692
+ const termSent = signalChild(child, graceSignal);
693
+ const exitedAfterTerm = termSent ? await termWait : childExited(child);
694
+ if (exitedAfterTerm) {
695
+ return { stopped: true, escalated: false, signal: graceSignal, termSent, killSent: false };
696
+ }
697
+ const killWait = waitForChildExit(child, killWaitMs);
698
+ const killSent = signalChild(child, killSignal);
699
+ const exitedAfterKill = killSent ? await killWait : childExited(child);
700
+ return {
701
+ stopped: exitedAfterKill,
702
+ escalated: true,
703
+ signal: killSignal,
704
+ termSent,
705
+ killSent,
706
+ };
707
+ }
708
+
709
+ function writeRuntimeLine(stream, value) {
710
+ if (stream && typeof stream.write === 'function') {
711
+ stream.write(`${JSON.stringify(value, null, 2)}\n`);
712
+ }
713
+ }
714
+
715
+ /**
716
+ * 长驻前台 supervisor(`mebular runtime supervise`):
717
+ * - reused/service/download_required/conflict:输出一次稳定 JSON 后退出(0 / 2);
718
+ * - child:以非 detached 方式启动 provider,输出 ready JSON 后保持存活;
719
+ * - SIGTERM/SIGINT:只优雅停止自己拉起的 child,然后退出;
720
+ * - startup 期间收到信号:abort ensure,停止已 spawn 的 child,输出 signal_during_start;
721
+ * - child 提前退出:返回明确的 child_exited 事件与退出码,不接管外部 daemon/service。
722
+ *
723
+ * 启动期间由 ensure 负责 child 清理(唯一 owner);supervise 只在 ensure 已返回成功但仍有
724
+ * 存活 child 的竞态窗口做安全兜底,不重复杀/等待。
725
+ *
726
+ * App 在 Phase 2 直接进程内调用 `ensureRuntime({ detached: false })` 并持有句柄;
727
+ * Plugin 在 Phase 3 spawn 本命令,把 supervise 进程当作自己的 child。
728
+ */
729
+ export async function superviseRuntime(options = {}) {
730
+ const {
731
+ stdout = process.stdout,
732
+ stderr = process.stderr,
733
+ signalSource = process,
734
+ childStopGraceMs = 2000,
735
+ childKillWaitMs = 5000,
736
+ ...ensureOptions
737
+ } = options;
738
+
739
+ const controller = new AbortController();
740
+ let phase = 'starting';
741
+ let startupSignal = null;
742
+ let startedChild = null;
743
+ let settled = false;
744
+ let resolveOutcome = null;
745
+ const outcomePromise = new Promise((resolvePromise) => {
746
+ resolveOutcome = resolvePromise;
747
+ });
748
+ const finish = (outcome) => {
749
+ if (settled) return;
750
+ settled = true;
751
+ resolveOutcome(outcome);
752
+ };
753
+
754
+ const onSignal = (signal) => {
755
+ if (phase === 'starting') {
756
+ if (startupSignal === null) startupSignal = signal;
757
+ controller.abort(signal);
758
+ return;
759
+ }
760
+ if (phase === 'ready') {
761
+ phase = 'stopping';
762
+ stopRuntimeChildGracefully(startedChild, {
763
+ graceMs: childStopGraceMs,
764
+ killWaitMs: childKillWaitMs,
765
+ })
766
+ .then((stop) => finish({ kind: 'signal', signal, stop }))
767
+ .catch((error) => finish({
768
+ kind: 'signal',
769
+ signal,
770
+ stop: {
771
+ stopped: false,
772
+ escalated: false,
773
+ signal: null,
774
+ reason: 'stop_failed',
775
+ error: String(error?.message ?? error),
776
+ },
777
+ }));
778
+ }
779
+ };
780
+ const onSigterm = () => onSignal('SIGTERM');
781
+ const onSigint = () => onSignal('SIGINT');
782
+ const removeSignalHandlers = () => {
783
+ signalSource?.removeListener?.('SIGTERM', onSigterm);
784
+ signalSource?.removeListener?.('SIGINT', onSigint);
785
+ signalSource?.off?.('SIGTERM', onSigterm);
786
+ signalSource?.off?.('SIGINT', onSigint);
787
+ };
788
+ signalSource?.on?.('SIGTERM', onSigterm);
789
+ signalSource?.on?.('SIGINT', onSigint);
790
+
791
+ const handleStartupSignal = async (result) => {
792
+ let stop = result?.cleanup ?? null;
793
+ if (startedChild !== null && isRuntimeChildAlive(startedChild)) {
794
+ // ensure 已尽力清理但 child 仍存活(极窄竞态):supervise 兜底,仍只作用于自己的 child。
795
+ stop = await stopRuntimeChildGracefully(startedChild, {
796
+ graceMs: childStopGraceMs,
797
+ killWaitMs: childKillWaitMs,
798
+ });
799
+ }
800
+ const stopped = stop === null ? true : stop.stopped === true;
801
+ writeRuntimeLine(stdout, {
802
+ ok: stopped,
803
+ mode: 'error',
804
+ reason: 'signal_during_start',
805
+ signal: startupSignal,
806
+ stopped,
807
+ ...(stop !== null ? { stop } : {}),
808
+ });
809
+ return stopped ? 0 : 1;
810
+ };
811
+
812
+ try {
813
+ let result;
814
+ try {
815
+ result = await ensureRuntime({
816
+ ...ensureOptions,
817
+ childStopGraceMs,
818
+ childKillWaitMs,
819
+ detached: false,
820
+ childStdio: ['ignore', 2, 2],
821
+ abortSignal: controller.signal,
822
+ onChildStarted: (child) => {
823
+ startedChild = child;
824
+ },
825
+ });
826
+ } catch (error) {
827
+ let stop = null;
828
+ if (startedChild !== null && isRuntimeChildAlive(startedChild)) {
829
+ stop = await stopRuntimeChildGracefully(startedChild, {
830
+ graceMs: childStopGraceMs,
831
+ killWaitMs: childKillWaitMs,
832
+ });
833
+ }
834
+ writeRuntimeLine(stderr, {
835
+ ok: false,
836
+ mode: 'error',
837
+ reason: 'supervise_failed',
838
+ message: String(error?.message ?? error),
839
+ ...(stop !== null ? { stop } : {}),
840
+ });
841
+ return 2;
842
+ }
843
+
844
+ if (startupSignal !== null) return await handleStartupSignal(result);
845
+
846
+ if (result.mode !== 'child' || !result.child) {
847
+ writeRuntimeLine(stdout, toPublicRuntimeResult(result));
848
+ return result.ok ? 0 : 2;
849
+ }
850
+
851
+ const child = result.child;
852
+ startedChild = child;
853
+ if (!isRuntimeChildAlive(child)) {
854
+ writeRuntimeLine(stderr, {
855
+ ok: false,
856
+ mode: 'child',
857
+ reason: 'child_exited',
858
+ exitCode: typeof child.exitCode === 'number' ? child.exitCode : null,
859
+ signal: typeof child.signalCode === 'string' ? child.signalCode : null,
860
+ });
861
+ return typeof child.exitCode === 'number' ? child.exitCode : 1;
862
+ }
863
+
864
+ phase = 'ready';
865
+ if (startupSignal !== null) {
866
+ // ensure 返回与 phase 切换之间的极窄竞态:仍按 startup 信号处理。
867
+ phase = 'stopping';
868
+ return await handleStartupSignal(result);
869
+ }
870
+ child.once?.('exit', (code, signal) => {
871
+ if (phase !== 'ready') return;
872
+ phase = 'exited';
873
+ finish({
874
+ kind: 'child_exit',
875
+ exitCode: typeof code === 'number' ? code : 1,
876
+ signal: typeof signal === 'string' ? signal : null,
877
+ });
878
+ });
879
+ writeRuntimeLine(stdout, toPublicRuntimeResult(result));
880
+ if (childExited(child) && phase === 'ready') {
881
+ phase = 'exited';
882
+ finish({
883
+ kind: 'child_exit',
884
+ exitCode: typeof child.exitCode === 'number' ? child.exitCode : 1,
885
+ signal: typeof child.signalCode === 'string' ? child.signalCode : null,
886
+ });
887
+ }
888
+
889
+ const outcome = await outcomePromise;
890
+ if (outcome.kind === 'signal') {
891
+ writeRuntimeLine(stderr, {
892
+ ok: outcome.stop?.stopped === true,
893
+ mode: 'child',
894
+ reason: outcome.stop?.stopped === true ? 'stopped' : 'stop_failed',
895
+ signal: outcome.signal,
896
+ stop: outcome.stop,
897
+ });
898
+ return outcome.stop?.stopped === true ? 0 : 1;
899
+ }
900
+
901
+ writeRuntimeLine(stderr, {
902
+ ok: false,
903
+ mode: 'child',
904
+ reason: 'child_exited',
905
+ exitCode: outcome.exitCode,
906
+ signal: outcome.signal,
907
+ });
908
+ return outcome.exitCode;
909
+ } finally {
910
+ removeSignalHandlers();
911
+ }
912
+ }
913
+
914
+ function daemonFromHealth(health, http) {
915
+ return {
916
+ status: health?.ok === true ? 'up' : 'down',
917
+ url: http.url,
918
+ httpStatus: health?.status ?? null,
919
+ reason: health?.ok === true ? null : (health?.reason ?? 'unreachable'),
920
+ instance: health?.instance ?? health?.body?.instance ?? null,
921
+ cloudId: health?.body?.cloudId ?? null,
922
+ version: health?.body?.version ?? null,
923
+ error: health?.error ?? null,
924
+ };
925
+ }
926
+
927
+ function publicService(service) {
928
+ if (!service) return null;
929
+ return {
930
+ ok: service.ok === true,
931
+ registered: service.registered === true,
932
+ running: service.running === true,
933
+ label: service.label ?? null,
934
+ autostart: service.autostart ?? null,
935
+ foreign: service.foreign === true,
936
+ unitPath: service.unitPath ?? null,
937
+ version: service.version ?? null,
938
+ runtimePath: service.runtimePath ?? null,
939
+ provider: service.provider ?? null,
940
+ owner: service.owner ?? null,
941
+ runtime: service.runtime ?? null,
942
+ ...(service.error ? { error: service.error } : {}),
943
+ };
944
+ }
945
+
946
+ function baseResult(context, { http = null, checkedAt }) {
947
+ return {
948
+ ok: true,
949
+ mode: null,
950
+ reason: null,
951
+ message: null,
952
+ cloudRoot: context?.cloudRoot ?? null,
953
+ cloudRootDisplay: context?.cloudRootDisplay ?? null,
954
+ profileId: context?.profileId ?? null,
955
+ profile: context?.profile ?? null,
956
+ home: context?.home ?? null,
957
+ homeKey: context?.homeKey ?? null,
958
+ http,
959
+ instance: null,
960
+ version: null,
961
+ runtimePath: context?.runtimePath ?? null,
962
+ current: null,
963
+ currentUsable: false,
964
+ currentSource: 'missing',
965
+ versionMismatch: false,
966
+ runtimeFile: context?.runtime === null || context?.runtime === undefined
967
+ ? null
968
+ : {
969
+ path: context.runtimePath ?? null,
970
+ version: context.runtime.version ?? null,
971
+ http: context.runtime.http ?? null,
972
+ },
973
+ provider: null,
974
+ providers: null,
975
+ service: null,
976
+ activeLock: null,
977
+ daemon: http === null ? null : daemonFromHealth({ ok: false, reason: 'unreachable' }, http),
978
+ bootstrap: { state: 'error', allowDownload: false },
979
+ download: null,
980
+ warnings: Array.isArray(context?.warning) ? [...context.warning] : (context?.warning ? [context.warning] : []),
981
+ checkedAt,
982
+ };
983
+ }
984
+
985
+ function withPort(http, port) {
986
+ const next = Number(port);
987
+ if (!Number.isInteger(next) || next <= 0 || next > 65535) {
988
+ throw cloudError('INVALID_PORT', `端口非法:${port}`);
989
+ }
990
+ return { ...http, port: next, url: `${http.scheme}://${http.host}:${next}/healthz` };
991
+ }
992
+
993
+ function errorResult(context, error, checkedAt, http = null) {
994
+ const result = baseResult(context, { http, checkedAt });
995
+ result.ok = false;
996
+ result.mode = 'error';
997
+ result.reason = error?.code ?? 'runtime_error';
998
+ result.message = error?.message ?? String(error);
999
+ result.bootstrap = { state: 'error', allowDownload: false };
1000
+ return result;
1001
+ }
1002
+
1003
+ function abortError(signal) {
1004
+ const error = cloudError('RUNTIME_ABORTED', 'runtime ensure 在启动期间被终止');
1005
+ error.abortSignal = signal ?? null;
1006
+ return error;
1007
+ }
1008
+
1009
+ /** 用 AbortSignal 中断 ensure 的等待;用于 supervise 在 startup 期间收到 SIGTERM/SIGINT。 */
1010
+ function awaitWithAbort(promise, signal) {
1011
+ if (!signal || typeof signal.addEventListener !== 'function') return promise;
1012
+ if (signal.aborted) return Promise.reject(abortError(signal.reason));
1013
+ return new Promise((resolvePromise, reject) => {
1014
+ const onAbort = () => {
1015
+ cleanup();
1016
+ reject(abortError(signal.reason));
1017
+ };
1018
+ const cleanup = () => signal.removeEventListener?.('abort', onAbort);
1019
+ signal.addEventListener('abort', onAbort, { once: true });
1020
+ Promise.resolve(promise).then(
1021
+ (value) => { cleanup(); resolvePromise(value); },
1022
+ (error) => { cleanup(); reject(error); },
1023
+ );
1024
+ });
1025
+ }
1026
+
1027
+ function abortedRuntimeResult(inspected, signal, cleanup = null) {
1028
+ const base = inspected ?? errorResult(
1029
+ null,
1030
+ cloudError('RUNTIME_ABORTED', 'runtime ensure 在启动期间被终止'),
1031
+ new Date().toISOString(),
1032
+ );
1033
+ return {
1034
+ ...base,
1035
+ ok: false,
1036
+ mode: 'error',
1037
+ reason: 'aborted',
1038
+ message: 'runtime ensure 在启动期间被终止',
1039
+ bootstrap: { state: 'error', allowDownload: false },
1040
+ aborted: true,
1041
+ abortSignal: signal ?? null,
1042
+ ...(cleanup !== null ? { cleanup } : {}),
1043
+ };
1044
+ }
1045
+
1046
+ function providerPublic(provider) {
1047
+ if (!provider) return null;
1048
+ return {
1049
+ id: provider.id ?? null,
1050
+ kind: provider.kind,
1051
+ path: provider.path,
1052
+ version: provider.version ?? null,
1053
+ runtimePath: provider.runtimePath ?? null,
1054
+ capabilities: Array.isArray(provider.capabilities) ? [...provider.capabilities] : [],
1055
+ source: provider.source ?? null,
1056
+ };
1057
+ }
1058
+
1059
+ function providersPublic(discovery) {
1060
+ if (!discovery) return null;
1061
+ return {
1062
+ root: discovery.root ?? null,
1063
+ entries: discovery.entries.map((entry) => ({
1064
+ ...providerPublic(entry),
1065
+ available: entry.available === true,
1066
+ })),
1067
+ available: discovery.available.map((entry) => providerPublic(entry)),
1068
+ selected: providerPublic(discovery.selected),
1069
+ current: discovery.current ?? null,
1070
+ currentUsable: discovery.currentUsable === true,
1071
+ currentSource: discovery.currentSource ?? 'missing',
1072
+ warnings: [...discovery.warnings],
1073
+ };
1074
+ }
1075
+
1076
+ function bootstrapForMode(mode, { requested = false } = {}) {
1077
+ if (mode === 'reused') return { state: 'ready', allowDownload: false };
1078
+ if (mode === 'download_required') return { state: 'download_required', allowDownload: false, downloadRequested: requested };
1079
+ if (mode === 'conflict') return { state: 'conflict', allowDownload: false };
1080
+ if (mode === 'service' || mode === 'child') return { state: 'down', allowDownload: false };
1081
+ return { state: 'error', allowDownload: false };
1082
+ }
1083
+
1084
+ function downloadInfo(requested) {
1085
+ return {
1086
+ required: true,
1087
+ allowed: false,
1088
+ requested: requested === true,
1089
+ reason: 'no_provider',
1090
+ // Phase 4 才实现;Phase 1 只给出手动安装引导,不下载、不启动安装器。
1091
+ next: ['open_mebular_app', 'install_cli'],
1092
+ };
1093
+ }
1094
+
1095
+ /**
1096
+ * 只读检查:解析上下文 + 探测健康 + 读取 service/provider,给出下一动作(不 spawn/不重启)。
1097
+ */
1098
+ async function inspectRuntime(options = {}) {
1099
+ const {
1100
+ env = process.env,
1101
+ userHome = homedir(),
1102
+ home: explicitHome,
1103
+ port: explicitPort,
1104
+ mode: requestedMode = 'auto',
1105
+ allowDownload = false,
1106
+ fetchImpl = fetch,
1107
+ probeHealthFn = null,
1108
+ probePortFn = isPortOpen,
1109
+ registryProviders = null,
1110
+ includeSelf = true,
1111
+ includeStandardApp = true,
1112
+ selfPath = defaultSelfCliPath(),
1113
+ service: injectedService = null,
1114
+ serviceHome,
1115
+ cliBin = selfPath,
1116
+ now = () => new Date().toISOString(),
1117
+ } = options;
1118
+ const checkedAt = now();
1119
+
1120
+ if (!['auto', 'child', 'service'].includes(requestedMode)) {
1121
+ return errorResult(null, cloudError('INVALID_START_MODE', `未知启动模式:${requestedMode}`), checkedAt);
1122
+ }
1123
+
1124
+ let context;
1125
+ try {
1126
+ context = await resolveRuntimeContext({ home: explicitHome, env, userHome });
1127
+ } catch (error) {
1128
+ return errorResult(null, error, checkedAt);
1129
+ }
1130
+ if (!context.ok) {
1131
+ const result = baseResult(context, { http: null, checkedAt });
1132
+ result.ok = false;
1133
+ result.mode = 'error';
1134
+ result.reason = context.reason ?? 'cloud_unavailable';
1135
+ result.message = `runtime 上下文不可用:${context.reason ?? 'cloud_unavailable'}`;
1136
+ result.bootstrap = { state: 'error', allowDownload: false };
1137
+ return result;
1138
+ }
1139
+
1140
+ let http = context.http;
1141
+ if (explicitPort !== undefined && explicitPort !== null) {
1142
+ try {
1143
+ http = withPort(http, explicitPort);
1144
+ } catch (error) {
1145
+ return errorResult(context, error, checkedAt, context.http);
1146
+ }
1147
+ }
1148
+
1149
+ const probeHealth = probeHealthFn
1150
+ ?? ((target, probeOptions) => probeRuntimeHealth(fetchImpl, target, probeOptions));
1151
+ let health;
1152
+ try {
1153
+ health = await probeHealth(http, { expectedInstance: context.homeKey, cloudId: context.profileId });
1154
+ } catch (error) {
1155
+ health = { ok: false, reason: 'probe_failed', error: String(error?.message ?? error), http };
1156
+ }
1157
+
1158
+ const activeLock = readActiveRuntimeLock(context.cloudRoot);
1159
+ const currentState = await readRuntimeCurrent(context.cloudRoot, { userHome });
1160
+ const service = injectedService
1161
+ ?? createRuntimeServiceAdapter({
1162
+ root: context.cloudRoot,
1163
+ home: context.home,
1164
+ cliBin,
1165
+ serviceHome,
1166
+ env,
1167
+ currentState,
1168
+ });
1169
+ let serviceStatus;
1170
+ try {
1171
+ serviceStatus = await service.status();
1172
+ } catch (error) {
1173
+ serviceStatus = {
1174
+ ok: false,
1175
+ registered: false,
1176
+ running: false,
1177
+ label: null,
1178
+ autostart: null,
1179
+ foreign: false,
1180
+ unitPath: null,
1181
+ error: error?.message ?? String(error),
1182
+ };
1183
+ }
1184
+ if (!serviceStatus || typeof serviceStatus !== 'object') {
1185
+ serviceStatus = {
1186
+ ok: false,
1187
+ registered: false,
1188
+ running: false,
1189
+ label: null,
1190
+ autostart: null,
1191
+ foreign: false,
1192
+ unitPath: null,
1193
+ error: 'service status returned no object',
1194
+ };
1195
+ }
1196
+
1197
+ const discovery = await discoverRuntimeProviders({
1198
+ root: context.cloudRoot,
1199
+ env,
1200
+ userHome,
1201
+ includeSelf,
1202
+ includeStandardApp,
1203
+ registryProviders,
1204
+ currentState,
1205
+ selfPath,
1206
+ });
1207
+
1208
+ const result = baseResult(context, { http, checkedAt });
1209
+ result.daemon = daemonFromHealth(health, http);
1210
+ result.instance = health?.instance ?? health?.body?.instance ?? null;
1211
+ result.version = health?.body?.version ?? context.runtime?.version ?? null;
1212
+ result.current = publicRuntimeCurrent(currentState.current);
1213
+ result.currentUsable = currentState.usable === true;
1214
+ result.currentSource = currentState.source;
1215
+ result.service = publicService(serviceStatus);
1216
+ result.providers = providersPublic(discovery);
1217
+ const activeConflict = activeLockConflict(activeLock, context.home);
1218
+ result.activeLock = activeLock === null
1219
+ ? null
1220
+ : {
1221
+ pid: activeLock.pid ?? null,
1222
+ home: activeLock.home ?? null,
1223
+ profileId: activeLock.profileId ?? null,
1224
+ startedAt: activeLock.startedAt ?? null,
1225
+ conflict: activeConflict !== null,
1226
+ };
1227
+ result.versionMismatch = health?.ok === true
1228
+ && currentState.usable === true
1229
+ && typeof result.version === 'string'
1230
+ && result.version !== currentState.current.version;
1231
+ if (result.versionMismatch) {
1232
+ result.warnings.push(
1233
+ `运行中的 daemon 版本 ${result.version} 与 current ${currentState.current.version} 不一致:已 attach;升级需显式执行 runtime upgrade`,
1234
+ );
1235
+ }
1236
+
1237
+ if (health?.ok === true) {
1238
+ result.mode = 'reused';
1239
+ result.bootstrap = bootstrapForMode('reused');
1240
+ result.warnings.push(...discovery.warnings);
1241
+ return result;
1242
+ }
1243
+
1244
+ const healthReason = health?.reason ?? 'unreachable';
1245
+ if (HEALTH_TERMINAL_REASONS.has(healthReason)) {
1246
+ result.mode = 'conflict';
1247
+ result.reason = healthReason;
1248
+ result.message = healthReason === 'instance_mismatch'
1249
+ ? `端口 ${http.port} 上是另一张忆云(instance=${health.instance ?? '未知'})`
1250
+ : healthReason === 'instance_missing'
1251
+ ? `端口 ${http.port} 上的守护没有 /healthz instance 身份,无法确认当前忆云`
1252
+ : `/healthz cloudId=${health.cloudId ?? '未知'} 与当前忆云不一致`;
1253
+ result.bootstrap = bootstrapForMode('conflict');
1254
+ result.warnings.push(...discovery.warnings);
1255
+ return result;
1256
+ }
1257
+
1258
+ if (activeConflict !== null) {
1259
+ result.mode = 'conflict';
1260
+ result.reason = 'CLOUD_ALREADY_ACTIVE';
1261
+ result.message = `已有忆云守护在运行(pid ${activeConflict.pid},home=${activeConflict.home ?? '未知'}):请先停止它`;
1262
+ result.bootstrap = bootstrapForMode('conflict');
1263
+ result.warnings.push(...discovery.warnings);
1264
+ return result;
1265
+ }
1266
+
1267
+ // service 状态未知时 fail-closed:不能因为探测失败就 fallback child,否则可能再起一个 daemon。
1268
+ if (serviceStatus.ok !== true) {
1269
+ result.mode = 'conflict';
1270
+ result.reason = 'service_unknown';
1271
+ result.message = `无法确认 mebular-serve 状态${serviceStatus.error ? `(${serviceStatus.error})` : ''}:请检查/重试 service,不会启动第二个 daemon`;
1272
+ result.bootstrap = bootstrapForMode('conflict');
1273
+ result.warnings.push(...discovery.warnings);
1274
+ return result;
1275
+ }
1276
+
1277
+ // 同 label 作业属于其他 home:绝不 restart/覆盖他人作业。
1278
+ if (serviceStatus.foreign === true) {
1279
+ result.mode = 'conflict';
1280
+ result.reason = 'service_foreign';
1281
+ result.message = 'mebular-serve label 被其他 home 的作业占用:不会重启/覆盖他人作业';
1282
+ result.bootstrap = bootstrapForMode('conflict');
1283
+ result.warnings.push(...discovery.warnings);
1284
+ return result;
1285
+ }
1286
+
1287
+ if (serviceStatus.registered === true) {
1288
+ // 不变量:service 已注册即代表当前 home 的常驻所有权。任何入口/--start 都不能用 child 覆盖它,
1289
+ // 否则会再起一个 daemon,抢端口/存储锁。
1290
+ result.mode = 'service';
1291
+ result.bootstrap = bootstrapForMode('service');
1292
+ result.warnings.push(...discovery.warnings);
1293
+ return result;
1294
+ }
1295
+
1296
+ if (requestedMode === 'service') {
1297
+ result.mode = 'error';
1298
+ result.reason = 'service_not_registered';
1299
+ result.message = '要求使用常驻服务,但当前 home 未注册 mebular-serve;Phase 1 不自动安装服务';
1300
+ result.bootstrap = { state: 'error', allowDownload: false };
1301
+ result.warnings.push(...discovery.warnings);
1302
+ return result;
1303
+ }
1304
+
1305
+ let portOpen = false;
1306
+ try {
1307
+ portOpen = typeof probePortFn === 'function' ? await probePortFn(http) : false;
1308
+ } catch {
1309
+ portOpen = false;
1310
+ }
1311
+ if (portOpen) {
1312
+ result.mode = 'conflict';
1313
+ result.reason = 'port_in_use';
1314
+ result.message = `端口 ${http.port} 已被占用但不是健康的 Mebular 守护:请关闭占用程序或换端口`;
1315
+ result.bootstrap = bootstrapForMode('conflict');
1316
+ result.warnings.push(...discovery.warnings);
1317
+ return result;
1318
+ }
1319
+
1320
+ const provider = discovery.selected;
1321
+ if (provider !== null) {
1322
+ result.mode = 'child';
1323
+ result.provider = providerPublic(provider);
1324
+ result.bootstrap = bootstrapForMode('child');
1325
+ } else {
1326
+ result.mode = 'download_required';
1327
+ result.reason = 'download_required';
1328
+ result.message = '没有可用的 Mebular runtime provider:请打开 Mebular App 或安装 CLI;Phase 1 不会自动下载';
1329
+ result.bootstrap = bootstrapForMode('download_required', { requested: allowDownload === true });
1330
+ result.download = downloadInfo(allowDownload);
1331
+ }
1332
+ result.warnings.push(...discovery.warnings);
1333
+ return result;
1334
+ }
1335
+
1336
+ function waitOptionsFrom(result, options, overrides = {}) {
1337
+ return {
1338
+ attempts: options.waitAttempts ?? 40,
1339
+ intervalMs: options.waitIntervalMs ?? 500,
1340
+ expectedInstance: result.homeKey,
1341
+ cloudId: result.profileId,
1342
+ ...overrides,
1343
+ };
1344
+ }
1345
+
1346
+ function waitForHealth(options, http, waitOptions) {
1347
+ if (typeof options.waitForHealthFn === 'function') {
1348
+ return options.waitForHealthFn(http, waitOptions);
1349
+ }
1350
+ return waitForRuntime({ fetchImpl: options.fetchImpl ?? fetch, http, ...waitOptions });
1351
+ }
1352
+
1353
+ function probeHealth(options, http, probeOptions) {
1354
+ if (typeof options.probeHealthFn === 'function') {
1355
+ return options.probeHealthFn(http, probeOptions);
1356
+ }
1357
+ return probeRuntimeHealth(options.fetchImpl ?? fetch, http, probeOptions);
1358
+ }
1359
+
1360
+ /**
1361
+ * 只读解析(不启动):按当前状态给出 `reused|service|child|download_required|conflict|error`。
1362
+ */
1363
+ export async function resolveRuntime(options = {}) {
1364
+ const inspected = await inspectRuntime(options);
1365
+ if (!inspected.ok) return inspected;
1366
+ return { ...inspected, ok: inspected.mode !== 'error' };
1367
+ }
1368
+
1369
+ /**
1370
+ * 确保 runtime 可用:
1371
+ * 健康 daemon → attach;已注册 service → 重启/复用;provider → 启动 child;
1372
+ * 否则 → download_required(Phase 1 绝不下载)。
1373
+ *
1374
+ * 只停止本次自己拉起的 child;service/外部 daemon 不主动杀。
1375
+ */
1376
+ export async function ensureRuntime(options = {}) {
1377
+ const { abortSignal = null, onChildStarted = null } = options;
1378
+ let inspected;
1379
+ try {
1380
+ inspected = await awaitWithAbort(inspectRuntime(options), abortSignal);
1381
+ } catch (error) {
1382
+ if (error?.code === 'RUNTIME_ABORTED') {
1383
+ return abortedRuntimeResult(null, error.abortSignal ?? abortSignal?.reason);
1384
+ }
1385
+ throw error;
1386
+ }
1387
+ if (abortSignal?.aborted) return abortedRuntimeResult(inspected, abortSignal.reason);
1388
+ if (!inspected.ok || inspected.mode === 'reused') {
1389
+ return { ...inspected, ok: inspected.ok === true && inspected.mode === 'reused' };
1390
+ }
1391
+ if (inspected.mode === 'download_required' || inspected.mode === 'conflict' || inspected.mode === 'error') {
1392
+ return { ...inspected, ok: false };
1393
+ }
1394
+
1395
+ const {
1396
+ env = process.env,
1397
+ execPath = process.execPath,
1398
+ spawnFn = spawn,
1399
+ detached = false,
1400
+ childStdio = 'ignore',
1401
+ childStopGraceMs = 2000,
1402
+ childKillWaitMs = 5000,
1403
+ startLockWaitMs = 20_000,
1404
+ startLockIntervalMs = 250,
1405
+ service: injectedService = null,
1406
+ cliBin = defaultSelfCliPath(),
1407
+ serviceHome,
1408
+ } = options;
1409
+
1410
+ const service = inspected.mode === 'service'
1411
+ ? (injectedService ?? createRuntimeServiceAdapter({
1412
+ root: inspected.cloudRoot,
1413
+ home: inspected.home,
1414
+ cliBin,
1415
+ serviceHome,
1416
+ env,
1417
+ }))
1418
+ : null;
1419
+
1420
+ const lock = await tryAcquireRuntimeStartLock({
1421
+ root: inspected.cloudRoot,
1422
+ home: inspected.home,
1423
+ startedAt: inspected.checkedAt,
1424
+ });
1425
+
1426
+ if (!lock.acquired) {
1427
+ // 另一个入口正在启动:等它健康后 attach,而不是再起一个 daemon。
1428
+ const attempts = Math.max(1, Math.ceil(startLockWaitMs / Math.max(1, startLockIntervalMs)));
1429
+ let waited;
1430
+ try {
1431
+ waited = await awaitWithAbort(waitForHealth(options, inspected.http, waitOptionsFrom(inspected, options, {
1432
+ attempts,
1433
+ intervalMs: startLockIntervalMs,
1434
+ onTick: undefined,
1435
+ })), abortSignal);
1436
+ } catch (error) {
1437
+ if (error?.code === 'RUNTIME_ABORTED') {
1438
+ return abortedRuntimeResult(inspected, error.abortSignal ?? abortSignal?.reason);
1439
+ }
1440
+ throw error;
1441
+ }
1442
+ if (waited.ok) {
1443
+ return {
1444
+ ...inspected,
1445
+ ok: true,
1446
+ mode: 'reused',
1447
+ instance: waited.instance ?? inspected.homeKey,
1448
+ version: waited.body?.version ?? inspected.version,
1449
+ daemon: daemonFromHealth(waited, inspected.http),
1450
+ bootstrap: bootstrapForMode('reused'),
1451
+ warnings: [...inspected.warnings, '另一个入口已启动 runtime,已 attach'],
1452
+ };
1453
+ }
1454
+ return {
1455
+ ...inspected,
1456
+ ok: false,
1457
+ mode: 'conflict',
1458
+ reason: 'start_locked',
1459
+ message: `另一个入口正在启动 runtime(pid ${lock.holder?.pid ?? '未知'});等待健康超时`,
1460
+ bootstrap: bootstrapForMode('conflict'),
1461
+ };
1462
+ }
1463
+
1464
+ try {
1465
+ // 双重检查:拿到启动锁后可能已被另一个入口启动。
1466
+ let current;
1467
+ try {
1468
+ current = await awaitWithAbort(probeHealth(options, inspected.http, {
1469
+ expectedInstance: inspected.homeKey,
1470
+ cloudId: inspected.profileId,
1471
+ }), abortSignal);
1472
+ } catch (error) {
1473
+ if (error?.code === 'RUNTIME_ABORTED') {
1474
+ return abortedRuntimeResult(inspected, error.abortSignal ?? abortSignal?.reason);
1475
+ }
1476
+ throw error;
1477
+ }
1478
+ if (current.ok) {
1479
+ return {
1480
+ ...inspected,
1481
+ ok: true,
1482
+ mode: 'reused',
1483
+ instance: current.instance ?? inspected.homeKey,
1484
+ version: current.body?.version ?? inspected.version,
1485
+ daemon: daemonFromHealth(current, inspected.http),
1486
+ bootstrap: bootstrapForMode('reused'),
1487
+ };
1488
+ }
1489
+
1490
+ if (inspected.mode === 'service') {
1491
+ if (abortSignal?.aborted) return abortedRuntimeResult(inspected, abortSignal.reason);
1492
+ try {
1493
+ await service.restart();
1494
+ } catch (error) {
1495
+ return {
1496
+ ...inspected,
1497
+ ok: false,
1498
+ mode: 'error',
1499
+ reason: error?.code ?? 'service_start_failed',
1500
+ message: error?.message ?? String(error),
1501
+ bootstrap: { state: 'error', allowDownload: false },
1502
+ };
1503
+ }
1504
+ let waited;
1505
+ try {
1506
+ waited = await awaitWithAbort(
1507
+ waitForHealth(options, inspected.http, waitOptionsFrom(inspected, options)),
1508
+ abortSignal,
1509
+ );
1510
+ } catch (error) {
1511
+ if (error?.code === 'RUNTIME_ABORTED') {
1512
+ return abortedRuntimeResult(inspected, error.abortSignal ?? abortSignal?.reason);
1513
+ }
1514
+ throw error;
1515
+ }
1516
+ if (!waited.ok) {
1517
+ return {
1518
+ ...inspected,
1519
+ ok: false,
1520
+ mode: 'error',
1521
+ reason: 'service_start_failed',
1522
+ message: `常驻服务已重启但健康校验失败(${waited.reason ?? 'timeout'})`,
1523
+ daemon: daemonFromHealth(waited, inspected.http),
1524
+ bootstrap: { state: 'error', allowDownload: false },
1525
+ };
1526
+ }
1527
+ return {
1528
+ ...inspected,
1529
+ ok: true,
1530
+ mode: 'service',
1531
+ instance: waited.instance ?? inspected.homeKey,
1532
+ version: waited.body?.version ?? inspected.version,
1533
+ daemon: daemonFromHealth(waited, inspected.http),
1534
+ service: inspected.service === null ? null : { ...inspected.service, running: true, restarted: true },
1535
+ bootstrap: bootstrapForMode('reused'),
1536
+ };
1537
+ }
1538
+
1539
+ const provider = inspected.providers?.selected ?? null;
1540
+ if (provider === null) {
1541
+ return {
1542
+ ...inspected,
1543
+ ok: false,
1544
+ mode: 'download_required',
1545
+ reason: 'download_required',
1546
+ bootstrap: bootstrapForMode('download_required', { requested: options.allowDownload === true }),
1547
+ download: downloadInfo(options.allowDownload === true),
1548
+ };
1549
+ }
1550
+
1551
+ if (abortSignal?.aborted) return abortedRuntimeResult(inspected, abortSignal.reason);
1552
+
1553
+ const command = runtimeCommandForProvider(provider, { execPath });
1554
+ const args = [...command.args, '--port', String(inspected.http.port)];
1555
+ let child;
1556
+ try {
1557
+ child = spawnFn(command.execPath, args, {
1558
+ env: {
1559
+ ...env,
1560
+ MEBULAR_HOME: inspected.home,
1561
+ MEBULAR_CLOUD_ROOT: inspected.cloudRoot,
1562
+ ELECTRON_RUN_AS_NODE: '1',
1563
+ MEBULAR_RUNTIME_PROVIDER: provider.kind,
1564
+ MEBULAR_RUNTIME_OWNER: provider.kind,
1565
+ ...(provider.version ? { MEBULAR_RUNTIME_VERSION: provider.version } : {}),
1566
+ ...(provider.path ? { MEBULAR_RUNTIME_PATH: provider.path } : {}),
1567
+ ...(provider.runtimePath ? { MEBULAR_RUNTIME_ROOT: provider.runtimePath } : {}),
1568
+ },
1569
+ stdio: childStdio,
1570
+ detached: detached === true,
1571
+ });
1572
+ if (detached === true && typeof child.unref === 'function') child.unref();
1573
+ if (typeof onChildStarted === 'function') onChildStarted(child);
1574
+ } catch (error) {
1575
+ if (child) {
1576
+ await stopRuntimeChildGracefully(child, {
1577
+ graceMs: childStopGraceMs,
1578
+ killWaitMs: childKillWaitMs,
1579
+ });
1580
+ }
1581
+ return {
1582
+ ...inspected,
1583
+ ok: false,
1584
+ mode: 'error',
1585
+ reason: 'spawn_failed',
1586
+ message: `启动 runtime provider 失败:${error?.message ?? error}`,
1587
+ bootstrap: { state: 'error', allowDownload: false },
1588
+ };
1589
+ }
1590
+
1591
+ let waited;
1592
+ try {
1593
+ waited = await awaitWithAbort(
1594
+ waitForHealth(options, inspected.http, waitOptionsFrom(inspected, options)),
1595
+ abortSignal,
1596
+ );
1597
+ } catch (error) {
1598
+ const cleanup = await stopRuntimeChildGracefully(child, {
1599
+ graceMs: childStopGraceMs,
1600
+ killWaitMs: childKillWaitMs,
1601
+ });
1602
+ if (error?.code === 'RUNTIME_ABORTED') {
1603
+ return abortedRuntimeResult(inspected, error.abortSignal ?? abortSignal?.reason, cleanup);
1604
+ }
1605
+ return {
1606
+ ...inspected,
1607
+ ok: false,
1608
+ mode: 'error',
1609
+ reason: 'start_failed',
1610
+ message: `runtime child 启动等待失败:${error?.message ?? error}`,
1611
+ cleanup,
1612
+ bootstrap: { state: 'error', allowDownload: false },
1613
+ };
1614
+ }
1615
+ if (!waited.ok) {
1616
+ const cleanup = await stopRuntimeChildGracefully(child, {
1617
+ graceMs: childStopGraceMs,
1618
+ killWaitMs: childKillWaitMs,
1619
+ });
1620
+ const conflict = HEALTH_TERMINAL_REASONS.has(waited.reason);
1621
+ return {
1622
+ ...inspected,
1623
+ ok: false,
1624
+ mode: conflict ? 'conflict' : 'error',
1625
+ reason: conflict ? waited.reason : 'start_failed',
1626
+ message: conflict
1627
+ ? `启动后端口上的 instance 不匹配(${waited.reason})`
1628
+ : `runtime child 启动后健康校验失败(${waited.reason ?? 'timeout'})`,
1629
+ daemon: daemonFromHealth(waited, inspected.http),
1630
+ cleanup,
1631
+ bootstrap: conflict
1632
+ ? bootstrapForMode('conflict')
1633
+ : { state: 'error', allowDownload: false },
1634
+ };
1635
+ }
1636
+
1637
+ return {
1638
+ ...inspected,
1639
+ ok: true,
1640
+ mode: 'child',
1641
+ child,
1642
+ instance: waited.instance ?? inspected.homeKey,
1643
+ version: waited.body?.version ?? inspected.version,
1644
+ daemon: daemonFromHealth(waited, inspected.http),
1645
+ bootstrap: bootstrapForMode('reused'),
1646
+ };
1647
+ } finally {
1648
+ await lock.release?.();
1649
+ }
1650
+ }
1651
+
1652
+ /**
1653
+ * 只读状态:始终返回解析结果(daemon down 也是 status 成功),不启动/不重启。
1654
+ */
1655
+ export async function runtimeStatus(options = {}) {
1656
+ const inspected = await inspectRuntime(options);
1657
+ if (!inspected.ok) return inspected;
1658
+ const up = inspected.daemon?.status === 'up';
1659
+ return {
1660
+ ...inspected,
1661
+ ok: true,
1662
+ mode: up ? 'reused' : 'down',
1663
+ reason: up ? null : (inspected.daemon?.reason ?? inspected.reason ?? 'unreachable'),
1664
+ bootstrap: up ? bootstrapForMode('reused') : inspected.bootstrap,
1665
+ };
1666
+ }
1667
+
1668
+ /** 去掉不可序列化的 child 句柄(CLI 输出稳定 JSON 用)。 */
1669
+ export function toPublicRuntimeResult(result) {
1670
+ if (!result || typeof result !== 'object') return result;
1671
+ const { child: _child, ...rest } = result;
1672
+ return rest;
1673
+ }