@mebular/mcp 0.3.5 → 0.3.7

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,757 @@
1
+ // Adapter descriptor: OpenCode / OpenChamber
2
+ // (`@mebular/opencode-plugin` in the host's global `plugins` array).
3
+ //
4
+ // Boundaries (see packages/opencode-plugin/README.md):
5
+ // * only `~/.config/opencode/opencode.json` → `plugins` is merged;
6
+ // * never writes OpenChamber's `opencode.managed.json` or `run/instances/*`;
7
+ // * never downloads from npm: package comes from the App bundle, a managed
8
+ // directory, or (dev/tests) an injected path / this repository;
9
+ // * never kills a host process: activation is an injected reload/restart
10
+ // callback, otherwise `next-start`;
11
+ // * idempotent merge, byte-level `.bak-<ts>`, atomic write, rollback.
12
+
13
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
14
+ import { chmod, copyFile, cp, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
15
+ import { homedir } from 'node:os';
16
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { APP_VERSION } from '../version.mjs';
19
+
20
+ export const PACKAGE_NAME = '@mebular/opencode-plugin';
21
+ export const PLUGIN_OPTIONS = Object.freeze({ agentId: 'opencode', recall: true, ingest: true });
22
+
23
+ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
24
+ const MANAGED_DIR = 'adapters';
25
+ const MANAGED_NAME = 'opencode-plugin';
26
+
27
+ /** assistant 落面以用户主目录为基(与 clients.mjs 的 `assistantUserHome` 同语义)。 */
28
+ export function resolveUserHome(options = {}) {
29
+ if (typeof options.userHome === 'string' && options.userHome.length > 0) return options.userHome;
30
+ const env = options.env ?? process.env;
31
+ const fromEnv = env?.MEBULAR_USER_HOME;
32
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv;
33
+ return homedir();
34
+ }
35
+
36
+ function expandPath(value, userHome) {
37
+ if (typeof value !== 'string' || value.trim().length === 0) return null;
38
+ const text = value.trim();
39
+ if (text === '~') return userHome;
40
+ if (/^~[\\/]/.test(text)) return join(userHome, text.slice(2));
41
+ return resolve(text);
42
+ }
43
+
44
+ export function configPathFor(options = {}) {
45
+ const explicit = options.configPath ?? options.primaryPath;
46
+ const userHome = resolveUserHome(options);
47
+ if (typeof explicit === 'string' && explicit.length > 0) return expandPath(explicit, userHome);
48
+ return join(userHome, '.config', 'opencode', 'opencode.json');
49
+ }
50
+
51
+ /** 宿主是否可被视为存在(配置文件或配置目录)。纯只读,不 spawn CLI。 */
52
+ export function detect(options = {}) {
53
+ const configPath = configPathFor(options);
54
+ const fileHit = existsSync(configPath);
55
+ const dirHit = existsSync(dirname(configPath));
56
+ return {
57
+ detected: fileHit || dirHit,
58
+ configPath,
59
+ signals: [
60
+ { kind: 'config-file', source: 'opencode.json', hit: fileHit },
61
+ { kind: 'config-dir', source: dirname(configPath), hit: dirHit },
62
+ ],
63
+ };
64
+ }
65
+
66
+ /** 禁写路径:OpenChamber 私有 managed config 及其 run/instances 副本。 */
67
+ export function isForbiddenPath(file, options = {}) {
68
+ if (typeof file !== 'string' || file.length === 0) return true;
69
+ if (basename(file) === 'opencode.managed.json') return true;
70
+ const userHome = resolveUserHome(options);
71
+ const openChamberDir = typeof options.openChamberDataDir === 'string' && options.openChamberDataDir.length > 0
72
+ ? options.openChamberDataDir
73
+ : join(userHome, '.config', 'openchamber');
74
+ const roots = [
75
+ join(openChamberDir, 'run', 'instances'),
76
+ ...(Array.isArray(options.forbiddenRoots) ? options.forbiddenRoots : []),
77
+ ];
78
+ if (roots.some((root) => typeof root === 'string' && (file === root || file.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)))) return true;
79
+ return (Array.isArray(options.forbiddenPaths) ? options.forbiddenPaths : []).includes(file);
80
+ }
81
+
82
+ function readManifest(dir) {
83
+ try {
84
+ const parsed = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));
85
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ function packageCandidates(options = {}) {
92
+ const userHome = resolveUserHome(options);
93
+ const explicit = options.adapterPackagePath ?? options.packagePath;
94
+ if (typeof explicit === 'string' && explicit.length > 0) {
95
+ return [{ path: expandPath(explicit, userHome), source: 'manual', exclusive: true }];
96
+ }
97
+ const candidates = [];
98
+ const home = options.home ?? options.mebularHome;
99
+ if (typeof home === 'string' && home.length > 0) {
100
+ candidates.push({
101
+ path: join(home, MANAGED_DIR, MANAGED_NAME, options.expectedVersion ?? APP_VERSION),
102
+ source: 'managed-dir',
103
+ managed: true,
104
+ });
105
+ }
106
+ const resourcesPath = options.resourcesPath
107
+ ?? process.env.MEBULAR_RESOURCES_PATH
108
+ ?? process.resourcesPath;
109
+ if (typeof resourcesPath === 'string' && resourcesPath.length > 0) {
110
+ candidates.push({ path: join(resourcesPath, MANAGED_DIR, MANAGED_NAME), source: 'bundled' });
111
+ candidates.push({ path: join(resourcesPath, 'node_modules', '@mebular', 'opencode-plugin'), source: 'bundled' });
112
+ }
113
+ candidates.push({
114
+ path: join(options.repoRoot ?? REPO_ROOT, 'packages', 'opencode-plugin'),
115
+ source: 'manual',
116
+ });
117
+ return candidates;
118
+ }
119
+
120
+ async function stageBundledPackage(source, options, expectedVersion) {
121
+ const home = options.home ?? options.mebularHome;
122
+ if (typeof home !== 'string' || home.length === 0) return null;
123
+ const target = join(home, MANAGED_DIR, MANAGED_NAME, expectedVersion);
124
+ const existing = readManifest(target);
125
+ if (existing?.name === PACKAGE_NAME && existing.version === expectedVersion) {
126
+ return { path: target, changed: false, created: false };
127
+ }
128
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
129
+ try {
130
+ await mkdir(dirname(target), { recursive: true });
131
+ await rm(tmp, { recursive: true, force: true });
132
+ await cp(source, tmp, { recursive: true });
133
+ await rm(target, { recursive: true, force: true });
134
+ await rename(tmp, target);
135
+ const staged = readManifest(target);
136
+ if (staged?.name !== PACKAGE_NAME || staged.version !== expectedVersion) {
137
+ return null;
138
+ }
139
+ return { path: target, changed: true, created: true };
140
+ } catch {
141
+ try { await rm(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
142
+ return null;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * 确保 adapter 包可用。优先 bundle(可 staging 到 `<home>/adapters/...`),
148
+ * 其次 managed dir,最后本仓库 `packages/opencode-plugin`(测试可注入绝对路径)。
149
+ * 不访问网络;版本必须与 App lockstep。
150
+ */
151
+ export async function ensurePackage(options = {}) {
152
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
153
+ const candidates = packageCandidates({ ...options, expectedVersion });
154
+ let mismatch = null;
155
+ for (const candidate of candidates) {
156
+ if (!candidate?.path) continue;
157
+ const manifest = readManifest(candidate.path);
158
+ if (!manifest) {
159
+ if (candidate.exclusive) return { ok: false, code: 'ADAPTER_PACKAGE_NOT_FOUND' };
160
+ continue;
161
+ }
162
+ if (manifest.name !== PACKAGE_NAME || manifest.version !== expectedVersion) {
163
+ mismatch = { version: manifest.version ?? null, name: manifest.name ?? null };
164
+ if (candidate.exclusive) break;
165
+ continue;
166
+ }
167
+ if (candidate.source === 'bundled' && (options.dryRun === true || options.stagePackage === false)) {
168
+ if (options.dryRun === true) {
169
+ const home = options.home ?? options.mebularHome;
170
+ const plannedPath = typeof home === 'string' && home.length > 0
171
+ ? join(home, MANAGED_DIR, MANAGED_NAME, expectedVersion)
172
+ : resolve(candidate.path);
173
+ const existingManaged = readManifest(plannedPath);
174
+ const alreadyManaged = existingManaged?.name === PACKAGE_NAME && existingManaged.version === expectedVersion;
175
+ return {
176
+ ok: true,
177
+ path: plannedPath,
178
+ version: expectedVersion,
179
+ source: 'managed-dir',
180
+ changed: !alreadyManaged,
181
+ created: false,
182
+ planned: !alreadyManaged,
183
+ managedPath: plannedPath,
184
+ };
185
+ }
186
+ // Read-only resolution (verify/rollback): inspect the bundled package
187
+ // itself; never stage it.
188
+ return {
189
+ ok: true,
190
+ path: resolve(candidate.path),
191
+ version: expectedVersion,
192
+ source: 'bundled',
193
+ changed: false,
194
+ created: false,
195
+ planned: false,
196
+ managedPath: null,
197
+ };
198
+ }
199
+ if (candidate.source === 'bundled' && options.stagePackage !== false) {
200
+ const staged = await stageBundledPackage(candidate.path, options, expectedVersion);
201
+ if (staged) {
202
+ return {
203
+ ok: true,
204
+ path: staged.path,
205
+ version: expectedVersion,
206
+ source: 'managed-dir',
207
+ changed: staged.changed,
208
+ created: staged.created,
209
+ planned: false,
210
+ managedPath: staged.created ? staged.path : null,
211
+ };
212
+ }
213
+ }
214
+ return {
215
+ ok: true,
216
+ path: resolve(candidate.path),
217
+ version: expectedVersion,
218
+ source: candidate.source,
219
+ changed: false,
220
+ created: false,
221
+ managedPath: null,
222
+ };
223
+ }
224
+ if (mismatch) return { ok: false, code: 'ADAPTER_VERSION_MISMATCH', version: mismatch.version };
225
+ return { ok: false, code: 'ADAPTER_PACKAGE_NOT_FOUND' };
226
+ }
227
+
228
+ function isPlainObject(value) {
229
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
230
+ }
231
+
232
+ function samePath(value, target) {
233
+ if (typeof value !== 'string' || value.length === 0) return false;
234
+ // `isAbsolute` covers POSIX `/...` and Windows drive/UNC paths. The old
235
+ // prefix check rejected `C:\...`, which made every fresh Windows install
236
+ // fail verify even though the plugin entry had just been written.
237
+ if (!(isAbsolute(value) || value.startsWith('./') || value.startsWith('../') || /^~[\\/]/.test(value))) return false;
238
+ try {
239
+ return resolve(value) === resolve(target);
240
+ } catch {
241
+ return false;
242
+ }
243
+ }
244
+
245
+ function entryRefs(entry) {
246
+ if (typeof entry === 'string') return [entry];
247
+ if (!isPlainObject(entry)) return [];
248
+ return ['package', 'path', 'module', 'plugin']
249
+ .map((key) => entry[key])
250
+ .filter((value) => typeof value === 'string' && value.length > 0);
251
+ }
252
+
253
+ function stripFileRef(ref) {
254
+ if (typeof ref !== 'string') return '';
255
+ return ref.startsWith('file:') ? ref.slice('file:'.length) : ref;
256
+ }
257
+
258
+ function normalizeLocalPath(ref, options = {}) {
259
+ let text = stripFileRef(ref).trim();
260
+ if (text.length === 0) return null;
261
+ const userHome = typeof options.userHome === 'string' && options.userHome.length > 0
262
+ ? options.userHome
263
+ : resolveUserHome(options);
264
+ if (text === '~') text = userHome;
265
+ else if (/^~[\\/]/.test(text)) text = join(userHome, text.slice(2));
266
+ try {
267
+ return resolve(text);
268
+ } catch {
269
+ return null;
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Managed root for the *current* Mebular home. Without an explicit home the
275
+ * root is derived only when the resolved plugin path itself lives under
276
+ * `<...>/adapters/opencode-plugin/<version>`; a repository/dev path yields no
277
+ * managed root and therefore cannot claim unrelated user paths.
278
+ */
279
+ function managedPluginRoot(options = {}, pluginPath = null) {
280
+ const home = options.home ?? options.mebularHome;
281
+ if (typeof home === 'string' && home.length > 0) {
282
+ const resolvedHome = normalizeLocalPath(home, options) ?? resolve(home);
283
+ return resolve(join(resolvedHome, 'adapters', MANAGED_NAME));
284
+ }
285
+ const resolved = normalizeLocalPath(pluginPath, options);
286
+ if (!resolved) return null;
287
+ const suffix = `${sep}adapters${sep}${MANAGED_NAME}`;
288
+ const index = resolved.lastIndexOf(suffix);
289
+ if (index <= 0) return null;
290
+ return resolved.slice(0, index + suffix.length);
291
+ }
292
+
293
+ function managedContext(options = {}, pluginPath = null) {
294
+ return {
295
+ ...options,
296
+ managedRoot: options.managedRoot ?? managedPluginRoot(options, pluginPath),
297
+ };
298
+ }
299
+
300
+ function normalizeMergeOptions(options) {
301
+ if (typeof options === 'string' && options.length > 0) return { home: options };
302
+ return isPlainObject(options) ? options : {};
303
+ }
304
+
305
+ /**
306
+ * Only `<current home>/adapters/opencode-plugin/...` is Mebular-owned. A user
307
+ * plugin that happens to live in `.../projects/adapters/opencode-plugin/...`
308
+ * must never be rewritten, verified as ours or rolled back.
309
+ */
310
+ function isManagedMebularPath(ref, context = {}) {
311
+ if (typeof context.managedRoot !== 'string' || context.managedRoot.length === 0) return false;
312
+ const candidate = normalizeLocalPath(ref, context);
313
+ if (!candidate) return false;
314
+ const root = resolve(context.managedRoot);
315
+ const equals = process.platform === 'win32'
316
+ ? candidate.toLowerCase() === root.toLowerCase()
317
+ : candidate === root;
318
+ if (equals) return true;
319
+ return process.platform === 'win32'
320
+ ? candidate.toLowerCase().startsWith(`${root.toLowerCase()}${sep}`)
321
+ : candidate.startsWith(`${root}${sep}`);
322
+ }
323
+
324
+ function isMebularEntry(entry, pluginPath, options = {}) {
325
+ const context = managedContext(options, pluginPath);
326
+ return entryRefs(entry).some((ref) => {
327
+ if (ref === PACKAGE_NAME || ref.startsWith(`${PACKAGE_NAME}/`)) return true;
328
+ if (isManagedMebularPath(ref, context)) return true;
329
+ if (samePath(ref, pluginPath)) return true;
330
+ if (ref.startsWith('file:') && samePath(ref.slice('file:'.length), pluginPath)) return true;
331
+ return false;
332
+ });
333
+ }
334
+
335
+ function stableStringify(value) {
336
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
337
+ if (isPlainObject(value)) {
338
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
339
+ }
340
+ return JSON.stringify(value);
341
+ }
342
+
343
+ function canonicalEntry(existing, pluginPath) {
344
+ const base = isPlainObject(existing) ? { ...existing } : {};
345
+ const usePath = typeof base.path === 'string' && typeof base.package !== 'string';
346
+ delete base.package;
347
+ delete base.path;
348
+ delete base.module;
349
+ delete base.plugin;
350
+ delete base.options;
351
+ const options = {
352
+ ...(isPlainObject(existing?.options) ? existing.options : {}),
353
+ ...PLUGIN_OPTIONS,
354
+ };
355
+ const entry = { ...base };
356
+ if (usePath) entry.path = pluginPath;
357
+ else entry.package = pluginPath;
358
+ entry.options = options;
359
+ return entry;
360
+ }
361
+
362
+ /**
363
+ * 合并 `plugins` 数组:按 package/path 去重,保留用户其他插件。
364
+ * `options.home`(或第三个参数直接传 home)限定 managed path 身份;
365
+ * 不传时仅当 pluginPath 自身位于 managed root 下才推导。
366
+ */
367
+ export function mergePlugins(document, pluginPath, options = {}) {
368
+ if (!isPlainObject(document)) return { error: 'CONFIG_STRUCTURE_UNKNOWN' };
369
+ const plugins = document.plugins;
370
+ if (plugins !== undefined && !Array.isArray(plugins)) return { error: 'CONFIG_STRUCTURE_UNKNOWN' };
371
+ const list = Array.isArray(plugins) ? plugins : [];
372
+ const context = managedContext(normalizeMergeOptions(options), pluginPath);
373
+ const matches = [];
374
+ list.forEach((entry, index) => {
375
+ if (isMebularEntry(entry, pluginPath, context)) matches.push(index);
376
+ });
377
+ const entry = canonicalEntry(matches.length > 0 ? list[matches[0]] : null, pluginPath);
378
+ const nextPlugins = [];
379
+ list.forEach((item, index) => {
380
+ if (matches.includes(index)) {
381
+ if (index === matches[0]) nextPlugins.push(entry);
382
+ return;
383
+ }
384
+ nextPlugins.push(item);
385
+ });
386
+ if (matches.length === 0) nextPlugins.push(entry);
387
+ const changed = stableStringify(list) !== stableStringify(nextPlugins);
388
+ return {
389
+ changed,
390
+ plugins: nextPlugins,
391
+ entry,
392
+ duplicates: Math.max(0, matches.length - 1),
393
+ document: { ...document, plugins: nextPlugins },
394
+ };
395
+ }
396
+
397
+ function removeMebularPlugins(document, pluginPath, options = {}) {
398
+ if (!isPlainObject(document)) return { error: 'CONFIG_STRUCTURE_UNKNOWN' };
399
+ const plugins = document.plugins;
400
+ if (!Array.isArray(plugins)) return { error: 'CONFIG_STRUCTURE_UNKNOWN' };
401
+ const context = managedContext(normalizeMergeOptions(options), pluginPath);
402
+ const nextPlugins = plugins.filter((entry) => !isMebularEntry(entry, pluginPath, context));
403
+ return {
404
+ changed: nextPlugins.length !== plugins.length,
405
+ plugins: nextPlugins,
406
+ document: { ...document, plugins: nextPlugins },
407
+ };
408
+ }
409
+
410
+ function tsStamp() {
411
+ return new Date().toISOString().replace(/[:.]/g, '-');
412
+ }
413
+
414
+ function adapterBackupDir(file, options = {}) {
415
+ const home = options.home ?? options.mebularHome;
416
+ if (typeof home === 'string' && home.length > 0) return join(home, MANAGED_DIR, 'backups');
417
+ return dirname(file);
418
+ }
419
+
420
+ async function uniqueBackupPath(file, options = {}, existingBackup) {
421
+ if (typeof existingBackup === 'string' && existingBackup.length > 0) return existingBackup;
422
+ const dir = adapterBackupDir(file, options);
423
+ await mkdir(dir, { recursive: true, mode: 0o700 });
424
+ const base = join(dir, `${basename(file)}.bak-${tsStamp()}`);
425
+ if (!existsSync(base)) return base;
426
+ for (let index = 1; index < 100; index += 1) {
427
+ const candidate = `${base}-${index}`;
428
+ if (!existsSync(candidate)) return candidate;
429
+ }
430
+ return `${base}-${process.pid}`;
431
+ }
432
+
433
+ async function atomicWrite(file, text, mode = 0o600) {
434
+ await mkdir(dirname(file), { recursive: true });
435
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
436
+ try {
437
+ await writeFile(tmp, text, { encoding: 'utf-8', mode });
438
+ try { await chmod(tmp, mode); } catch { /* Windows 无 POSIX mode */ }
439
+ await rename(tmp, file);
440
+ } catch (error) {
441
+ try { await rm(tmp, { force: true }); } catch { /* ignore */ }
442
+ throw error;
443
+ }
444
+ }
445
+
446
+ function lineDiff(before, after) {
447
+ const a = String(before ?? '').split('\n');
448
+ const b = String(after ?? '').split('\n');
449
+ const out = [];
450
+ const max = Math.max(a.length, b.length);
451
+ for (let index = 0; index < max; index += 1) {
452
+ if (a[index] === b[index]) continue;
453
+ if (a[index] !== undefined) out.push(`- ${a[index]}`);
454
+ if (b[index] !== undefined) out.push(`+ ${b[index]}`);
455
+ }
456
+ return out.join('\n');
457
+ }
458
+
459
+ function normalizedPackage(options = {}) {
460
+ if (options.packageInfo?.ok === true) return options.packageInfo;
461
+ return null;
462
+ }
463
+
464
+ /**
465
+ * Replace only the top-level `plugins` value, keeping every other byte of the
466
+ * host config intact (reuse the tested JSON splice from clients.mjs).
467
+ */
468
+ async function formatPluginsWrite(existingText, plugins, fallbackDocument) {
469
+ if (typeof existingText !== 'string' || existingText.trim().length === 0) {
470
+ return `${JSON.stringify(fallbackDocument, null, 2)}\n`;
471
+ }
472
+ try {
473
+ const { mergeJsonEntry } = await import('../clients.mjs');
474
+ const merged = mergeJsonEntry(existingText, {
475
+ format: 'opencode-json',
476
+ entry: plugins,
477
+ keyPath: ['plugins'],
478
+ preserveFormatting: true,
479
+ });
480
+ if (typeof merged?.text === 'string' && merged.text.length > 0) return merged.text;
481
+ } catch {
482
+ // Fall back to full serialization if the splice is unavailable.
483
+ }
484
+ return `${JSON.stringify(fallbackDocument, null, 2)}\n`;
485
+ }
486
+
487
+ /**
488
+ * 配置步骤:只合并 `plugins`,写前备份、原子写、结构未知不写。
489
+ * `options.dryRun` 只返回 diff,不落盘。
490
+ */
491
+ export async function configure(options = {}) {
492
+ const configPath = configPathFor(options);
493
+ if (isForbiddenPath(configPath, options)) return { ok: false, code: 'FORBIDDEN_PATH' };
494
+ const packageInfo = normalizedPackage(options) ?? await ensurePackage({
495
+ ...options,
496
+ ...(options.dryRun === true ? { dryRun: true, stagePackage: false } : {}),
497
+ });
498
+ if (!packageInfo.ok) return packageInfo;
499
+ const pluginPath = packageInfo.path;
500
+
501
+ let existingText = null;
502
+ try {
503
+ existingText = await readFile(configPath, 'utf-8');
504
+ } catch (error) {
505
+ if (error?.code !== 'ENOENT') return { ok: false, code: 'CONFIG_UNREADABLE' };
506
+ }
507
+
508
+ let document = {};
509
+ if (existingText !== null && existingText.trim().length > 0) {
510
+ try {
511
+ document = JSON.parse(existingText);
512
+ } catch {
513
+ return { ok: false, code: 'CONFIG_UNPARSEABLE' };
514
+ }
515
+ if (!isPlainObject(document)) return { ok: false, code: 'CONFIG_STRUCTURE_UNKNOWN' };
516
+ }
517
+
518
+ const merged = mergePlugins(document, pluginPath, {
519
+ home: options.home ?? options.mebularHome,
520
+ userHome: resolveUserHome(options),
521
+ ...(typeof options.managedRoot === 'string' ? { managedRoot: options.managedRoot } : {}),
522
+ });
523
+ if (merged.error) return { ok: false, code: merged.error };
524
+ if (!merged.changed) {
525
+ return {
526
+ ok: true,
527
+ changed: false,
528
+ configPath,
529
+ backupPath: null,
530
+ entry: merged.entry,
531
+ preview: '',
532
+ };
533
+ }
534
+
535
+ const nextText = await formatPluginsWrite(existingText, merged.plugins, merged.document);
536
+ if (options.dryRun === true) {
537
+ return {
538
+ ok: true,
539
+ changed: true,
540
+ dryRun: true,
541
+ configPath,
542
+ backupPath: null,
543
+ entry: merged.entry,
544
+ preview: lineDiff(existingText ?? '', nextText),
545
+ };
546
+ }
547
+
548
+ let backupPath = null;
549
+ let originalMode = 0o600;
550
+ if (existingText !== null) {
551
+ backupPath = await uniqueBackupPath(configPath, options, options.backupPath);
552
+ await copyFile(configPath, backupPath);
553
+ try {
554
+ originalMode = (await stat(configPath)).mode & 0o777;
555
+ } catch {
556
+ originalMode = 0o600;
557
+ }
558
+ }
559
+ try {
560
+ await atomicWrite(configPath, nextText, originalMode);
561
+ } catch {
562
+ if (backupPath) {
563
+ try { await copyFile(backupPath, configPath); } catch { /* ignore */ }
564
+ }
565
+ return { ok: false, code: 'WRITE_FAILED', rolledBack: Boolean(backupPath) };
566
+ }
567
+ return {
568
+ ok: true,
569
+ changed: true,
570
+ configPath,
571
+ backupPath,
572
+ entry: merged.entry,
573
+ preview: lineDiff(existingText ?? '', nextText),
574
+ };
575
+ }
576
+
577
+ /** 激活:只调用注入的安全回调;没有能力即 next-start,绝不杀进程。 */
578
+ export async function activate(options = {}) {
579
+ if (options.canRestartHost === true && typeof options.reloadHost === 'function') {
580
+ try {
581
+ await options.reloadHost();
582
+ return { ok: true, activation: 'reload' };
583
+ } catch {
584
+ return { ok: false, code: 'ACTIVATION_FAILED', activation: 'next-start' };
585
+ }
586
+ }
587
+ if (options.canRestartHost === true && typeof options.restartHost === 'function') {
588
+ try {
589
+ await options.restartHost();
590
+ return { ok: true, activation: 'restart' };
591
+ } catch {
592
+ return { ok: false, code: 'ACTIVATION_FAILED', activation: 'next-start' };
593
+ }
594
+ }
595
+ return { ok: true, activation: 'next-start' };
596
+ }
597
+
598
+ function entryPluginPath(entry, fallback) {
599
+ const refs = entryRefs(entry);
600
+ if (refs.length === 0) return fallback ?? null;
601
+ const ref = refs[0];
602
+ if (ref === PACKAGE_NAME) return fallback ?? null;
603
+ if (ref.startsWith('file:')) return ref.slice('file:'.length);
604
+ return ref;
605
+ }
606
+
607
+ /** 验证:配置回读 + 条目唯一 + 包存在 + 版本 lockstep。ingest 健康留给 repair。 */
608
+ export async function verify(options = {}) {
609
+ const configPath = configPathFor(options);
610
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
611
+ const checks = [];
612
+ if (!existsSync(configPath)) {
613
+ return { ok: false, code: 'VERIFY_CONFIG_MISSING', checks: [{ name: 'config-exists', ok: false }], ingested: null };
614
+ }
615
+ checks.push({ name: 'config-exists', ok: true });
616
+ let document;
617
+ try {
618
+ document = JSON.parse(await readFile(configPath, 'utf-8'));
619
+ } catch {
620
+ return { ok: false, code: 'VERIFY_CONFIG_UNPARSEABLE', checks: [...checks, { name: 'config-readable', ok: false }], ingested: null };
621
+ }
622
+ if (!isPlainObject(document) || !Array.isArray(document.plugins)) {
623
+ return { ok: false, code: 'VERIFY_STRUCTURE_UNKNOWN', checks: [...checks, { name: 'plugins-array', ok: false }], ingested: null };
624
+ }
625
+ checks.push({ name: 'plugins-array', ok: true });
626
+ const packageInfo = normalizedPackage(options) ?? await ensurePackage({ ...options, stagePackage: false });
627
+ const pluginPath = packageInfo.ok ? packageInfo.path : null;
628
+ // Count every Mebular entry (package name, current path, all managed
629
+ // `<home>/adapters/opencode-plugin/<version>` paths for the *current* home),
630
+ // not just the path this run resolved: an upgrade that leaves the old version
631
+ // behind must fail, while unrelated user paths stay untouched.
632
+ const verifyContext = managedContext({
633
+ home: options.home ?? options.mebularHome,
634
+ userHome: resolveUserHome(options),
635
+ ...(typeof options.managedRoot === 'string' ? { managedRoot: options.managedRoot } : {}),
636
+ }, pluginPath);
637
+ const matches = document.plugins.filter((entry) => isMebularEntry(entry, pluginPath, verifyContext));
638
+ const unique = matches.length === 1;
639
+ checks.push({ name: 'entry-unique', ok: unique, count: matches.length });
640
+ if (!unique) {
641
+ return {
642
+ ok: false,
643
+ code: matches.length > 1 ? 'VERIFY_ENTRY_DUPLICATE' : 'VERIFY_ENTRY_MISSING',
644
+ checks,
645
+ ingested: null,
646
+ };
647
+ }
648
+ const entry = matches[0];
649
+ const optionsOk = isPlainObject(entry) && isPlainObject(entry.options)
650
+ && entry.options.agentId === PLUGIN_OPTIONS.agentId
651
+ && entry.options.recall === true
652
+ && entry.options.ingest === true;
653
+ checks.push({ name: 'options', ok: optionsOk });
654
+
655
+ const referenced = entryPluginPath(entry, pluginPath);
656
+ const manifest = referenced ? readManifest(referenced) : null;
657
+ const packageOk = manifest?.name === PACKAGE_NAME;
658
+ checks.push({ name: 'package-exists', ok: packageOk });
659
+ const versionOk = manifest?.version === expectedVersion;
660
+ checks.push({ name: 'version-lockstep', ok: versionOk });
661
+
662
+ const ok = checks.every((check) => check.ok);
663
+ return {
664
+ ok,
665
+ code: ok ? null : packageOk ? 'VERIFY_OPTIONS_MISMATCH' : 'VERIFY_PACKAGE_MISSING',
666
+ checks,
667
+ version: manifest?.version ?? null,
668
+ ingested: null,
669
+ health: 'deferred',
670
+ };
671
+ }
672
+
673
+ async function latestBackup(file, options = {}) {
674
+ try {
675
+ const dir = adapterBackupDir(file, options);
676
+ const prefix = `${basename(file)}.bak-`;
677
+ const candidates = readdirSync(dir).filter((name) => name.startsWith(prefix)).sort().reverse();
678
+ return candidates.length > 0 ? join(dir, candidates[0]) : null;
679
+ } catch {
680
+ return null;
681
+ }
682
+ }
683
+
684
+ /** 回滚:显式备份优先;否则最新备份;再否则移除 Mebular 自己的 plugin 条目。 */
685
+ export async function rollback(options = {}) {
686
+ const home = options.home ?? options.mebularHome;
687
+ const packageInfo = normalizedPackage(options);
688
+ if (options.removePackage === true && packageInfo?.created === true && typeof packageInfo.managedPath === 'string' && typeof home === 'string') {
689
+ const managedRoot = join(home, MANAGED_DIR);
690
+ if (packageInfo.managedPath === managedRoot || packageInfo.managedPath.startsWith(`${managedRoot}${sep}`)) {
691
+ try { await rm(packageInfo.managedPath, { recursive: true, force: true }); } catch { /* ignore */ }
692
+ }
693
+ }
694
+
695
+ const configPath = configPathFor(options);
696
+ if (!existsSync(configPath)) return { ok: true, removed: false, restoredFrom: null };
697
+
698
+ const target = options.backupPath ?? await latestBackup(configPath, options);
699
+ if (target && existsSync(target)) {
700
+ const safety = await uniqueBackupPath(configPath, options);
701
+ await copyFile(configPath, safety);
702
+ try {
703
+ await atomicWrite(configPath, await readFile(target, 'utf-8'));
704
+ } catch {
705
+ return { ok: false, code: 'ROLLBACK_FAILED' };
706
+ }
707
+ return { ok: true, removed: false, restoredFrom: 'backup', backupPath: safety };
708
+ }
709
+
710
+ let document;
711
+ let existingText;
712
+ try {
713
+ existingText = await readFile(configPath, 'utf-8');
714
+ document = JSON.parse(existingText);
715
+ } catch {
716
+ return { ok: false, code: 'CONFIG_UNPARSEABLE' };
717
+ }
718
+ const packageInfoForPath = normalizedPackage(options) ?? await ensurePackage({ ...options, stagePackage: false });
719
+ const pluginPath = packageInfoForPath.ok ? packageInfoForPath.path : null;
720
+ const removed = removeMebularPlugins(document, pluginPath, {
721
+ home: options.home ?? options.mebularHome,
722
+ userHome: resolveUserHome(options),
723
+ ...(typeof options.managedRoot === 'string' ? { managedRoot: options.managedRoot } : {}),
724
+ });
725
+ if (removed.error) return { ok: false, code: removed.error };
726
+ if (!removed.changed) return { ok: true, removed: false, restoredFrom: null };
727
+
728
+ const safety = await uniqueBackupPath(configPath, options);
729
+ await copyFile(configPath, safety);
730
+ try {
731
+ await atomicWrite(configPath, await formatPluginsWrite(existingText, removed.plugins, removed.document));
732
+ } catch {
733
+ return { ok: false, code: 'ROLLBACK_FAILED' };
734
+ }
735
+ return { ok: true, removed: true, restoredFrom: null, backupPath: safety };
736
+ }
737
+
738
+ /**
739
+ * descriptor 工厂。opencode/openchamber 共享同一份 global 配置,但状态按 hostId 分开。
740
+ */
741
+ export function createOpenCodeAdapter({ hostId = 'opencode', displayName = 'OpenCode' } = {}) {
742
+ return {
743
+ hostId,
744
+ displayName,
745
+ status: 'supported',
746
+ package: { name: PACKAGE_NAME, version: APP_VERSION, source: 'bundled' },
747
+ detect,
748
+ ensurePackage,
749
+ configure,
750
+ activate,
751
+ verify,
752
+ rollback,
753
+ };
754
+ }
755
+
756
+ export const openCodeAdapter = createOpenCodeAdapter({ hostId: 'opencode', displayName: 'OpenCode' });
757
+ export const openChamberAdapter = createOpenCodeAdapter({ hostId: 'openchamber', displayName: 'OpenChamber' });