@mebular/mcp 0.3.5 → 0.3.8

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,405 @@
1
+ // Adapter provisioning orchestration (W1/W5).
2
+ //
3
+ // Flow: detect → ensure package (never npm) → configure (idempotent, backup,
4
+ // atomic) → activate (injected reload/restart only) → verify (readback) →
5
+ // persist `<home>/adapters.json`. Failures roll back the config/package and
6
+ // record a stable code; MCP connection success is never affected.
7
+
8
+ import { rm } from 'node:fs/promises';
9
+ import { homedir } from 'node:os';
10
+ import { join, sep } from 'node:path';
11
+ import { probeAdapterHealth } from './adapter-health.mjs';
12
+ import { getAdapter } from './adapters/index.mjs';
13
+ import { loadAdapterState, updateAdapterHost, publicAdapterState } from './adapter-state.mjs';
14
+ import { homeDir } from './home.mjs';
15
+ import { APP_VERSION } from './version.mjs';
16
+
17
+ const MANAGED_DIR = 'adapters';
18
+
19
+ function failure(code, extra = {}) {
20
+ return { ok: false, code, ...extra };
21
+ }
22
+
23
+ /**
24
+ * Remove a package this run staged into `<home>/adapters/...` after a failed
25
+ * configure. Only runs for `created` packages and only inside the managed root;
26
+ * pre-existing installs and user directories are never touched.
27
+ */
28
+ async function cleanupStagedPackage(packageInfo, home) {
29
+ if (packageInfo?.created !== true || typeof packageInfo.managedPath !== 'string') return false;
30
+ if (typeof home !== 'string' || home.length === 0) return false;
31
+ const managedRoot = join(home, MANAGED_DIR);
32
+ const target = packageInfo.managedPath;
33
+ if (target !== managedRoot && !target.startsWith(`${managedRoot}${sep}`)) return false;
34
+ try {
35
+ await rm(target, { recursive: true, force: true });
36
+ return true;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ function deferredHealth() {
43
+ return {
44
+ state: 'deferred',
45
+ code: null,
46
+ health: 'deferred',
47
+ available: false,
48
+ ingested: null,
49
+ lastIngestedAt: null,
50
+ };
51
+ }
52
+
53
+ function resolveUserHome(options = {}) {
54
+ if (typeof options.userHome === 'string' && options.userHome.length > 0) return options.userHome;
55
+ const env = options.env ?? process.env;
56
+ const fromEnv = env?.MEBULAR_USER_HOME;
57
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv;
58
+ return homedir();
59
+ }
60
+
61
+ function displayPath(path, userHome) {
62
+ if (typeof path !== 'string' || path.length === 0) return null;
63
+ if (typeof userHome === 'string' && userHome.length > 0) {
64
+ const prefix = userHome.endsWith(sep) ? userHome : `${userHome}${sep}`;
65
+ if (path.startsWith(prefix)) return `~${path.slice(userHome.length)}`;
66
+ }
67
+ return path;
68
+ }
69
+
70
+ async function record(hostId, patch, home) {
71
+ try {
72
+ await updateAdapterHost(hostId, patch, { home });
73
+ } catch {
74
+ // State is diagnostic only; never fail provisioning because it could not
75
+ // be written (the config/package result is still authoritative).
76
+ }
77
+ }
78
+
79
+ function unsupportedStatus() {
80
+ return 'unsupported';
81
+ }
82
+
83
+ /**
84
+ * Ensure one host adapter. `options.dryRun` only reports the planned change.
85
+ *
86
+ * Only explicit connect/repair callers should invoke this for a host; the
87
+ * connected-only fan-out lives in `ensureAdaptersForConnected`.
88
+ */
89
+ export async function ensureAdapter(hostId, options = {}) {
90
+ const home = options.home ?? homeDir();
91
+ const connected = options.connected === true;
92
+ const dryRun = options.dryRun === true;
93
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
94
+ const adapter = getAdapter(hostId);
95
+ const previousState = loadAdapterState({ home }).hosts[hostId] ?? null;
96
+ // Captured before any write so a fresh install's health window cannot skip
97
+ // evidence produced while provisioning runs.
98
+ const startedAt = Date.now();
99
+
100
+ if (!adapter) {
101
+ if (!dryRun) await record(hostId, { detected: false, ...(connected ? { connected: true } : {}), adapter: 'unsupported', lastError: 'ADAPTER_UNAVAILABLE' }, home);
102
+ return failure('ADAPTER_UNAVAILABLE', { hostId });
103
+ }
104
+ if (adapter.status === 'unsupported' || adapter.status === 'pending') {
105
+ const code = adapter.status === 'pending' ? 'ADAPTER_UNAVAILABLE' : 'ADAPTER_UNSUPPORTED';
106
+ if (!dryRun) {
107
+ await record(hostId, {
108
+ detected: false,
109
+ ...(connected ? { connected: true } : {}),
110
+ adapter: unsupportedStatus(adapter),
111
+ lastError: code,
112
+ }, home);
113
+ }
114
+ return failure(code, { hostId, status: 'unsupported', reason: adapter.reason ?? null });
115
+ }
116
+
117
+ let detection;
118
+ try {
119
+ detection = await adapter.detect({ ...options, home, expectedVersion });
120
+ } catch {
121
+ if (!dryRun) await record(hostId, { detected: false, ...(connected ? { connected: true } : {}), adapter: 'degraded', lastError: 'DETECT_FAILED' }, home);
122
+ return failure('DETECT_FAILED', { hostId, status: 'degraded' });
123
+ }
124
+
125
+ if (detection?.detected !== true && options.force !== true && connected !== true) {
126
+ if (!dryRun) await record(hostId, { detected: false, ...(connected ? { connected: true } : {}), lastError: 'HOST_NOT_DETECTED' }, home);
127
+ return failure('HOST_NOT_DETECTED', { hostId, status: 'absent' });
128
+ }
129
+
130
+ const packageInfo = await adapter.ensurePackage({
131
+ ...options,
132
+ home,
133
+ expectedVersion,
134
+ ...(dryRun ? { dryRun: true, stagePackage: false } : {}),
135
+ });
136
+ if (!packageInfo?.ok) {
137
+ if (!dryRun) {
138
+ await record(hostId, {
139
+ detected: detection?.detected === true,
140
+ ...(connected ? { connected: true } : {}),
141
+ adapter: 'degraded',
142
+ lastError: packageInfo?.code ?? 'ADAPTER_PACKAGE_NOT_FOUND',
143
+ }, home);
144
+ }
145
+ return failure(packageInfo?.code ?? 'ADAPTER_PACKAGE_NOT_FOUND', { hostId, status: 'degraded' });
146
+ }
147
+
148
+ const configured = await adapter.configure({
149
+ ...options,
150
+ home,
151
+ expectedVersion,
152
+ packageInfo,
153
+ configPath: detection?.configPath ?? options.configPath,
154
+ });
155
+ if (!configured?.ok) {
156
+ // The plan's failure path rolls back a package staged by this run. Configure
157
+ // performs its own config restore; remove only the managed copy we created.
158
+ if (!dryRun) await cleanupStagedPackage(packageInfo, home);
159
+ if (!dryRun) {
160
+ await record(hostId, {
161
+ detected: detection?.detected === true,
162
+ ...(connected ? { connected: true } : {}),
163
+ adapter: 'degraded',
164
+ version: packageInfo.version,
165
+ source: packageInfo.source,
166
+ configPath: displayPath(detection?.configPath ?? options.configPath, resolveUserHome(options)),
167
+ lastError: configured?.code ?? 'CONFIGURE_FAILED',
168
+ }, home);
169
+ }
170
+ return failure(configured?.code ?? 'CONFIGURE_FAILED', { hostId, status: 'degraded' });
171
+ }
172
+
173
+ if (dryRun) {
174
+ return {
175
+ ok: true,
176
+ hostId,
177
+ dryRun: true,
178
+ changed: configured.changed === true,
179
+ status: configured.changed === true ? 'planned' : 'installed',
180
+ activation: 'next-start',
181
+ version: packageInfo.version,
182
+ source: packageInfo.source,
183
+ preview: configured.preview ?? '',
184
+ ingested: null,
185
+ };
186
+ }
187
+
188
+ const activation = configured.changed === true
189
+ ? await adapter.activate({ ...options, home, expectedVersion, packageInfo })
190
+ : { ok: true, activation: previousState?.activation ?? 'next-start' };
191
+ if (!activation?.ok) {
192
+ await adapter.rollback({
193
+ ...options,
194
+ home,
195
+ expectedVersion,
196
+ packageInfo,
197
+ removePackage: true,
198
+ backupPath: configured.backupPath ?? null,
199
+ configPath: configured.configPath,
200
+ }).catch(() => null);
201
+ await record(hostId, {
202
+ detected: detection?.detected === true,
203
+ ...(connected ? { connected: true } : {}),
204
+ adapter: 'degraded',
205
+ version: packageInfo.version,
206
+ source: packageInfo.source,
207
+ configPath: displayPath(detection?.configPath ?? options.configPath, resolveUserHome(options)),
208
+ lastError: activation?.code ?? 'ACTIVATION_FAILED',
209
+ }, home);
210
+ return failure(activation?.code ?? 'ACTIVATION_FAILED', { hostId, status: 'degraded' });
211
+ }
212
+
213
+ const verified = await adapter.verify({
214
+ ...options,
215
+ home,
216
+ expectedVersion,
217
+ packageInfo,
218
+ configPath: configured.configPath,
219
+ });
220
+ if (!verified?.ok) {
221
+ if (configured.changed === true) {
222
+ await adapter.rollback({
223
+ ...options,
224
+ home,
225
+ expectedVersion,
226
+ packageInfo,
227
+ removePackage: true,
228
+ backupPath: configured.backupPath ?? null,
229
+ configPath: configured.configPath,
230
+ }).catch(() => null);
231
+ }
232
+ await record(hostId, {
233
+ detected: detection?.detected === true,
234
+ ...(connected ? { connected: true } : {}),
235
+ adapter: 'degraded',
236
+ version: packageInfo.version,
237
+ source: packageInfo.source,
238
+ configPath: displayPath(detection?.configPath ?? options.configPath, resolveUserHome(options)),
239
+ lastError: verified?.code ?? 'VERIFY_FAILED',
240
+ }, home);
241
+ return failure(verified?.code ?? 'VERIFY_FAILED', {
242
+ hostId,
243
+ status: 'degraded',
244
+ checks: verified?.checks ?? [],
245
+ });
246
+ }
247
+
248
+ // A newer adapter version starts a new health baseline: traces produced by the
249
+ // previous version must not make the just-upgraded plugin look healthy before
250
+ // it has ingested anything itself. Same version keeps its original baseline.
251
+ const sameInstalledVersion = typeof previousState?.version === 'string'
252
+ && previousState.version === packageInfo.version;
253
+ const installedAt = sameInstalledVersion
254
+ && Number.isFinite(previousState?.installedAt)
255
+ && previousState.installedAt >= 0
256
+ ? previousState.installedAt
257
+ : startedAt;
258
+ let health;
259
+ if (options.health === false) {
260
+ health = deferredHealth();
261
+ } else {
262
+ try {
263
+ health = await probeAdapterHealth(hostId, {
264
+ home,
265
+ installedAt,
266
+ ...(options.healthOptions ?? {}),
267
+ ...(typeof options.fetchImpl === 'function' ? { fetchImpl: options.fetchImpl } : {}),
268
+ });
269
+ } catch {
270
+ // Health is diagnostic only; provisioning success is authoritative.
271
+ health = deferredHealth();
272
+ }
273
+ }
274
+
275
+ let status;
276
+ let lastError = null;
277
+ // A version change clears the previous adapter version's health evidence too;
278
+ // only evidence from the current installation counts.
279
+ let lastIngestedAt = sameInstalledVersion && Number.isFinite(previousState?.lastIngestedAt)
280
+ ? previousState.lastIngestedAt
281
+ : null;
282
+ if (health.state === 'healthy') {
283
+ status = 'active';
284
+ if (health.lastIngestedAt !== null && health.lastIngestedAt !== undefined) lastIngestedAt = health.lastIngestedAt;
285
+ } else if (health.state === 'degraded') {
286
+ status = 'degraded';
287
+ lastError = health.code ?? 'HEALTH_NO_INGEST';
288
+ } else {
289
+ // No positive evidence yet (or sidecar unavailable): stay installed so the
290
+ // next startup/repair re-checks health without a false degraded report.
291
+ status = 'installed';
292
+ }
293
+
294
+ await record(hostId, {
295
+ detected: detection?.detected === true,
296
+ ...(connected ? { connected: true } : {}),
297
+ adapter: status,
298
+ version: packageInfo.version,
299
+ source: packageInfo.source,
300
+ configPath: displayPath(detection?.configPath ?? options.configPath, resolveUserHome(options)),
301
+ activation: activation.activation,
302
+ lastError,
303
+ verifiedAt: Date.now(),
304
+ installedAt,
305
+ // `null` clears a previous-version timestamp on upgrade (sanitizer drops it).
306
+ lastIngestedAt,
307
+ }, home);
308
+
309
+ return {
310
+ ok: true,
311
+ hostId,
312
+ status,
313
+ changed: configured.changed === true,
314
+ activation: activation.activation,
315
+ version: packageInfo.version,
316
+ source: packageInfo.source,
317
+ verified: true,
318
+ installedAt,
319
+ ingested: health.ingested ?? null,
320
+ health: health.state,
321
+ healthCode: health.code ?? null,
322
+ lastIngestedAt: lastIngestedAt ?? null,
323
+ checks: verified.checks ?? [],
324
+ };
325
+ }
326
+
327
+ /** Dry-run alias (no writes). */
328
+ export async function dryRun(hostId, options = {}) {
329
+ return ensureAdapter(hostId, { ...options, dryRun: true });
330
+ }
331
+
332
+ /** Repair one host; refuses hosts that are not connected. */
333
+ export async function repairAdapter(hostId, options = {}) {
334
+ const home = options.home ?? homeDir();
335
+ const state = loadAdapterState({ home });
336
+ const connected = options.connected === true || state.hosts[hostId]?.connected === true;
337
+ if (!connected) return failure('NOT_CONNECTED', { hostId, status: 'absent' });
338
+ return ensureAdapter(hostId, { ...options, mode: 'repair', connected: true });
339
+ }
340
+
341
+ /**
342
+ * Fan-out for App startup/upgrade and `mebular adapter repair`.
343
+ * Exactly one of:
344
+ * * `connectedHostIds` (live MCP connection detection), or
345
+ * * state hosts with `connected === true`.
346
+ * Unconnected hosts are never touched.
347
+ */
348
+ export async function ensureAdaptersForConnected(options = {}) {
349
+ const home = options.home ?? homeDir();
350
+ const state = loadAdapterState({ home });
351
+ const explicit = Array.isArray(options.connectedHostIds)
352
+ ? [...new Set(options.connectedHostIds.filter((id) => typeof id === 'string' && id.length > 0))]
353
+ : null;
354
+ const ids = explicit ?? Object.entries(state.hosts)
355
+ .filter(([, record]) => record?.connected === true)
356
+ .map(([hostId]) => hostId);
357
+
358
+ const hosts = [];
359
+ for (const hostId of ids) {
360
+ if (explicit === null && state.hosts[hostId]?.connected !== true) continue;
361
+ hosts.push(await repairAdapter(hostId, { ...options, home, connected: true }));
362
+ }
363
+
364
+ const degraded = hosts.filter((entry) => entry.status === 'degraded' || entry.ok !== true)
365
+ .filter((entry) => !['ADAPTER_UNSUPPORTED', 'ADAPTER_UNAVAILABLE', 'NOT_CONNECTED'].includes(entry.code));
366
+ return {
367
+ ok: degraded.length === 0,
368
+ scope: 'adapter-provisioning',
369
+ hosts,
370
+ summary: {
371
+ total: hosts.length,
372
+ active: hosts.filter((entry) => entry.status === 'active').length,
373
+ installed: hosts.filter((entry) => entry.status === 'installed').length,
374
+ unsupported: hosts.filter((entry) => ['ADAPTER_UNSUPPORTED', 'ADAPTER_UNAVAILABLE', 'NOT_CONNECTED'].includes(entry.code)).length,
375
+ degraded: degraded.length,
376
+ },
377
+ };
378
+ }
379
+
380
+ /** Read-only `adapters.json` view. */
381
+ export function adapterStatus(options = {}) {
382
+ return publicAdapterState(options);
383
+ }
384
+
385
+ /** Roll back the host config (and a package staged during this run). */
386
+ export async function rollbackAdapter(hostId, options = {}) {
387
+ const home = options.home ?? homeDir();
388
+ const adapter = getAdapter(hostId);
389
+ if (!adapter || adapter.status === 'unsupported' || adapter.status === 'pending') {
390
+ return failure('ADAPTER_UNAVAILABLE', { hostId });
391
+ }
392
+ const result = await adapter.rollback({ ...options, home });
393
+ if (!result?.ok) {
394
+ await record(hostId, { lastError: result?.code ?? 'ROLLBACK_FAILED' }, home);
395
+ return failure(result?.code ?? 'ROLLBACK_FAILED', { hostId });
396
+ }
397
+ await record(hostId, { adapter: 'absent', lastError: null, verifiedAt: Date.now() }, home);
398
+ return {
399
+ ok: true,
400
+ hostId,
401
+ status: 'absent',
402
+ restoredFrom: result.restoredFrom === 'backup' ? 'backup' : null,
403
+ removed: result.removed === true,
404
+ };
405
+ }
@@ -0,0 +1,154 @@
1
+ // Adapter state (`<home>/adapters.json`, W1/W6).
2
+ //
3
+ // Rules:
4
+ // * 0600 file / 0700-ish parent (only when newly created);
5
+ // * atomic write (temp + rename);
6
+ // * corrupted file fails open (empty state, `corrupted: true`);
7
+ // * only whitelisted scalar fields are persisted — never tokens, message
8
+ // bodies, or raw error text.
9
+
10
+ import { readFileSync } from 'node:fs';
11
+ import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises';
12
+ import { dirname, join } from 'node:path';
13
+ import { homeDir } from './home.mjs';
14
+
15
+ export const ADAPTER_STATE_SCHEMA = 1;
16
+
17
+ const ADAPTER_VALUES = new Set(['absent', 'installed', 'active', 'degraded', 'unsupported']);
18
+ const ACTIVATION_VALUES = new Set(['reload', 'restart', 'next-start']);
19
+ const SOURCE_VALUES = new Set(['bundled', 'managed-dir', 'manual']);
20
+ const HOST_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
21
+ const ERROR_CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
22
+
23
+ export function adapterStatePath(home = homeDir()) {
24
+ return join(home, 'adapters.json');
25
+ }
26
+
27
+ export function emptyAdapterState() {
28
+ return { schema: ADAPTER_STATE_SCHEMA, updatedAt: 0, hosts: {} };
29
+ }
30
+
31
+ function stableErrorCode(value) {
32
+ if (typeof value === 'string' && ERROR_CODE_RE.test(value)) return value;
33
+ if (value !== null && typeof value === 'object' && typeof value.code === 'string' && ERROR_CODE_RE.test(value.code)) {
34
+ return value.code;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ function safeNumber(value) {
40
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : null;
41
+ }
42
+
43
+ function safePath(value) {
44
+ return typeof value === 'string' && value.length > 0 && value.length <= 1024 ? value : null;
45
+ }
46
+
47
+ /** Only whitelisted fields survive; unknown keys are dropped. */
48
+ export function sanitizeHostRecord(record) {
49
+ const input = record !== null && typeof record === 'object' && !Array.isArray(record) ? record : {};
50
+ const out = {};
51
+ if (typeof input.detected === 'boolean') out.detected = input.detected;
52
+ if (typeof input.connected === 'boolean') out.connected = input.connected;
53
+ if (ADAPTER_VALUES.has(input.adapter)) out.adapter = input.adapter;
54
+ if (typeof input.version === 'string' && input.version.length <= 64) out.version = input.version;
55
+ if (SOURCE_VALUES.has(input.source)) out.source = input.source;
56
+ const configPath = safePath(input.configPath);
57
+ if (configPath !== null) out.configPath = configPath;
58
+ if (ACTIVATION_VALUES.has(input.activation)) out.activation = input.activation;
59
+ out.lastError = stableErrorCode(input.lastError);
60
+ const verifiedAt = safeNumber(input.verifiedAt);
61
+ if (verifiedAt !== null) out.verifiedAt = verifiedAt;
62
+ const installedAt = safeNumber(input.installedAt);
63
+ if (installedAt !== null) out.installedAt = installedAt;
64
+ const lastIngestedAt = safeNumber(input.lastIngestedAt);
65
+ if (lastIngestedAt !== null) out.lastIngestedAt = lastIngestedAt;
66
+ return out;
67
+ }
68
+
69
+ function sanitizeState(parsed) {
70
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
71
+ const hosts = parsed.hosts;
72
+ if (hosts === null || typeof hosts !== 'object' || Array.isArray(hosts)) return null;
73
+ const outHosts = {};
74
+ for (const [hostId, record] of Object.entries(hosts)) {
75
+ if (!HOST_ID_RE.test(hostId)) continue;
76
+ outHosts[hostId] = sanitizeHostRecord(record);
77
+ }
78
+ return {
79
+ schema: ADAPTER_STATE_SCHEMA,
80
+ updatedAt: safeNumber(parsed.updatedAt) ?? 0,
81
+ hosts: outHosts,
82
+ };
83
+ }
84
+
85
+ /** Fail-open load: missing/corrupt/unknown shape → empty state, never throw. */
86
+ export function loadAdapterState(options = {}) {
87
+ const home = options.home ?? homeDir();
88
+ const file = adapterStatePath(home);
89
+ let text;
90
+ try {
91
+ text = readFileSync(file, 'utf-8');
92
+ } catch {
93
+ return { ...emptyAdapterState(), corrupted: false };
94
+ }
95
+ try {
96
+ const parsed = JSON.parse(text);
97
+ const state = sanitizeState(parsed);
98
+ if (state === null) return { ...emptyAdapterState(), corrupted: true };
99
+ return { ...state, corrupted: false };
100
+ } catch {
101
+ return { ...emptyAdapterState(), corrupted: true };
102
+ }
103
+ }
104
+
105
+ /** Atomic save with 0600 permissions. */
106
+ export async function saveAdapterState(state, options = {}) {
107
+ const home = options.home ?? homeDir();
108
+ const file = adapterStatePath(home);
109
+ const sanitized = sanitizeState({
110
+ schema: ADAPTER_STATE_SCHEMA,
111
+ updatedAt: Date.now(),
112
+ hosts: state?.hosts ?? {},
113
+ }) ?? { ...emptyAdapterState(), updatedAt: Date.now() };
114
+ const text = `${JSON.stringify(sanitized, null, 2)}\n`;
115
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
116
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
117
+ try {
118
+ await writeFile(tmp, text, { encoding: 'utf-8', mode: 0o600 });
119
+ try { await chmod(tmp, 0o600); } catch { /* Windows 无 POSIX mode */ }
120
+ await rename(tmp, file);
121
+ } catch (error) {
122
+ try { await rm(tmp, { force: true }); } catch { /* ignore */ }
123
+ throw error;
124
+ }
125
+ return sanitized;
126
+ }
127
+
128
+ /** Merge one host record; timestamps are owned by the caller for determinism. */
129
+ export async function updateAdapterHost(hostId, patch, options = {}) {
130
+ if (!HOST_ID_RE.test(hostId)) throw new Error('invalid hostId');
131
+ const home = options.home ?? homeDir();
132
+ const state = loadAdapterState({ home });
133
+ const previous = state.hosts[hostId] ?? {};
134
+ const next = sanitizeHostRecord({ ...previous, ...(patch ?? {}) });
135
+ state.hosts[hostId] = next;
136
+ await saveAdapterState(state, { home });
137
+ return next;
138
+ }
139
+
140
+ export function readAdapterHost(hostId, options = {}) {
141
+ const state = loadAdapterState(options);
142
+ return state.hosts[hostId] ?? null;
143
+ }
144
+
145
+ /** Read-only public view (safe to serialize to stdout). */
146
+ export function publicAdapterState(options = {}) {
147
+ const state = loadAdapterState(options);
148
+ return {
149
+ schema: state.schema,
150
+ updatedAt: state.updatedAt,
151
+ hosts: state.hosts,
152
+ ...(state.corrupted ? { corrupted: true } : {}),
153
+ };
154
+ }