@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,830 @@
1
+ // Adapter descriptor: DeepSeek Harness (DSH)
2
+ // (`@mebular/dsh-plugin` added to a DSH profile).
3
+ //
4
+ // Boundaries (see docs/integrations/DSH.md):
5
+ // * the official CLI owns the profile: `dsh plugin --profile <profile> add
6
+ // <absolute-path>`; this module never hand-writes DSH YAML;
7
+ // * readback prefers `dsh --profile <profile> --dump-config`, then profile
8
+ // files (`package.json` dependency / `cordis*.yml` entry);
9
+ // * never touches DSH databases, session storage or transcripts;
10
+ // * never downloads from npm: the package comes from the App bundle, a managed
11
+ // directory, or (dev/tests) an injected path / this repository;
12
+ // * profile resolution is explicit > `DSH_PROFILE` > canonical `web` (> a
13
+ // single profile); `web` is the documented profile of this web-host plugin,
14
+ // not a guess among arbitrary profiles;
15
+ // * never kills a host process: activation is an injected reload/restart
16
+ // callback, otherwise `next-start`;
17
+ // * idempotent configure, profile backup before the CLI runs, rollback via the
18
+ // official `remove` command or the profile backup.
19
+
20
+ import { existsSync, readFileSync, readdirSync, statSync, accessSync, constants as fsConstants } from 'node:fs';
21
+ import { copyFile, cp, mkdir, rename, rm } from 'node:fs/promises';
22
+ import { execFile } from 'node:child_process';
23
+ import { homedir } from 'node:os';
24
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+ import { APP_VERSION } from '../version.mjs';
27
+
28
+ export const PACKAGE_NAME = '@mebular/dsh-plugin';
29
+ export const PLUGIN_ID = 'mebular';
30
+
31
+ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
32
+ const MANAGED_DIR = 'adapters';
33
+ const MANAGED_NAME = 'dsh-plugin';
34
+ const PROFILE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
35
+ const PROFILE_FILES = ['package.json', 'cordis.yml', 'cordis.patch.yml', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'];
36
+ const DEPENDENCY_SECTIONS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
37
+ const FORBIDDEN_SEGMENTS = new Set(['sessions', 'session', 'session-storage', 'storage', 'db', 'database']);
38
+ const FORBIDDEN_EXTENSIONS = /\.(?:db|sqlite|sqlite3|jsonl|log)$/i;
39
+
40
+ /** assistant 落面以用户主目录为基(与 clients.mjs 的 `assistantUserHome` 同语义)。 */
41
+ export function resolveUserHome(options = {}) {
42
+ if (typeof options.userHome === 'string' && options.userHome.length > 0) return options.userHome;
43
+ const env = options.env ?? process.env;
44
+ const fromEnv = env?.MEBULAR_USER_HOME;
45
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv;
46
+ return homedir();
47
+ }
48
+
49
+ function expandPath(value, userHome) {
50
+ if (typeof value !== 'string' || value.trim().length === 0) return null;
51
+ const text = value.trim();
52
+ if (text === '~') return userHome;
53
+ if (/^~[\\/]/.test(text)) return join(userHome, text.slice(2));
54
+ return resolve(text);
55
+ }
56
+
57
+ /** `<userHome>/.dsh`, or an explicit `dshHome` / `DSH_HOME` (tests inject one). */
58
+ export function resolveDshHome(options = {}, userHome = resolveUserHome(options)) {
59
+ const explicit = options.dshHome;
60
+ if (typeof explicit === 'string' && explicit.length > 0) return expandPath(explicit, userHome);
61
+ const env = options.env ?? process.env;
62
+ const fromEnv = env?.DSH_HOME;
63
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return expandPath(fromEnv, userHome);
64
+ return join(userHome, '.dsh');
65
+ }
66
+
67
+ function isExecutable(file) {
68
+ try {
69
+ if (!statSync(file).isFile()) return false;
70
+ accessSync(file, fsConstants.X_OK);
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ /** Locate the official CLI without running it. PATH is read from the injected env only. */
78
+ export function findDshCli(options = {}) {
79
+ const env = options.env ?? process.env;
80
+ const explicit = options.dshCliPath ?? options.cliPath ?? env?.DSH_CLI;
81
+ if (typeof explicit === 'string' && explicit.length > 0) {
82
+ const expanded = expandPath(explicit, resolveUserHome(options));
83
+ return expanded && isExecutable(expanded) ? expanded : null;
84
+ }
85
+ const pathValue = typeof env?.PATH === 'string' ? env.PATH : '';
86
+ const names = process.platform === 'win32' ? ['dsh.cmd', 'dsh.exe', 'dsh'] : ['dsh'];
87
+ for (const dir of pathValue.split(delimiter)) {
88
+ if (typeof dir !== 'string' || dir.length === 0) continue;
89
+ for (const name of names) {
90
+ const candidate = join(dir, name);
91
+ if (isExecutable(candidate)) return candidate;
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+
97
+ function listProfiles(dshHome) {
98
+ const dir = join(dshHome, 'profiles');
99
+ try {
100
+ return readdirSync(dir, { withFileTypes: true })
101
+ .filter((entry) => entry.isDirectory() && PROFILE_ID_RE.test(entry.name))
102
+ .map((entry) => entry.name)
103
+ .sort();
104
+ } catch {
105
+ return [];
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Resolve the target profile:
111
+ * 1. explicit `options.profile`;
112
+ * 2. `DSH_PROFILE`;
113
+ * 3. `web` when present — the canonical profile of Mebular's DSH *web*
114
+ * plugin (`@mebular/dsh-plugin`), not an arbitrary guess;
115
+ * 4. the only profile under `<dshHome>/profiles`;
116
+ * 5. otherwise fail closed (`DSH_PROFILE_UNKNOWN`).
117
+ */
118
+ export function resolveProfile(options = {}, profiles = listProfiles(resolveDshHome(options))) {
119
+ const env = options.env ?? process.env;
120
+ const explicit = typeof options.profile === 'string' && options.profile.trim().length > 0
121
+ ? options.profile.trim()
122
+ : typeof env?.DSH_PROFILE === 'string' && env.DSH_PROFILE.trim().length > 0
123
+ ? env.DSH_PROFILE.trim()
124
+ : null;
125
+ if (explicit) {
126
+ if (!PROFILE_ID_RE.test(explicit)) return { id: null, source: 'invalid', profiles };
127
+ return { id: explicit, source: options.profile ? 'option' : 'env', profiles };
128
+ }
129
+ // Mebular's DSH plugin is a web-host plugin; `web` is its documented
130
+ // canonical profile. Prefer it over an ambiguous multi-profile set.
131
+ if (profiles.includes('web')) return { id: 'web', source: 'canonical-web', profiles };
132
+ if (profiles.length === 1) return { id: profiles[0], source: 'single', profiles };
133
+ if (profiles.length === 0) return { id: null, source: 'none', profiles };
134
+ return { id: null, source: 'ambiguous', profiles };
135
+ }
136
+
137
+ function profilePaths(profileDir) {
138
+ const patchPath = join(profileDir, 'cordis.patch.yml');
139
+ const cordisPath = join(profileDir, 'cordis.yml');
140
+ const configPath = existsSync(patchPath) ? patchPath : existsSync(cordisPath) ? cordisPath : patchPath;
141
+ return {
142
+ profileDir,
143
+ configPath,
144
+ packagePath: join(profileDir, 'package.json'),
145
+ patchPath,
146
+ cordisPath,
147
+ installedPackagePath: join(profileDir, 'node_modules', '@mebular', 'dsh-plugin'),
148
+ };
149
+ }
150
+
151
+ function readManifest(dir) {
152
+ try {
153
+ const parsed = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));
154
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
159
+
160
+ function readJsonFile(file) {
161
+ try {
162
+ const parsed = JSON.parse(readFileSync(file, 'utf-8'));
163
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
164
+ } catch {
165
+ return null;
166
+ }
167
+ }
168
+
169
+ function readTextFile(file) {
170
+ try {
171
+ return readFileSync(file, 'utf-8');
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+
177
+ function isProfileStructureKnown(profileDir) {
178
+ if (!existsSync(profileDir)) return false;
179
+ const packagePath = join(profileDir, 'package.json');
180
+ if (existsSync(packagePath) && readJsonFile(packagePath) === null) return false;
181
+ return PROFILE_FILES.some((name) => existsSync(join(profileDir, name)));
182
+ }
183
+
184
+ function specVersion(spec, options = {}) {
185
+ if (typeof spec !== 'string' || spec.trim().length === 0) return null;
186
+ let text = spec.trim();
187
+ if (text.startsWith('npm:')) text = text.slice('npm:'.length);
188
+ if (text.startsWith('workspace:')) text = text.slice('workspace:'.length);
189
+ if (text.startsWith('file:')) {
190
+ const raw = text.slice('file:'.length);
191
+ const file = isAbsolute(raw) || raw === '~' || /^~[\\/]/.test(raw)
192
+ ? expandPath(raw, resolveUserHome(options))
193
+ : resolve(options.profileDir ?? '.', raw);
194
+ const manifest = file ? readManifest(file) : null;
195
+ return typeof manifest?.version === 'string' ? manifest.version : null;
196
+ }
197
+ const match = text.match(/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/);
198
+ return match ? match[1] : null;
199
+ }
200
+
201
+ function specPath(spec) {
202
+ if (typeof spec !== 'string') return null;
203
+ const text = spec.trim();
204
+ if (text.startsWith('file:')) return text.slice('file:'.length);
205
+ return null;
206
+ }
207
+
208
+ function readMebularDependency(packagePath) {
209
+ const manifest = readJsonFile(packagePath);
210
+ if (!manifest) return null;
211
+ for (const section of DEPENDENCY_SECTIONS) {
212
+ const value = manifest[section]?.[PACKAGE_NAME];
213
+ if (typeof value === 'string' && value.length > 0) return { section, spec: value };
214
+ }
215
+ return null;
216
+ }
217
+
218
+ /** Read-only profile readback: dependency, plugin entry, installed manifest. */
219
+ export function readProfileInstall(profileDir, options = {}) {
220
+ const paths = profilePaths(profileDir);
221
+ const readOptions = { ...options, profileDir };
222
+ const result = {
223
+ present: false,
224
+ version: null,
225
+ dependencySpec: null,
226
+ entryPath: null,
227
+ source: null,
228
+ };
229
+ const dependency = readMebularDependency(paths.packagePath);
230
+ if (dependency) {
231
+ result.present = true;
232
+ result.source = 'dependency';
233
+ result.dependencySpec = dependency.spec;
234
+ const rawPath = specPath(dependency.spec);
235
+ result.entryPath = rawPath
236
+ ? (isAbsolute(rawPath) || rawPath === '~' || /^~[\\/]/.test(rawPath)
237
+ ? expandPath(rawPath, resolveUserHome(options))
238
+ : resolve(profileDir, rawPath))
239
+ : null;
240
+ result.version = specVersion(dependency.spec, readOptions);
241
+ }
242
+ const patch = readTextFile(paths.patchPath) ?? readTextFile(paths.cordisPath);
243
+ if (typeof patch === 'string' && patch.includes(PACKAGE_NAME)) {
244
+ result.present = true;
245
+ if (result.source === null) result.source = 'profile-entry';
246
+ }
247
+ const installed = readManifest(paths.installedPackagePath);
248
+ if (installed?.name === PACKAGE_NAME) {
249
+ result.present = true;
250
+ result.source = result.source ?? 'profile-entry';
251
+ if (typeof installed.version === 'string') {
252
+ result.version = installed.version;
253
+ result.entryPath = result.entryPath ?? paths.installedPackagePath;
254
+ }
255
+ }
256
+ return result;
257
+ }
258
+
259
+ function existingMatches(existing, expectedPath, expectedVersion) {
260
+ if (!existing?.present) return false;
261
+ if (existing.entryPath) {
262
+ try {
263
+ if (resolve(existing.entryPath) === resolve(expectedPath) && existing.version === expectedVersion) return true;
264
+ } catch {
265
+ // fall through to the version-only check
266
+ }
267
+ }
268
+ return existing.version === expectedVersion;
269
+ }
270
+
271
+ function packageCandidates(options = {}) {
272
+ const userHome = resolveUserHome(options);
273
+ const explicit = options.adapterPackagePath ?? options.packagePath;
274
+ if (typeof explicit === 'string' && explicit.length > 0) {
275
+ return [{ path: expandPath(explicit, userHome), source: 'manual', exclusive: true }];
276
+ }
277
+ const candidates = [];
278
+ const home = options.home ?? options.mebularHome;
279
+ if (typeof home === 'string' && home.length > 0) {
280
+ candidates.push({
281
+ path: join(home, MANAGED_DIR, MANAGED_NAME, options.expectedVersion ?? APP_VERSION),
282
+ source: 'managed-dir',
283
+ managed: true,
284
+ });
285
+ }
286
+ const resourcesPath = options.resourcesPath
287
+ ?? (options.env ?? process.env).MEBULAR_RESOURCES_PATH
288
+ ?? process.resourcesPath;
289
+ if (typeof resourcesPath === 'string' && resourcesPath.length > 0) {
290
+ candidates.push({ path: join(resourcesPath, MANAGED_DIR, MANAGED_NAME), source: 'bundled' });
291
+ candidates.push({ path: join(resourcesPath, 'node_modules', '@mebular', 'dsh-plugin'), source: 'bundled' });
292
+ }
293
+ candidates.push({
294
+ path: join(options.repoRoot ?? REPO_ROOT, 'packages', 'dsh-plugin'),
295
+ source: 'manual',
296
+ });
297
+ return candidates;
298
+ }
299
+
300
+ async function stageBundledPackage(source, options, expectedVersion) {
301
+ const home = options.home ?? options.mebularHome;
302
+ if (typeof home !== 'string' || home.length === 0) return null;
303
+ const target = join(home, MANAGED_DIR, MANAGED_NAME, expectedVersion);
304
+ const existing = readManifest(target);
305
+ if (existing?.name === PACKAGE_NAME && existing.version === expectedVersion) {
306
+ return { path: target, changed: false, created: false };
307
+ }
308
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
309
+ try {
310
+ await mkdir(dirname(target), { recursive: true });
311
+ await rm(tmp, { recursive: true, force: true });
312
+ await cp(source, tmp, { recursive: true });
313
+ await rm(target, { recursive: true, force: true });
314
+ await rename(tmp, target);
315
+ const staged = readManifest(target);
316
+ if (staged?.name !== PACKAGE_NAME || staged.version !== expectedVersion) return null;
317
+ return { path: target, changed: true, created: true };
318
+ } catch {
319
+ try { await rm(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
320
+ return null;
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Ensure the adapter package is available. Bundled candidates may be staged to
326
+ * `<home>/adapters/dsh-plugin/<version>`; managed dir and repository/dev paths
327
+ * are used directly. No network access; the version must match the App.
328
+ */
329
+ export async function ensurePackage(options = {}) {
330
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
331
+ const candidates = packageCandidates({ ...options, expectedVersion });
332
+ let mismatch = null;
333
+ for (const candidate of candidates) {
334
+ if (!candidate?.path) continue;
335
+ const manifest = readManifest(candidate.path);
336
+ if (!manifest) {
337
+ if (candidate.exclusive) return { ok: false, code: 'ADAPTER_PACKAGE_NOT_FOUND' };
338
+ continue;
339
+ }
340
+ if (manifest.name !== PACKAGE_NAME || manifest.version !== expectedVersion) {
341
+ mismatch = { version: manifest.version ?? null, name: manifest.name ?? null };
342
+ if (candidate.exclusive) break;
343
+ continue;
344
+ }
345
+ if (candidate.source === 'bundled' && (options.dryRun === true || options.stagePackage === false)) {
346
+ if (options.dryRun === true) {
347
+ const home = options.home ?? options.mebularHome;
348
+ const plannedPath = typeof home === 'string' && home.length > 0
349
+ ? join(home, MANAGED_DIR, MANAGED_NAME, expectedVersion)
350
+ : resolve(candidate.path);
351
+ const existingManaged = readManifest(plannedPath);
352
+ const alreadyManaged = existingManaged?.name === PACKAGE_NAME && existingManaged.version === expectedVersion;
353
+ return {
354
+ ok: true,
355
+ path: plannedPath,
356
+ version: expectedVersion,
357
+ source: 'managed-dir',
358
+ changed: !alreadyManaged,
359
+ created: false,
360
+ planned: !alreadyManaged,
361
+ managedPath: plannedPath,
362
+ };
363
+ }
364
+ return {
365
+ ok: true,
366
+ path: resolve(candidate.path),
367
+ version: expectedVersion,
368
+ source: 'bundled',
369
+ changed: false,
370
+ created: false,
371
+ planned: false,
372
+ managedPath: null,
373
+ };
374
+ }
375
+ if (candidate.source === 'bundled' && options.stagePackage !== false) {
376
+ const staged = await stageBundledPackage(candidate.path, options, expectedVersion);
377
+ if (staged) {
378
+ return {
379
+ ok: true,
380
+ path: staged.path,
381
+ version: expectedVersion,
382
+ source: 'managed-dir',
383
+ changed: staged.changed,
384
+ created: staged.created,
385
+ planned: false,
386
+ managedPath: staged.created ? staged.path : null,
387
+ };
388
+ }
389
+ }
390
+ return {
391
+ ok: true,
392
+ path: resolve(candidate.path),
393
+ version: expectedVersion,
394
+ source: candidate.source,
395
+ changed: false,
396
+ created: false,
397
+ managedPath: null,
398
+ };
399
+ }
400
+ if (mismatch) return { ok: false, code: 'ADAPTER_VERSION_MISMATCH', version: mismatch.version };
401
+ return { ok: false, code: 'ADAPTER_PACKAGE_NOT_FOUND' };
402
+ }
403
+
404
+ /** DSH databases / session storage must never be written by provisioning. */
405
+ export function isForbiddenPath(file, options = {}) {
406
+ if (typeof file !== 'string' || file.length === 0) return true;
407
+ const absolute = resolve(file);
408
+ const segments = absolute.split(sep).map((part) => part.toLowerCase());
409
+ if (segments.some((part) => FORBIDDEN_SEGMENTS.has(part))) return true;
410
+ if (FORBIDDEN_EXTENSIONS.test(basename(absolute))) return true;
411
+ if (typeof options.forbiddenPath === 'string' && resolve(options.forbiddenPath) === absolute) return true;
412
+ const roots = [
413
+ ...(Array.isArray(options.forbiddenRoots) ? options.forbiddenRoots : []),
414
+ ];
415
+ if (roots.some((root) => typeof root === 'string' && (absolute === resolve(root) || absolute.startsWith(`${resolve(root)}${sep}`)))) return true;
416
+ return (Array.isArray(options.forbiddenPaths) ? options.forbiddenPaths : []).some((entry) => (
417
+ typeof entry === 'string' && resolve(entry) === absolute
418
+ ));
419
+ }
420
+
421
+ function tsStamp() {
422
+ return new Date().toISOString().replace(/[:.]/g, '-');
423
+ }
424
+
425
+ function backupRoot(options = {}) {
426
+ const home = options.home ?? options.mebularHome;
427
+ if (typeof home !== 'string' || home.length === 0) return null;
428
+ return join(home, MANAGED_DIR, 'backups');
429
+ }
430
+
431
+ async function createProfileBackup(profileDir, options = {}) {
432
+ const root = backupRoot(options);
433
+ if (!root) return null;
434
+ const target = join(root, `dsh-profile-${tsStamp()}-${process.pid}`);
435
+ let copied = 0;
436
+ try {
437
+ for (const name of PROFILE_FILES) {
438
+ const source = join(profileDir, name);
439
+ if (!existsSync(source)) continue;
440
+ await mkdir(target, { recursive: true, mode: 0o700 });
441
+ await copyFile(source, join(target, name));
442
+ copied += 1;
443
+ }
444
+ return copied > 0 ? target : null;
445
+ } catch {
446
+ try { await rm(target, { recursive: true, force: true }); } catch { /* ignore */ }
447
+ return null;
448
+ }
449
+ }
450
+
451
+ async function latestBackup(options = {}) {
452
+ const root = backupRoot(options);
453
+ if (!root) return null;
454
+ try {
455
+ const names = readdirSync(root)
456
+ .filter((name) => name.startsWith('dsh-profile-'))
457
+ .sort()
458
+ .reverse();
459
+ return names.length > 0 ? join(root, names[0]) : null;
460
+ } catch {
461
+ return null;
462
+ }
463
+ }
464
+
465
+ async function restoreProfileBackup(backupDir, profileDir) {
466
+ if (typeof backupDir !== 'string' || !existsSync(backupDir)) return false;
467
+ let names = [];
468
+ try {
469
+ names = readdirSync(backupDir);
470
+ } catch {
471
+ return false;
472
+ }
473
+ let restored = false;
474
+ for (const name of names) {
475
+ if (!PROFILE_FILES.includes(name)) continue;
476
+ try {
477
+ await copyFile(join(backupDir, name), join(profileDir, name));
478
+ restored = true;
479
+ } catch {
480
+ // Keep restoring the other files; the caller records a stable failure.
481
+ }
482
+ }
483
+ return restored;
484
+ }
485
+
486
+ function cliEnv(options, dshHome) {
487
+ return {
488
+ ...process.env,
489
+ ...(options.env ?? {}),
490
+ ...(typeof dshHome === 'string' && dshHome.length > 0 ? { DSH_HOME: dshHome } : {}),
491
+ };
492
+ }
493
+
494
+ function runCli(cliPath, args, options, dshHome) {
495
+ return new Promise((resolvePromise) => {
496
+ try {
497
+ execFile(
498
+ cliPath,
499
+ args,
500
+ {
501
+ timeout: options.cliTimeoutMs ?? 15_000,
502
+ maxBuffer: 1024 * 1024,
503
+ windowsHide: true,
504
+ ...(typeof options.cwd === 'string' ? { cwd: options.cwd } : {}),
505
+ env: cliEnv(options, dshHome),
506
+ },
507
+ (error, stdout, stderr) => {
508
+ resolvePromise({
509
+ ok: !error,
510
+ code: typeof error?.code === 'number' ? error.code : error ? 1 : 0,
511
+ stdout: typeof stdout === 'string' ? stdout.slice(0, 64 * 1024) : '',
512
+ stderr: typeof stderr === 'string' ? stderr.slice(0, 64 * 1024) : '',
513
+ timedOut: error?.killed === true,
514
+ });
515
+ },
516
+ );
517
+ } catch {
518
+ resolvePromise({ ok: false, code: 1, stdout: '', stderr: '', timedOut: false });
519
+ }
520
+ });
521
+ }
522
+
523
+ async function readOfficialConfig(cliPath, profile, options, dshHome) {
524
+ const result = await runCli(cliPath, ['--profile', profile, '--dump-config'], options, dshHome);
525
+ if (!result.ok) return { ok: false, present: false };
526
+ return { ok: true, present: result.stdout.includes(PACKAGE_NAME) };
527
+ }
528
+
529
+ function normalizeProfileTarget(options = {}) {
530
+ const userHome = resolveUserHome(options);
531
+ const dshHome = resolveDshHome(options, userHome);
532
+ const explicitDir = typeof options.profileDir === 'string' && options.profileDir.length > 0
533
+ ? expandPath(options.profileDir, userHome)
534
+ : null;
535
+ const resolved = resolveProfile(options, listProfiles(dshHome));
536
+ const profile = resolved.id ?? (explicitDir ? basename(explicitDir) : null);
537
+ const profileDir = explicitDir ?? (resolved.id ? join(dshHome, 'profiles', resolved.id) : null);
538
+ return { userHome, dshHome, resolved, profile, profileDir };
539
+ }
540
+
541
+ /**
542
+ * Detect DSH: CLI presence, `<dshHome>/profiles`, and a resolvable profile.
543
+ * Pure read-only; never spawns the CLI and never guesses a port.
544
+ */
545
+ export async function detect(options = {}) {
546
+ const { dshHome, resolved, profile, profileDir } = normalizeProfileTarget(options);
547
+ const cliPath = findDshCli(options);
548
+ const paths = profileDir ? profilePaths(profileDir) : null;
549
+ const profilesDir = join(dshHome, 'profiles');
550
+ const profileHit = profileDir ? existsSync(profileDir) : false;
551
+ const configHit = paths ? existsSync(paths.configPath) : false;
552
+ return {
553
+ detected: Boolean(cliPath) || existsSync(dshHome) || existsSync(profilesDir),
554
+ configPath: paths?.configPath ?? null,
555
+ dshHome,
556
+ cliPath,
557
+ profile: profile ?? null,
558
+ profileDir: profileDir ?? null,
559
+ profileSource: resolved.source,
560
+ profileUnknown: profile === null,
561
+ signals: [
562
+ { kind: 'cli', source: 'dsh', hit: Boolean(cliPath) },
563
+ { kind: 'profiles-dir', source: profilesDir, hit: existsSync(profilesDir) },
564
+ { kind: 'profile-dir', source: profileDir ?? '', hit: profileHit },
565
+ { kind: 'profile-config', source: paths?.configPath ?? '', hit: configHit },
566
+ ],
567
+ };
568
+ }
569
+
570
+ function lineDiff(before, after) {
571
+ const a = String(before ?? '').split('\n');
572
+ const b = String(after ?? '').split('\n');
573
+ const out = [];
574
+ const max = Math.max(a.length, b.length);
575
+ for (let index = 0; index < max; index += 1) {
576
+ if (a[index] === b[index]) continue;
577
+ if (a[index] !== undefined) out.push(`- ${a[index]}`);
578
+ if (b[index] !== undefined) out.push(`+ ${b[index]}`);
579
+ }
580
+ return out.join('\n');
581
+ }
582
+
583
+ function normalizedPackage(options = {}) {
584
+ return options.packageInfo?.ok === true ? options.packageInfo : null;
585
+ }
586
+
587
+ /**
588
+ * Configure the profile through the official CLI. `dryRun` only reports the
589
+ * planned command and never spawns the CLI or writes a backup.
590
+ */
591
+ export async function configure(options = {}) {
592
+ const { dshHome, resolved, profile, profileDir } = normalizeProfileTarget(options);
593
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
594
+ if (!profile || !profileDir) return { ok: false, code: 'DSH_PROFILE_UNKNOWN', reason: resolved.source };
595
+ if (isForbiddenPath(profileDir, options)) return { ok: false, code: 'FORBIDDEN_PATH' };
596
+ const paths = profilePaths(profileDir);
597
+ if (isForbiddenPath(paths.configPath, options)) return { ok: false, code: 'FORBIDDEN_PATH' };
598
+ if (typeof options.configPath === 'string' && isForbiddenPath(options.configPath, options)) {
599
+ return { ok: false, code: 'FORBIDDEN_PATH' };
600
+ }
601
+ if (!isProfileStructureKnown(profileDir)) return { ok: false, code: 'DSH_PROFILE_UNKNOWN', reason: 'structure' };
602
+
603
+ const packageInfo = normalizedPackage(options) ?? await ensurePackage({
604
+ ...options,
605
+ expectedVersion,
606
+ ...(options.dryRun === true ? { dryRun: true, stagePackage: false } : {}),
607
+ });
608
+ if (!packageInfo.ok) return packageInfo;
609
+
610
+ const existing = readProfileInstall(profileDir, options);
611
+ if (existingMatches(existing, packageInfo.path, expectedVersion)) {
612
+ return {
613
+ ok: true,
614
+ changed: false,
615
+ configPath: paths.configPath,
616
+ backupPath: null,
617
+ preview: '',
618
+ command: null,
619
+ existing,
620
+ };
621
+ }
622
+
623
+ const command = ['plugin', '--profile', profile, 'add', packageInfo.path];
624
+ if (options.dryRun === true) {
625
+ return {
626
+ ok: true,
627
+ changed: true,
628
+ dryRun: true,
629
+ configPath: paths.configPath,
630
+ backupPath: null,
631
+ preview: `+ dsh ${command.join(' ')}`,
632
+ command: ['dsh', ...command],
633
+ existing,
634
+ };
635
+ }
636
+
637
+ const cliPath = findDshCli(options);
638
+ if (!cliPath) return { ok: false, code: 'DSH_CLI_NOT_FOUND' };
639
+
640
+ const backupPath = await createProfileBackup(profileDir, options);
641
+ const result = await runCli(cliPath, command, options, dshHome);
642
+ if (!result.ok) {
643
+ if (backupPath) await restoreProfileBackup(backupPath, profileDir);
644
+ return {
645
+ ok: false,
646
+ code: result.timedOut ? 'DSH_PLUGIN_ADD_TIMEOUT' : 'DSH_PLUGIN_ADD_FAILED',
647
+ configPath: paths.configPath,
648
+ backupPath,
649
+ };
650
+ }
651
+
652
+ const official = await readOfficialConfig(cliPath, profile, options, dshHome);
653
+ const after = readProfileInstall(profileDir, options);
654
+ const verified = (official.ok && official.present) || after.present;
655
+ if (!verified) {
656
+ if (backupPath) await restoreProfileBackup(backupPath, profileDir);
657
+ return {
658
+ ok: false,
659
+ code: 'DSH_CONFIGURE_UNVERIFIED',
660
+ configPath: paths.configPath,
661
+ backupPath,
662
+ };
663
+ }
664
+
665
+ return {
666
+ ok: true,
667
+ changed: true,
668
+ configPath: paths.configPath,
669
+ backupPath,
670
+ preview: lineDiff('', `dsh ${command.join(' ')}`),
671
+ command: ['dsh', ...command],
672
+ existing: after,
673
+ };
674
+ }
675
+
676
+ /** Activation: only injected safe callbacks; otherwise next-start. Never signals a process. */
677
+ export async function activate(options = {}) {
678
+ if (options.canRestartHost === true && typeof options.reloadHost === 'function') {
679
+ try {
680
+ await options.reloadHost();
681
+ return { ok: true, activation: 'reload' };
682
+ } catch {
683
+ return { ok: false, code: 'ACTIVATION_FAILED', activation: 'next-start' };
684
+ }
685
+ }
686
+ if (options.canRestartHost === true && typeof options.restartHost === 'function') {
687
+ try {
688
+ await options.restartHost();
689
+ return { ok: true, activation: 'restart' };
690
+ } catch {
691
+ return { ok: false, code: 'ACTIVATION_FAILED', activation: 'next-start' };
692
+ }
693
+ }
694
+ return { ok: true, activation: 'next-start' };
695
+ }
696
+
697
+ function referencedManifest(existing, packageInfo) {
698
+ if (existing?.entryPath) {
699
+ const manifest = readManifest(existing.entryPath);
700
+ if (manifest?.name === PACKAGE_NAME) return manifest;
701
+ }
702
+ if (packageInfo?.path) {
703
+ const manifest = readManifest(packageInfo.path);
704
+ if (manifest?.name === PACKAGE_NAME) return manifest;
705
+ }
706
+ return null;
707
+ }
708
+
709
+ /**
710
+ * Verify readback: official dump-config when the CLI exists, else profile
711
+ * files; package presence and version lockstep. Ingest health is left to repair.
712
+ */
713
+ export async function verify(options = {}) {
714
+ const { dshHome, resolved, profile, profileDir } = normalizeProfileTarget(options);
715
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
716
+ const checks = [];
717
+ if (!profile || !profileDir) {
718
+ return { ok: false, code: 'DSH_PROFILE_UNKNOWN', checks: [{ name: 'profile-known', ok: false }], ingested: null, reason: resolved.source };
719
+ }
720
+ checks.push({ name: 'profile-known', ok: true });
721
+ if (isForbiddenPath(profileDir, options)) {
722
+ return { ok: false, code: 'FORBIDDEN_PATH', checks: [...checks, { name: 'path-allowed', ok: false }], ingested: null };
723
+ }
724
+ if (!isProfileStructureKnown(profileDir)) {
725
+ return { ok: false, code: 'VERIFY_STRUCTURE_UNKNOWN', checks: [...checks, { name: 'profile-structure', ok: false }], ingested: null };
726
+ }
727
+ checks.push({ name: 'profile-structure', ok: true });
728
+
729
+ const existing = readProfileInstall(profileDir, options);
730
+ const cliPath = findDshCli(options);
731
+ let official = null;
732
+ if (cliPath) {
733
+ official = await readOfficialConfig(cliPath, profile, options, dshHome);
734
+ }
735
+ const entryOk = official?.ok ? official.present : existing.present;
736
+ checks.push({ name: 'entry-present', ok: entryOk, source: official?.ok ? 'cli' : 'profile' });
737
+ if (!entryOk) {
738
+ return { ok: false, code: 'VERIFY_ENTRY_MISSING', checks, version: existing.version ?? null, ingested: null };
739
+ }
740
+
741
+ const packageInfo = normalizedPackage(options) ?? await ensurePackage({ ...options, expectedVersion, stagePackage: false });
742
+ const manifest = referencedManifest(existing, packageInfo);
743
+ const packageOk = manifest?.name === PACKAGE_NAME;
744
+ checks.push({ name: 'package-exists', ok: packageOk });
745
+
746
+ const installedVersion = existing.version
747
+ ?? (existing.dependencySpec ? specVersion(existing.dependencySpec, options) : null)
748
+ ?? (entryOk ? packageInfo.version : null);
749
+ const versionOk = installedVersion === expectedVersion;
750
+ checks.push({ name: 'version-lockstep', ok: versionOk });
751
+
752
+ const ok = checks.every((check) => check.ok);
753
+ return {
754
+ ok,
755
+ code: ok ? null : packageOk ? 'VERIFY_VERSION_MISMATCH' : 'VERIFY_PACKAGE_MISSING',
756
+ checks,
757
+ version: installedVersion ?? manifest?.version ?? null,
758
+ ingested: null,
759
+ health: 'deferred',
760
+ };
761
+ }
762
+
763
+ /**
764
+ * Rollback: official `dsh plugin remove` when available, otherwise restore the
765
+ * profile backup. Databases and session storage are never touched.
766
+ */
767
+ export async function rollback(options = {}) {
768
+ const { dshHome, profile, profileDir } = normalizeProfileTarget(options);
769
+ if (!profile || !profileDir) return { ok: false, code: 'DSH_PROFILE_UNKNOWN' };
770
+ if (isForbiddenPath(profileDir, options)) return { ok: false, code: 'FORBIDDEN_PATH' };
771
+
772
+ let removed = false;
773
+ let restoredFrom = null;
774
+ let usedBackup = null;
775
+ const cliPath = findDshCli(options);
776
+ let cliSucceeded = false;
777
+ if (cliPath) {
778
+ const result = await runCli(cliPath, ['plugin', '--profile', profile, 'remove', PACKAGE_NAME], options, dshHome);
779
+ if (result.ok) {
780
+ cliSucceeded = true;
781
+ removed = true;
782
+ }
783
+ }
784
+
785
+ if (!cliSucceeded) {
786
+ const backupPath = options.backupPath ?? await latestBackup(options);
787
+ if (backupPath && existsSync(backupPath)) {
788
+ const restored = await restoreProfileBackup(backupPath, profileDir);
789
+ if (!restored) return { ok: false, code: 'DSH_ROLLBACK_FAILED' };
790
+ restoredFrom = 'backup';
791
+ usedBackup = backupPath;
792
+ } else if (!readProfileInstall(profileDir, options).present) {
793
+ // Nothing to remove and nothing to restore: already clean.
794
+ return { ok: true, removed: false, restoredFrom: null };
795
+ } else {
796
+ return { ok: false, code: 'DSH_ROLLBACK_UNAVAILABLE' };
797
+ }
798
+ }
799
+
800
+ const home = options.home ?? options.mebularHome;
801
+ const packageInfo = normalizedPackage(options);
802
+ if (options.removePackage === true
803
+ && packageInfo?.created === true
804
+ && typeof packageInfo.managedPath === 'string'
805
+ && typeof home === 'string') {
806
+ const managedRoot = join(home, MANAGED_DIR);
807
+ if (packageInfo.managedPath === managedRoot || packageInfo.managedPath.startsWith(`${managedRoot}${sep}`)) {
808
+ try { await rm(packageInfo.managedPath, { recursive: true, force: true }); } catch { /* ignore */ }
809
+ }
810
+ }
811
+
812
+ return { ok: true, removed, restoredFrom, backupPath: usedBackup };
813
+ }
814
+
815
+ export function createDshAdapter({ hostId = 'dsh', displayName = 'DeepSeek Harness (DSH)' } = {}) {
816
+ return {
817
+ hostId,
818
+ displayName,
819
+ status: 'supported',
820
+ package: { name: PACKAGE_NAME, version: APP_VERSION, source: 'bundled' },
821
+ detect,
822
+ ensurePackage,
823
+ configure,
824
+ activate,
825
+ verify,
826
+ rollback,
827
+ };
828
+ }
829
+
830
+ export const dshAdapter = createDshAdapter();