@mebular/mcp 0.1.1 → 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,812 @@
1
+ // 共享 service 层:`mebular-serve` 的所有权、描述符、安装/状态/重启/卸载。
2
+ //
3
+ // 边界:
4
+ // - 描述符优先指向 `<cloudRoot>/runtime/current.json` 的共享 runtime CLI;没有可用
5
+ // current 时,只有调用方显式提供 App/CLI provider 才允许回退(并记录 owner/provider),
6
+ // 绝不下载/安装 runtime;
7
+ // - `runtime service install`(无 fallback)在 current 不可用时返回稳定的
8
+ // `runtime_required`,不写 unit/manifest;
9
+ // - 一个 serviceHome 下只有一个 `mebular-serve` manifest;新的 manifest 记录
10
+ // runtimePath/version/provider/owner/execPath,便于 status/upgrade 与 Plugin 检测;
11
+ // - uninstall 只移除 unit/manifest,不删除 runtime、provider 注册表或任何数据。
12
+
13
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { homedir } from 'node:os';
15
+ import { join, resolve } from 'node:path';
16
+ import { cloudError } from './profiles.mjs';
17
+ import { readRuntimeCurrent, publicRuntimeCurrent } from './runtime-current.mjs';
18
+ import { loadServiceModule } from './service-loader.mjs';
19
+
20
+ export const RUNTIME_SERVICE_KIND = 'mebular-serve';
21
+
22
+ /**
23
+ * 当前 daemon 进程的来源(supervisor/service 启动时写入 env)。用于 Console 在 current
24
+ * 不可用时保留 App/CLI owner,不下载第二个 runtime。
25
+ */
26
+ export function runtimeProviderFromEnv({ env = process.env, execPath = process.execPath, cliPath = null } = {}) {
27
+ const path = typeof env.MEBULAR_RUNTIME_PATH === 'string' && env.MEBULAR_RUNTIME_PATH.length > 0
28
+ ? env.MEBULAR_RUNTIME_PATH
29
+ : (typeof cliPath === 'string' && cliPath.length > 0 ? cliPath : process.argv[1]);
30
+ if (typeof path !== 'string' || path.length === 0) return null;
31
+ return {
32
+ path,
33
+ kind: typeof env.MEBULAR_RUNTIME_PROVIDER === 'string' && env.MEBULAR_RUNTIME_PROVIDER.length > 0
34
+ ? env.MEBULAR_RUNTIME_PROVIDER
35
+ : 'cli',
36
+ owner: typeof env.MEBULAR_RUNTIME_OWNER === 'string' && env.MEBULAR_RUNTIME_OWNER.length > 0
37
+ ? env.MEBULAR_RUNTIME_OWNER
38
+ : 'cli',
39
+ version: typeof env.MEBULAR_RUNTIME_VERSION === 'string' && env.MEBULAR_RUNTIME_VERSION.length > 0
40
+ ? env.MEBULAR_RUNTIME_VERSION
41
+ : null,
42
+ runtimePath: typeof env.MEBULAR_RUNTIME_ROOT === 'string' && env.MEBULAR_RUNTIME_ROOT.length > 0
43
+ ? env.MEBULAR_RUNTIME_ROOT
44
+ : null,
45
+ execPath,
46
+ electron: env.ELECTRON_RUN_AS_NODE === '1' || Boolean(process.versions?.electron),
47
+ };
48
+ }
49
+
50
+ function serviceOptions({ serviceHome, platform, run, now, autostart, label, sha } = {}) {
51
+ const home = serviceHome ?? process.env.MEBULAR_SERVICE_UNIT_HOME ?? homedir();
52
+ return {
53
+ home,
54
+ ...(platform ? { platform } : {}),
55
+ ...(run ? { run } : {}),
56
+ ...(now !== undefined ? { now } : {}),
57
+ ...(autostart !== undefined ? { autostart } : {}),
58
+ ...(label ? { label } : {}),
59
+ ...(sha ? { sha } : {}),
60
+ };
61
+ }
62
+
63
+ function normalizeFallbackProvider(provider) {
64
+ if (!provider || typeof provider !== 'object') return null;
65
+ if (typeof provider.path !== 'string' || provider.path.trim().length === 0) return null;
66
+ const path = provider.path.trim();
67
+ if (!existsSync(path)) return null;
68
+ return {
69
+ kind: typeof provider.kind === 'string' && provider.kind.length > 0 ? provider.kind : 'cli',
70
+ path,
71
+ version: typeof provider.version === 'string' && provider.version.length > 0 ? provider.version : null,
72
+ owner: typeof provider.owner === 'string' && provider.owner.length > 0
73
+ ? provider.owner
74
+ : (typeof provider.kind === 'string' && provider.kind.length > 0 ? provider.kind : 'cli'),
75
+ execPath: typeof provider.execPath === 'string' && provider.execPath.length > 0 ? provider.execPath : process.execPath,
76
+ electron: provider.electron === true || provider.env?.ELECTRON_RUN_AS_NODE === '1',
77
+ runtimePath: typeof provider.runtimePath === 'string' && provider.runtimePath.length > 0 ? provider.runtimePath : null,
78
+ };
79
+ }
80
+
81
+ function sourceFromCurrent(currentState, fallbackProvider) {
82
+ return {
83
+ ok: true,
84
+ source: 'shared',
85
+ provider: 'shared',
86
+ owner: 'shared',
87
+ version: currentState.current.version,
88
+ runtimePath: currentState.current.runtimePath,
89
+ cliPath: currentState.current.cliPath,
90
+ execPath: fallbackProvider?.execPath ?? process.execPath,
91
+ electron: fallbackProvider?.electron === true,
92
+ current: publicRuntimeCurrent(currentState.current),
93
+ currentSource: currentState.source,
94
+ warnings: [...currentState.warnings],
95
+ };
96
+ }
97
+
98
+ function sourceFromProvider(provider) {
99
+ return {
100
+ ok: true,
101
+ source: provider.kind,
102
+ provider: provider.kind,
103
+ owner: provider.owner,
104
+ version: provider.version,
105
+ runtimePath: provider.runtimePath,
106
+ cliPath: provider.path,
107
+ execPath: provider.execPath,
108
+ electron: provider.electron === true,
109
+ current: null,
110
+ currentSource: 'fallback',
111
+ warnings: [],
112
+ };
113
+ }
114
+
115
+ /**
116
+ * 解析 service 当前应使用的 runtime 来源。
117
+ *
118
+ * `currentState` 可注入(已读过的 current),否则从 root 读取。current 可用时永远优先;
119
+ * 不可用时才使用显式 App/CLI fallback;都没有 → `runtime_required`。
120
+ */
121
+ export function resolveRuntimeServiceSource({
122
+ currentState = null,
123
+ fallbackProvider = null,
124
+ } = {}) {
125
+ const state = currentState && typeof currentState === 'object'
126
+ ? currentState
127
+ : { current: null, usable: false, source: 'missing', warnings: [] };
128
+ const fallback = normalizeFallbackProvider(fallbackProvider);
129
+ if (state.usable === true && state.current) {
130
+ return sourceFromCurrent(state, fallback);
131
+ }
132
+ if (fallback !== null) {
133
+ return {
134
+ ...sourceFromProvider(fallback),
135
+ warnings: [...(state.warnings ?? [])],
136
+ };
137
+ }
138
+ return {
139
+ ok: false,
140
+ source: null,
141
+ provider: null,
142
+ owner: null,
143
+ version: state.current?.version ?? null,
144
+ runtimePath: state.current?.runtimePath ?? null,
145
+ cliPath: state.current?.cliPath ?? null,
146
+ execPath: process.execPath,
147
+ electron: false,
148
+ current: publicRuntimeCurrent(state.current),
149
+ currentSource: state.source ?? 'missing',
150
+ reason: 'runtime_required',
151
+ message: '没有可用的共享 runtime(current 缺失/无效):请先安装 runtime 或打开 Mebular App/CLI',
152
+ warnings: [...(state.warnings ?? [])],
153
+ };
154
+ }
155
+
156
+ /** 构造共享 service 描述符;runtime 元数据会随 manifest 落盘(不含秘密)。 */
157
+ export function runtimeServiceDescriptor({
158
+ root,
159
+ home,
160
+ source,
161
+ http = null,
162
+ extraArgs = [],
163
+ providerEnv = {},
164
+ } = {}) {
165
+ if (!source || source.ok === false || typeof source.cliPath !== 'string' || source.cliPath.length === 0) {
166
+ throw cloudError('runtime_required', '缺少可用的 runtime 来源,无法构造 mebular-serve 描述符');
167
+ }
168
+ if (typeof home !== 'string' || home.length === 0) {
169
+ throw cloudError('SERVICE_DESCRIPTOR_INVALID', '缺少 service 实例 home');
170
+ }
171
+ const port = Number(http?.port);
172
+ const listenArgs = Number.isInteger(port) && port > 0 ? ['--port', String(port)] : [];
173
+ const runtime = {
174
+ version: source.version ?? null,
175
+ runtimePath: source.runtimePath ?? null,
176
+ cliPath: source.cliPath,
177
+ provider: source.provider ?? source.source ?? null,
178
+ owner: source.owner ?? source.provider ?? source.source ?? null,
179
+ execPath: source.execPath ?? process.execPath,
180
+ electron: source.electron === true,
181
+ cloudRoot: typeof root === 'string' && root.length > 0 ? root : null,
182
+ home,
183
+ };
184
+ return {
185
+ kind: RUNTIME_SERVICE_KIND,
186
+ args: [source.cliPath, 'serve', ...listenArgs, ...extraArgs],
187
+ heartbeatDir: home,
188
+ workingDir: home,
189
+ execPath: runtime.execPath,
190
+ env: {
191
+ MEBULAR_HOME: home,
192
+ ...(typeof root === 'string' && root.length > 0 ? { MEBULAR_CLOUD_ROOT: root } : {}),
193
+ ...(source.electron === true ? { ELECTRON_RUN_AS_NODE: '1' } : {}),
194
+ ...(source.provider ? { MEBULAR_RUNTIME_PROVIDER: source.provider } : {}),
195
+ ...(source.owner ? { MEBULAR_RUNTIME_OWNER: source.owner } : {}),
196
+ ...(source.version ? { MEBULAR_RUNTIME_VERSION: source.version } : {}),
197
+ ...(source.cliPath ? { MEBULAR_RUNTIME_PATH: source.cliPath } : {}),
198
+ ...(source.runtimePath ? { MEBULAR_RUNTIME_ROOT: source.runtimePath } : {}),
199
+ ...providerEnv,
200
+ },
201
+ runtime,
202
+ };
203
+ }
204
+
205
+ function manifestPathFrom(lib, serviceHome) {
206
+ if (typeof lib?.manifestPath === 'function') return lib.manifestPath(RUNTIME_SERVICE_KIND, serviceHome);
207
+ return join(serviceHome, '.mebular', 'services', `${RUNTIME_SERVICE_KIND}.json`);
208
+ }
209
+
210
+ function readManifestSync(path) {
211
+ try {
212
+ return JSON.parse(readFileSync(path, 'utf-8'));
213
+ } catch {
214
+ return null;
215
+ }
216
+ }
217
+
218
+ function publicManifestRuntime(manifest) {
219
+ const runtime = manifest?.runtime;
220
+ if (!runtime || typeof runtime !== 'object') return null;
221
+ return {
222
+ version: typeof runtime.version === 'string' ? runtime.version : null,
223
+ runtimePath: typeof runtime.runtimePath === 'string' ? runtime.runtimePath : null,
224
+ cliPath: typeof runtime.cliPath === 'string' ? runtime.cliPath : null,
225
+ provider: typeof runtime.provider === 'string' ? runtime.provider : null,
226
+ owner: typeof runtime.owner === 'string' ? runtime.owner : null,
227
+ execPath: typeof runtime.execPath === 'string' ? runtime.execPath : (typeof manifest?.execPath === 'string' ? manifest.execPath : null),
228
+ electron: runtime.electron === true,
229
+ home: typeof runtime.home === 'string' ? runtime.home : null,
230
+ cloudRoot: typeof runtime.cloudRoot === 'string' ? runtime.cloudRoot : null,
231
+ };
232
+ }
233
+
234
+ function expectedServiceLabel(lib, home) {
235
+ try {
236
+ if (typeof lib?.defaultLabel === 'function') {
237
+ return lib.defaultLabel(RUNTIME_SERVICE_KIND, undefined, home);
238
+ }
239
+ } catch {
240
+ // fall through
241
+ }
242
+ return null;
243
+ }
244
+
245
+ function conflictResult(action, message, details = {}) {
246
+ return {
247
+ ok: false,
248
+ action,
249
+ reason: details.reason ?? 'service_conflict',
250
+ message,
251
+ ...details,
252
+ };
253
+ }
254
+
255
+ async function loadLib(serviceLib) {
256
+ return serviceLib ?? loadServiceModule();
257
+ }
258
+
259
+ /**
260
+ * 安装/更新共享 service。
261
+ *
262
+ * 先解析 runtime 来源,再做 manifest 冲突检查;任何前置失败都不会写 unit/manifest。
263
+ * 安装失败时尽力恢复旧 unit/manifest(若有),避免半安装覆盖。
264
+ */
265
+ export async function installRuntimeService({
266
+ root,
267
+ home,
268
+ serviceHome,
269
+ http = null,
270
+ userHome = homedir(),
271
+ currentState = null,
272
+ fallbackProvider = null,
273
+ sourceOverride = null,
274
+ autostart = true,
275
+ replaceExisting = false,
276
+ serviceLib = null,
277
+ platform = process.platform,
278
+ run,
279
+ now,
280
+ sha,
281
+ } = {}) {
282
+ const action = 'install';
283
+ if (typeof root !== 'string' || root.length === 0) {
284
+ return conflictResult(action, '缺少 cloudRoot,无法安装共享 service', { reason: 'cloud_unavailable' });
285
+ }
286
+ if (typeof home !== 'string' || home.length === 0) {
287
+ return conflictResult(action, '缺少 service 实例 home,无法安装共享 service', { reason: 'SERVICE_DESCRIPTOR_INVALID' });
288
+ }
289
+
290
+ const state = currentState ?? await readRuntimeCurrent(root, { userHome });
291
+ const source = sourceOverride ?? resolveRuntimeServiceSource({ currentState: state, fallbackProvider });
292
+ if (source.ok !== true) {
293
+ return {
294
+ ...conflictResult(action, source.message, { reason: source.reason, current: source.current, warnings: source.warnings }),
295
+ source: null,
296
+ service: null,
297
+ };
298
+ }
299
+
300
+ let lib;
301
+ try {
302
+ lib = await loadLib(serviceLib);
303
+ } catch (error) {
304
+ return conflictResult(action, `共享 service 模块不可用:${error?.message ?? error}`, {
305
+ reason: 'service_unavailable',
306
+ });
307
+ }
308
+
309
+ const descriptor = runtimeServiceDescriptor({ root, home, source, http });
310
+ const options = serviceOptions({
311
+ serviceHome,
312
+ platform,
313
+ run,
314
+ now,
315
+ autostart,
316
+ sha,
317
+ });
318
+
319
+ let statusBefore = null;
320
+ try {
321
+ statusBefore = lib.serviceStatus(descriptor, options);
322
+ } catch (error) {
323
+ return conflictResult(action, `无法确认现有 mebular-serve 状态:${error?.message ?? error}`, {
324
+ reason: 'service_unknown',
325
+ });
326
+ }
327
+ if (statusBefore?.foreign === true) {
328
+ return conflictResult(action, 'mebular-serve 标签被其他 home 的作业占用:拒绝安装/覆盖', {
329
+ reason: 'service_foreign',
330
+ service: statusBefore,
331
+ });
332
+ }
333
+
334
+ const manifestPath = manifestPathFrom(lib, options.home);
335
+ const previousManifest = readManifestSync(manifestPath);
336
+ const previousRuntime = publicManifestRuntime(previousManifest);
337
+ const expectedLabel = expectedServiceLabel(lib, home);
338
+ const legacyManifestOtherHome = previousRuntime === null
339
+ && typeof previousManifest?.label === 'string'
340
+ && previousManifest.label.length > 0
341
+ && typeof expectedLabel === 'string'
342
+ && previousManifest.label !== expectedLabel;
343
+ const samePath = (left, right) => typeof left === 'string' && left.length > 0
344
+ && typeof right === 'string' && right.length > 0
345
+ && resolve(left) === resolve(right);
346
+ const sameService = previousManifest === null
347
+ || previousRuntime === null
348
+ || previousRuntime.home === null
349
+ || samePath(previousRuntime.home, home);
350
+ const sameRoot = previousManifest === null
351
+ || previousRuntime === null
352
+ || previousRuntime.cloudRoot === null
353
+ || samePath(previousRuntime.cloudRoot, root);
354
+ if (legacyManifestOtherHome && !replaceExisting) {
355
+ return conflictResult(action, '已存在另一个 home 的 legacy mebular-serve(manifest 无 runtime 元数据):拒绝覆盖', {
356
+ reason: 'service_conflict',
357
+ existing: {
358
+ label: previousManifest.label ?? null,
359
+ unitPath: previousManifest.unitPath ?? null,
360
+ runtime: previousRuntime,
361
+ },
362
+ service: statusBefore,
363
+ current: source.current,
364
+ });
365
+ }
366
+ const usingFallbackWithoutCurrent = source.currentSource === 'fallback';
367
+ if (previousManifest !== null
368
+ && !replaceExisting
369
+ && usingFallbackWithoutCurrent
370
+ && previousRuntime !== null
371
+ && typeof previousRuntime.cliPath === 'string'
372
+ && previousRuntime.cliPath.length > 0
373
+ && !samePath(previousRuntime.cliPath, source.cliPath)) {
374
+ return conflictResult(action, 'current 不可用且已有不同来源的 mebular-serve:拒绝覆盖现有 service', {
375
+ reason: 'service_conflict',
376
+ existing: {
377
+ label: previousManifest.label ?? null,
378
+ unitPath: previousManifest.unitPath ?? null,
379
+ runtime: previousRuntime,
380
+ },
381
+ service: statusBefore,
382
+ current: source.current,
383
+ });
384
+ }
385
+ if (previousManifest !== null && !replaceExisting && (!sameService || !sameRoot)) {
386
+ return conflictResult(action, '已存在另一个 home/cloudRoot 的 mebular-serve:拒绝覆盖', {
387
+ reason: 'service_conflict',
388
+ existing: {
389
+ label: previousManifest.label ?? null,
390
+ unitPath: previousManifest.unitPath ?? null,
391
+ runtime: previousRuntime,
392
+ },
393
+ service: statusBefore,
394
+ current: source.current,
395
+ });
396
+ }
397
+
398
+ // 同 home 且 source 完全一致、已在运行:幂等 no-op,避免 Console 安装按钮重启健康 daemon。
399
+ if (statusBefore?.registered === true
400
+ && statusBefore?.running === true
401
+ && previousRuntime !== null
402
+ && previousRuntime.cliPath === source.cliPath
403
+ && previousRuntime.version === source.version
404
+ && previousRuntime.provider === source.provider) {
405
+ return {
406
+ ok: true,
407
+ action,
408
+ already: true,
409
+ registered: true,
410
+ running: true,
411
+ label: statusBefore.label ?? null,
412
+ unitPath: statusBefore.unitPath ?? null,
413
+ manifestPath,
414
+ autostart: statusBefore.autostart ?? autostart,
415
+ runtime: previousRuntime,
416
+ current: source.current,
417
+ provider: source.provider,
418
+ owner: source.owner,
419
+ version: source.version,
420
+ warnings: source.warnings,
421
+ };
422
+ }
423
+
424
+ const previousUnit = typeof statusBefore?.unitPath === 'string' && existsSync(statusBefore.unitPath)
425
+ ? { path: statusBefore.unitPath, content: readFileSync(statusBefore.unitPath, 'utf-8') }
426
+ : null;
427
+ const previousManifestRaw = previousManifest === null ? null : JSON.stringify(previousManifest, null, 2);
428
+
429
+ const restorePrevious = () => {
430
+ try {
431
+ if (previousUnit !== null) {
432
+ writeFileSync(previousUnit.path, previousUnit.content, { mode: 0o644 });
433
+ } else if (typeof statusBefore?.unitPath === 'string' && existsSync(statusBefore.unitPath)) {
434
+ rmSync(statusBefore.unitPath, { force: true });
435
+ }
436
+ if (previousManifestRaw !== null) {
437
+ writeFileSync(manifestPath, previousManifestRaw, { mode: 0o600 });
438
+ } else if (existsSync(manifestPath)) {
439
+ rmSync(manifestPath, { force: true });
440
+ }
441
+ return true;
442
+ } catch {
443
+ return false;
444
+ }
445
+ };
446
+
447
+ let result;
448
+ try {
449
+ result = lib.installService(descriptor, options);
450
+ } catch (error) {
451
+ const restored = restorePrevious();
452
+ return conflictResult(action, `共享 service 安装失败:${error?.message ?? error}`, {
453
+ reason: 'service_install_failed',
454
+ restored,
455
+ current: source.current,
456
+ runtime: descriptor.runtime,
457
+ });
458
+ }
459
+
460
+ if (result?.ok !== true || result?.started !== true) {
461
+ const restored = restorePrevious();
462
+ let restarted = false;
463
+ if (previousManifest !== null && typeof lib.restartService === 'function') {
464
+ try {
465
+ restarted = lib.restartService(descriptor, options)?.ok === true;
466
+ } catch {
467
+ restarted = false;
468
+ }
469
+ }
470
+ return conflictResult(action, `共享 service 安装失败或未启动:${result?.startError ?? result?.error ?? 'unknown'}`, {
471
+ reason: result?.foreign === true ? 'service_foreign' : 'service_install_failed',
472
+ restored,
473
+ restarted,
474
+ unitPath: result?.unitPath ?? null,
475
+ current: source.current,
476
+ runtime: descriptor.runtime,
477
+ });
478
+ }
479
+
480
+ return {
481
+ ok: true,
482
+ action,
483
+ already: false,
484
+ registered: true,
485
+ running: true,
486
+ label: result.label ?? null,
487
+ unitPath: result.unitPath ?? null,
488
+ manifestPath,
489
+ autostart: result.autostart ?? autostart,
490
+ runtime: descriptor.runtime,
491
+ current: source.current,
492
+ provider: source.provider,
493
+ owner: source.owner,
494
+ version: source.version,
495
+ warnings: [...source.warnings, ...(Array.isArray(result.warning) ? result.warning : [])],
496
+ };
497
+ }
498
+
499
+ function descriptorForExistingService({ root, home, manifest }) {
500
+ const runtime = publicManifestRuntime(manifest);
501
+ const cliPath = runtime?.cliPath ?? (Array.isArray(manifest?.args) ? manifest.args[0] : null) ?? '';
502
+ return {
503
+ kind: RUNTIME_SERVICE_KIND,
504
+ args: Array.isArray(manifest?.args) ? [...manifest.args] : [cliPath, 'serve'].filter(Boolean),
505
+ heartbeatDir: home,
506
+ workingDir: home,
507
+ ...(typeof manifest?.execPath === 'string' ? { execPath: manifest.execPath } : {}),
508
+ env: {
509
+ MEBULAR_HOME: home,
510
+ ...(typeof root === 'string' && root.length > 0 ? { MEBULAR_CLOUD_ROOT: root } : {}),
511
+ },
512
+ ...(runtime ? { runtime } : {}),
513
+ };
514
+ }
515
+
516
+ /** 只读 service 状态:版本/current/running/owner 都来自非敏感文件。 */
517
+ export async function runtimeServiceStatus({
518
+ root,
519
+ home,
520
+ serviceHome,
521
+ userHome = homedir(),
522
+ currentState = null,
523
+ fallbackProvider = null,
524
+ serviceLib = null,
525
+ platform = process.platform,
526
+ run,
527
+ now,
528
+ } = {}) {
529
+ const action = 'status';
530
+ const state = currentState ?? (typeof root === 'string' && root.length > 0
531
+ ? await readRuntimeCurrent(root, { userHome })
532
+ : { current: null, usable: false, source: 'unavailable', warnings: ['cloudRoot 不可用'] });
533
+ let lib;
534
+ try {
535
+ lib = await loadLib(serviceLib);
536
+ } catch (error) {
537
+ return {
538
+ ok: false,
539
+ action,
540
+ reason: 'service_unavailable',
541
+ message: `共享 service 模块不可用:${error?.message ?? error}`,
542
+ current: publicRuntimeCurrent(state.current),
543
+ currentUsable: state.usable === true,
544
+ warnings: [...(state.warnings ?? [])],
545
+ };
546
+ }
547
+
548
+ const options = serviceOptions({ serviceHome, platform, run, now });
549
+ const manifestPath = manifestPathFrom(lib, options.home);
550
+ const manifest = readManifestSync(manifestPath);
551
+ const runtime = publicManifestRuntime(manifest);
552
+
553
+ let descriptor;
554
+ const source = resolveRuntimeServiceSource({ currentState: state, fallbackProvider });
555
+ if (source.ok === true) {
556
+ descriptor = runtimeServiceDescriptor({ root, home, source });
557
+ } else {
558
+ descriptor = descriptorForExistingService({ root, home, manifest });
559
+ }
560
+
561
+ let status;
562
+ try {
563
+ status = lib.serviceStatus(descriptor, options);
564
+ } catch (error) {
565
+ return {
566
+ ok: false,
567
+ action,
568
+ reason: 'service_unknown',
569
+ message: `无法读取 mebular-serve 状态:${error?.message ?? error}`,
570
+ current: publicRuntimeCurrent(state.current),
571
+ currentUsable: state.usable === true,
572
+ runtime,
573
+ warnings: [...(state.warnings ?? [])],
574
+ };
575
+ }
576
+
577
+ return {
578
+ ok: true,
579
+ action,
580
+ kind: RUNTIME_SERVICE_KIND,
581
+ home,
582
+ serviceHome: options.home,
583
+ label: status?.label ?? null,
584
+ manifestLabel: manifest?.label ?? null,
585
+ expectedLabel: expectedServiceLabel(lib, home),
586
+ registered: status?.registered === true,
587
+ running: status?.running === true,
588
+ autostart: status?.autostart ?? null,
589
+ foreign: status?.foreign === true,
590
+ foreignOwner: status?.foreignOwner ?? null,
591
+ unitPath: status?.unitPath ?? null,
592
+ manifestPath,
593
+ runtime,
594
+ version: runtime?.version ?? state.current?.version ?? null,
595
+ runtimePath: runtime?.runtimePath ?? state.current?.runtimePath ?? null,
596
+ provider: runtime?.provider ?? null,
597
+ owner: runtime?.owner ?? null,
598
+ cliPath: runtime?.cliPath ?? (Array.isArray(status?.args) ? status.args[0] : null) ?? null,
599
+ args: Array.isArray(status?.args) ? [...status.args] : [],
600
+ execPath: status?.execPath ?? runtime?.execPath ?? null,
601
+ current: publicRuntimeCurrent(state.current),
602
+ currentUsable: state.usable === true,
603
+ currentSource: state.source,
604
+ warnings: [...(state.warnings ?? [])],
605
+ };
606
+ }
607
+
608
+ /** 重启共享 service(只执行平台计划;不启动第二个 daemon)。 */
609
+ export async function restartRuntimeService({
610
+ root,
611
+ home,
612
+ serviceHome,
613
+ userHome = homedir(),
614
+ currentState = null,
615
+ fallbackProvider = null,
616
+ serviceLib = null,
617
+ platform = process.platform,
618
+ run,
619
+ now,
620
+ } = {}) {
621
+ const action = 'restart';
622
+ const status = await runtimeServiceStatus({
623
+ root,
624
+ home,
625
+ serviceHome,
626
+ userHome,
627
+ currentState,
628
+ fallbackProvider,
629
+ serviceLib,
630
+ platform,
631
+ run,
632
+ now,
633
+ });
634
+ if (status.ok !== true) return { ...status, action };
635
+ if (status.registered !== true) {
636
+ return {
637
+ ...status,
638
+ ok: false,
639
+ action,
640
+ reason: 'service_not_registered',
641
+ message: '当前 home 未注册 mebular-serve;未启动第二个 daemon',
642
+ };
643
+ }
644
+ let lib;
645
+ try {
646
+ lib = await loadLib(serviceLib);
647
+ } catch (error) {
648
+ return { ...status, ok: false, action, reason: 'service_unavailable', message: String(error?.message ?? error) };
649
+ }
650
+ const manifest = readManifestSync(status.manifestPath);
651
+ const descriptor = descriptorForExistingService({ root, home, manifest });
652
+ let result;
653
+ try {
654
+ result = lib.restartService(descriptor, serviceOptions({ serviceHome, platform, run, now }));
655
+ } catch (error) {
656
+ return { ...status, ok: false, action, reason: 'service_restart_failed', message: String(error?.message ?? error) };
657
+ }
658
+ return {
659
+ ...status,
660
+ ok: result?.ok === true,
661
+ action,
662
+ restarted: result?.ok === true,
663
+ commands: result?.commands ?? [],
664
+ manual: result?.manual ?? null,
665
+ reason: result?.ok === true ? null : 'service_restart_failed',
666
+ };
667
+ }
668
+
669
+ /** 重启计划(不执行;Console /admin/api/restart 复用)。 */
670
+ export async function planRuntimeServiceRestart({
671
+ root,
672
+ home,
673
+ serviceHome,
674
+ userHome = homedir(),
675
+ currentState = null,
676
+ fallbackProvider = null,
677
+ serviceLib = null,
678
+ platform = process.platform,
679
+ run,
680
+ now,
681
+ } = {}) {
682
+ const status = await runtimeServiceStatus({
683
+ root,
684
+ home,
685
+ serviceHome,
686
+ userHome,
687
+ currentState,
688
+ fallbackProvider,
689
+ serviceLib,
690
+ platform,
691
+ run,
692
+ now,
693
+ });
694
+ if (status.ok !== true) {
695
+ return { registered: false, manual: status.message ?? '服务管理不可用:请手动重启', status };
696
+ }
697
+ if (status.registered !== true) {
698
+ return {
699
+ registered: false,
700
+ manual: `未注册为服务:请手动重启(nohup mebular serve > ${home}/serve.log 2>&1 &)`,
701
+ status,
702
+ };
703
+ }
704
+ let lib;
705
+ try {
706
+ lib = await loadLib(serviceLib);
707
+ } catch (error) {
708
+ return { registered: false, manual: `服务管理不可用(${error?.message ?? error}):请手动重启`, status };
709
+ }
710
+ const manifest = readManifestSync(status.manifestPath);
711
+ const descriptor = descriptorForExistingService({ root, home, manifest });
712
+ try {
713
+ const plan = lib.restartPlanFor(descriptor, serviceOptions({ serviceHome, platform, run, now }));
714
+ return { ...plan, status };
715
+ } catch (error) {
716
+ return { registered: false, manual: `服务重启计划不可用(${error?.message ?? error}):请手动重启`, status };
717
+ }
718
+ }
719
+
720
+ /**
721
+ * 卸载共享 service:只移除 unit/manifest。
722
+ * 不删除 runtime 目录、runtime-providers.json、store、identity 或任何数据。
723
+ */
724
+ export async function uninstallRuntimeService({
725
+ root,
726
+ home,
727
+ serviceHome,
728
+ serviceLib = null,
729
+ platform = process.platform,
730
+ run,
731
+ now,
732
+ } = {}) {
733
+ const action = 'uninstall';
734
+ let lib;
735
+ try {
736
+ lib = await loadLib(serviceLib);
737
+ } catch (error) {
738
+ return {
739
+ ok: false,
740
+ action,
741
+ reason: 'service_unavailable',
742
+ message: `共享 service 模块不可用:${error?.message ?? error}`,
743
+ };
744
+ }
745
+ const options = serviceOptions({ serviceHome, platform, run, now });
746
+ const manifestPath = manifestPathFrom(lib, options.home);
747
+ const manifest = readManifestSync(manifestPath);
748
+ const manifestRuntime = publicManifestRuntime(manifest);
749
+ const expectedLabel = expectedServiceLabel(lib, home);
750
+ if (!manifestRuntime?.home
751
+ && typeof manifest?.label === 'string'
752
+ && manifest.label.length > 0
753
+ && typeof expectedLabel === 'string'
754
+ && manifest.label !== expectedLabel) {
755
+ return {
756
+ ok: false,
757
+ action,
758
+ reason: 'service_conflict',
759
+ message: 'manifest 属于另一个 home 的 legacy mebular-serve:拒绝卸载他人服务',
760
+ existing: { label: manifest.label, unitPath: manifest?.unitPath ?? null, runtime: null },
761
+ };
762
+ }
763
+ if (manifestRuntime?.home && resolve(manifestRuntime.home) !== resolve(home)) {
764
+ return {
765
+ ok: false,
766
+ action,
767
+ reason: 'service_conflict',
768
+ message: 'manifest 属于另一个 home 的 mebular-serve:拒绝卸载他人服务',
769
+ existing: { label: manifest?.label ?? null, unitPath: manifest?.unitPath ?? null, runtime: manifestRuntime },
770
+ };
771
+ }
772
+ if (manifestRuntime?.cloudRoot && typeof root === 'string' && resolve(manifestRuntime.cloudRoot) !== resolve(root)) {
773
+ return {
774
+ ok: false,
775
+ action,
776
+ reason: 'service_conflict',
777
+ message: 'manifest 属于另一个 cloudRoot 的 mebular-serve:拒绝卸载他人服务',
778
+ existing: { label: manifest?.label ?? null, unitPath: manifest?.unitPath ?? null, runtime: manifestRuntime },
779
+ };
780
+ }
781
+ const cliPath = (Array.isArray(manifest?.args) ? manifest.args[0] : null) ?? '';
782
+ const descriptor = {
783
+ kind: RUNTIME_SERVICE_KIND,
784
+ args: Array.isArray(manifest?.args) ? [...manifest.args] : (cliPath ? [cliPath, 'serve'] : []),
785
+ heartbeatDir: home,
786
+ workingDir: home,
787
+ ...(typeof manifest?.execPath === 'string' ? { execPath: manifest.execPath } : {}),
788
+ env: {
789
+ MEBULAR_HOME: home,
790
+ ...(typeof root === 'string' && root.length > 0 ? { MEBULAR_CLOUD_ROOT: root } : {}),
791
+ },
792
+ ...(manifestRuntime ? { runtime: manifestRuntime } : {}),
793
+ };
794
+ let result;
795
+ try {
796
+ result = lib.uninstallService(descriptor, options);
797
+ } catch (error) {
798
+ return { ok: false, action, reason: 'service_uninstall_failed', message: String(error?.message ?? error) };
799
+ }
800
+ return {
801
+ ok: true,
802
+ action,
803
+ kind: RUNTIME_SERVICE_KIND,
804
+ removed: result?.removed === true,
805
+ serviceHome: options.home,
806
+ manifestPath,
807
+ unitPath: result?.unitPath ?? manifest?.unitPath ?? null,
808
+ label: result?.label ?? manifest?.label ?? null,
809
+ note: result?.note ?? null,
810
+ runtimePreserved: true,
811
+ };
812
+ }