universal-plugin-hub 1.0.30 → 1.0.35
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/client/client.js +306 -30
- package/package.json +1 -1
- package/src/index.js +34 -15
- package/src/install.js +178 -1
- package/src/oauth-store.js +12 -1
- package/src/routes.js +83 -36
- package/src/runtime.js +134 -0
package/client/client.js
CHANGED
|
@@ -31,6 +31,62 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
31
31
|
return msg.length > 50 ? msg.slice(0, 48) + "…" : msg;
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
// A persisted change and a live one are different outcomes. The write answers
|
|
35
|
+
// `scheduled` with a token because applying it can restart this plugin, so
|
|
36
|
+
// the real result is read back from /apply-status instead of being assumed.
|
|
37
|
+
// Returns a promise that resolves once the outcome is reported; callers must
|
|
38
|
+
// not await it before refreshing, or every action pays the poll window.
|
|
39
|
+
function showApplicationToast(showToast, result, title, body) {
|
|
40
|
+
const toast = (t, b) => { showToast(t, b, { restart: false }); };
|
|
41
|
+
const saved = () => toast(title, body);
|
|
42
|
+
const failed = (message) => toast("已保存,但未即时生效", message || "DSH 未能完成运行时配置应用,请查看启动日志。");
|
|
43
|
+
const application = result && result.application;
|
|
44
|
+
// No runtime report at all: the host has no applicator, so neither the
|
|
45
|
+
// write nor this helper can claim the change is live.
|
|
46
|
+
if (!application) {
|
|
47
|
+
toast("已保存", "当前 DSH 未提供运行时应用接口,请重启后确认是否生效。");
|
|
48
|
+
return Promise.resolve();
|
|
49
|
+
}
|
|
50
|
+
if (application === "applied") {
|
|
51
|
+
saved();
|
|
52
|
+
return Promise.resolve();
|
|
53
|
+
}
|
|
54
|
+
if (application !== "scheduled" && application !== "pending") {
|
|
55
|
+
failed(result.applicationError);
|
|
56
|
+
return Promise.resolve();
|
|
57
|
+
}
|
|
58
|
+
const token = result.applicationToken;
|
|
59
|
+
return (async () => {
|
|
60
|
+
// Poll for this change's own outcome. A restart of the hub resets the
|
|
61
|
+
// server's status to `applied` for the token it was given, and a
|
|
62
|
+
// transient failure while that restart happens is retried rather than
|
|
63
|
+
// swallowed — that restart is the success path for a linked plugin.
|
|
64
|
+
for (let attempt = 0; attempt < 40; attempt++) {
|
|
65
|
+
await new Promise((resolve) => setTimeout(resolve, attempt < 3 ? 120 : 300));
|
|
66
|
+
let status = null;
|
|
67
|
+
try { status = await api("/apply-status" + (token === undefined ? "" : `?token=${encodeURIComponent(token)}`)); } catch { continue; }
|
|
68
|
+
if (!status) continue;
|
|
69
|
+
// Identity first: a newer change's `applied` must not be reported as
|
|
70
|
+
// this change's success. `APPLIED_TOKEN` (-1) is the server telling
|
|
71
|
+
// us our own change was applied by a previous, now-restarted fiber.
|
|
72
|
+
const APPLIED_TOKEN = -1;
|
|
73
|
+
if (token !== undefined && status.token !== undefined
|
|
74
|
+
&& status.token !== token && status.token !== APPLIED_TOKEN) {
|
|
75
|
+
toast("已保存", "配置已保存,更新状态已被后续操作接管。");
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (status.application === "applied") { saved(); return; }
|
|
79
|
+
if (status.application === "failed") { failed(status.applicationError); return; }
|
|
80
|
+
if (status.application === "restart-required") {
|
|
81
|
+
toast("已保存,但未即时生效", "该变更需要重启 DSH 后才会加载。");
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
// `idle`/`unknown`/`pending`: the change has not been applied yet.
|
|
85
|
+
}
|
|
86
|
+
toast("已保存", "DSH 仍在应用配置,稍后可在列表中确认。");
|
|
87
|
+
})();
|
|
88
|
+
}
|
|
89
|
+
|
|
34
90
|
// Inline progress card shown while a browser sign-in is in flight. Rendered
|
|
35
91
|
// as part of the dialog body (not a labelled grid row) so it reads as one
|
|
36
92
|
// object with its own title, message and actions, using the same tokens as
|
|
@@ -2477,6 +2533,105 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
2477
2533
|
.cpm-mcp-footer .cpm-btn {
|
|
2478
2534
|
transition: opacity 0.15s ease, background 0.15s ease, color 0.15s ease;
|
|
2479
2535
|
}
|
|
2536
|
+
/* Destructive icon control at the far left of the footer.
|
|
2537
|
+
Shape: corner-shape: squircle continues the corner past the arc into the
|
|
2538
|
+
straight edge, so the outline has no curvature seam where a circular corner
|
|
2539
|
+
meets a straight side. It is progressive enhancement — browsers without it
|
|
2540
|
+
fall back to the plain border-radius below, which is why the radius stays.
|
|
2541
|
+
The identity scale:1 on the base state keeps the hover scale from creating a
|
|
2542
|
+
stacking context only while hovered, which would re-order it against the
|
|
2543
|
+
footer's own layers. */
|
|
2544
|
+
.cpm-mcp-footer-del {
|
|
2545
|
+
--del-size: 32px;
|
|
2546
|
+
--del-radius: 10px;
|
|
2547
|
+
flex: 0 0 auto;
|
|
2548
|
+
width: var(--del-size);
|
|
2549
|
+
height: var(--del-size);
|
|
2550
|
+
padding: 0;
|
|
2551
|
+
border-radius: var(--del-radius);
|
|
2552
|
+
corner-shape: squircle;
|
|
2553
|
+
/* The resting state already carries the squircle surface, so the control
|
|
2554
|
+
reads as a button before the pointer arrives; hover only deepens it. */
|
|
2555
|
+
border: 1px solid rgba(0, 0, 0, 0.07);
|
|
2556
|
+
background: rgba(0, 0, 0, 0.045);
|
|
2557
|
+
color: var(--cpm-muted);
|
|
2558
|
+
cursor: pointer;
|
|
2559
|
+
display: inline-flex;
|
|
2560
|
+
align-items: center;
|
|
2561
|
+
justify-content: center;
|
|
2562
|
+
box-sizing: border-box;
|
|
2563
|
+
line-height: 1;
|
|
2564
|
+
scale: 1;
|
|
2565
|
+
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease,
|
|
2566
|
+
scale 0.2s cubic-bezier(0.34, 1.4, 0.64, 1);
|
|
2567
|
+
}
|
|
2568
|
+
/* The lid is its own group so it can swing while the can tips. */
|
|
2569
|
+
.cpm-mcp-footer-del svg {
|
|
2570
|
+
display: block;
|
|
2571
|
+
margin: auto;
|
|
2572
|
+
overflow: visible;
|
|
2573
|
+
}
|
|
2574
|
+
.cpm-mcp-footer-del .cpm-del-lid {
|
|
2575
|
+
transform-box: fill-box;
|
|
2576
|
+
transform-origin: 12px 6px;
|
|
2577
|
+
transition: translate 0.22s cubic-bezier(0.34, 1.4, 0.64, 1), rotate 0.22s cubic-bezier(0.34, 1.4, 0.64, 1);
|
|
2578
|
+
translate: 0px 0px;
|
|
2579
|
+
rotate: 0deg;
|
|
2580
|
+
}
|
|
2581
|
+
.cpm-mcp-footer-del .cpm-del-body {
|
|
2582
|
+
transform-box: fill-box;
|
|
2583
|
+
transform-origin: 50% 100%;
|
|
2584
|
+
transition: rotate 0.22s ease;
|
|
2585
|
+
rotate: 0deg;
|
|
2586
|
+
}
|
|
2587
|
+
.cpm-dark .cpm-mcp-footer-del {
|
|
2588
|
+
background: rgba(255, 255, 255, 0.055);
|
|
2589
|
+
border-color: rgba(255, 255, 255, 0.08);
|
|
2590
|
+
}
|
|
2591
|
+
.cpm-mcp-footer-del:hover {
|
|
2592
|
+
color: #ef4444;
|
|
2593
|
+
background: rgba(239, 68, 68, 0.12);
|
|
2594
|
+
border-color: rgba(239, 68, 68, 0.32);
|
|
2595
|
+
scale: 1.06;
|
|
2596
|
+
}
|
|
2597
|
+
/* Lid lifts and tips off the can while the can rocks the other way — one
|
|
2598
|
+
gesture, two parts, same spring. */
|
|
2599
|
+
.cpm-mcp-footer-del:hover .cpm-del-lid {
|
|
2600
|
+
translate: 0px -1.7px;
|
|
2601
|
+
rotate: -9deg;
|
|
2602
|
+
}
|
|
2603
|
+
.cpm-mcp-footer-del:hover .cpm-del-body { rotate: 3.5deg; }
|
|
2604
|
+
.cpm-mcp-footer-del:active { scale: 0.94; }
|
|
2605
|
+
.cpm-mcp-footer-del:active .cpm-del-lid { translate: 0px -0.8px; rotate: -5deg; }
|
|
2606
|
+
.cpm-mcp-footer-del:active .cpm-del-body { rotate: 1.5deg; }
|
|
2607
|
+
.cpm-mcp-footer-del:focus-visible {
|
|
2608
|
+
outline: 2px solid rgba(239, 68, 68, 0.55);
|
|
2609
|
+
outline-offset: 2px;
|
|
2610
|
+
}
|
|
2611
|
+
.cpm-mcp-footer-del:disabled {
|
|
2612
|
+
opacity: 0.4;
|
|
2613
|
+
cursor: not-allowed;
|
|
2614
|
+
scale: 1;
|
|
2615
|
+
color: var(--cpm-muted);
|
|
2616
|
+
}
|
|
2617
|
+
.cpm-mcp-footer-del:disabled:hover { background: rgba(0, 0, 0, 0.045); border-color: rgba(0, 0, 0, 0.07); }
|
|
2618
|
+
.cpm-dark .cpm-mcp-footer-del:disabled:hover { background: rgba(255, 255, 255, 0.055); border-color: rgba(255, 255, 255, 0.08); }
|
|
2619
|
+
.cpm-mcp-footer-del:disabled:hover .cpm-del-lid { translate: 0px 0px; rotate: 0deg; }
|
|
2620
|
+
.cpm-mcp-footer-del:disabled:hover .cpm-del-body { rotate: 0deg; }
|
|
2621
|
+
/* Must follow the base and :hover rules above: equal specificity means the
|
|
2622
|
+
later declaration wins, and the base transition shorthand re-expands
|
|
2623
|
+
transition-duration. Placed earlier, this block was dead CSS. */
|
|
2624
|
+
@media (prefers-reduced-motion: reduce) {
|
|
2625
|
+
/* The colour change still says "destructive"; only the lift and tilt go. */
|
|
2626
|
+
.cpm-mcp-footer-del,
|
|
2627
|
+
.cpm-mcp-footer-del .cpm-del-lid,
|
|
2628
|
+
.cpm-mcp-footer-del .cpm-del-body {
|
|
2629
|
+
transition-duration: .01s;
|
|
2630
|
+
}
|
|
2631
|
+
.cpm-mcp-footer-del:hover { scale: 1; }
|
|
2632
|
+
.cpm-mcp-footer-del:hover .cpm-del-lid,
|
|
2633
|
+
.cpm-mcp-footer-del:hover .cpm-del-body { rotate: 0deg; translate: 0px 0px; }
|
|
2634
|
+
}
|
|
2480
2635
|
.cpm-mcp-footer .cpm-btn-secondary {
|
|
2481
2636
|
background: rgba(0, 0, 0, 0.05);
|
|
2482
2637
|
border: 1px solid rgba(0, 0, 0, 0.08);
|
|
@@ -4140,6 +4295,32 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
4140
4295
|
h("path", { d: "M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" }),
|
|
4141
4296
|
);
|
|
4142
4297
|
|
|
4298
|
+
// Lid and can are separate groups so the hover can lift the lid off the can
|
|
4299
|
+
// while the can rocks the other way. The gap between them at rest (y 4..5.6
|
|
4300
|
+
// for the handle, the bar at y 6) is what makes the lift read.
|
|
4301
|
+
const IconTrash = ({ size = 14, color = "currentColor" }) =>
|
|
4302
|
+
h("svg", {
|
|
4303
|
+
width: size,
|
|
4304
|
+
height: size,
|
|
4305
|
+
viewBox: "0 0 24 24",
|
|
4306
|
+
fill: "none",
|
|
4307
|
+
stroke: color,
|
|
4308
|
+
strokeWidth: 1.9,
|
|
4309
|
+
strokeLinecap: "round",
|
|
4310
|
+
strokeLinejoin: "round",
|
|
4311
|
+
style: { flexShrink: 0 },
|
|
4312
|
+
},
|
|
4313
|
+
h("g", { className: "cpm-del-lid" },
|
|
4314
|
+
h("path", { d: "M3.2 6.2h17.6" }),
|
|
4315
|
+
h("path", { d: "M8.6 6.2V4.1a1.7 1.7 0 0 1 1.7-1.7h3.4a1.7 1.7 0 0 1 1.7 1.7v2.1" }),
|
|
4316
|
+
),
|
|
4317
|
+
h("g", { className: "cpm-del-body" },
|
|
4318
|
+
h("path", { d: "M18.6 6.2l-0.9 13.1a1.8 1.8 0 0 1-1.8 1.7H8.1a1.8 1.8 0 0 1-1.8-1.7L5.4 6.2" }),
|
|
4319
|
+
h("line", { x1: 10.2, y1: 10.6, x2: 10.2, y2: 16.6 }),
|
|
4320
|
+
h("line", { x1: 13.8, y1: 10.6, x2: 13.8, y2: 16.6 }),
|
|
4321
|
+
),
|
|
4322
|
+
);
|
|
4323
|
+
|
|
4143
4324
|
const IconClose = ({ size = 14, color = "currentColor" }) =>
|
|
4144
4325
|
h("svg", {
|
|
4145
4326
|
width: size,
|
|
@@ -5429,35 +5610,51 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
5429
5610
|
}
|
|
5430
5611
|
|
|
5431
5612
|
// ────────────────────────────── Browse & Detail Container ──────────────────────────────
|
|
5432
|
-
function McpOverview({ serverRows,
|
|
5613
|
+
function McpOverview({ serverRows, pluginRows }) {
|
|
5433
5614
|
const rootRef = useRef(null);
|
|
5434
|
-
const
|
|
5615
|
+
const serverRef = useRef(null);
|
|
5435
5616
|
const [reservedHeight, setReservedHeight] = useState(0);
|
|
5436
5617
|
const reserveSpace = serverRows.length > 0 && pluginRows.length > 0;
|
|
5437
5618
|
useSafeLayoutEffect(() => {
|
|
5438
5619
|
const viewport = rootRef.current?.parentElement;
|
|
5439
|
-
|
|
5620
|
+
const server = serverRef.current;
|
|
5621
|
+
if (!viewport || !reserveSpace || !server) { setReservedHeight(0); return; }
|
|
5622
|
+
// A window resize and the observer's own viewport callback describe the
|
|
5623
|
+
// same change, and each measure forces a synchronous layout. Coalesce
|
|
5624
|
+
// them into one measure per frame.
|
|
5625
|
+
let frame = 0;
|
|
5626
|
+
const schedule = () => {
|
|
5627
|
+
if (frame) return;
|
|
5628
|
+
frame = requestAnimationFrame(() => { frame = 0; measure(); });
|
|
5629
|
+
};
|
|
5440
5630
|
const measure = () => {
|
|
5441
5631
|
const style = getComputedStyle(viewport);
|
|
5442
5632
|
const available = viewport.clientHeight - (parseFloat(style.paddingTop) || 0) - (parseFloat(style.paddingBottom) || 0);
|
|
5443
|
-
|
|
5633
|
+
// Anchor the plugin section's top edge to the midpoint. Only the
|
|
5634
|
+
// server section's actual, current height may push it down; never
|
|
5635
|
+
// reserve space for tools that are not expanded yet.
|
|
5636
|
+
const next = Math.max(0, Math.round(available / 2), server.offsetHeight);
|
|
5444
5637
|
setReservedHeight((prev) => prev === next ? prev : next);
|
|
5445
5638
|
};
|
|
5446
5639
|
measure();
|
|
5447
|
-
const observer = typeof ResizeObserver === "function" ? new ResizeObserver(
|
|
5640
|
+
const observer = typeof ResizeObserver === "function" ? new ResizeObserver(schedule) : null;
|
|
5448
5641
|
observer?.observe(viewport);
|
|
5449
|
-
|
|
5450
|
-
window.addEventListener("resize",
|
|
5451
|
-
return () => {
|
|
5642
|
+
observer?.observe(server);
|
|
5643
|
+
window.addEventListener("resize", schedule);
|
|
5644
|
+
return () => {
|
|
5645
|
+
if (frame) cancelAnimationFrame(frame);
|
|
5646
|
+
observer?.disconnect();
|
|
5647
|
+
window.removeEventListener("resize", schedule);
|
|
5648
|
+
};
|
|
5452
5649
|
}, [reserveSpace]);
|
|
5453
5650
|
return h("div", { ref: rootRef, className: "cpm-mcp-overview", style: { position: "relative", maxWidth: "var(--cpm-grid-width)", margin: "0 auto", width: "100%" } },
|
|
5454
|
-
reserveSpace && h("div", { ref: measureRef, "aria-hidden": true, style: { position: "absolute", top: 0, left: 0, width: "100%", visibility: "hidden", pointerEvents: "none", display: "flow-root" } },
|
|
5455
|
-
h("div", { style: { fontSize: 14, fontWeight: 700, margin: "8px 4px 12px" } }, "服务器"),
|
|
5456
|
-
h("div", { style: { borderRadius: 16, border: "1px solid var(--cpm-border)", overflow: "hidden" } }, expandedServerRows),
|
|
5457
|
-
),
|
|
5458
5651
|
serverRows.length > 0 && h("section", { className: "cpm-mcp-user-section", style: { display: "flow-root", minHeight: reserveSpace ? reservedHeight : undefined } },
|
|
5459
|
-
|
|
5460
|
-
|
|
5652
|
+
// Measure the intrinsic content, not the section with minHeight applied:
|
|
5653
|
+
// expansion can push the next section down, and collapse can release it.
|
|
5654
|
+
h("div", { ref: serverRef, style: { display: "flow-root" } },
|
|
5655
|
+
h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "8px 4px 12px" } }, "服务器"),
|
|
5656
|
+
h("div", { style: { borderRadius: 16, border: "1px solid var(--cpm-border)", background: "var(--cpm-card-bg)", overflow: "hidden" } }, serverRows),
|
|
5657
|
+
),
|
|
5461
5658
|
),
|
|
5462
5659
|
pluginRows.length > 0 && h("section", { className: "cpm-mcp-plugin-section", style: { display: "flow-root" } },
|
|
5463
5660
|
h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "22px 4px 12px" } }, "来自插件"),
|
|
@@ -5638,7 +5835,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
5638
5835
|
const renderMcpServerRow = (opts) => {
|
|
5639
5836
|
const { owner, name, transport, connected, canEdit, record, first, conn } = opts;
|
|
5640
5837
|
const key = `${owner}::${name}`;
|
|
5641
|
-
const isExpanded =
|
|
5838
|
+
const isExpanded = !!globalExpanded[key];
|
|
5642
5839
|
const info = globalToolData[key];
|
|
5643
5840
|
const toolsList = info?.tools || [];
|
|
5644
5841
|
const disabledTools = info?.disabledTools || [];
|
|
@@ -6818,8 +7015,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
6818
7015
|
|
|
6819
7016
|
const removePlugin = async (pluginName) => {
|
|
6820
7017
|
try {
|
|
6821
|
-
await api("/plugins/" + encodeURIComponent(pluginName), { method: "DELETE" });
|
|
6822
|
-
showToast
|
|
7018
|
+
const result = await api("/plugins/" + encodeURIComponent(pluginName), { method: "DELETE" });
|
|
7019
|
+
void showApplicationToast(showToast, result, "已卸载插件", "插件副本与技能注册已实时移除并生效。");
|
|
6823
7020
|
setView({ type: "browse", sourceId: activeSourceId });
|
|
6824
7021
|
await refreshState();
|
|
6825
7022
|
onInstalled();
|
|
@@ -6907,7 +7104,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
6907
7104
|
else if (result.converted && result.converted.length) parts.push(`${result.converted.length} 个子代理`);
|
|
6908
7105
|
if (result.connectors && result.connectors.length) parts.push(`${result.connectors.length} 个 MCP 服务`);
|
|
6909
7106
|
const summary = parts.length ? `${parts.join("、")}已就绪。` : "插件已安装就绪。";
|
|
6910
|
-
showToast
|
|
7107
|
+
void showApplicationToast(showToast, result, "安装完成", summary);
|
|
6911
7108
|
setInstallFor(null);
|
|
6912
7109
|
await refreshState();
|
|
6913
7110
|
onInstalled();
|
|
@@ -7253,7 +7450,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
7253
7450
|
},
|
|
7254
7451
|
!hasMcps && h("div", { className: "cpm-empty", style: { textAlign: "center", padding: "40px 16px" } }, "还没有添加 MCP,点右上角「添加」→「添加 MCP」"),
|
|
7255
7452
|
h(McpOverview, {
|
|
7256
|
-
expandedServerRows: mcps.map((m, i) => renderMcpServerRow({ owner: "user-mcp", row: m, name: m.name, transport: m.transport, connected: m.enabled === true, canEdit: true, first: i === 0, measureExpanded: true })),
|
|
7257
7453
|
serverRows: mcps.map((m, i) => renderMcpServerRow({
|
|
7258
7454
|
owner: "user-mcp",
|
|
7259
7455
|
row: m,
|
|
@@ -8003,6 +8199,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8003
8199
|
} : { name: "", transport: "stdio", url: "", oauth: "none", oauthClientId: "", oauthClientSecret: "", oauthHasClientSecret: false, oauthCallbackPort: "", oauthScope: "", command: "", args: "", headersList: [], envList: [] });
|
|
8004
8200
|
const [testing, setTesting] = useState(false);
|
|
8005
8201
|
const [saving, setSaving] = useState(false);
|
|
8202
|
+
const [confirmDelete, setConfirmDelete] = useState(false);
|
|
8203
|
+
const [deleting, setDeleting] = useState(false);
|
|
8204
|
+
// The confirmation renders inside this dialog, so it must handle Escape
|
|
8205
|
+
// first: the outer handler would otherwise close the whole editor and
|
|
8206
|
+
// discard the form behind it.
|
|
8207
|
+
useEffect(() => {
|
|
8208
|
+
if (!confirmDelete) return;
|
|
8209
|
+
const onKey = (e) => {
|
|
8210
|
+
if (e.key !== "Escape") return;
|
|
8211
|
+
e.stopPropagation();
|
|
8212
|
+
e.preventDefault();
|
|
8213
|
+
setConfirmDelete(false);
|
|
8214
|
+
};
|
|
8215
|
+
window.addEventListener("keydown", onKey, true);
|
|
8216
|
+
return () => window.removeEventListener("keydown", onKey, true);
|
|
8217
|
+
}, [confirmDelete]);
|
|
8006
8218
|
const upd = (patch) => setForm((prev) => ({ ...prev, ...patch }));
|
|
8007
8219
|
const argsJsonError = (s) => {
|
|
8008
8220
|
const t = String(s || "").trim();
|
|
@@ -8052,6 +8264,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8052
8264
|
oauthScope: form.oauthScope,
|
|
8053
8265
|
args,
|
|
8054
8266
|
env,
|
|
8267
|
+
// Only a real rename sends this; `/mcps/update` otherwise works off
|
|
8268
|
+
// `name` alone, and the save still has to find the old record.
|
|
8269
|
+
...(owner || !initial || form.name.trim() === initial.name ? {} : { previousName: initial.name }),
|
|
8055
8270
|
};
|
|
8056
8271
|
};
|
|
8057
8272
|
|
|
@@ -8102,6 +8317,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8102
8317
|
showToast("请输入启动命令", "stdio 连接需要本地启动命令,如 npx、node 或 uvx", { restart: false });
|
|
8103
8318
|
return;
|
|
8104
8319
|
}
|
|
8320
|
+
if (data.previousName && data.name === data.previousName) delete data.previousName;
|
|
8105
8321
|
setSaving(true);
|
|
8106
8322
|
try {
|
|
8107
8323
|
const saveUrl = owner
|
|
@@ -8113,7 +8329,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8113
8329
|
setSaving(false);
|
|
8114
8330
|
return;
|
|
8115
8331
|
}
|
|
8116
|
-
|
|
8332
|
+
if (initial && data.previousName) {
|
|
8333
|
+
void showApplicationToast(showToast, res, "MCP 已重命名", `「${data.previousName}」已改名为「${data.name}」`);
|
|
8334
|
+
} else {
|
|
8335
|
+
void showApplicationToast(showToast, res, initial ? "MCP 已更新" : "MCP 已添加", `「${data.name}」已${initial ? "更新" : "注册为可用 MCP 服务"}`);
|
|
8336
|
+
}
|
|
8117
8337
|
await onSaved();
|
|
8118
8338
|
} catch (err) {
|
|
8119
8339
|
showToast("保存失败", cleanMcpError(err), { restart: false });
|
|
@@ -8122,6 +8342,24 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8122
8342
|
}
|
|
8123
8343
|
};
|
|
8124
8344
|
|
|
8345
|
+
const removeMcp = async () => {
|
|
8346
|
+
setDeleting(true);
|
|
8347
|
+
try {
|
|
8348
|
+
const result = await api(`/mcps/${encodeURIComponent(initial.name)}`, { method: "DELETE" });
|
|
8349
|
+
const cacheKey = `user-mcp::${initial.name}`;
|
|
8350
|
+
if (GLOBAL_MCP_TOOLS_CACHE[cacheKey]) {
|
|
8351
|
+
delete GLOBAL_MCP_TOOLS_CACHE[cacheKey];
|
|
8352
|
+
try { localStorage.setItem("cpm_mcp_tools_cache_v1", JSON.stringify(GLOBAL_MCP_TOOLS_CACHE)); } catch {}
|
|
8353
|
+
}
|
|
8354
|
+
setConfirmDelete(false);
|
|
8355
|
+
void showApplicationToast(showToast, result, "MCP 已删除", `「${initial.name}」已从服务器列表移除`);
|
|
8356
|
+
await onSaved();
|
|
8357
|
+
} catch (err) {
|
|
8358
|
+
showToast("删除失败", cleanMcpError(err), { restart: false });
|
|
8359
|
+
setDeleting(false);
|
|
8360
|
+
}
|
|
8361
|
+
};
|
|
8362
|
+
|
|
8125
8363
|
return h("div", { className: "cpm-dialog", onClick: onCancel },
|
|
8126
8364
|
h("div", { className: "cpm-mcp-modal", onClick: (e) => e.stopPropagation() },
|
|
8127
8365
|
h("button", { className: "cpm-mcp-close-top", onClick: onCancel }, h(IconClose, { size: 14 })),
|
|
@@ -8133,7 +8371,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8133
8371
|
className: "cpm-mcp-input",
|
|
8134
8372
|
placeholder: "mcp-name,如 github、notion",
|
|
8135
8373
|
value: form.name,
|
|
8136
|
-
|
|
8374
|
+
// Renaming is allowed for user-added servers only. A plugin
|
|
8375
|
+
// connector's name is its connector id: the plugin owns it,
|
|
8376
|
+
// and the route that saves it is keyed by that same name.
|
|
8377
|
+
disabled: !!owner,
|
|
8137
8378
|
onChange: (e) => upd({ name: e.target.value }),
|
|
8138
8379
|
}),
|
|
8139
8380
|
),
|
|
@@ -8327,7 +8568,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8327
8568
|
),
|
|
8328
8569
|
),
|
|
8329
8570
|
h("div", { className: "cpm-mcp-footer", style: { gap: 10 } },
|
|
8330
|
-
|
|
8571
|
+
// Delete sits alone on the left, away from the two confirm
|
|
8572
|
+
// actions: a destructive control next to "save" is one slip away
|
|
8573
|
+
// from a misclick. Only user-added servers can be deleted — a
|
|
8574
|
+
// plugin's connector belongs to the plugin, which re-registers it
|
|
8575
|
+
// on every enable, so deleting it here would come straight back.
|
|
8576
|
+
initial && !owner
|
|
8577
|
+
? h("button", {
|
|
8578
|
+
type: "button",
|
|
8579
|
+
className: "cpm-mcp-footer-del",
|
|
8580
|
+
// Accessible name only — the user asked for no tooltip here.
|
|
8581
|
+
"aria-label": "删除这个 MCP",
|
|
8582
|
+
disabled: testing || saving || !!oauthFlow.pending,
|
|
8583
|
+
onClick: () => setConfirmDelete(true),
|
|
8584
|
+
}, h(IconTrash, { size: 15 }))
|
|
8585
|
+
: h("div", { style: { flex: 1 } }),
|
|
8586
|
+
initial && !owner ? h("div", { style: { flex: 1 } }) : null,
|
|
8331
8587
|
h("button", {
|
|
8332
8588
|
className: "cpm-btn cpm-btn-secondary",
|
|
8333
8589
|
disabled: testing || saving || (form.transport === "stdio" && !!argsError),
|
|
@@ -8342,6 +8598,26 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
8342
8598
|
}, saving ? "保存中…" : "保存并启用"),
|
|
8343
8599
|
),
|
|
8344
8600
|
),
|
|
8601
|
+
confirmDelete && h("div", { className: "cpm-dialog", onClick: () => setConfirmDelete(false) },
|
|
8602
|
+
h("div", { className: "cpm-dialog-box", onClick: (e) => e.stopPropagation() },
|
|
8603
|
+
h("div", { className: "cpm-dialog-title" }, `删除 MCP「${initial.name}」`),
|
|
8604
|
+
h("div", { className: "cpm-field", style: { fontSize: 13, lineHeight: 1.6, color: "var(--cpm-muted)" } },
|
|
8605
|
+
"将移除它的连接配置、已保存的授权和工具开关记录。如需再次使用,可在「添加」里重新配置。",
|
|
8606
|
+
),
|
|
8607
|
+
h("div", { className: "cpm-dialog-actions" },
|
|
8608
|
+
h("button", {
|
|
8609
|
+
className: "cpm-btn cpm-btn-secondary",
|
|
8610
|
+
onClick: () => setConfirmDelete(false),
|
|
8611
|
+
}, "取消"),
|
|
8612
|
+
h("button", {
|
|
8613
|
+
className: "cpm-btn cpm-btn-primary",
|
|
8614
|
+
style: { background: "#dc2626", borderColor: "#dc2626", color: "#fff" },
|
|
8615
|
+
disabled: deleting,
|
|
8616
|
+
onClick: removeMcp,
|
|
8617
|
+
}, deleting ? "删除中…" : "确认删除"),
|
|
8618
|
+
),
|
|
8619
|
+
),
|
|
8620
|
+
),
|
|
8345
8621
|
);
|
|
8346
8622
|
}
|
|
8347
8623
|
|
|
@@ -9264,12 +9540,12 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
9264
9540
|
const toggle = async () => {
|
|
9265
9541
|
setToggling(true);
|
|
9266
9542
|
try {
|
|
9267
|
-
await api(`/plugins/${record.name}/toggle`, {
|
|
9543
|
+
const result = await api(`/plugins/${record.name}/toggle`, {
|
|
9268
9544
|
method: "POST",
|
|
9269
9545
|
body: JSON.stringify({ enabled: !record.enabled }),
|
|
9270
9546
|
});
|
|
9271
9547
|
await refreshState();
|
|
9272
|
-
showToast
|
|
9548
|
+
void showApplicationToast(showToast, result, record.enabled ? "已禁用插件" : "已启用插件", "插件状态已实时更新并生效。");
|
|
9273
9549
|
} catch (e) {
|
|
9274
9550
|
showToast("操作失败", e.message, { restart: false });
|
|
9275
9551
|
} finally {
|
|
@@ -9280,12 +9556,12 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
9280
9556
|
const toggleConn = async (connectorName, currentConnected) => {
|
|
9281
9557
|
setTogglingConn(connectorName);
|
|
9282
9558
|
try {
|
|
9283
|
-
await api(`/plugins/${record.name}/connectors/${connectorName}/toggle`, {
|
|
9559
|
+
const result = await api(`/plugins/${record.name}/connectors/${connectorName}/toggle`, {
|
|
9284
9560
|
method: "POST",
|
|
9285
9561
|
body: JSON.stringify({ enabled: !currentConnected }),
|
|
9286
9562
|
});
|
|
9287
9563
|
await refreshState();
|
|
9288
|
-
showToast
|
|
9564
|
+
void showApplicationToast(showToast, result, !currentConnected ? "已连接 Connector" : "已断开 Connector", `MCP 服务 ${connectorName} 配置已实时更新。`);
|
|
9289
9565
|
} catch (e) {
|
|
9290
9566
|
showToast("操作失败", e.message, { restart: false });
|
|
9291
9567
|
} finally {
|
|
@@ -9298,7 +9574,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
9298
9574
|
try {
|
|
9299
9575
|
const result = await api(`/plugins/${record.name}/update`, { method: "POST" });
|
|
9300
9576
|
await refreshState();
|
|
9301
|
-
showToast
|
|
9577
|
+
void showApplicationToast(showToast, result, "更新完成", `${result.skills.length} 个技能已实时重新就绪并生效。`);
|
|
9302
9578
|
} catch (e) {
|
|
9303
9579
|
showToast("更新失败", e.message, { restart: false });
|
|
9304
9580
|
} finally {
|
|
@@ -9309,7 +9585,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
9309
9585
|
const remove = async () => {
|
|
9310
9586
|
setBusy(true);
|
|
9311
9587
|
try {
|
|
9312
|
-
await api(`/plugins/${record.name}`, { method: "DELETE" });
|
|
9588
|
+
const result = await api(`/plugins/${record.name}`, { method: "DELETE" });
|
|
9313
9589
|
for (const k of Object.keys(GLOBAL_MCP_TOOLS_CACHE)) {
|
|
9314
9590
|
if (k.startsWith(`${record.name}::`)) {
|
|
9315
9591
|
delete GLOBAL_MCP_TOOLS_CACHE[k];
|
|
@@ -9319,7 +9595,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
9319
9595
|
localStorage.setItem("cpm_mcp_tools_cache_v1", JSON.stringify(GLOBAL_MCP_TOOLS_CACHE));
|
|
9320
9596
|
} catch {}
|
|
9321
9597
|
await refreshState();
|
|
9322
|
-
showToast
|
|
9598
|
+
void showApplicationToast(showToast, result, "已卸载插件", "插件副本与技能注册已实时移除并生效。");
|
|
9323
9599
|
onClose();
|
|
9324
9600
|
} catch (e) {
|
|
9325
9601
|
showToast("卸载失败", e.message, { restart: false });
|
|
@@ -10219,7 +10495,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
|
|
|
10219
10495
|
return;
|
|
10220
10496
|
}
|
|
10221
10497
|
await refreshState();
|
|
10222
|
-
showToast
|
|
10498
|
+
void showApplicationToast(showToast, res, "配置成功", `已成功保存 ${authDialog.connectorName} 认证信息并注册为可用 MCP 服务`);
|
|
10223
10499
|
closeAuthDialog();
|
|
10224
10500
|
} catch (err) {
|
|
10225
10501
|
showToast("保存失败", err.message);
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"title": "Universal Plugin Hub",
|
|
4
4
|
"displayName": "Universal Plugin Hub",
|
|
5
5
|
"description": "在 DSH 中使用 Claude Code、Codex 等软件生态的插件,一站式管理插件、Skills 与 MCP。支持添加 Git 插件源和 marketplace、上传插件和 Skills、添加 MCP 服务器,自动扫描并开关本地 Skills,接入插件提供的子代理、MCP、Hooks 与 LSP。",
|
|
6
|
-
"version": "1.0.
|
|
6
|
+
"version": "1.0.35",
|
|
7
7
|
"engines": {
|
|
8
8
|
"dsh": ">=0.1.5-rc.1"
|
|
9
9
|
},
|
package/src/index.js
CHANGED
|
@@ -10,12 +10,45 @@ import { mountRoutes } from './routes.js'
|
|
|
10
10
|
import { cancelAllOAuthVerifications } from './oauth.js'
|
|
11
11
|
import { syncAllInstalledSkillsToDsh, installProfilePackages, findDshMainNodeModules, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
|
|
12
12
|
import { createSkillsManager } from './skills.js'
|
|
13
|
+
import { createProfileApplicator } from './runtime.js'
|
|
13
14
|
import { createRequire } from 'node:module'
|
|
14
15
|
import { join } from 'node:path'
|
|
15
16
|
|
|
16
17
|
export const name = 'universal-plugin-hub'
|
|
17
18
|
|
|
18
19
|
export function apply(ctx) {
|
|
20
|
+
// The running host knows which profile it booted. Guessing from the
|
|
21
|
+
// filesystem writes patches into the wrong profile (e.g. a custom profile
|
|
22
|
+
// name would land in `web`), and the change then never loads.
|
|
23
|
+
// `profileContext` is provided asynchronously, so it must be injected —
|
|
24
|
+
// reading it eagerly here returns undefined on a real host.
|
|
25
|
+
// Everything below that resolves a profile path has to run *after* this, so
|
|
26
|
+
// it lives inside the injection rather than beside it.
|
|
27
|
+
let provisioned = Promise.resolve()
|
|
28
|
+
ctx.inject(['profileContext'], (hostCtx) => {
|
|
29
|
+
const name = hostCtx.profileContext?.name
|
|
30
|
+
if (typeof name === 'string' && name.trim()) process.env.DSH_PROFILE = name.trim()
|
|
31
|
+
|
|
32
|
+
// Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
|
|
33
|
+
try {
|
|
34
|
+
syncAllInstalledSkillsToDsh()
|
|
35
|
+
} catch (err) {
|
|
36
|
+
ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Host packages disappear when a package manager re-resolves the profile
|
|
40
|
+
// (pnpm moves unrecognized packages to node_modules/.ignored), so repair
|
|
41
|
+
// them on every start instead of trusting a one-time install step.
|
|
42
|
+
// Detached on purpose: Cordis awaits whatever apply returns, and this does
|
|
43
|
+
// network probes and tarball extraction — the hub fiber must not wait on it.
|
|
44
|
+
// Exposed on the callback for tests that need to await it.
|
|
45
|
+
const provisioning = installProfilePackages([...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]).catch((err) => {
|
|
46
|
+
ctx.logger?.warn?.(`[universal-plugin-hub] host package provisioning skipped: ${err.message}`)
|
|
47
|
+
})
|
|
48
|
+
provisioned = provisioning
|
|
49
|
+
})
|
|
50
|
+
// Exposed only so a test can await the detached provisioning.
|
|
51
|
+
apply.provisioned = () => provisioned
|
|
19
52
|
const skills = createSkillsManager()
|
|
20
53
|
ctx.inject(['skills'], (hostCtx) => {
|
|
21
54
|
hostCtx.effect(() => skills.attach(hostCtx.skills, () => {
|
|
@@ -37,23 +70,9 @@ export function apply(ctx) {
|
|
|
37
70
|
}
|
|
38
71
|
hostCtx.effect(() => skills.attachAgents(hostCtx, createScope), 'universal-plugin-hub: scoped skill switches')
|
|
39
72
|
})
|
|
40
|
-
// Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
|
|
41
|
-
try {
|
|
42
|
-
syncAllInstalledSkillsToDsh()
|
|
43
|
-
} catch (err) {
|
|
44
|
-
ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// Host packages disappear when a package manager re-resolves the profile
|
|
48
|
-
// (pnpm moves unrecognized packages to node_modules/.ignored), so repair
|
|
49
|
-
// them on every start instead of trusting a one-time install step.
|
|
50
|
-
installProfilePackages([...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]).catch((err) => {
|
|
51
|
-
ctx.logger?.warn?.(`[universal-plugin-hub] host package provisioning skipped: ${err.message}`)
|
|
52
|
-
})
|
|
53
|
-
|
|
54
73
|
ctx.inject(['webServer'], (hostCtx) => {
|
|
55
74
|
hostCtx.effect(() => {
|
|
56
|
-
const unmount = mountRoutes(hostCtx.webServer, skills)
|
|
75
|
+
const unmount = mountRoutes(hostCtx.webServer, skills, createProfileApplicator(ctx))
|
|
57
76
|
return () => { unmount(); cancelAllOAuthVerifications() }
|
|
58
77
|
}, 'universal-plugin-hub: http routes')
|
|
59
78
|
})
|
package/src/install.js
CHANGED
|
@@ -22,7 +22,7 @@ import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets }
|
|
|
22
22
|
import { buildPluginIcons } from './icons.js'
|
|
23
23
|
import { beginOAuthVerification, completeOAuthVerification, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
|
|
24
24
|
import { encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
|
|
25
|
-
import { oauthStoreDir } from './oauth-store.js'
|
|
25
|
+
import { oauthStoreDir, readOAuthRecord, writeOAuthRecord, deleteOAuthRecord } from './oauth-store.js'
|
|
26
26
|
|
|
27
27
|
const OAUTH_BRIDGE_PATH = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
|
|
28
28
|
|
|
@@ -310,6 +310,183 @@ export function unregisterConnector(pluginName, connectorName) {
|
|
|
310
310
|
return { ok: true, connected: false }
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
+
/**
|
|
314
|
+
* Delete a user-added MCP server completely: registration, saved definition,
|
|
315
|
+
* per-tool state and any OAuth credentials. `unregisterConnector` alone is the
|
|
316
|
+
* "turn it off" path and deliberately keeps the saved remote config so the
|
|
317
|
+
* server can be switched back on; a delete must leave nothing behind, or
|
|
318
|
+
* re-adding the same name would silently inherit the old sign-in.
|
|
319
|
+
*/
|
|
320
|
+
export function removeUserMcp(connectorName) {
|
|
321
|
+
const state = readState()
|
|
322
|
+
const saved = (Array.isArray(state.userMcps) ? state.userMcps : []).find((x) => x && x.name === connectorName)
|
|
323
|
+
if (!saved) throw new Error(`MCP 不存在:${connectorName}`)
|
|
324
|
+
|
|
325
|
+
// Credential keys cover both OAuth modes; the mode the server was saved with
|
|
326
|
+
// decides which file exists, and deleting a missing one is a no-op.
|
|
327
|
+
const remote = remoteConfigFromEntry(getConnectorEntry('user-mcp', connectorName)?.config) || saved
|
|
328
|
+
// A server can have been edited to a new URL since it signed in, so clear the
|
|
329
|
+
// record for every URL it is known to have used — the live one and the stored
|
|
330
|
+
// one — or the old sign-in survives the delete and is inherited on re-add.
|
|
331
|
+
const urls = new Set([remote?.url, saved.url, ...(Array.isArray(saved.usedUrls) ? saved.usedUrls : [])]
|
|
332
|
+
.filter((u) => typeof u === 'string' && u.trim()))
|
|
333
|
+
const credentialKeys = [...urls].flatMap((u) =>
|
|
334
|
+
['auto_register', 'custom'].map((mode) => oauthCredentialKey('user-mcp', connectorName, u, mode)))
|
|
335
|
+
const url = remote?.url || saved.url || null
|
|
336
|
+
|
|
337
|
+
unregisterConnector('user-mcp', connectorName)
|
|
338
|
+
|
|
339
|
+
const toolsKey = `user-mcp::${connectorName}`
|
|
340
|
+
const toolsState = readMcpToolsState()
|
|
341
|
+
if (Object.prototype.hasOwnProperty.call(toolsState, toolsKey)) {
|
|
342
|
+
delete toolsState[toolsKey]
|
|
343
|
+
writeMcpToolsState(toolsState)
|
|
344
|
+
}
|
|
345
|
+
MEMORY_TOOLS_CACHE.delete(toolsKey)
|
|
346
|
+
for (const key of credentialKeys) {
|
|
347
|
+
try { deleteOAuthRecord(key) } catch {}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
state.userMcps = (Array.isArray(state.userMcps) ? state.userMcps : []).filter((x) => x && x.name !== connectorName)
|
|
351
|
+
writeState(state)
|
|
352
|
+
return { ok: true, name: connectorName }
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Normalize one saved user MCP definition. `fallback` supplies the previous
|
|
357
|
+
* record, so a body that omits a field inherits the stored value instead of
|
|
358
|
+
* resetting it.
|
|
359
|
+
*/
|
|
360
|
+
export function userMcpConfig(name, body = {}, fallback = {}) {
|
|
361
|
+
// Only a *missing* field inherits the stored value. An explicit empty string
|
|
362
|
+
// is the user clearing the field; treating it as "keep previous" would make
|
|
363
|
+
// the editor unable to remove a callback port, scope or client id.
|
|
364
|
+
const pick = (value, previous) => (value === undefined ? previous : value)
|
|
365
|
+
// Remember every URL this server has used. A credential file is named by a
|
|
366
|
+
// hash of its URL, so once a server is edited to a new URL the old sign-in is
|
|
367
|
+
// unreachable unless its URL was recorded here.
|
|
368
|
+
const usedUrls = new Set(Array.isArray(fallback.usedUrls) ? fallback.usedUrls : [])
|
|
369
|
+
for (const candidate of [fallback.url, body.url]) {
|
|
370
|
+
if (typeof candidate === 'string' && candidate.trim()) usedUrls.add(candidate)
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
name,
|
|
374
|
+
usedUrls: [...usedUrls],
|
|
375
|
+
transport: (body.transport || fallback.transport) === 'http' ? 'http' : 'stdio',
|
|
376
|
+
url: pick(body.url, fallback.url ?? null),
|
|
377
|
+
command: pick(body.command, fallback.command ?? null),
|
|
378
|
+
args: Array.isArray(body.args) ? body.args : (fallback.args || []),
|
|
379
|
+
env: body.env && typeof body.env === 'object' ? body.env : (fallback.env || {}),
|
|
380
|
+
headers: body.headers && typeof body.headers === 'object' ? body.headers : (fallback.headers || {}),
|
|
381
|
+
oauth: body.oauth || fallback.oauth || 'none',
|
|
382
|
+
oauthClientId: pick(body.oauthClientId, fallback.oauthClientId || ''),
|
|
383
|
+
oauthCallbackPort: pick(body.oauthCallbackPort, fallback.oauthCallbackPort ?? null),
|
|
384
|
+
oauthScope: pick(body.oauthScope, fallback.oauthScope || ''),
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Rename a user-added MCP. Everything that is keyed by the server name has to
|
|
390
|
+
* move with it: the cordis registration id, the saved OAuth record (its file
|
|
391
|
+
* name is a hash of the name, so a rename without this copy would look like a
|
|
392
|
+
* fresh, unauthenticated server), and per-tool state. OAuth records are copied
|
|
393
|
+
* before the re-registration so the new registration reuses the existing
|
|
394
|
+
* sign-in instead of starting a new browser handshake.
|
|
395
|
+
*/
|
|
396
|
+
export function renameUserMcp(oldName, newName, payload) {
|
|
397
|
+
if (oldName === newName) {
|
|
398
|
+
return saveConnectorAuth('user-mcp', newName, payload)
|
|
399
|
+
}
|
|
400
|
+
const state = readState()
|
|
401
|
+
if (!Array.isArray(state.userMcps)) state.userMcps = []
|
|
402
|
+
const idx = state.userMcps.findIndex((x) => x && x.name === oldName)
|
|
403
|
+
if (idx < 0) throw new Error(`MCP 不存在:${oldName}`)
|
|
404
|
+
if (state.userMcps.some((x) => x && x.name === newName)) throw new Error(`已存在同名 MCP:${newName}`)
|
|
405
|
+
|
|
406
|
+
const saved = state.userMcps[idx]
|
|
407
|
+
// One lookup for both facts: `readCordisPatch` re-reads and re-parses the
|
|
408
|
+
// patch file on every call, and this runs inside a user-visible action.
|
|
409
|
+
const entry = getConnectorEntry('user-mcp', oldName)
|
|
410
|
+
const wasEnabled = !!entry
|
|
411
|
+
const remote = remoteConfigFromEntry(entry?.config)
|
|
412
|
+
const url = remote?.url || saved.url || payload?.url || null
|
|
413
|
+
const modes = ['auto_register', 'custom']
|
|
414
|
+
// Carry every URL this server has used, exactly as `removeUserMcp` clears
|
|
415
|
+
// them: the sign-in may belong to a URL the server has since been edited
|
|
416
|
+
// away from, and copying only the current one would strand it.
|
|
417
|
+
const urls = [...new Set([url, saved.url, ...(Array.isArray(saved.usedUrls) ? saved.usedUrls : [])]
|
|
418
|
+
.filter((u) => typeof u === 'string' && u.trim()))]
|
|
419
|
+
|
|
420
|
+
for (const source of urls) {
|
|
421
|
+
for (const mode of modes) {
|
|
422
|
+
const from = oauthCredentialKey('user-mcp', oldName, source, mode)
|
|
423
|
+
const to = oauthCredentialKey('user-mcp', newName, source, mode)
|
|
424
|
+
const record = readOAuthRecord(from)
|
|
425
|
+
if (record && Object.keys(record).length > 0) writeOAuthRecord(to, record)
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
if (wasEnabled) {
|
|
430
|
+
const clientId = url ? readSavedOAuthClient('user-mcp', newName, url, 'custom').clientId : ''
|
|
431
|
+
// `saveConnectorAuth` reports failure both by returning `{ok:false}` and by
|
|
432
|
+
// throwing (e.g. a missing OAuth client id), so the rollback lives in one
|
|
433
|
+
// place that both paths reach.
|
|
434
|
+
const rollback = () => {
|
|
435
|
+
for (const source of urls) for (const mode of modes) deleteOAuthRecord(oauthCredentialKey('user-mcp', newName, source, mode))
|
|
436
|
+
}
|
|
437
|
+
let result
|
|
438
|
+
try {
|
|
439
|
+
result = saveConnectorAuth('user-mcp', newName, {
|
|
440
|
+
...payload,
|
|
441
|
+
// A cleared field stays cleared: falling back to the stored id would put
|
|
442
|
+
// the old client back into the live registration while the definition
|
|
443
|
+
// says empty, and the next toggle would fail on the mismatch.
|
|
444
|
+
oauthClientId: payload?.oauthClientId !== undefined ? payload.oauthClientId : (clientId || ''),
|
|
445
|
+
})
|
|
446
|
+
} catch (error) {
|
|
447
|
+
// Leave the old server untouched: a failed rename must not strand the
|
|
448
|
+
// user with neither name registered.
|
|
449
|
+
rollback()
|
|
450
|
+
throw error
|
|
451
|
+
}
|
|
452
|
+
if (!result || !result.ok) {
|
|
453
|
+
rollback()
|
|
454
|
+
return result
|
|
455
|
+
}
|
|
456
|
+
// Only drop the old registration when it is a different entry. Names are
|
|
457
|
+
// normalized but ids are slugified, so `a.dot` and `a-dot` share one id —
|
|
458
|
+
// unregistering by the old name would delete the entry just written and
|
|
459
|
+
// leave the server silently disabled.
|
|
460
|
+
if (getConnectorId('user-mcp', oldName) !== getConnectorId('user-mcp', newName)) {
|
|
461
|
+
unregisterConnector('user-mcp', oldName)
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const toolsState = readMcpToolsState()
|
|
466
|
+
const oldKey = `user-mcp::${oldName}`
|
|
467
|
+
const newKey = `user-mcp::${newName}`
|
|
468
|
+
if (toolsState[oldKey] || toolsState[newKey]) {
|
|
469
|
+
const merged = { ...(toolsState[oldKey] || {}), ...(toolsState[newKey] || {}) }
|
|
470
|
+
if (Array.isArray(toolsState[oldKey]?.disabledTools)) merged.disabledTools = toolsState[oldKey].disabledTools
|
|
471
|
+
delete merged.cachedTools
|
|
472
|
+
toolsState[newKey] = merged
|
|
473
|
+
delete toolsState[oldKey]
|
|
474
|
+
writeMcpToolsState(toolsState)
|
|
475
|
+
}
|
|
476
|
+
MEMORY_TOOLS_CACHE.delete(oldKey)
|
|
477
|
+
MEMORY_TOOLS_CACHE.delete(newKey)
|
|
478
|
+
for (const source of urls) for (const mode of modes) deleteOAuthRecord(oauthCredentialKey('user-mcp', oldName, source, mode))
|
|
479
|
+
|
|
480
|
+
// Keep the whole edited form, not just the name: `/mcps/update` routes a
|
|
481
|
+
// rename here with the same body a plain save sends, so a rename that also
|
|
482
|
+
// edits command/url/args/env/headers must persist those edits — and on an
|
|
483
|
+
// enabled server the patch was already written from them, so storing the old
|
|
484
|
+
// record would silently revert the edit on the next toggle.
|
|
485
|
+
state.userMcps[idx] = userMcpConfig(newName, payload, saved)
|
|
486
|
+
writeState(state)
|
|
487
|
+
return { ok: true, name: newName, previousName: oldName }
|
|
488
|
+
}
|
|
489
|
+
|
|
313
490
|
// ── LSP server registration (cordis.patch.yml → @deepseek-ai/dsh-lsp-stdio) ──
|
|
314
491
|
//
|
|
315
492
|
// DSH exposes LSP as a capability seam with three packages:
|
package/src/oauth-store.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
2
|
import { dirname, join } from 'node:path'
|
|
3
3
|
import { execFileSync } from 'node:child_process'
|
|
4
4
|
import { randomBytes } from 'node:crypto'
|
|
@@ -84,3 +84,14 @@ export function saveOAuthClientCredentials(key, client) {
|
|
|
84
84
|
}
|
|
85
85
|
writeOAuthRecord(key, record)
|
|
86
86
|
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Delete a credential record outright. Used when the connector it belongs to is
|
|
90
|
+
* removed: leaving the file behind would resurrect a stale sign-in if a server
|
|
91
|
+
* of the same name were added again with the same URL and OAuth mode.
|
|
92
|
+
*/
|
|
93
|
+
export function deleteOAuthRecord(key) {
|
|
94
|
+
const file = oauthCredentialPath(key)
|
|
95
|
+
RECORD_CACHE.delete(file)
|
|
96
|
+
try { rmSync(file, { force: true }) } catch {}
|
|
97
|
+
}
|
package/src/routes.js
CHANGED
|
@@ -15,19 +15,20 @@ import { getOrFetchIcon, readLocalIcon } from './icons.js'
|
|
|
15
15
|
import {
|
|
16
16
|
installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered,
|
|
17
17
|
toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
|
|
18
|
-
fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, getConnectorEntry, readMcpToolsState,
|
|
18
|
+
fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
|
|
19
19
|
} from './install.js'
|
|
20
20
|
import { inspectLocalPlugin, importLocalPlugin, saveUploadedZip } from './local.js'
|
|
21
21
|
import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
|
|
22
22
|
import { remoteConfigFromEntry } from './oauth-config.js'
|
|
23
|
+
import { scheduledResult } from './runtime.js'
|
|
23
24
|
|
|
24
25
|
const API_PREFIX = '/universal-plugin-hub/api'
|
|
25
26
|
|
|
26
|
-
export function mountRoutes(webServer, skills = null) {
|
|
27
|
+
export function mountRoutes(webServer, skills = null, applyProfile = null) {
|
|
27
28
|
const r = webServer.register({
|
|
28
29
|
kind: 'prefix',
|
|
29
30
|
path: API_PREFIX,
|
|
30
|
-
handler: (req, res) => handle(req, res, API_PREFIX, skills),
|
|
31
|
+
handler: (req, res) => handle(req, res, API_PREFIX, skills, applyProfile),
|
|
31
32
|
})
|
|
32
33
|
return () => {
|
|
33
34
|
try { if (typeof r === 'function') r() } catch {}
|
|
@@ -38,23 +39,8 @@ function normalizeMcpName(value) {
|
|
|
38
39
|
return String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
|
|
39
40
|
}
|
|
40
41
|
|
|
41
|
-
function userMcpConfig(name, body) {
|
|
42
|
-
return {
|
|
43
|
-
name,
|
|
44
|
-
transport: body.transport === 'http' ? 'http' : 'stdio',
|
|
45
|
-
url: body.url || null,
|
|
46
|
-
command: body.command || null,
|
|
47
|
-
args: Array.isArray(body.args) ? body.args : [],
|
|
48
|
-
env: body.env && typeof body.env === 'object' ? body.env : {},
|
|
49
|
-
headers: body.headers && typeof body.headers === 'object' ? body.headers : {},
|
|
50
|
-
oauth: body.oauth || 'none',
|
|
51
|
-
oauthClientId: body.oauthClientId || '',
|
|
52
|
-
oauthCallbackPort: body.oauthCallbackPort || null,
|
|
53
|
-
oauthScope: body.oauthScope || '',
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
42
|
|
|
57
|
-
async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
43
|
+
async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile = null) {
|
|
58
44
|
const url = new URL(req.url, 'http://localhost')
|
|
59
45
|
const path = url.pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
|
|
60
46
|
const method = req.method ?? 'GET'
|
|
@@ -119,6 +105,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
119
105
|
})
|
|
120
106
|
}
|
|
121
107
|
|
|
108
|
+
// The runtime outcome of the last saved change. It is intentionally a
|
|
109
|
+
// separate read: applying a change can restart this plugin, so the write
|
|
110
|
+
// answers immediately and the result arrives here.
|
|
111
|
+
if (method === 'GET' && path === '/apply-status') {
|
|
112
|
+
const token = Number(url.searchParams.get('token'))
|
|
113
|
+
return sendJson(res, 200, {
|
|
114
|
+
ok: true,
|
|
115
|
+
...(typeof applyProfile?.status === 'function'
|
|
116
|
+
? applyProfile.status(Number.isFinite(token) ? token : undefined)
|
|
117
|
+
: { application: 'unknown' }),
|
|
118
|
+
})
|
|
119
|
+
}
|
|
120
|
+
|
|
122
121
|
if (path === '/skills' && method === 'GET' && skills) return sendJson(res, 200, { skills: await skills.list() })
|
|
123
122
|
if (path === '/skills/refresh' && method === 'POST' && skills) {
|
|
124
123
|
requireSameOrigin(req); skills.refresh()
|
|
@@ -323,7 +322,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
323
322
|
for (const block of patch) {
|
|
324
323
|
if (!block || !Array.isArray(block.insert)) continue
|
|
325
324
|
for (const item of block.insert) {
|
|
326
|
-
if (!item || typeof item.id !== 'string' || !item.id.startsWith('
|
|
325
|
+
if (!item || typeof item.id !== 'string' || !item.id.startsWith(getConnectorId('user-mcp', ''))) continue
|
|
327
326
|
const cfg = item.config || {}
|
|
328
327
|
if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
|
|
329
328
|
state.userMcps.push(userMcpConfig(cfg.serverName, {
|
|
@@ -342,15 +341,22 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
342
341
|
const entry = getConnectorEntry('user-mcp', x.name)
|
|
343
342
|
const remote = remoteConfigFromEntry(entry?.config) || readMcpToolsState()[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
|
|
344
343
|
const client = remote?.oauth === 'custom' ? readSavedOAuthClient('user-mcp', x.name, remote.url, remote.oauth) : null
|
|
344
|
+
// The live registration says what is *running*; the saved definition
|
|
345
|
+
// says what the editor should show. The client id comes from the
|
|
346
|
+
// credential record, since the definition never stores the secret.
|
|
345
347
|
return {
|
|
346
348
|
...x,
|
|
347
349
|
...(remote ? {
|
|
348
350
|
transport: 'http', url: remote.url, headers: remote.headers,
|
|
349
|
-
oauth: remote.oauth,
|
|
351
|
+
oauth: remote.oauth,
|
|
352
|
+
oauthClientId: client?.clientId || x.oauthClientId || remote.oauthClientId,
|
|
350
353
|
oauthHasClientSecret: client?.hasClientSecret || false,
|
|
351
|
-
|
|
354
|
+
// Fall back to the live config only when the definition has no
|
|
355
|
+
// opinion, so a cleared field stays cleared.
|
|
356
|
+
oauthCallbackPort: x.oauthCallbackPort ?? remote.oauthCallbackPort ?? null,
|
|
357
|
+
oauthScope: x.oauthScope ?? remote.oauthScope ?? '',
|
|
352
358
|
} : {}),
|
|
353
|
-
enabled: enabledIds.has('
|
|
359
|
+
enabled: enabledIds.has(getConnectorId('user-mcp', x.name)),
|
|
354
360
|
}
|
|
355
361
|
})
|
|
356
362
|
return sendJson(res, 200, { ok: true, mcps })
|
|
@@ -383,26 +389,63 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
383
389
|
state.userMcps.push(userMcpConfig(name, body))
|
|
384
390
|
writeState(state)
|
|
385
391
|
}
|
|
386
|
-
|
|
392
|
+
// A rejected create registered nothing, so there is nothing to apply.
|
|
393
|
+
if (!result || !result.ok) return sendJson(res, 200, result)
|
|
394
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
|
|
387
395
|
}
|
|
388
396
|
|
|
389
397
|
if (method === 'POST' && path === '/mcps/update') {
|
|
390
398
|
requireSameOrigin(req)
|
|
391
399
|
const body = await readJsonBody(req)
|
|
400
|
+
// `previousName` is only sent when the user renamed the server in the
|
|
401
|
+
// editor; without it the name in the body is also the stored one.
|
|
402
|
+
const previousName = body.previousName
|
|
403
|
+
? safeSegment(normalizeMcpName(body.previousName), 'MCP 名称')
|
|
404
|
+
: null
|
|
392
405
|
const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
|
|
393
406
|
const state = readState()
|
|
394
407
|
if (!Array.isArray(state.userMcps)) state.userMcps = []
|
|
395
|
-
const idx = state.userMcps.findIndex((x) => x && x.name === name)
|
|
396
|
-
if (idx < 0) throw new Error(`MCP 不存在:${name}`)
|
|
408
|
+
const idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
|
|
409
|
+
if (idx < 0) throw new Error(`MCP 不存在:${previousName || name}`)
|
|
410
|
+
if (previousName && previousName !== name) {
|
|
411
|
+
// Capture enablement before the rename: a disabled server registers
|
|
412
|
+
// nothing, so asking HMR to start its id would target an entry that
|
|
413
|
+
// does not exist.
|
|
414
|
+
const renamingEnabled = !!getConnectorEntry('user-mcp', previousName)
|
|
415
|
+
const renamed = renameUserMcp(previousName, name, body)
|
|
416
|
+
// A rename that failed registered nothing, so there is nothing to apply.
|
|
417
|
+
if (!renamed || !renamed.ok) return sendJson(res, 200, renamed)
|
|
418
|
+
return sendJson(res, 200, scheduledResult(
|
|
419
|
+
renamed, applyProfile, renamingEnabled ? [getConnectorId('user-mcp', name)] : []))
|
|
420
|
+
}
|
|
397
421
|
const wasEnabled = !!getConnectorEntry('user-mcp', name)
|
|
398
422
|
let result = { ok: true }
|
|
399
423
|
if (wasEnabled) {
|
|
400
424
|
result = saveConnectorAuth('user-mcp', name, body)
|
|
401
425
|
if (!result || !result.ok) return sendJson(res, 200, result)
|
|
402
426
|
}
|
|
403
|
-
|
|
427
|
+
// Pass the stored record so an edit keeps the URL history a later delete
|
|
428
|
+
// needs to find every credential this server ever issued.
|
|
429
|
+
state.userMcps[idx] = userMcpConfig(name, body, state.userMcps[idx])
|
|
404
430
|
writeState(state)
|
|
405
|
-
return sendJson(res, 200, result)
|
|
431
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile, wasEnabled ? [getConnectorId('user-mcp', name)] : []))
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// One segment only: `/mcps/<name>/tools` belongs to the tool routes below.
|
|
435
|
+
// Decode and validate before the single-segment test, or an encoded slash
|
|
436
|
+
// slips past it; and reject a name that normalizes to nothing rather than
|
|
437
|
+
// falling back to the literal "mcp", which could match a real server.
|
|
438
|
+
if (method === 'DELETE' && path.startsWith('/mcps/')) {
|
|
439
|
+
// Check segments *after* decoding: `prod%2Fdb` decodes to a two-segment
|
|
440
|
+
// path and must not fall through to the server named `prod-db`.
|
|
441
|
+
const decoded = decodeURIComponent(path.slice('/mcps/'.length))
|
|
442
|
+
if (decoded.includes('/')) return sendJson(res, 404, { error: 'not found' })
|
|
443
|
+
requireSameOrigin(req)
|
|
444
|
+
const normalized = String(decoded || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '')
|
|
445
|
+
if (!normalized) throw new Error('无效的 MCP 名称')
|
|
446
|
+
const name = safeSegment(normalized, 'MCP 名称')
|
|
447
|
+
const result = removeUserMcp(name)
|
|
448
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile))
|
|
406
449
|
}
|
|
407
450
|
|
|
408
451
|
if (method === 'POST' && path === '/mcps/toggle') {
|
|
@@ -414,10 +457,12 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
414
457
|
if (!cfg) throw new Error(`MCP 不存在:${name}`)
|
|
415
458
|
if (body.enabled !== false) {
|
|
416
459
|
const result = saveConnectorAuth('user-mcp', name, cfg)
|
|
417
|
-
|
|
460
|
+
// A rejected enable registered nothing: do not schedule a reconcile.
|
|
461
|
+
if (!result || !result.ok) return sendJson(res, 200, result)
|
|
462
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
|
|
418
463
|
}
|
|
419
464
|
unregisterConnector('user-mcp', name)
|
|
420
|
-
return sendJson(res, 200, { ok: true })
|
|
465
|
+
return sendJson(res, 200, scheduledResult({ ok: true }, applyProfile))
|
|
421
466
|
}
|
|
422
467
|
|
|
423
468
|
// ── user MCP tool list / per-tool toggle (same shape as plugin connectors) ──
|
|
@@ -476,7 +521,9 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
476
521
|
const connectorName = safeSegment(parts[2], 'connector name')
|
|
477
522
|
const body = await readJsonBody(req)
|
|
478
523
|
const result = toggleConnector(pluginName, connectorName, body.enabled !== false)
|
|
479
|
-
|
|
524
|
+
// A rejected toggle registered nothing: do not schedule a reconcile.
|
|
525
|
+
if (!result || !result.ok) return sendJson(res, 200, result)
|
|
526
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
|
|
480
527
|
}
|
|
481
528
|
|
|
482
529
|
if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/verify')) {
|
|
@@ -496,7 +543,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
496
543
|
const connectorName = safeSegment(parts[2], 'connector name')
|
|
497
544
|
const body = await readJsonBody(req)
|
|
498
545
|
const result = saveConnectorAuth(pluginName, connectorName, body)
|
|
499
|
-
return sendJson(res, 200, result)
|
|
546
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId(pluginName, connectorName)]))
|
|
500
547
|
}
|
|
501
548
|
|
|
502
549
|
// ── plugin detail ────────────────────────────────────────────────────
|
|
@@ -572,14 +619,14 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
572
619
|
pluginName,
|
|
573
620
|
})
|
|
574
621
|
invalidateMarketplaceCache(sourceId)
|
|
575
|
-
return sendJson(res, 200, result)
|
|
622
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile))
|
|
576
623
|
}
|
|
577
624
|
|
|
578
625
|
if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/toggle')) {
|
|
579
626
|
requireSameOrigin(req)
|
|
580
627
|
const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
|
|
581
628
|
const body = await readJsonBody(req)
|
|
582
|
-
return sendJson(res, 200, await togglePlugin(pluginName, body.enabled === true))
|
|
629
|
+
return sendJson(res, 200, scheduledResult(await togglePlugin(pluginName, body.enabled === true), applyProfile))
|
|
583
630
|
}
|
|
584
631
|
|
|
585
632
|
if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
|
|
@@ -587,7 +634,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
587
634
|
const pluginName = safeSegment(path.slice('/plugins/'.length, -'/update'.length), 'plugin name')
|
|
588
635
|
const result = await updatePlugin(pluginName)
|
|
589
636
|
invalidateMarketplaceCache()
|
|
590
|
-
return sendJson(res, 200, result)
|
|
637
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile))
|
|
591
638
|
}
|
|
592
639
|
|
|
593
640
|
if (method === 'POST' && path === '/restart') {
|
|
@@ -630,7 +677,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
|
630
677
|
const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
|
|
631
678
|
const result = uninstallPlugin(pluginName)
|
|
632
679
|
invalidateMarketplaceCache()
|
|
633
|
-
return sendJson(res, 200, result)
|
|
680
|
+
return sendJson(res, 200, scheduledResult(result, applyProfile))
|
|
634
681
|
}
|
|
635
682
|
|
|
636
683
|
return sendJson(res, 404, { error: 'not found' })
|
package/src/runtime.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apply saved hub changes to the running DSH profile.
|
|
3
|
+
*
|
|
4
|
+
* Writing cordis.patch.yml is persistence, not activation. The host owns the
|
|
5
|
+
* loader lifecycle, so new plugin/MCP entries go through its HMR service rather
|
|
6
|
+
* than a second connection layer or a process restart.
|
|
7
|
+
*
|
|
8
|
+
* Two constraints shape this module:
|
|
9
|
+
*
|
|
10
|
+
* 1. The application runs *after* the HTTP response. The hub loads from a
|
|
11
|
+
* linked directory, so a reconciliation may stop and restart the hub fiber;
|
|
12
|
+
* awaiting that inside a request the hub is serving would leave the response
|
|
13
|
+
* waiting on its own plugin being torn down.
|
|
14
|
+
* 2. A restart rebuilds the applicator, and with it the status. So the status
|
|
15
|
+
* is seeded from a token the client was already given: after a restart the
|
|
16
|
+
* new instance answers `applied` for that token instead of `idle`, and the
|
|
17
|
+
* poll converges instead of spinning out its window.
|
|
18
|
+
*
|
|
19
|
+
* Every outcome carries the token it belongs to, so a poll for change A can
|
|
20
|
+
* never read the result of change B.
|
|
21
|
+
*/
|
|
22
|
+
export function createProfileApplicator(ctx) {
|
|
23
|
+
let queue = Promise.resolve()
|
|
24
|
+
let seq = 0
|
|
25
|
+
// Tokens that survived this process. A restarted fiber starts empty, so the
|
|
26
|
+
// first token it mints continues from the highest one the host handed out.
|
|
27
|
+
let last = Object.freeze({ application: 'idle', token: 0 })
|
|
28
|
+
let queued = null
|
|
29
|
+
|
|
30
|
+
// A reconciliation the host never settles would pin the status at `pending`
|
|
31
|
+
// and retain every closure queued behind it. Bound it: a timeout is reported
|
|
32
|
+
// as a failure the client can act on, and the queue moves on.
|
|
33
|
+
const RECONCILE_TIMEOUT_MS = 60_000
|
|
34
|
+
|
|
35
|
+
function applyProfile(requiredIds = []) {
|
|
36
|
+
const token = ++seq
|
|
37
|
+
last = Object.freeze({ application: 'pending', token })
|
|
38
|
+
// A change arriving while the queued reconciliation has not started yet is
|
|
39
|
+
// folded into it: one reconcile covers both, instead of restarting the hub
|
|
40
|
+
// once per rapid save. Its required ids join the same set.
|
|
41
|
+
if (queued && !queued.started) {
|
|
42
|
+
queued.token = token
|
|
43
|
+
queued.ids.push(...requiredIds)
|
|
44
|
+
// `done` must resolve with *this* change's token, not the token the run
|
|
45
|
+
// started with: report the caller's own identity.
|
|
46
|
+
const done = queued.run.then((outcome) => ({ ...outcome, token }))
|
|
47
|
+
done.then((outcome) => {
|
|
48
|
+
if (token === seq) last = Object.freeze({ ...outcome, at: Date.now() })
|
|
49
|
+
}, () => {})
|
|
50
|
+
return { token, done }
|
|
51
|
+
}
|
|
52
|
+
const pending = { started: false, token, ids: [...requiredIds], run: null }
|
|
53
|
+
queued = pending
|
|
54
|
+
const run = pending.run = queue.then(async () => {
|
|
55
|
+
pending.started = true
|
|
56
|
+
const ids = [...new Set(pending.ids)]
|
|
57
|
+
try {
|
|
58
|
+
// Resolve inside the try: a throwing service lookup must become a
|
|
59
|
+
// reported failure, not a rejection that strands the status.
|
|
60
|
+
const hmr = ctx?.root?.get?.('hmr') || ctx?.get?.('hmr')
|
|
61
|
+
if (!hmr || typeof hmr.reconcileProfile !== 'function') {
|
|
62
|
+
return { application: 'restart-required', restartReason: 'no-hmr', token: pending.token }
|
|
63
|
+
}
|
|
64
|
+
const reconcile = () => hmr.reconcileProfile(ids)
|
|
65
|
+
let timer
|
|
66
|
+
const timeout = new Promise((_, reject) => {
|
|
67
|
+
timer = setTimeout(() => reject(new Error(`reconcileProfile did not settle within ${RECONCILE_TIMEOUT_MS}ms`)), RECONCILE_TIMEOUT_MS)
|
|
68
|
+
timer.unref?.()
|
|
69
|
+
})
|
|
70
|
+
const result = await Promise.race([
|
|
71
|
+
typeof hmr.runExclusive === 'function' ? hmr.runExclusive(reconcile) : reconcile(),
|
|
72
|
+
timeout,
|
|
73
|
+
]).finally(() => clearTimeout(timer))
|
|
74
|
+
// `reconcileProfile` reports a restart need either profile-wide or per
|
|
75
|
+
// pending module; either one means the change is not live yet.
|
|
76
|
+
const restartReason = result?.restartReason
|
|
77
|
+
|| (Array.isArray(result?.pending) && result.pending.length ? result.pending[0]?.reason : undefined)
|
|
78
|
+
return {
|
|
79
|
+
application: restartReason ? 'restart-required' : 'applied',
|
|
80
|
+
token: pending.token,
|
|
81
|
+
...(restartReason ? { restartReason } : {}),
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
// The saved change is still valid. Report that it is not live instead
|
|
85
|
+
// of turning a successful install into a misleading "install failed".
|
|
86
|
+
return {
|
|
87
|
+
application: 'failed',
|
|
88
|
+
token: pending.token,
|
|
89
|
+
applicationError: error instanceof Error ? error.message : String(error),
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
})
|
|
93
|
+
// One failed application must not poison later, independent changes.
|
|
94
|
+
queue = run.then(() => {}, () => {})
|
|
95
|
+
run.then((outcome) => {
|
|
96
|
+
// Only the newest change owns the status; an older, slower one must not
|
|
97
|
+
// overwrite a newer result a poll is already waiting on.
|
|
98
|
+
if (token === seq) last = Object.freeze({ ...outcome, at: Date.now() })
|
|
99
|
+
}, () => {})
|
|
100
|
+
return { token, done: run }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// A poll for a token this instance has not issued means the change was
|
|
104
|
+
// applied by a previous fiber that the reconciliation restarted — which is
|
|
105
|
+
// the success path for a linked plugin, not a superseded change.
|
|
106
|
+
applyProfile.status = (token) => {
|
|
107
|
+
if (typeof token === 'number' && token > seq) {
|
|
108
|
+
return Object.freeze({ application: 'applied', token: APPLIED_TOKEN })
|
|
109
|
+
}
|
|
110
|
+
return last
|
|
111
|
+
}
|
|
112
|
+
return applyProfile
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Status served to a poll whose token predates this (restarted) instance. */
|
|
116
|
+
export const APPLIED_TOKEN = -1
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Persist first, apply in the background. The response reports `scheduled`
|
|
120
|
+
* plus the token the client polls with; the outcome arrives through
|
|
121
|
+
* `status()`.
|
|
122
|
+
*/
|
|
123
|
+
export function scheduledResult(result, applyProfile, requiredIds = []) {
|
|
124
|
+
if (typeof applyProfile !== 'function') return result
|
|
125
|
+
// Never await: a reconciliation can stop this very plugin. A fault while
|
|
126
|
+
// enqueueing must not turn a persisted change into an error response.
|
|
127
|
+
let token
|
|
128
|
+
try {
|
|
129
|
+
token = applyProfile(requiredIds).token
|
|
130
|
+
} catch (error) {
|
|
131
|
+
return { ...result, application: 'failed', applicationError: error instanceof Error ? error.message : String(error) }
|
|
132
|
+
}
|
|
133
|
+
return { ...result, application: 'scheduled', applicationToken: token }
|
|
134
|
+
}
|