dsh-mcp-manager-plus 0.4.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.
package/lib/patch.js ADDED
@@ -0,0 +1,525 @@
1
+ /**
2
+ * dsh-mcp-manager-plus — profile patch-layer reader/writer.
3
+ *
4
+ * A profile composes its plugin tree from bundle patch layers plus the user's
5
+ * own layer at `$DSH_HOME/profiles/<profile>/cordis.patch.yml`. That file is a
6
+ * top-level YAML array of loader patch entries; a user-added MCP server is one
7
+ * of them:
8
+ *
9
+ * - insert:
10
+ * - id: mcp-github
11
+ * name: '@deepseek-ai/dsh-mcp-client'
12
+ * config: { serverName: github, transport: stdio, ... }
13
+ *
14
+ * Turning a row off is a sibling entry (`- id: mcp-github` + `disabled: true`),
15
+ * which is how the patch dialect expresses "off" for a row any layer inserted.
16
+ * Both shapes therefore live in one file, and this module owns reading and
17
+ * rewriting them without disturbing anything else in it.
18
+ *
19
+ * Two properties matter more than anything here:
20
+ *
21
+ * 1. **Never brick the boot.** Every candidate document is re-parsed as a
22
+ * top-level array before it is written; a document that does not parse is
23
+ * refused rather than committed.
24
+ * 2. **Never touch what it does not own.** The file is hand-written by users.
25
+ * Comments, unrelated rows and unknown keys survive a rewrite verbatim;
26
+ * only the exact block being changed is re-emitted.
27
+ *
28
+ * @module dsh-mcp-manager-plus/patch
29
+ */
30
+
31
+ import { readFileSync } from 'node:fs';
32
+
33
+ /** The MCP bridge package a managed row mounts. */
34
+ export const MCP_CLIENT_PACKAGE = '@deepseek-ai/dsh-mcp-client';
35
+
36
+ /** Row-id prefix this plugin mints for rows it creates. */
37
+ export const ROW_ID_PREFIX = 'mcp-';
38
+
39
+ /**
40
+ * Split a document into top-level items, preserving every line that is not
41
+ * part of an item (the preamble comment block, and any comments or blank runs
42
+ * that trail an item).
43
+ *
44
+ * An item starts at a line that opens a top-level YAML sequence entry
45
+ * (`- …`) or a top-level flow collection (`[]`, `[ ]`). Everything from that
46
+ * line up to the line before the next start belongs to the item, so comments
47
+ * written above a row stay with that row when it is rewritten.
48
+ *
49
+ * A bare empty-list placeholder is marked, not treated as an ordinary item:
50
+ * the shipped profile template ships one, and keeping it alongside a real row
51
+ * would put TWO top-level documents in one file (invalid YAML).
52
+ *
53
+ * @param text - raw file text.
54
+ * @returns `{ eol, preamble, items, placeholder }`.
55
+ */
56
+ export function splitTopLevel(text) {
57
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
58
+ const lines = text.split(/\r?\n/u);
59
+ // A trailing newline produces one empty final element; keep it out of the
60
+ // model and re-add it on join so round-trips are byte-stable.
61
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
62
+
63
+ const starts = [];
64
+ let placeholderIndex = -1;
65
+ for (let index = 0; index < lines.length; index += 1) {
66
+ const line = lines[index];
67
+ if (/^-(?:[ \t]|$)/u.test(line)) starts.push(index);
68
+ else if (/^\[[^\]]*\][ \t]*(?:#.*)?$/u.test(line)) placeholderIndex = index;
69
+ }
70
+ // The placeholder is never kept as content: it is either the sole document
71
+ // body (re-emitted by joinTopLevel) or replaced by the first real row.
72
+ if (starts.length === 0) {
73
+ const preamble = placeholderIndex === -1 ? lines : lines.filter((_, i) => i !== placeholderIndex);
74
+ return { eol, preamble, items: [], placeholder: placeholderIndex !== -1 };
75
+ }
76
+
77
+ const items = [];
78
+ for (let index = 0; index < starts.length; index += 1) {
79
+ const from = starts[index];
80
+ const to = index + 1 < starts.length ? starts[index + 1] : lines.length;
81
+ items.push({ lines: lines.slice(from, to) });
82
+ }
83
+ const firstStart = starts[0];
84
+ const preambleSource = firstStart > 0 ? lines.slice(0, firstStart) : [];
85
+ return {
86
+ eol,
87
+ preamble: preambleSource.filter((_, i) => i !== placeholderIndex),
88
+ items,
89
+ placeholder: placeholderIndex !== -1,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Reassemble a document from its parts. An empty-list placeholder is emitted
95
+ * only when the document has no items, because a comment-only file is not a
96
+ * top-level array and the loader refuses to boot such a profile.
97
+ * @param parts - `{ eol, preamble, items }`.
98
+ * @returns file text ending in a newline.
99
+ */
100
+ export function joinTopLevel(parts) {
101
+ const { eol, preamble, items } = parts;
102
+ const chunks = [];
103
+ if (preamble.length > 0) chunks.push(preamble.join(eol));
104
+ let wroteItem = false;
105
+ for (const item of items) {
106
+ const body = item.lines.join(eol);
107
+ if (body.trim() === '') continue;
108
+ chunks.push(body);
109
+ wroteItem = true;
110
+ }
111
+ if (!wroteItem) chunks.push('[]');
112
+ let text = chunks.join(eol);
113
+ if (text.trim() === '') return `[]${eol}`;
114
+ if (!text.endsWith(eol)) text += eol;
115
+ return text;
116
+ }
117
+
118
+ /** Text of one item. */
119
+ export function itemText(item, eol) {
120
+ return item.lines.join(eol);
121
+ }
122
+
123
+ /**
124
+ * Parse one item as a single-element loader patch list.
125
+ * @param text - the item's text.
126
+ * @param yaml - the `js-yaml` module.
127
+ * @param schema - the entry-list schema (with the `!!js` tag).
128
+ * @returns the patch row, or null when the item is not one.
129
+ */
130
+ export function parseItem(text, yaml, schema) {
131
+ const trimmed = text.trim();
132
+ if (trimmed === '' || /^\[[^\]]*\]$/u.test(trimmed)) return null;
133
+ try {
134
+ const parsed = yaml.load(trimmed, { schema });
135
+ if (!Array.isArray(parsed) || parsed.length !== 1) return null;
136
+ const row = parsed[0];
137
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) return null;
138
+ return row;
139
+ } catch {
140
+ return null;
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Validate a candidate document before it is written.
146
+ * @param text - candidate content.
147
+ * @param yaml - the `js-yaml` module.
148
+ * @param schema - the entry-list schema.
149
+ * @returns an error message, or null when the document is a valid patch list.
150
+ */
151
+ export function validateDocument(text, yaml, schema) {
152
+ const stripped = text.replace(/^[ \t]*#.*$/gmu, '').trim();
153
+ if (stripped === '' || stripped === '[]' || stripped === '[ ]') return null;
154
+ try {
155
+ const parsed = yaml.load(text, { schema });
156
+ if (parsed === null || parsed === undefined) return null;
157
+ if (!Array.isArray(parsed)) return '补丁层必须是顶层 YAML 数组';
158
+ for (const row of parsed) {
159
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) {
160
+ return '补丁层的每个条目都必须是 YAML 映射';
161
+ }
162
+ }
163
+ return null;
164
+ } catch (error) {
165
+ return `补丁层解析失败:${String(error?.reason ?? error?.message ?? error)}`;
166
+ }
167
+ }
168
+
169
+ // ── YAML emission ───────────────────────────────────────────────────────────
170
+
171
+ /**
172
+ * Whether a value is a `!!js` expression node, as the entry-list dialect's
173
+ * schema constructs it. Such a value is a scalar on the wire, not a nested
174
+ * mapping, so it must be handed back to the file with its tag intact — writing
175
+ * it as an ordinary mapping would turn a dynamic expression into a literal
176
+ * object and silently change what the row configures.
177
+ * @param value - any config value.
178
+ * @returns true for an expression node.
179
+ */
180
+ export function isJsExprValue(value) {
181
+ return (
182
+ value !== null &&
183
+ typeof value === 'object' &&
184
+ !Array.isArray(value) &&
185
+ typeof value.__jsExpr === 'string' &&
186
+ Object.keys(value).length === 1
187
+ );
188
+ }
189
+
190
+ /**
191
+ * YAML scalar for a value — JSON strings are valid YAML double-quoted scalars.
192
+ * A `!!js` expression node round-trips as its tagged scalar; an expression
193
+ * containing a newline becomes a block scalar, which is the only form the
194
+ * dialect can carry one in.
195
+ */
196
+ export function scalar(value) {
197
+ if (isJsExprValue(value)) {
198
+ const expr = value.__jsExpr;
199
+ if (expr.includes('\n')) return `!!js |-\n${expr}`;
200
+ return `!!js ${expr}`;
201
+ }
202
+ if (typeof value === 'string') return JSON.stringify(value);
203
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
204
+ if (value === null || value === undefined) return 'null';
205
+ return JSON.stringify(value);
206
+ }
207
+
208
+ /**
209
+ * Emit a mapping's entries at a fixed indent. Sequences of scalars use the
210
+ * compact `- value` form; sequences of mappings and nested mappings open a
211
+ * block, which is what a hand-written MCP row looks like.
212
+ * @param object - the mapping.
213
+ * @param indent - indentation of the keys.
214
+ * @param lines - accumulator.
215
+ */
216
+ export function emitMapping(object, indent, lines) {
217
+ const pad = ' '.repeat(indent);
218
+ for (const [key, value] of Object.entries(object)) {
219
+ if (value !== null && typeof value === 'object' && !isJsExprValue(value)) {
220
+ if (Array.isArray(value)) {
221
+ if (value.length === 0) {
222
+ lines.push(`${pad}${key}: []`);
223
+ continue;
224
+ }
225
+ lines.push(`${pad}${key}:`);
226
+ for (const item of value) {
227
+ if (item !== null && typeof item === 'object' && !isJsExprValue(item)) {
228
+ lines.push(`${pad} -`);
229
+ emitMapping(item, indent + 4, lines);
230
+ } else {
231
+ lines.push(`${pad} - ${scalar(item)}`);
232
+ }
233
+ }
234
+ continue;
235
+ }
236
+ if (Object.keys(value).length === 0) {
237
+ lines.push(`${pad}${key}: {}`);
238
+ continue;
239
+ }
240
+ lines.push(`${pad}${key}:`);
241
+ emitMapping(value, indent + 2, lines);
242
+ continue;
243
+ }
244
+ lines.push(`${pad}${key}: ${scalar(value)}`);
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Emit one `- insert:` block holding the given rows.
250
+ * @param rows - `{ id, name, config, extra }` entries.
251
+ * @returns YAML text (no trailing newline).
252
+ */
253
+ export function emitInsertBlock(rows) {
254
+ const lines = ['- insert:'];
255
+ for (const row of rows) {
256
+ lines.push(` - id: ${row.id}`);
257
+ lines.push(` name: ${JSON.stringify(row.name)}`);
258
+ const config = row.config !== null && typeof row.config === 'object' ? row.config : {};
259
+ if (Object.keys(config).length === 0) {
260
+ lines.push(' config: {}');
261
+ } else {
262
+ lines.push(' config:');
263
+ emitMapping(config, 8, lines);
264
+ }
265
+ for (const [key, value] of Object.entries(row.extra ?? {})) {
266
+ if (value !== null && typeof value === 'object' && !isJsExprValue(value)) {
267
+ lines.push(` ${key}:`);
268
+ emitMapping(value, 8, lines);
269
+ } else {
270
+ lines.push(` ${key}: ${scalar(value)}`);
271
+ }
272
+ }
273
+ }
274
+ return lines.join('\n');
275
+ }
276
+
277
+ /** Emit a `- id: X` + `disabled: bool` override block. */
278
+ export function emitDisabledBlock(rowId, disabled) {
279
+ return `- id: ${rowId}\n disabled: ${disabled ? 'true' : 'false'}`;
280
+ }
281
+
282
+ // ── document model ──────────────────────────────────────────────────────────
283
+
284
+ /**
285
+ * Build the management view of a patch document: the MCP rows it inserts, the
286
+ * per-row overrides it carries, and its structural problems.
287
+ * @param text - raw file text.
288
+ * @param yaml - the `js-yaml` module.
289
+ * @param schema - the entry-list schema.
290
+ * @returns `{ parts, rows, overrides, issues }`.
291
+ */
292
+ export function readDocument(text, yaml, schema) {
293
+ const parts = splitTopLevel(text);
294
+ const rows = [];
295
+ const overrides = { disabled: new Map(), config: new Map(), items: new Map() };
296
+ const issues = [];
297
+
298
+ for (const item of parts.items) {
299
+ const body = itemText(item, parts.eol);
300
+ const stripped = body.replace(/^[ \t]*#.*$/gmu, '').trim();
301
+ if (stripped === '' || stripped === '[]' || stripped === '[ ]') continue;
302
+ const row = parseItem(body, yaml, schema);
303
+ if (row === null) {
304
+ issues.push('补丁层中有本插件无法解析的条目,已原样保留并跳过管理');
305
+ continue;
306
+ }
307
+ if (Array.isArray(row.insert)) {
308
+ for (const inserted of row.insert) {
309
+ if (inserted === null || typeof inserted !== 'object' || Array.isArray(inserted)) continue;
310
+ if (inserted.name !== MCP_CLIENT_PACKAGE) continue;
311
+ const config = inserted.config;
312
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) continue;
313
+ rows.push({
314
+ id: typeof inserted.id === 'string' ? inserted.id : '',
315
+ name: MCP_CLIENT_PACKAGE,
316
+ config,
317
+ extra: extraKeysOf(inserted),
318
+ item,
319
+ });
320
+ }
321
+ continue;
322
+ }
323
+ if (typeof row.id !== 'string' || row.id === '') continue;
324
+ const existing = overrides.items.get(row.id) ?? [];
325
+ existing.push(item);
326
+ overrides.items.set(row.id, existing);
327
+ if (row.disabled !== undefined) overrides.disabled.set(row.id, row.disabled === true);
328
+ if (row.config !== undefined && row.config !== null && typeof row.config === 'object') {
329
+ overrides.config.set(row.id, row.config);
330
+ }
331
+ }
332
+
333
+ return { parts, rows, overrides, issues };
334
+ }
335
+
336
+ /** Row keys other than the ones this plugin models, preserved on rewrite. */
337
+ export function extraKeysOf(row) {
338
+ const extra = {};
339
+ for (const [key, value] of Object.entries(row)) {
340
+ if (key === 'id' || key === 'name' || key === 'config') continue;
341
+ extra[key] = value;
342
+ }
343
+ return extra;
344
+ }
345
+
346
+ /**
347
+ * Replace the item containing `row` with a freshly emitted block holding the
348
+ * given rows.
349
+ * @param parts - document parts.
350
+ * @param row - the row whose item is rewritten.
351
+ * @param rows - the rows the rewritten block holds.
352
+ * @returns new document text.
353
+ */
354
+ export function rewriteInsertBlock(parts, row, rows) {
355
+ const replacement = rows.length === 0 ? null : emitInsertBlock(rows);
356
+ const items = [];
357
+ let replaced = false;
358
+ for (const item of parts.items) {
359
+ if (item === row.item) {
360
+ replaced = true;
361
+ if (replacement !== null) items.push({ lines: replacement.split('\n') });
362
+ continue;
363
+ }
364
+ items.push(item);
365
+ }
366
+ if (!replaced) throw new Error('未找到目标行所在的块');
367
+ return joinTopLevel({ ...parts, items });
368
+ }
369
+
370
+ /**
371
+ * The rows sharing one `- insert:` block with `row`, as `{ id, name, config }`
372
+ * entries. Used so an edit or a removal can never drop a sibling row that
373
+ * happens to live in the same block.
374
+ * @param parts - document parts.
375
+ * @param row - a row read from that block.
376
+ * @param yaml - the `js-yaml` module.
377
+ * @param schema - the entry-list schema.
378
+ * @returns the block's rows, in their original order.
379
+ */
380
+ export function blockRows(parts, row, yaml, schema) {
381
+ const parsed = parseItem(itemText(row.item, parts.eol), yaml, schema);
382
+ const inserted = Array.isArray(parsed?.insert) ? parsed.insert : [];
383
+ return inserted
384
+ .filter((entry) => entry !== null && typeof entry === 'object' && !Array.isArray(entry))
385
+ .map((entry) => ({
386
+ id: typeof entry.id === 'string' ? entry.id : '',
387
+ name: typeof entry.name === 'string' ? entry.name : MCP_CLIENT_PACKAGE,
388
+ config: entry.config !== null && typeof entry.config === 'object' ? entry.config : {},
389
+ extra: extraKeysOf(entry),
390
+ }));
391
+ }
392
+
393
+ /**
394
+ * Rewrite one row in place, keeping every sibling row of its block.
395
+ * @param parts - document parts.
396
+ * @param row - the row to replace.
397
+ * @param next - `{ id, name, config, extra }` the row becomes.
398
+ * @param yaml - the `js-yaml` module.
399
+ * @param schema - the entry-list schema.
400
+ * @returns new document text.
401
+ */
402
+ export function updateRowInBlock(parts, row, next, yaml, schema) {
403
+ const rows = blockRows(parts, row, yaml, schema).map((entry) =>
404
+ entry.id === row.id ? { ...entry, ...next } : entry,
405
+ );
406
+ return rewriteInsertBlock(parts, row, rows);
407
+ }
408
+
409
+ /**
410
+ * Drop one row from its block, keeping every sibling row; the block itself
411
+ * disappears only when it held nothing else.
412
+ * @param parts - document parts.
413
+ * @param row - the row to drop.
414
+ * @param yaml - the `js-yaml` module.
415
+ * @param schema - the entry-list schema.
416
+ * @returns `{ text, blockRemoved }`.
417
+ */
418
+ export function removeRowFromBlock(parts, row, yaml, schema) {
419
+ const rows = blockRows(parts, row, yaml, schema).filter((entry) => entry.id !== row.id);
420
+ return { text: rewriteInsertBlock(parts, row, rows), blockRemoved: rows.length === 0 };
421
+ }
422
+
423
+ /**
424
+ * Append one block at the end of the document.
425
+ * @param parts - document parts.
426
+ * @param block - YAML text for the new item.
427
+ * @returns new document text.
428
+ */
429
+ export function appendBlock(parts, block) {
430
+ return joinTopLevel({ ...parts, items: [...parts.items, { lines: block.split('\n') }] });
431
+ }
432
+
433
+ /**
434
+ * Remove every override item that carries `disabled` for one of the given row
435
+ * ids. Used before writing a fresh `disabled` override so repeated toggles
436
+ * cannot accumulate duplicate blocks.
437
+ *
438
+ * Only `disabled`-bearing items are dropped. A row may also carry a
439
+ * hand-written `config:` override, which belongs to the user and must survive
440
+ * a toggle — the patch dialect applies each row independently, so two items
441
+ * targeting one id with different keys compose rather than conflict.
442
+ *
443
+ * @param parts - document parts.
444
+ * @param ids - row ids whose disable overrides are dropped.
445
+ * @param yaml - the `js-yaml` module.
446
+ * @param schema - the entry-list schema.
447
+ * @returns `{ parts, removed }`.
448
+ */
449
+ export function dropDisabledOverrides(parts, ids, yaml, schema) {
450
+ const wanted = new Set(ids);
451
+ const items = [];
452
+ let removed = 0;
453
+ for (const item of parts.items) {
454
+ const row = parseItem(itemText(item, parts.eol), yaml, schema);
455
+ const isDisableOverride =
456
+ row !== null &&
457
+ row.insert === undefined &&
458
+ typeof row.id === 'string' &&
459
+ wanted.has(row.id) &&
460
+ row.disabled !== undefined;
461
+ if (isDisableOverride) {
462
+ removed += 1;
463
+ continue;
464
+ }
465
+ items.push(item);
466
+ }
467
+ return { parts: { ...parts, items }, removed };
468
+ }
469
+
470
+ /**
471
+ * Remove every item that is a pure override (`id` plus `disabled`/`config`, no
472
+ * `insert`) targeting one of the given row ids. Used when a row is removed
473
+ * outright: every override addressing it becomes an orphan that the loader
474
+ * would warn about on the next boot.
475
+ * @param parts - document parts.
476
+ * @param ids - row ids whose overrides are dropped.
477
+ * @param yaml - the `js-yaml` module.
478
+ * @param schema - the entry-list schema.
479
+ * @returns `{ parts, removed }`.
480
+ */
481
+ export function dropOverrides(parts, ids, yaml, schema) {
482
+ const wanted = new Set(ids);
483
+ const items = [];
484
+ let removed = 0;
485
+ for (const item of parts.items) {
486
+ const row = parseItem(itemText(item, parts.eol), yaml, schema);
487
+ if (row !== null && row.insert === undefined && typeof row.id === 'string' && wanted.has(row.id)) {
488
+ removed += 1;
489
+ continue;
490
+ }
491
+ items.push(item);
492
+ }
493
+ return { parts: { ...parts, items }, removed };
494
+ }
495
+
496
+ /**
497
+ * The row ids an `- insert:` item's rows use, for collision checks.
498
+ * @param parts - document parts.
499
+ * @param yaml - the `js-yaml` module.
500
+ * @param schema - the entry-list schema.
501
+ * @returns a Set of ids.
502
+ */
503
+ export function insertedIds(parts, yaml, schema) {
504
+ const ids = new Set();
505
+ for (const item of parts.items) {
506
+ const row = parseItem(itemText(item, parts.eol), yaml, schema);
507
+ if (row === null || !Array.isArray(row.insert)) continue;
508
+ for (const inserted of row.insert) {
509
+ if (inserted !== null && typeof inserted === 'object' && typeof inserted.id === 'string') {
510
+ ids.add(inserted.id);
511
+ }
512
+ }
513
+ }
514
+ return ids;
515
+ }
516
+
517
+ /** Read a patch file, treating a missing file as an empty document. */
518
+ export function readPatchText(patchPath) {
519
+ try {
520
+ return readFileSync(patchPath, 'utf8');
521
+ } catch (error) {
522
+ if (error?.code === 'ENOENT') return '';
523
+ throw new Error(`补丁层读取失败:${String(error?.message ?? error)}`);
524
+ }
525
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "dsh-mcp-manager-plus",
3
+ "version": "0.4.0",
4
+ "description": "MCP manager settings page for DeepSeek Harness: list, enable, configure and add MCP servers from the browser, written durably to the profile's user patch layer.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/appthin/dsh-mcp-manager-plus.git"
9
+ },
10
+ "type": "module",
11
+ "main": "lib/index.js",
12
+ "exports": {
13
+ ".": {
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./client": "./lib/client.js",
17
+ "./cordis.patch.yml": "./cordis.patch.yml",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "files": [
21
+ "lib",
22
+ "cordis.patch.yml",
23
+ "README.md",
24
+ "README.en.md",
25
+ "CHANGELOG.md",
26
+ "LICENSE"
27
+ ],
28
+ "scripts": {
29
+ "test": "node test/run.mjs"
30
+ },
31
+ "keywords": [
32
+ "deepseek",
33
+ "harness",
34
+ "dsh",
35
+ "dsh-plugin",
36
+ "mcp",
37
+ "model-context-protocol"
38
+ ],
39
+ "dsh": {
40
+ "bundle": {
41
+ "patch": "./cordis.patch.yml"
42
+ },
43
+ "client": {
44
+ "platform": "web",
45
+ "inject": []
46
+ }
47
+ }
48
+ }