// Library: one set of instructions, MCP servers and skills, written into
// every agent that should have them (#29). magpie keeps the library in its
// own folder and writes each agent's files from it; what the user has in
// those files besides stays theirs, and every file is kept aside before
// magpie writes it. Everything shown here comes from /api/library.
//
// A page the Library plugin adds to the window (kernel.js): mount wires it
// up, open and relang read the library again, redraw draws it again as it
// is, and close, dirty and discard are what app.js asks of it before the
// reader leaves it.
magpie.plugin("library", (ctx) => {
let page = null;
let loading = null; // the read open started, which server waits for
let lib = null; // the page, as /api/library gives it
let taken = 0; // how many times lib was set, for a read to tell a newer answer came first
let tab = "instructions";
let shown = ""; // the tab the page last drew, which fades in only when it changes
let fits = []; // textareas to fit before the page is painted
try { tab = localStorage.getItem("magpie.libTab") || tab; } catch {}
const texts = {}; // set → its shared instructions as typed, while not saved
let openSet = null; // the set of instructions opened to edit
let addingSet = false; // a new set being named
let removingSet = null; // a set whose Remove was clicked once
const extras = {}; // agent → its own additions as typed, while not saved
const open = new Set(); // agents whose instructions row is open
let probe = null; // skills found at a source: { source, candidates, pick:Set, agents:Set }
let probing = false;
let checking = false; // asking GitHub which skills it has changed
let autoChecked = false; // the page checked by itself, as the server said it was due (#1449)
let updatingAll = false; // Update all, picked from the bar's menu
let regrouping = false; // the skills' repositories fetched to group them again
let modal = null; // what the library has open in the dialog
const hid = new Set(); // the write failures the reader hid, by agent and what (#3745)
const GLYPH = {
cmd: "M3 4.5h10v7H3z M5.5 7l1.5 1.2-1.5 1.3 M8.5 9.5h2",
web: "M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11z M2.5 8h11 M8 2.5c1.6 1.7 2.3 3.5 2.3 5.5S9.6 11.8 8 13.5 M8 2.5C6.4 4.2 5.7 6 5.7 8s.7 3.8 2.3 5.5",
skill: "M4 2.5h6.5L12 4v9.5H4z M6 6h4 M6 8.5h4 M6 11h2.5",
doc: "M4 2.5h5.5L12 5v8.5H4z M9.5 2.5V5H12",
folder: "M2.5 4.5h4l1.2 1.3h5.8v6.7h-11z",
up: "M8 12.5v-9 M4.5 7 8 3.5 11.5 7",
down: "M8 3.5v9 M4.5 9 8 12.5 11.5 9",
trash: "M3.5 4.5h9 M6.5 4.5V3h3v1.5 M4.5 4.5l.6 8.5h5.8l.6-8.5",
search: "M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M10 10l3 3",
out: "M9.5 3.5h3v3 M12.5 3.5 7.5 8.5 M11 9.5v3H3.5V5h3",
key: "M10 2.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4z M7.8 8.2 3 13 M4.5 11.5 6 13",
person: "M8 3a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z M3.5 13.5c.6-2.4 2.3-3.6 4.5-3.6s3.9 1.2 4.5 3.6",
back: "m9.5 4.5-3 3.5 3 3.5",
hook: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9",
// a person with a second, smaller one it hands work to
subagent: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4",
// a clock with an arrow going back round it, as macOS draws backups
backup: "M3.2 8a4.8 4.8 0 1 0 1.4-3.4 M2.8 2.6v2.4h2.4 M8 5.3V8l1.9 1.2",
power: "M8 2.5v5 M4.7 4.6a4.8 4.8 0 1 0 6.6 0",
};
const tilde = (p) => (lib?.home && p?.startsWith(lib.home) ? "~" + p.slice(lib.home.length) : p || "");
const agentOf = (id) => lib.agents.find((a) => a.id === id);
const nameOf = (id) => agentOf(id)?.name || id;
// An agent with no MCP of its own (Pi) reads its servers through an
// extension, which each of its chips says.
// An agent hidden on the Agents page is left out here too (#71): what it
// already has stays with it, and a new server or skill isn't given to it.
// One gone from this computer (gone: uninstalled, or its CLI) is listed
// only on the rows of what it still has (withGone), for that to be taken
// out: an agent that isn't installed was on every row (@jiahao_jayden).
// An agent in a stopped WSL distro (asleep) is listed by what magpie last
// knew of it, its ticks kept for when the distro next runs; one whose
// places magpie never saw (unseen) only on the rows that name it, like
// a gone one, its chip greyed out: opening its files would start WSL
// (#3896, cybercaius on Discord).
// In gateway mode (gatewaymode.go) none is shown: the page is the
// MCP servers the router gives other computers' apps.
const shownAgents = () => gatewayPage() ? [] : lib.agents.filter((a) => !a.gone && !a.unseen && !isHidden(a));
// With no agent to write to, none on this computer or gateway mode, the
// library is its MCP servers alone, served to any app through the router
// (treeman_26897 on Discord: magpie on a server, an MCP entry point for
// remote clients, had no way to turn the router on).
const gatewayPage = () => typeof gatewayMode !== "undefined" && !!gatewayMode;
const agentless = () => !!lib && (gatewayPage() || !lib.agents.length);
const withGone = (all, on) => [...all, ...lib.agents.filter((a) => (a.gone || a.unseen && !isHidden(a)) && (on || []).includes(a.id) && !all.some((x) => x.id === a.id))];
const mcpAgents = () => shownAgents().filter((a) => a.mcp)
.map((a) => a.mcpVia ? { ...a, aside: t("{agent} reads MCP servers through the {ext} extension", { agent: a.name, ext: a.mcpVia }) } : a);
const skillAgents = () => shownAgents().filter((a) => a.skills);
// the MCP hub's agents: not a stopped distro's, whose files say what it
// has of the hub, and can't be read without starting it
const hubAgents = () => mcpAgents().filter((a) => !a.asleep);
// one line for each stopped WSL distro the page lists agents of: they
// show what magpie last saw, and a change waits for the distro to run.
// The Instructions page passes its own rows' agents ({asleep, unseen,
// name}).
function asleepAsides(seen = lib.agents.filter((a) => a.asleep && !isHidden(a))) {
return [...new Set(seen.map((a) => a.asleep))].map((d) => {
const unseen = seen.filter((a) => a.asleep === d && a.unseen).map((a) => a.name);
const p = el("p", "lib-aside lib-asleep", t("WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.", { distro: d }));
if (unseen.length) p.append(" " + t("{agents} can be changed once it runs.", { agents: unseen.join(", ") }));
p.dataset.distro = d;
return p;
});
}
// the hub's mark: magpie's bird, the one server each agent is given,
// its tail three lines out to three servers (the owner's pick, 10-31)
function hubMark() {
const g = el("span", "lib-glyph lib-hubmark");
g.innerHTML = '';
return g;
}
function glyph(d, cls = "lib-glyph") {
const g = el("span", cls);
g.append(svg(d, 16, 1.3));
return g;
}
// A row's mark: the thing's own icon where the market knows it, else a
// glyph for what it is — never a made-up picture.
function mark(url, d) {
if (!url) return glyph(d);
const box = logo(url, "");
box.classList.add("lib-logo");
box.querySelector("img").onerror = () => box.replaceWith(glyph(d));
return box;
}
function button(text, cls, onclick) {
const b = el("button", "text " + (cls || ""), text);
b.onclick = (e) => { e.stopPropagation(); onclick(e, b); };
return b;
}
// a path shown on the page: a click shows it in the file manager
function pathLink(p) {
const b = el("button", "lib-path", tilde(p));
b.title = t("Show in {fm}", { fm: fileManager() });
b.onclick = (e) => { e.stopPropagation(); reveal(p); };
return b;
}
function fileManager() { return /^Mac/.test(navigator.platform) ? "Finder" : /^Win/.test(navigator.platform) ? "Explorer" : t("the file manager"); }
// the app's webview opens no new windows: a link goes to the system browser
function browse(u) { api("open", { url: u }).catch((e) => status(e.message, "err")); }
function reveal(p) { api("library/reveal", { path: p }).catch((e) => status(e.message, "err")); }
const bridgedWhy = () => t("Added from a Remote magpie with this computer's key for it, so it stays on this computer");
// A switch: on or off, nothing between.
function toggle(on, label, onChange) {
const s = el("button", "lib-switch" + (on ? " on" : ""));
s.setAttribute("role", "switch");
s.setAttribute("aria-checked", on ? "true" : "false");
s.setAttribute("aria-label", label);
s.append(el("i"));
s.onclick = (e) => { e.stopPropagation(); onChange(!on); };
return s;
}
// An agent's icon, made once and copied: a list of hundreds of skills has
// a chip for each agent on every row, and making each icon afresh (its
// image, and a probe of whether it loads) was most of drawing the list.
// One whose picture didn't load is let go, so the next row makes it
// afresh: kept, its copies would all be empty until the page was loaded
// again (as Claude Code's were seen to, in the skills list).
// It's made apart from the Providers page's kept icons, which are its
// own rows' to take back.
const icons = new Map();
function agentIcon(name) {
let i = icons.get(name);
if (!i) {
const kept = keptIcons;
keptIcons = null;
try { i = icon(name); } finally { keptIcons = kept; }
icons.set(name, i);
const im = i.querySelector(":scope > img");
if (im) im.onerror = () => { if (icons.get(name) === i) icons.delete(name); };
greyIcon(i);
}
return i.cloneNode(true);
}
// A copy already drawn whose picture failed asks for it again, a few
// times and a little later each time; the grey copy is left to the filter.
document.addEventListener("error", (e) => {
const im = e.target;
if (im.tagName !== "IMG" || im.classList.contains("grey") || !im.parentElement?.classList.contains("ic") || !im.closest("#view-library, #modal.lib")) return;
const n = +(im.dataset.tries || 0);
if (n >= 3) return;
im.dataset.tries = n + 1;
setTimeout(() => { if (im.isConnected) im.src = srcOf(im) + "?try=" + (n + 1); }, 400 * (n + 1));
}, true);
const srcOf = (im) => (im.getAttribute("src") || "").split("?")[0];
// A chip's icon is grey while its agent hasn't the item. A filter made it
// so on every paint of every chip — most of what a scroll through
// hundreds of skills painted — so it's made grey once instead: a picture
// gets a grey copy (by the filter's own sum), which stands in for
// it once ready, and an icon drawn in the text's colour takes that colour
// grey (library.css). Until then, or if it can't be, the filter does it.
function greyIcon(i) {
if (i.querySelector(":scope > .mask, :scope > svg")) { i.classList.add("flat"); return; }
const src = i.querySelector(":scope > img") && srcOf(i.querySelector(":scope > img"));
if (!src) return;
greyCopy(src).then((url) => {
if (!url) return;
const add = (ic) => {
if (ic.classList.contains("baked")) return;
const g = el("img", "grey");
g.src = url;
g.alt = "";
g.draggable = false;
ic.append(g);
ic.classList.add("baked");
};
add(i);
for (const x of document.querySelectorAll(".lib-ag > .ic:not(.baked) > img")) if (srcOf(x) === src) add(x.parentElement);
}, () => {});
}
// grayscale(1)'s own sum: each colour's red, green and blue become this
const lum = (r, g, b) => Math.round(r * .2126 + g * .7152 + b * .0722);
let tint;
function greyColour(v) {
tint ||= document.createElement("canvas").getContext("2d");
// a colour in any spelling, read back as #rrggbb or rgba(…); anything
// else (none, url(#…), currentColor) is left as it is
if (/^\s*(none|currentcolor|inherit|transparent|url\()/i.test(v)) return v;
tint.fillStyle = "#010203";
tint.fillStyle = v;
const c = tint.fillStyle;
let m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(c);
if (m) {
if (c === "#010203" && !/010203/.test(v)) return v;
const y = lum(parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)).toString(16).padStart(2, "0");
return "#" + y + y + y;
}
m = /^rgba?\(\s*([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\s*\)$/.exec(c);
if (!m) return v;
const y = lum(+m[1], +m[2], +m[3]);
return `rgba(${y}, ${y}, ${y}, ${m[4] ?? 1})`;
}
async function greyCopy(src) {
const r = await fetch(src);
if (!r.ok) return null;
let blob;
if (/svg/.test(r.headers.get("content-type") || "") || /\.svg$/.test(src)) {
// the drawing with each of its colours made grey — the same as the
// filter, which is a sum over each colour (blending and gradients
// mix colours in sRGB, as the filter does, so they come out the same)
// and drawn as sharp as the drawing itself
// (a name inside another, as data-fill, is left: checked by hand, as a
// lookbehind in the pattern is a syntax error before Safari 16.4, #220)
const inWord = (s, at) => /[\w-]/.test(s[at - 1] || "");
const s = (await r.text()).replace(/(fill|stroke|stop-color|flood-color|lighting-color|color)(\s*=\s*)(["'])([^"']*)\3/g, (all, k, eq, q, v, at, s) => inWord(s, at) ? all : k + eq + q + greyColour(v) + q)
.replace(/(fill|stroke|stop-color|flood-color|lighting-color|color)(\s*:\s*)([^;"'}]+)/g, (all, k, eq, v, at, s) => inWord(s, at) ? all : k + eq + greyColour(v));
if (/<(image|feColorMatrix|feComponentTransfer|feTurbulence)\b/.test(s)) return null; // a colour the sum can't reach
blob = new Blob([s], { type: "image/svg+xml" });
} else {
// a picture made grey pixel by pixel
const im = new Image();
im.src = URL.createObjectURL(await r.blob());
await im.decode();
const c = document.createElement("canvas");
c.width = im.naturalWidth;
c.height = im.naturalHeight;
const x = c.getContext("2d");
x.drawImage(im, 0, 0);
URL.revokeObjectURL(im.src);
const d = x.getImageData(0, 0, c.width, c.height), p = d.data;
for (let k = 0; k < p.length; k += 4) p[k] = p[k + 1] = p[k + 2] = p[k] * .2126 + p[k + 1] * .7152 + p[k + 2] * .0722;
x.putImageData(d, 0, 0);
blob = await new Promise((done) => c.toBlob(done));
if (!blob) return null;
}
const url = URL.createObjectURL(blob);
const t = new Image();
t.src = url;
await t.decode(); // ready before it stands in, so nothing blinks
return url;
}
// Agent chips for a server or a skill: each agent that could have it, lit
// when it does. A chip whose agent couldn't be given it says why. One that
// has it whatever is ticked (opts.always: a skill kept in ~/.agents/skills,
// which the agent reads itself, #595) is lit, can't be clicked, and says
// why; it is left out of what a click sends, and keeps what it had.
function agentChips(all, on, onChange, opts = {}) {
on ||= [];
const box = el("div", "lib-agents");
box.style.setProperty("--lib-agent-count", all.length);
// the row it is put in says so (.with-agents), for its name's room:
// Safari before 15.4 has no :has(). Every caller appends it at once.
queueMicrotask(() => box.parentElement?.classList.contains("lib-row") && box.parentElement.classList.add("with-agents"));
for (const [i, a] of all.entries()) {
const always = opts.always?.(a) || "";
const has = on.includes(a.id) || !!always;
const c = el("button", "lib-ag" + (has ? " on" : "") + (always ? " always" : ""));
c.dataset.agent = a.id;
// how many chips are to its right, how far it slides into the hand
c.style.setProperty("--k", all.length - 1 - i);
c.append(agentIcon(a.icon));
if (opts.names) c.append(el("span", "n", a.name));
const problem = !always && opts.problems?.[a.id];
const blocked = always || opts.blocked?.(a);
const via = !has && opts.via?.(a);
let tip = has ? t("{agent} has it — click to take it away", { agent: a.name }) : t("Give it to {agent}", { agent: a.name });
if (via) { c.classList.add("via"); tip = t("{agent} reads it through {other} — click to give it its own", { agent: a.name, other: via }); }
if (problem) { c.classList.add("warn"); tip = a.name + ": " + problem; }
// not disabled: a disabled button tells nothing on a click, and
// WebKit shows it no tooltip either — 蓝猫 clicked Claude Desktop's
// grey chip for a remote server and nothing said why
if (blocked) { c.classList.add("blocked"); c.setAttribute("aria-disabled", "true"); tip = blocked; }
if (a.gone) { c.classList.add("gone"); tip = t("{agent} isn't installed here — click to take it away", { agent: a.name }); }
if (a.unseen) { c.classList.add("asleep", "unseen", "blocked"); c.setAttribute("aria-disabled", "true"); tip = t("WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this", { distro: a.asleep, agent: a.name }); }
else if (a.asleep) {
c.classList.add("asleep");
const v = { distro: a.asleep, agent: a.name };
if (!problem && !blocked) tip = has ? t("WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs", v) : t("WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs", v);
}
c.title = a.aside && !problem && !blocked ? tip + "\n" + a.aside : tip;
c.setAttribute("aria-pressed", has ? "true" : "false");
// What's lit is read off the chips clicked, not the list they were
// drawn with: a row's chips change in place, several clicks before
// magpie has answered the first, and take on the handlers of chips
// drawn for them (morphChips). An agent not shown keeps what it has.
c.onclick = (e) => {
e.stopPropagation();
const me = e.currentTarget;
if (cannot(me)) { status(me.title, "warn", 8000); return; }
const lit = litOf(me.parentElement);
const kept = keptOf(me.parentElement, all, on);
onChange([...kept, ...(lit.includes(a.id) ? lit.filter((x) => x !== a.id) : [...lit, a.id])], me);
};
box.append(c);
}
if (opts.all) allChip(box, all, on, onChange);
return box;
}
// cannot says a chip's agent can't be given the item, or has it whatever
// is ticked: a click says why rather than switching it
const cannot = (c) => c.getAttribute("aria-disabled") === "true";
// The agents a row's chips have lit by a click: not one lit because it
// has the item whatever is ticked.
function litOf(box) {
return [...box.children].filter((x) => x.dataset.agent && !x.classList.contains("always") && !x.classList.contains("unseen") && x.getAttribute("aria-pressed") === "true").map((x) => x.dataset.agent);
}
// What a click leaves as it was: an agent not shown, one that has the
// item whatever is ticked, whose chip can't be clicked, and one in a
// stopped distro magpie can't show the ticks of (unseen).
function keptOf(box, all, on) {
const fixed = [...box.children].filter((x) => x.classList.contains("always") || x.classList.contains("unseen")).map((x) => x.dataset.agent);
return on.filter((id) => !all.some((x) => x.id === id) || fixed.includes(id));
}
// All, ahead of a row's chips: one click gives the item to every agent
// shown that can take it (not those a chip is greyed out for: no SSE, no
// remote server), and when they all have it, takes it from every one.
// An agent not shown keeps what it has, as with a chip. The pickers that
// choose the agents before an item is added (installing skills, adding or
// bringing in servers) have it too (#1531): most start with every agent
// lit, and one agent alone was a click on each of the others.
function allChip(box, all, on, onChange) {
const can = [...box.children].filter((c) => !cannot(c) && !c.classList.contains("gone")).map((c) => c.dataset.agent);
if (can.length < 2) return;
const c = el("button", "lib-ag all", t("All"));
c.dataset.all = "1";
c.onclick = (e) => {
e.stopPropagation();
const me = e.currentTarget;
const lit = litOf(me.parentElement);
const kept = keptOf(me.parentElement, all, on);
onChange(can.every((id) => lit.includes(id)) ? kept : [...new Set([...kept, ...lit, ...can])], me);
};
box.prepend(c);
paintAll(box);
}
// the All chip shows whether every agent that can take the item has it
function paintAll(box) {
const c = box.querySelector(":scope > .lib-ag.all");
if (!c) return;
const can = [...box.children].filter((x) => x.dataset.agent && !cannot(x) && !x.classList.contains("gone"));
const n = can.length, full = can.every((x) => x.getAttribute("aria-pressed") === "true");
c.classList.toggle("on", full);
c.setAttribute("aria-pressed", full ? "true" : "false");
c.title = full ? t("Every agent that can take it has it — click to take it from all {n}", { n }) : t("Give it to all {n} agents that can take it", { n });
}
// A row's chips switched in place: the page isn't drawn again, which
// lost the chips' hover (they folded back together and spread again under
// the pointer) and blinked their icons (#69). The chip shows the click at
// once and the next click needn't wait: a row writes one list at a time,
// and clicks made meanwhile are sent together once it's answered, so the
// last click is what the agents end up with. What magpie wrote is then
// painted onto the same buttons — or, when it couldn't, what it has, which
// takes back the clicks it refused. Nothing else on the page is drawn
// again for it: the rest is drawn from the new answer when the page next is.
const writing = new Map(); // path + name → { list, name, want, box } while a row's agents are written
let refused = 0; // when a row's write last failed, whose error another row's "Written" doesn't cover
function chipsChange(path, name, list, rowOf) {
return async (next, c) => {
// All lights or darkens every chip of the row, a chip only itself
const every = !!c.dataset.all;
for (const x of every ? [...c.parentElement.children].filter((y) => y.dataset.agent && !y.classList.contains("always")) : [c]) {
const on = next.includes(x.dataset.agent);
x.classList.toggle("on", on);
if (on || x === c) x.classList.remove("via");
x.setAttribute("aria-pressed", on ? "true" : "false");
}
paintAll(c.parentElement);
const key = path + "\n" + name;
const w = writing.get(key);
if (w) { w.want = next; w.box = c.parentElement; w.every = every; take(lib); return; }
const me = { list, name, want: next, box: c.parentElement, every };
writing.set(key, me);
take(lib);
let sent = null, failed = false;
try {
// clicks that came back to what was sent aren't sent again
const same = () => [...sent].sort().join() === [...me.want].sort().join();
while (!sent || !same()) {
sent = me.want;
const v = await api("library/" + path, { name, agents: sent });
take(v);
if (same() && me.every && Date.now() - refused > 6000) { reportAll(v, me); continue; }
if (same() && Date.now() - refused > 6000) report(v.result, null, sent);
}
} catch (e) {
failed = true;
refused = Date.now();
status(e.message, "err", 6000);
}
writing.delete(key);
syncProblems();
// the page held the clicks: what magpie really has is read again
if (failed) await api("library").then(take, () => {});
const x = lib[list].find((y) => y.name === name);
const fresh = x && rowOf(x).querySelector(":scope > .lib-agents");
if (!me.box.isConnected) { if (failed) render(); } // drawn again meanwhile, from the clicks
else if (fresh && !morphChips(me.box, fresh)) me.box.replaceWith(fresh);
};
}
// What All did, said of the item: on for how many of the agents it went
// to, and which of them couldn't be given it, and why.
function reportAll(v, me) {
const what = ({ servers: "mcp:", hooks: "hook:", subagents: "subagent:" }[me.list] || "skill:") + me.name;
const shown = [...me.box.children].filter((x) => x.dataset.agent && !cannot(x)).map((x) => x.dataset.agent);
const n = shown.filter((id) => me.want.includes(id)).length;
const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent));
if (!bad.length) {
status(n ? t("{name} is on for all {n} agents", { name: me.name, n }) : t("{name} is off for every agent", { name: me.name }), "ok");
return;
}
const p = bad[0];
status((n ? t("{name} is on for {ok} of {n} agents", { name: me.name, ok: n - bad.length, n }) : t("{name} couldn't be taken from every agent", { name: me.name })) + " — "
+ t("{agent}: {error}", { agent: nameOf(p.agent), error: p.error }) + (bad.length > 1 ? " " + t("(and {n} more)", { n: bad.length - 1 }) : ""), "warn", 8000);
}
// take is the page as magpie answered it, with the rows still being
// written kept as they were last clicked. A server or skill added,
// removed or renamed changes what the market calls added (#300): one gone
// from the library loses its mark at once, and the market is asked again.
function take(v) {
// What the reader hid stays hidden while it still fails and nothing
// else does: every change writes every agent again, so a file magpie
// can't stat fails at each one (#3745). A failure not hidden brings the
// card back whole, and an item written meanwhile is new when it fails
// again. v.problems is everything that stands, whatever answered.
const failing = new Set((v.problems || []).filter(failure).map(problemKey));
for (const k of hid) if (!failing.has(k)) hid.delete(k);
if ([...failing].some((k) => !hid.has(k))) hid.clear();
const was = lib && shelf();
lib = v;
taken++;
for (const w of writing.values()) {
const x = lib[w.list].find((y) => y.name === w.name);
if (x) x.agents = w.want;
}
if (!was || shelf() === was) return;
for (const [kind, list] of [["mcp", lib.servers], ["skills", lib.skills]]) {
const m = market[kind];
if (!m.items) continue;
const names = new Set((list || []).map((x) => x.name));
for (const x of m.items) if (x.have && !names.has(x.have)) x.have = "";
drawMarket(kind);
fetchMarket(kind);
}
}
function morphChips(box, fresh) {
const was = [...box.children], now = [...fresh.children];
if (was.length !== now.length || was.some((c, i) => c.dataset.agent !== now[i].dataset.agent)) return false;
was.forEach((c, i) => {
const n = now[i];
c.className = n.className;
c.title = n.title;
if (cannot(n)) c.setAttribute("aria-disabled", "true"); else c.removeAttribute("aria-disabled");
c.setAttribute("aria-pressed", n.getAttribute("aria-pressed"));
c.onclick = n.onclick;
});
return true;
}
// ---------- loading and changing ----------
// quiet is a read on coming back to the window: the page is drawn again
// only when the library changed meanwhile, so a click that brings the
// window forward doesn't redraw what it clicked on.
// The first read is a glance: the page but for the skills the agents
// have of their own and which copies are out of date, which take reading
// their skill folders through, and on a machine with many big skills
// that took minutes before anything showed (0day404, #541). It is drawn
// at once, and the whole page after it; only the Skills tab shows what
// the glance left out, so the others aren't drawn again for it.
async function load(quiet) {
let glanced = false;
if (!lib) {
renderLoading();
const at = taken;
try {
const g = await api("library?glance=1");
if (!lib && taken === at) {
take(g);
glanced = true;
render();
}
} catch {}
}
try {
const at = taken;
const v = await api("library");
// a change answered meanwhile, with the library as it is after it
if (taken !== at) return;
const was = lib && seen(lib);
take(v);
if (glanced && tab !== "skills") return;
if ((quiet === true || glanced) && seen(lib) === was) return;
// opening the page (its nav clicked, while on it too) draws it again
// only for a change, or for RTK's tab, which is asked again: a page
// drawn over again replaced the row under the reader's pointer (#3099)
if (quiet === "open" && seen(lib) === was && tab !== "rtk" && page.querySelector(":scope > .lib-body")) return;
rtk = null; // asked again when its tab is drawn: an agent may have been installed since
piView = null;
render();
} catch (e) {
status(e.message, "err");
}
}
// the library as the page shows it: what a change did is said once, not shown
const seen = (v) => JSON.stringify({ ...v, result: undefined });
// Every change answers with the page as it is after it, and what it did;
// one to the instructions with them alone, the rest kept as it is (#1624).
// One change is on its way at a time: while it is, the page's buttons
// can't be pressed and the one pressed says it is saving, so a second
// click doesn't make or remove a set twice (Hipple, #1624: a minute a
// click with nothing to show for it).
let changing = false;
async function change(path, body, done) {
if (changing) return false;
changing = true;
const ev = window.event;
const pressed = ev?.type === "click" && ev.target?.closest?.("button:not(.lib-switch):not(.lib-radio)");
const held = [...document.querySelectorAll("#view-library button, #modal.lib button")].filter((b) => !b.disabled);
for (const b of held) b.disabled = true;
page.setAttribute("aria-busy", "true");
if (pressed && pressed.textContent.trim()) saving(pressed, t("Saving…"));
status(t("Saving…"), "", 120000);
let ok = false;
try {
const v = await api("library/" + path, body);
take(v.part === "instructions" ? { ...lib, instructions: v.instructions, problems: v.problems, result: v.result } : v);
status(""); // what it did, said next, or nothing for one that says nothing
report(v.result, done);
ok = true;
return true;
} catch (e) {
status(e.message, "err", 6000);
return false;
} finally {
changing = false;
page.removeAttribute("aria-busy");
for (const b of held) b.disabled = false;
if (pressed) doneSaving(pressed);
if (ok) render();
}
}
// given, for a row's agent chips, is the agents that have it now: an
// agent written that isn't one of them had it taken out (#332).
function report(res, done, given) {
if (!res) return;
// an update that found its source without the skill: said so, not
// as done or failed (スライム on Discord)
if (res.gone?.length) {
status(goneSaid(res.gone), "warn", 10000);
return;
}
// skills installed together (lc on Discord): those the library had
// already, and those left out because another by that name is in the
// way, are named, beside how many were installed
const had = res.had || [], skipped = res.skipped || [], linked = res.linked || [];
if (had.length || skipped.length || linked.length) {
const n = res.installed?.length || 0, parts = [];
if (n) parts.push(n === 1 ? t("1 skill installed") : t("{n} skills installed", { n }));
// a skill from a folder, linked to the one installed (skill_link.go)
if (linked.length) parts.push(t("updates from GitHub now: {names}", { names: linked.join(", ") }));
if (res.linkedKept?.length) parts.push(t("files of their own kept with the backups: {names}", { names: res.linkedKept.join(", ") }));
if (had.length) parts.push(t("already in the library: {names}", { names: had.join(", ") }));
for (const p of skipped) parts.push(t("{name} skipped: {error}", { name: p.what.replace(/^skill:/, ""), error: p.error }));
status(parts.join(" · "), skipped.length ? "warn" : "ok", skipped.length ? 12000 : 6000);
return;
}
if (res.problems?.length) {
const p = res.problems[0];
status(t("{agent}: {error}", { agent: tilde(nameOf(p.agent)), error: p.error }) + (res.problems.length > 1 ? " " + t("(and {n} more)", { n: res.problems.length - 1 }) : ""), "warn", 8000);
return;
}
const n = res.changed?.length || 0;
const out = given ? (res.changed || []).filter((id) => !given.includes(id)).length : 0;
if (done) status(done, "ok");
else if (out && out === n) status(n === 1 ? t("Removed from {agent}", { agent: nameOf(res.changed[0]) }) : t("Removed from {n} agents", { n }), "ok");
else if (out) status(t("{n} agents updated", { n }), "ok");
else if (n) status(n === 1 ? t("Written to {agent}", { agent: nameOf(res.changed[0]) }) : t("Written to {n} agents", { n }), "ok");
else status(t("Saved — the agents already had it"), "ok");
}
// What the last change couldn't write, whole: a chip's amber dot holds
// only its own item's, so an agent's instructions, its MCP file, a
// project or a skill that wouldn't update were said once in a toast
// ("see Library") and shown nowhere.
// Each is listed on the tab it is about; another tab says only how many
// wait where, with a button to go there: Claude Desktop's own skills
// listed one by one on the MCP servers tab read as duplicated servers
// (#1896). An agent's own skills in the library's way are one row for
// the agent, settled together, not a write that failed: Try again, which
// can't change them, is offered only beside a write that did fail.
function problemsCard() {
// the write failures the reader hid are left out while they are all
// that fails; an agent's own skills, still to settle, stay
const all = lib.problems || [];
const quiet = all.some(failure) && all.filter(failure).every((p) => hid.has(problemKey(p)));
const list = quiet ? all.filter((p) => !failure(p)) : all;
if (!list.length) return null;
const here = list.filter((p) => !problemTab(p.what) || problemTab(p.what) === tab);
const away = {};
for (const p of list) if (!here.includes(p)) away[problemTab(p.what)] = (away[problemTab(p.what)] || 0) + 1;
const owns = new Map(); // agent → its own skills by the library's names
const rest = [];
for (const p of here) {
if (!failure(p)) {
if (!owns.has(p.agent)) owns.set(p.agent, []);
owns.get(p.agent).push(p.what.slice("skill:".length));
} else rest.push(p);
}
const card = el("div", "lib-problems");
card.setAttribute("role", "status");
const ttl = el("div", "lib-problems-head");
const failed = rest.length || list.some((p) => !here.includes(p) && failure(p));
ttl.append(el("span", "lib-problems-dot"), el("b", "", failed ? t("Some of the Library couldn't be written") : t("Some agents have skills of their own by the library's names")));
if (failed) {
const again = button(t("Try again"), "action", () => change("all/sync", {}));
again.title = t("Writes the library into every agent again");
// the reader who can't mend it here, or won't now, puts it away; a
// change's toast still says what failed, and something new that
// can't be written brings it back (#3745)
const hide = button("", "lib-x", () => hideFailed(card));
hide.append(svg("M4.5 4.5l7 7M11.5 4.5l-7 7", 11, 1.6));
hide.title = t("Hide until something new can't be written");
ttl.append(again, hide);
}
card.append(ttl);
const ul = el("ul");
for (const p of rest) {
const li = el("li");
const who = p.what.startsWith("project:") ? tilde(p.agent) : p.agent ? nameOf(p.agent) : "";
if (who) li.append(el("b", "", who), el("span", "lib-problems-sep", " · "));
li.append(el("span", "", problemWhat(p.what)), el("span", "lib-problems-err", p.error));
ul.append(li);
}
// an agent's own skills in the library's way are settled right here:
// the library's in their place (the agent's kept aside), or the agent's
for (const [id, names] of owns) {
const li = el("li", "lib-problems-own");
const who = nameOf(id), name = names.join(", ");
const one = names.length === 1;
li.append(el("b", "", who), el("span", "lib-problems-sep", " · "), el("span", "", one ? t("Skill {name}", { name }) : t("Skills {names}", { names: name })));
// Claude Desktop's are Anthropic's built in or made in Desktop, listed
// in its manifest: kept, never put aside for the library's
const desktop = id === "claude-desktop";
li.append(el("span", "lib-problems-err", desktop
? (one ? t("Claude Desktop has its own {name}, so it doesn't get the library's", { name }) : t("Claude Desktop has its own of these, so it doesn't get the library's"))
: (one ? t("{agent} has a skill of its own called {name}, not the same as the library's", { agent: who, name }) : t("{agent} has skills of its own by these names, not the same as the library's", { agent: who }))));
const body = one ? { name: names[0], agent: id } : { names, agent: id };
const fix = el("div", "lib-problems-fix");
if (!desktop) {
const use = button(t("Use the library's"), "action", () => change("skills/use-library", body, one ? t("{agent} has the library's {name} now; its own is kept with the backups", { agent: who, name }) : t("{agent} has the library's {names} now; its own are kept with the backups", { agent: who, names: name })));
use.title = one ? t("Sets {agent}'s own {name} aside with the backups and gives it the library's in its place", { agent: who, name }) : t("Sets {agent}'s own {names} aside with the backups and gives it the library's in their place", { agent: who, names: name });
fix.append(use);
}
const keep = button(t("Keep {agent}'s", { agent: who }), "action", () => change("skills/keep-own", body, one ? t("{agent} keeps its own {name}", { agent: who, name }) : t("{agent} keeps its own {names}", { agent: who, names: name })));
keep.title = one ? t("{agent} keeps its own {name}, and the library no longer gives it this skill", { agent: who, name }) : t("{agent} keeps its own {names}, and the library no longer gives it these skills", { agent: who, names: name });
fix.append(keep);
li.append(fix);
ul.append(li);
}
if (ul.childElementCount) card.append(ul);
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), subagents: t("Subagents") };
const others = Object.keys(away).filter((k) => k in tabNames);
if (others.length) {
const more = el("div", "lib-problems-away");
for (const k of others) {
const go = button(t("{tab}: {n} more", { n: away[k], tab: tabNames[k] }), "action", () => openTab(k));
go.dataset.tab = k;
more.append(go);
}
card.append(more);
}
return card;
}
// a write that failed, as against an agent's own skill in the library's
// way, which is the agent's to settle
function failure(p) {
return !(p.own && p.what.startsWith("skill:") && p.agent);
}
// a failure is the same from one sync to the next by its agent and its
// item: the error can name a temp file new at each write (edit.WriteAtomic)
function problemKey(p) {
return p.agent + "\n" + p.what;
}
function hideFailed(card) {
const focused = card.contains(document.activeElement);
for (const p of lib.problems || []) if (failure(p)) hid.add(problemKey(p));
// the view keeps its scroll, as render keeps it for Try again:
// Chromium's scroll anchoring would move it as the card goes
const top = page.scrollTop;
syncProblems();
page.scrollTop = top;
// the keyboard's place: the card's next button, or the tab open
if (focused) (page.querySelector(":scope > .lib-problems button") || page.querySelector(".lib-tabs .opt.on"))?.focus({ preventScroll: true });
}
// the tab a problem is about; "" is one shown on every tab
function problemTab(what) {
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", subagent: "subagents" }[what.split(":")[0]] || "";
}
function problemWhat(what) {
const [kind, ...rest] = what.split(":");
const name = rest.join(":");
if (kind === "instructions") return t("Instructions");
if (kind === "mcp") return name ? t("MCP server {name}", { name }) : t("MCP servers");
if (kind === "skill") return t("Skill {name}", { name });
if (kind === "hook") return t("Hook {name}", { name });
if (kind === "subagent") return t("Subagent {name}", { name });
if (kind === "project") return name ? t("Skill {name}", { name }) : t("The project");
return what;
}
// a chip's write changes the list without drawing the page again: the
// card is put right in place (the chip clicked is held where it is on the
// screen by app.js, as for any click)
function syncProblems() {
const was = page.querySelector(":scope > .lib-problems");
const card = problemsCard();
if (!was && !card) return;
if (was && card && was.textContent === card.textContent) return;
if (was && card) was.replaceWith(card);
else if (was) was.remove();
else page.querySelector(":scope > .lib-head")?.after(card);
}
// Until the library comes, the page is drawn as it will be: the real tabs
// (one can be picked already) and, for the tab open, its rows in outline,
// so nothing moves when they're filled in. The outline shows only if the
// wait is long enough to see it.
function renderLoading() {
page.replaceChildren();
shown = "";
page.append(libHead(null), skeleton(tab));
}
function skeleton(which) {
const box = el("div", "lib-body lib-skel");
box.setAttribute("aria-busy", "true");
const bar = (w, h, cls = "") => {
const b = el("span", "skeleton " + cls);
b.style.cssText = `width:${w};height:${h}px`;
return b;
};
// name and path lengths vary, as they will
const widths = [[34, 46], [22, 40], [30, 52], [26, 38], [38, 44], [20, 36], [28, 48]];
const rows = (n, sw) => {
const list = el("div", "list lib-list");
for (let i = 0; i < n; i++) {
const [a, b] = widths[i % widths.length];
const row = el("div", "row lib-row");
const who = el("div", "who");
who.append(bar(a + "%", 10), bar(b + "%", 8));
row.append(bar("26px", 26, "lib-sk-icon"), who, el("span", "grow"));
if (sw) row.append(bar("34px", 20, "lib-sk-switch"));
list.append(row);
}
return list;
};
const head = (w) => {
const rh = el("div", "row-head");
rh.append(bar(w, 8));
return rh;
};
const intro = el("div", "lib-intro lib-sk-intro");
intro.append(bar("min(520px, 80%)", 9));
box.append(intro);
if (which === "instructions") {
const card = el("div", "list lib-list");
const ch = el("div", "row lib-row");
ch.append(bar("26px", 26, "lib-sk-icon"), bar("150px", 11));
card.append(ch, rows(1, false).firstChild);
box.append(card, head("60px"), rows(6, true));
} else if (which === "rtk") {
box.append(rows(1, false), head("60px"), rows(5, true));
} else if (which === "pi") {
box.append(head("60px"), rows(4, true));
} else {
box.append(rows(5, true));
}
return box;
}
function openTab(id) {
tab = id;
try { localStorage.setItem("magpie.libTab", id); } catch {}
// RTK's count read afresh each time its tab is opened: an agent run
// since adds to it (#741); the page keeps the last one until then
if (id === "rtk" && rtk) loadRTK();
// Pi's extensions too: one installed or changed outside magpie since
if (id === "pi" && piView) loadPi();
if (!lib) return page.querySelector(":scope > .lib-skel")?.replaceWith(skeleton(id));
render(); syncLists();
}
// the tabs and the Library folder; without the library yet (lib is null
// while it loads) the tabs have no counts and the folder waits
function libHead(counts) {
const head = el("div", "lib-head");
const n = (k) => (counts?.[k] ? " · " + counts[k] : "");
const tabs = segs(agentless() ? [["mcp", t("MCP servers") + n("mcp")]] : [
["instructions", t("Instructions")],
["mcp", t("MCP servers") + n("mcp")],
["skills", t("Skills") + n("skills")],
["hooks", t("Hooks") + n("hooks")],
["subagents", t("Subagents") + n("subagents")],
["rtk", "RTK"],
...(hasPi() ? [["pi", t("Pi packages")]] : []),
], tab, openTab);
tabs.classList.add("lib-tabs");
head.append(tabs);
// the buttons keep together at the end, on a line of their own when the
// window is too narrow for the tabs and them
const acts = el("span", "lib-headacts");
// The market sits under everything the tab lists, many screens down with
// dozens of skills (#1348): the strip that stays at the top goes to it.
if (lib && (tab === "mcp" || tab === "skills")) {
const go = button("", "lib-discover", (e) => {
const mk = page.querySelector(`.mk[data-market="${tab}"]`);
if (!mk || !window.scrollOnPurpose?.(e, 1500)) return;
// its heading just under the strip, however many lines that takes
const top = mk.getBoundingClientRect().top - page.getBoundingClientRect().top + page.scrollTop - head.getBoundingClientRect().height - 8;
page.scrollTo({ top, behavior: calm() ? "auto" : "smooth" });
mk.querySelector("input")?.focus({ preventScroll: true });
});
go.append(glyph(GLYPH.search, "lib-mini"), el("span", "", t("Discover")));
go.title = tab === "mcp" ? t("Go to the MCP servers you can add, under the list") : t("Go to the skills you can add, under the list");
// a narrow window's title bar shows the icon alone (app.css
// .tools-tight): the name stays the button's, not only its tooltip's
go.setAttribute("aria-label", t("Discover"));
acts.append(go);
}
const more = button("", "lib-more", () => lib && reveal(lib.dir));
more.append(glyph(GLYPH.folder, "lib-mini"), el("span", "", t("Library folder")));
more.setAttribute("aria-label", t("Library folder"));
if (lib) more.title = tilde(lib.dir);
else more.disabled = true;
// magpie's backups beside it, on every tab: at the foot of a long
// page they were hard to find (Dade on Discord: 备份在最底部)
const back = button("", "lib-backups", () => lib && reveal(lib.backups));
back.append(glyph(GLYPH.backup, "lib-mini"), el("span", "", t("Backups")));
back.setAttribute("aria-label", t("Backups"));
if (lib) back.title = t("magpie keeps a copy of every file before it writes it.") + "\n" + tilde(lib.backups);
else back.disabled = true;
acts.append(more, back);
head.append(acts);
return head;
}
// ---------- the page ----------
function render() {
if (!lib) return;
const top = page.scrollTop;
const focus = document.activeElement?.dataset?.lib; // keep the caret where the reader is typing
const caret = focus ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null;
page.replaceChildren();
fits = [];
// the MCP servers alone with no agent to write to; the tab the reader
// last picked is kept for when there is one
if (agentless()) tab = "mcp";
// Pi's tab only while a Pi is here; the pick is kept for when one is
else if (tab === "pi" && !hasPi()) tab = "instructions";
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length });
page.append(head);
head.classList.toggle("stuck", top > 0);
// what changed in a tab is drawn in place: only another tab (or the
// first one after the skeleton) fades in
const problems = problemsCard();
if (problems) page.append(problems);
const body = el("div", "lib-body" + (shown !== tab ? " enter" : ""));
shown = tab;
if (tab === "instructions") renderInstructions(body);
else if (tab === "mcp") renderServers(body);
else if (tab === "rtk") renderRTK(body);
else if (tab === "pi") renderPi(body);
else if (tab === "hooks") renderHooks(body);
else if (tab === "subagents") renderSubagents(body);
else renderSkills(body);
page.append(body);
for (const n of body.querySelectorAll(".row-head .note")) n.title = n.textContent;
for (const f of fits.splice(0)) f();
page.scrollTop = top;
syncLists(); // a long list's rows where the view is, before it's painted
if (focus) {
const e = page.querySelector(`[data-lib="${CSS.escape(focus)}"]`);
if (e) { e.focus({ preventScroll: true }); if (caret && e.setSelectionRange) e.setSelectionRange(caret[0], caret[1]); }
}
}
function empty(title, text, action) {
const box = el("div", "lib-empty");
box.append(el("b", "", title), el("p", "", text));
if (action) box.append(action);
return box;
}
function intro(text) { return el("p", "lib-intro", text); }
// ---------- RTK ----------
// RTK (rtk-ai.app) cuts down what the shell commands an agent runs print,
// so their output costs fewer tokens. magpie runs rtk's own installer for
// each agent switched on, takes out what it wrote for one switched off
// (with or without rtk), and reads the agents' files for which have it.
let rtk = null; // /api/library/rtk
const rtkBusy = new Set(); // agents being switched
let rtkLoading = false;
async function loadRTK() {
if (rtkLoading) return;
rtkLoading = true;
try {
rtk = await api("library/rtk");
} catch (e) {
status(e.message, "err");
}
rtkLoading = false;
if (tab === "rtk" && rtk) render();
}
function renderRTK(body) {
body.append(intro(t("RTK rewrites the shell commands an agent runs — git status, cargo test, ls… — to print only what the model needs, so they cost fewer tokens. Switch it on for an agent and magpie runs RTK's own installer for it.")));
if (!rtk) {
body.append(el("div", "row skeleton"));
loadRTK();
return;
}
const card = el("div", "list lib-card");
const ttl = el("div", "lib-cardhead");
// RTK's own mark (rtk-ai.app), drawn in the text's colour
const logo = el("span", "lib-glyph lib-rtk-logo");
logo.append(maskSpan("icons/rtk.png"));
ttl.append(logo, el("b", "", "RTK"), el("span", "grow"));
if (rtk.path) {
ttl.append(el("span", "note mono", rtk.version ? "v" + rtk.version : tilde(rtk.path)));
// a newer release: upgraded the way this rtk was installed
// …unless the package manager that installed it (winget, Homebrew)
// doesn't have it yet: an upgrade through it would change nothing
// (#1025), so none is offered until it does
const waiting = !rtkUpgrading && rtk.waiting;
const behind = !waiting && rtk.latest && rtk.version && vNewer(rtk.latest, rtk.version);
// why there is no upgrade to run: a cargo RTK with no cargo to be
// found says what to install or run (新v学员)
const noUpgrade = rtk.noUpgrade === "cargo"
? t("RTK was installed with cargo, but magpie can't find cargo to upgrade it. Install Rust from rustup.rs, or run {cmd} in a terminal.", { cmd: rtk.manual })
: t("magpie can't tell how this RTK was installed — update it the way you installed it");
if (rtkUpgrading) ttl.append(tag(t("Upgrading…"), "lib-new"));
else if (waiting) ttl.append(tag(t("v{v} is out · waiting for {via}", { v: rtk.latest, via: rtk.waiting }), "", t("RTK {v} is out, but {via} has {has} so far — usually within a few days. Upgrade comes back once {via} has it.", { v: rtk.latest, via: rtk.waiting, has: rtk.waitingHas || rtk.version })));
else if (behind) ttl.append(tag(t("v{v} is out", { v: rtk.latest }), "lib-new", t("RTK {v} is the latest release; this one is {have}", { v: rtk.latest, have: rtk.version })));
else if (rtk.latest && rtk.version) ttl.append(tag(t("Up to date"), "", t("RTK {v} is the latest release", { v: rtk.latest })));
if (behind || rtkUpgrading) {
const ub = button(rtkUpgrading ? t("Upgrading…") : t("Upgrade"), "action", upgradeRTK);
ub.disabled = rtkUpgrading || !rtk.upgrade;
ub.title = rtk.upgrade ? (rtk.admin ? t("Runs {cmd}, as administrator: Windows asks first", { cmd: rtk.upgrade }) : t("Runs {cmd}", { cmd: rtk.upgrade })) : noUpgrade;
ttl.append(ub);
}
card.append(ttl);
// an upgrade under way says what it runs; one that failed says why,
// with the tool's exit code and what it said, until the next try (#741)
if (rtkUpgrading && rtk.upgrade) card.append(el("p", "lib-rtk-gain", t("Running {cmd} — this can take a few minutes.", { cmd: rtk.upgrade })));
else if (rtkUpgradeErr) card.append(el("p", "lib-rtk-note lib-rtk-err", t("The upgrade failed: {why}", { why: rtkUpgradeErr })));
// no upgrade to run: said on the card, not only in the disabled
// button's tooltip, which a click never shows (新v学员: a cargo RTK
// on Windows whose Upgrade did nothing)
else if (behind && !rtk.upgrade) card.append(el("p", "lib-rtk-note lib-rtk-noupgrade", noUpgrade));
if (rtk.note) card.append(el("p", "lib-rtk-note", rtk.note));
// found where magpie looks, but not on the PATH the agents get: their
// hooks run rtk by name, so it does nothing for them (#601)
if (rtk.offPath) {
const dir = tilde(rtk.path.replace(/[\\/][^\\/]*$/, ""));
card.append(el("p", "lib-rtk-note lib-rtk-offpath", t("RTK is in {dir}, which isn't on your PATH. Agents run rtk by name, so they can't find it and RTK does nothing for them (Pi says \"rtk binary not found in PATH\").", { dir })));
card.append(el("p", "lib-rtk-cmd", !rtk.pathDir
? t("Add {dir} to PATH in your shell profile, then check again.", { dir })
: rtk.pathLink
? t("Put RTK on PATH links it into {dir}.", { dir: tilde(rtk.pathDir) })
: t("Put RTK on PATH adds {dir} to your user PATH.", { dir: tilde(rtk.pathDir) })));
const acts = el("div", "lib-acts");
if (rtk.pathDir) {
const pb = button(rtkPathing ? t("Putting RTK on PATH…") : t("Put RTK on PATH"), "action", pathRTK);
pb.disabled = rtkPathing;
acts.append(pb);
}
acts.append(button(t("Check again"), rtk.pathDir ? "" : "action", () => { rtk = null; render(); }));
card.append(acts);
}
// RTK's own count (rtk gain): every agent and terminal, all time —
// said on the page, so an empty one isn't read as magpie counting
// only some (#741); one rtk couldn't give says why
const g = rtk.gain;
const gain = el("p", "lib-rtk-gain", g
? t("{saved} tokens saved over {n} commands — {pct}% on average", { saved: tokens(g.saved), n: g.commands.toLocaleString(intlLang()), pct: Math.round(g.pct) })
: rtk.gainErr
? t("magpie couldn't read what RTK saved: {why}", { why: rtk.gainErr })
: t("Nothing saved yet: the agents' commands go through RTK once it's switched on and the agent is restarted."));
gain.append(" ", el("span", "lib-rtk-scope", t("RTK's own count (rtk gain): every command run through RTK on this computer, from any agent or terminal.")));
card.append(gain);
// Codex's Windows sandbox: rtk runs there as another account, or one
// that can't write RTK's history, so what it saves isn't in that count
if (rtk.codexSandbox) card.append(el("p", "lib-rtk-note lib-rtk-sandbox", rtk.codexSandbox === "elevated"
? t("Codex runs its commands in its Windows sandbox, as its own sandbox account: RTK keeps what it saves there in that account's history, not yours, so it isn't counted here.")
: t("Codex runs its commands in its Windows sandbox, which can't write RTK's history: what RTK saves there isn't recorded, so it isn't counted here.")));
if (rtk.days?.length) card.append(rtkChart(rtk.days));
} else {
card.append(ttl);
card.append(el("p", "lib-rtk-gain", rtkInstalling
? t("Installing RTK… this can take a minute.")
: t("RTK isn't installed. magpie can install it for you, or get it from its site.")));
if (rtk.install) card.append(el("p", "lib-rtk-cmd", rtk.install));
// why the last install failed stays on the card, beside Get RTK, not
// only in a status line gone after ten seconds (Scott__D on X: the
// install never succeeded, and nothing on the page said why)
if (rtkInstallErr && !rtkInstalling) card.append(el("p", "lib-rtk-note lib-rtk-err lib-rtk-install-err", t("The install failed: {why}", { why: rtkInstallErr })));
const acts = el("div", "lib-acts");
if (rtk.install) {
const ib = button(rtkInstalling ? t("Installing…") : t("Install RTK"), "action", installRTK);
ib.disabled = rtkInstalling;
acts.append(ib);
}
acts.append(button(t("Get RTK"), rtk.install ? "" : "action", () => browse(rtk.url)), button(t("Check again"), "", () => { rtk = null; render(); }));
card.append(acts);
}
body.append(card);
// an agent in WSL runs its distro's own RTK (rtk_wsl.go): one card each
for (const d of rtk.wsl || []) body.append(rtkDistroCard(d));
const rh = el("div", "row-head");
rh.append(el("span", "label", t("Agents")), el("span", "grow"), el("span", "note", t("restart an agent after switching it")));
body.append(rh);
const list = el("div", "list lib-list");
const rows = rtk.agents.filter((a) => !isHidden(a));
for (const a of rows) {
const row = el("div", "row lib-row");
const who = el("div", "who");
who.append(el("div", "name", a.name));
row.append(icon(a.icon), who, el("span", "grow"));
// an agent in WSL: its distro's RTK, not this computer's
const kind = a.id.split("@")[0];
const d = a.wsl ? (rtk.wsl || []).find((x) => x.name === a.wsl) : null;
const path = a.wsl ? d?.path : rtk.path, offPath = a.wsl ? d?.offPath : rtk.offPath;
if (a.asleep) row.append(tag(t("Not running"), "", t("WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.", { distro: a.wsl, agent: a.name })));
// its hook calls an rtk that isn't there: switching it off still works
else if (a.on && !path) row.append(tag(t("RTK missing"), "warn", a.wsl
? t("{agent}'s hook calls rtk, which isn't installed in WSL {distro}, so its shell commands fail. Install RTK there, or switch this off.", { agent: a.name, distro: a.wsl })
: t("{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.", { agent: a.name })));
// …or one that is, off the PATH the agent gets
else if (a.on && offPath) row.append(tag(t("Not on PATH"), "warn", a.wsl
? t("{agent}'s hook runs rtk by name and can't find it in WSL {distro}, so RTK does nothing for it. Add RTK's folder to PATH there.", { agent: a.name, distro: a.wsl })
: t("{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.", { agent: a.name })));
// an agent RTK has no hook for (rtkNoHook in rtk.go): listed, with its own why
if (a.noHook) row.append(tag(t("No RTK hook"), "warn", rtkNoHookWhy(a)));
// RTK before 0.51 installs Antigravity's hook only per project
else if (a.blocked && kind === "agy") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.51 or newer: older ones install it only per project. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));
// RTK before 0.44 has no Droid agent
else if (a.blocked && kind === "droid") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.44 or newer: older ones have no hook for it. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));
else if (a.blocked && kind !== "opencode") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.50 or newer: older ones only add @RTK.md to AGENTS.md, which rewrites no command. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));
// OpenCode 2 loads only the plugin RTK 0.52 on writes (rtk-ai/rtk#4187);
// an older one's, already there, can be switched off
else if (a.blocked) row.append(tag(t("Update RTK"), "warn", a.on
? t("OpenCode 2 refuses to load this plugin: RTK before 0.52 writes it for OpenCode 1. Update RTK (brew upgrade rtk, or its installer again) and switch it on again, or switch this off.")
: t("OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.")));
const sw = toggle(a.on, t("{agent} runs its commands through RTK", { agent: a.name }), (on) => setRTK(a, on));
if ((!path && !a.on) || a.asleep || (a.blocked && !a.on) || rtkBusy.has(a.id) || rtkInstalling || rtkInstallingIn || rtkUpgrading) sw.disabled = true;
row.append(sw);
list.append(row);
}
if (!rows.length) list.append(el("div", "lib-none", t("None of your agents is one RTK has a hook for.")));
body.append(list);
}
// Why RTK has no hook for an agent: each agent's own reason and its own
// rtk-ai/rtk issue, never another agent's (新v学员 on Discord: Grok Build's
// said DeepSeek Harness's hooks can't rewrite and linked dsh's issue).
// Keyed as rtkNoHook in rtk.go; TestRTKNoHookIssuesAreEachAgents holds the
// two together. An agent with no entry gets no reason and no link.
function rtkNoHookWhy(a) {
const agent = a.name;
switch (a.id.split("@")[0]) {
case "dsh": return t("RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).", { agent });
case "grok": return t("RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent });
case "grok-app": return t("RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent });
case "qoder": return t("RTK can't be given to {agent} yet: RTK's installer has no option for Qoder (github.com/rtk-ai/rtk/issues/1327).", { agent });
case "qoder-cn": return t("RTK can't be given to {agent} yet: {agent} is Qoder's China build, and RTK's installer has no option for Qoder (github.com/rtk-ai/rtk/issues/1327).", { agent });
case "cline": return t("RTK can't be given to {agent} yet: RTK's installer only writes a .clinerules into one project, asking the model to type rtk itself, and has nothing for every project (github.com/rtk-ai/rtk/issues/3841).", { agent });
case "kimi": return t("RTK can't be given to {agent}: {agent}'s hooks can only allow or deny a command, not change it, so RTK's installer only adds instructions to one project's AGENTS.md and has nothing for every project.", { agent });
default: return t("RTK can't be given to {agent} yet: RTK has no hook for it.", { agent });
}
}
async function setRTK(a, on) {
rtkBusy.add(a.id);
render();
try {
rtk = await api("library/rtk", { agent: a.id, on });
const names = (rtk.restart || [a.id]).map((id) => rtk.agents.find((x) => x.id === id)?.name || id).join(", ");
status(on ? t("RTK is on for {agent} — restart it to use it", { agent: names }) : t("RTK is off for {agent} — restart it to see it", { agent: names }), "ok", 6000);
} catch (e) {
status(e.message, "err", 8000);
}
rtkBusy.delete(a.id);
render();
}
// ---------- Pi extensions ----------
// Each Pi here (this computer's, and each WSL distro's) with the
// extensions and packages it loads (piext.go). One is switched off or on
// in its settings.json the way `pi config` does it, and copied to
// another Pi: a package as its entry in that Pi's settings.json, which
// Pi installs itself when it starts; an extension as its file or folder.
// leokon3 on Discord: moving an extension from the WSL Pi to Windows'.
const hasPi = () => !!lib && !gatewayPage() && lib.agents.some((a) => a.id.split("@")[0] === "pi" && !a.gone && !a.unseen && !isHidden(a));
let piView = null; // /api/library/pi
const piBusy = new Set(); // "" being switched or copied
let piLoading = false;
async function loadPi() {
if (piLoading) return;
piLoading = true;
try {
piView = await api("library/pi");
} catch (e) {
status(e.message, "err");
}
piLoading = false;
if (tab === "pi" && piView) render();
}
function renderPi(body) {
body.append(intro(t("The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.")));
if (!piView) {
body.append(el("div", "row skeleton"));
loadPi();
return;
}
const pis = (piView.pis || []).filter((p) => !isHidden({ id: p.id }));
const live = pis.filter((p) => !p.asleep && !p.err);
for (const p of pis) {
const rh = el("div", "row-head lib-pi-head");
rh.dataset.pi = p.id;
rh.append(el("span", "label", p.name), el("span", "grow"));
if (p.dir && !p.asleep) rh.append(pathLink(p.dir));
body.append(rh);
const list = el("div", "list lib-list lib-pi");
list.dataset.pi = p.id;
const others = live.filter((x) => x.id !== p.id);
if (p.asleep) {
list.append(el("div", "lib-none", t("WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.", { distro: p.wsl, agent: p.name })));
} else if (p.err) {
list.append(el("div", "lib-none lib-pi-err", t("magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}", { file: "settings.json", why: p.err })));
} else {
for (const x of p.extensions || []) list.append(piRow(p, others, { ext: x.id }, x.name, tilde(x.path), x.on, null));
for (const k of p.packages || []) {
const tags = [tag(k.kind)];
if (!k.installed) tags.push(tag(t("Not installed"), "", t("Pi installs it when it next starts")));
else if (k.version) tags.push(tag("v" + k.version));
list.append(piRow(p, others, { pkg: k.source }, k.name, k.source, k.on, tags, k.filtered));
}
if (!(p.extensions || []).length && !(p.packages || []).length) list.append(el("div", "lib-none", t("No extensions or packages yet.")));
}
body.append(list);
}
}
function piRow(p, others, what, name, sub, on, tags, filtered) {
const key = p.id + " " + (what.ext || what.pkg);
const row = el("div", "row lib-row lib-pi-row");
row.dataset.id = what.ext || what.pkg;
const who = el("div", "who");
const n = el("div", "name mono", name);
for (const g of tags || []) n.append(g);
who.append(n, el("div", "sub mono", sub));
row.append(who);
if (others.length) {
const b = button(t("Copy to…"), "lib-pi-copy", () => {
openProtoMenu(b, others.map((x) => ({ v: x.id, name: x.name, literalName: true, note: "" })), "", (to) => copyPi(p, others.find((x) => x.id === to), what, name), "Copy to another Pi", "", "right");
});
b.disabled = piBusy.has(key);
row.append(b);
}
const sw = toggle(on, t("{agent} loads {name}", { agent: p.name, name }), (v) => setPi(p, what, name, v));
if (filtered) sw.title = t("This entry loads only some of the package; change it with pi config");
sw.disabled = !!filtered || piBusy.has(key);
row.append(sw);
return row;
}
async function setPi(p, what, name, on) {
const key = p.id + " " + (what.ext || what.pkg);
piBusy.add(key);
render();
try {
piView = await api("library/pi", { pi: p.id, ...what, on });
status(on ? t("{name} is on for {agent}: Pi loads it when it next starts, or at /reload", { name, agent: p.name }) : t("{name} is off for {agent}: Pi drops it when it next starts, or at /reload", { name, agent: p.name }), "ok", 6000);
} catch (e) {
status(e.message, "err", 8000);
}
piBusy.delete(key);
render();
}
async function copyPi(p, to, what, name) {
if (!to) return;
const key = p.id + " " + (what.ext || what.pkg);
piBusy.add(key);
render();
try {
const v = await api("library/pi/copy", { from: p.id, to: to.id, ...what });
piView = v;
status(what.pkg
? t("{name} is in {agent}'s packages now: Pi installs it when it next starts", { name, agent: to.name })
: v.install
? t("{name} is copied to {agent}. It needs its packages: run npm install in {dir} there", { name, agent: to.name, dir: v.install })
: t("{name} is copied to {agent}: Pi loads it when it next starts, or at /reload", { name, agent: to.name }), "ok", v.install ? 12000 : 6000);
} catch (e) {
status(e.message, "err", 8000);
}
piBusy.delete(key);
render();
}
// what rtk saved day by day (week by week past 92 days), over the last
// 30 or 90 days or since it first ran: each bar the commands' whole
// output, the part RTK kept from the model on top of what still went
let rtkRange = 0; // days; 0 all
try { rtkRange = +(localStorage.getItem("magpie.rtkRange") ?? 0) || 0; } catch {}
const isoDay = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const dayOf = (s) => { const [y, m, d] = s.split("-").map(Number); return new Date(y, m - 1, d); };
function rtkChart(days) {
const chart = el("div", "chart lib-rtk-chart");
const today = new Date(); today.setHours(0, 0, 0, 0);
let first = dayOf(days[0].date);
if (rtkRange) { first = new Date(today); first.setDate(first.getDate() - rtkRange + 1); }
if (first > today) first = new Date(today);
const n = Math.round((today - first) / 864e5) + 1;
const step = n > 92 ? 7 : 1;
const buckets = [], at = new Map();
for (let d = new Date(first); d <= today; d.setDate(d.getDate() + step)) {
const b = { day: new Date(d), commands: 0, input: 0, saved: 0 };
for (let i = 0; i < step; i++) { const x = new Date(d); x.setDate(x.getDate() + i); at.set(isoDay(x), b); }
buckets.push(b);
}
const sum = { commands: 0, input: 0, saved: 0 };
for (const r of days) {
const b = at.get(r.date);
if (!b) continue;
b.commands += r.commands; b.input += r.input; b.saved += r.saved;
sum.commands += r.commands; sum.input += r.input; sum.saved += r.saved;
}
const peak = Math.max(1, ...buckets.map((b) => b.input));
const head = el("div", "sess-chart-head");
const seg = segs([[30, t("30 days")], [90, t("90 days")], [0, t("All")]], rtkRange, (r) => {
rtkRange = r;
try { localStorage.setItem("magpie.rtkRange", String(r)); } catch {}
chart.replaceWith(rtkChart(days));
});
head.append(el("span", "label", t(step === 7 ? "Saved by week" : "Saved by day")), seg, el("span", "grow"), el("span", "peak", tokens(peak)));
const bars = el("div", "bars"), labels = el("div", "labels");
const k = buckets.length;
const every = k <= 8 ? 1 : k <= 31 ? Math.ceil(k / 6) : Math.ceil(k / 5);
const short = (d) => `${d.getMonth() + 1}/${d.getDate()}`;
buckets.forEach((b, i) => {
const bar = el("div", "bar");
const saved = el("i", "out"), kept = el("i", "in");
saved.style.height = (100 * b.saved / peak).toFixed(1) + "%";
kept.style.height = (100 * Math.max(0, b.input - b.saved) / peak).toFixed(1) + "%";
bar.append(saved, kept);
const when = step === 7 ? t("week of {label}", { label: short(b.day) }) : short(b.day);
bar.title = b.commands
? t("{when} · {saved} tokens saved over {n} commands — {pct}%", { when, saved: tokens(b.saved), n: b.commands.toLocaleString(intlLang()), pct: b.input ? Math.round(100 * b.saved / b.input) : 0 })
: t("{when} · nothing", { when });
bars.append(bar);
const end = i === k - 1 && (k - 1) % every >= every / 2;
labels.append(el("span", "", i % every === 0 || end ? short(b.day) : ""));
});
const foot = el("div", "lib-rtk-foot");
const key = (cls, text) => { const x = el("span", "lib-rtk-key"); x.append(el("i", cls), el("span", "", text)); return x; };
foot.append(key("out", t("saved")), key("in", t("still sent")), el("span", "grow"),
el("span", "", sum.commands
? t("{saved} tokens saved over {n} commands — {pct}%", { saved: tokens(sum.saved), n: sum.commands.toLocaleString(intlLang()), pct: sum.input ? Math.round(100 * sum.saved / sum.input) : 0 })
: t("Nothing run through RTK in this time")));
chart.append(head, bars, labels, foot);
return chart;
}
// vNewer: version a is after b
function vNewer(a, b) {
const x = a.split(/[.-]/).map((n) => parseInt(n, 10) || 0), y = b.split(/[.-]/).map((n) => parseInt(n, 10) || 0);
for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
return false;
}
let rtkUpgrading = false;
let rtkUpgradeErr = ""; // why the last upgrade failed, shown on the card
async function upgradeRTK() {
rtkUpgrading = true;
rtkUpgradeErr = "";
render();
let failed = false;
try {
rtk = await api("library/rtk/upgrade", {});
if (rtk.note) status(rtk.note, "", 10000);
else status(t("RTK is now {v}", { v: rtk.version }), "ok", 6000);
} catch (e) {
failed = true;
rtkUpgradeErr = e.message;
status(t("RTK's upgrade failed — the RTK card says why"), "err", 10000);
}
rtkUpgrading = false;
render();
// the version it left, whatever the installer said
if (failed) loadRTK();
}
let rtkPathing = false;
async function pathRTK() {
rtkPathing = true;
render();
try {
rtk = await api("library/rtk/path", {});
status(rtk.restart?.length ? t("RTK is on your PATH — restart your agents, and the terminals they run in, to use it") : t("RTK is on your PATH"), "ok", 6000);
} catch (e) {
status(e.message, "err", 10000);
}
rtkPathing = false;
render();
}
// RTK in a WSL distro: its agents' hooks run there, so they run its own
// rtk, installed by RTK's own Linux script run in the distro. A distro
// that isn't running is never started for it.
let rtkInstallingIn = "";
const rtkInstallErrIn = {};
function rtkDistroCard(d) {
const card = el("div", "list lib-card lib-rtk-wsl");
const ttl = el("div", "lib-cardhead");
ttl.append(el("b", "", t("RTK in WSL {distro}", { distro: d.name })), el("span", "grow"));
if (d.path) ttl.append(el("span", "note mono", d.version ? "v" + d.version : d.path));
card.append(ttl);
const acts = el("div", "lib-acts");
const again = (cls) => button(t("Check again"), cls, () => { rtk = null; render(); });
if (d.asleep) {
card.append(el("p", "lib-rtk-gain", t("WSL {distro} isn't running: magpie doesn't start it to look for RTK or change its agents. Start the distro, then Check again.", { distro: d.name })));
acts.append(again("action"));
} else if (!d.path) {
const installing = rtkInstallingIn === d.name;
card.append(el("p", "lib-rtk-gain", installing
? t("Installing RTK in WSL {distro}… this can take a minute.", { distro: d.name })
: d.install
? t("RTK isn't installed in WSL {distro}. Agents there run their hooks in the distro, so they need RTK there: magpie can run RTK's own installer in it.", { distro: d.name })
: t("magpie couldn't look for RTK in WSL {distro}.", { distro: d.name })));
if (d.install) card.append(el("p", "lib-rtk-cmd", d.install));
if (rtkInstallErrIn[d.name] && !installing) card.append(el("p", "lib-rtk-note lib-rtk-err lib-rtk-install-err", t("The install failed: {why}", { why: rtkInstallErrIn[d.name] })));
if (d.install) {
const ib = button(installing ? t("Installing…") : t("Install RTK in WSL {distro}", { distro: d.name }), "action", () => installRTKIn(d.name));
ib.disabled = !!rtkInstallingIn || rtkInstalling;
acts.append(ib);
}
acts.append(again(d.install ? "" : "action"));
} else if (d.offPath) {
const dir = d.path.replace(/\/[^/]*$/, "");
card.append(el("p", "lib-rtk-note lib-rtk-offpath", t("RTK is in {dir} in WSL {distro}, which isn't on its shells' PATH. Agents there run rtk by name, so they can't find it. Add {dir} to PATH in your shell profile there, then Check again.", { dir, distro: d.name })));
acts.append(again("action"));
} else {
card.append(el("p", "lib-rtk-gain", t("Agents in WSL {distro} run its own RTK, at {path}. What it saves there is in its own count (rtk gain in the distro), not the one above.", { distro: d.name, path: d.path })));
}
if (acts.childNodes.length) card.append(acts);
return card;
}
async function installRTKIn(distro) {
rtkInstallingIn = distro;
delete rtkInstallErrIn[distro];
render();
try {
rtk = await api("library/rtk/install", { distro });
status(t("RTK is installed in WSL {distro} — switch it on for its agents below", { distro }), "ok", 6000);
} catch (e) {
rtkInstallErrIn[distro] = e.message;
status(e.message, "err", 10000);
}
rtkInstallingIn = "";
render();
}
let rtkInstalling = false, rtkInstallErr = "";
async function installRTK() {
rtkInstalling = true;
rtkInstallErr = "";
render();
try {
rtk = await api("library/rtk/install", {});
status(t("RTK is installed — switch it on for your agents below"), "ok", 6000);
} catch (e) {
rtkInstallErr = e.message;
status(e.message, "err", 10000);
}
rtkInstalling = false;
render();
}
function tokens(n) {
if (n >= 1e6) return (n / 1e6).toFixed(1) + "M";
if (n >= 1e3) return (n / 1e3).toFixed(1) + "k";
return String(n);
}
// ---------- instructions ----------
// Measured at height auto, the textarea is short for a moment. What holds
// it is held at its height meanwhile, so the page never is: a page gone
// short has its view's scroll clamped by the browser, which no height put
// back undoes, and an input method's every keystroke is an input (#2636:
// the page jumped while a word was composed).
function autosize(ta, min) {
const fit = () => {
const box = ta.parentElement, was = box?.style.minHeight;
if (box) box.style.minHeight = box.offsetHeight + "px";
ta.style.height = "auto";
ta.style.height = Math.max(min, ta.scrollHeight + 2) + "px";
if (box) box.style.minHeight = was;
};
ta.addEventListener("input", fit);
// fitted once it's on the page, before it's painted, so what's under it
// doesn't move a frame later
fits.push(fit);
requestAnimationFrame(fit); // and one drawn outside render()
}
function iv() { return lib.instructions; }
const setOf = (id) => lib.instructions.sets.find((x) => x.id === id);
const setName = (x) => x.name || t("Default");
function unsavedTexts() {
const out = {};
for (const [id, v] of Object.entries(texts)) if (setOf(id) && v !== setOf(id).text) out[id] = v;
return out;
}
function dirty() {
if (Object.keys(unsavedTexts()).length) return true;
return Object.entries(extras).some(([id, v]) => v !== (lib.instructions.agents.find((a) => a.agent === id)?.extra || ""));
}
async function saveInstructions() {
const c = {};
const tx = unsavedTexts();
if (Object.keys(tx).length) c.texts = tx;
const ex = {};
for (const [id, v] of Object.entries(extras)) if (v !== (lib.instructions.agents.find((a) => a.agent === id)?.extra || "")) ex[id] = v;
if (Object.keys(ex).length) c.extra = ex;
if (!Object.keys(c).length) return;
if (await change("instructions/save", c)) {
for (const k of Object.keys(texts)) delete texts[k];
for (const k of Object.keys(extras)) delete extras[k];
render();
}
}
async function discard(force = false) {
if (force !== true && dirty() && !(await confirmDiscard())) return;
for (const k of Object.keys(texts)) delete texts[k];
for (const k of Object.keys(extras)) delete extras[k];
render();
}
function renderInstructions(body) {
const iv = lib.instructions;
body.append(intro(t("Write it once: every agent switched on below reads it before each conversation, in its own instructions file.")));
// the sets of shared instructions: one is on, the one the agents read;
// a set opens to be edited (#106)
const card = el("div", "list lib-list lib-sets");
const ttl = el("div", "lib-cardhead");
ttl.append(glyph(GLYPH.doc), el("b", "", t("Shared instructions")), el("span", "grow"), el("span", "note", "Markdown · " + (/^Mac/.test(navigator.platform) ? "⌘S" : "Ctrl+S")));
card.append(ttl);
for (const x of iv.sets) card.append(...setRow(x));
if (addingSet) card.append(newSetRow());
else {
const add = el("div", "lib-acts lib-setadd");
add.append(button("+ " + t("New set"), "action", () => { addingSet = true; render(); }));
card.append(add);
}
const bar = el("div", "lib-savebar");
bar.append(el("span", "note", t("Not saved yet")), el("span", "grow"), button(t("Discard"), "", discard), button(t("Save"), "primary", saveInstructions));
bar.hidden = !dirty();
body.append(card);
const rh = el("div", "row-head");
// which set the agents switched on read, said where they're switched
// on (Fate: a set made and written was read by none, the Default being
// the one in use)
const inUse = (iv.sets || []).find((x) => x.active) || (iv.sets || [])[0];
rh.append(el("span", "label", t("Agents")));
if (inUse) rh.append(el("span", "note lib-reads", t("They read {name}", { name: setName(inUse) }) + ((inUse.text || "").trim() ? "" : " · " + t("Empty"))));
rh.append(el("span", "grow"), el("span", "note", t("magpie writes its part between two marker lines — the rest of each file stays yours")));
body.append(rh);
const list = el("div", "list lib-list");
// a hidden agent still reading them is listed, to switch it off (#475)
const rows = iv.agents.filter((a) => !isHidden({ id: a.agent }) || a.on);
for (const a of rows) list.append(...instructionsRow(a));
if (!rows.length) list.append(el("div", "lib-none", t("None of your agents reads a user-wide instructions file magpie knows.")));
body.append(list);
// a stopped WSL distro's agents are rows above when magpie saw their
// file; one it didn't see isn't said to keep none
const skip = shownAgents().filter((a) => !a.instructions && !a.asleep);
if (skip.length) body.append(el("p", "lib-aside", t(skip.length > 1 ? "{agents} keep no user-wide instructions file." : "{agents} keeps no user-wide instructions file.", { agents: skip.map((a) => a.name).join(", ") })));
body.append(...asleepAsides(rows.filter((a) => a.asleep)));
body.append(bar);
}
function setRow(x) {
const isOpen = openSet === x.id;
const text = texts[x.id] ?? x.text;
const row = el("div", "row lib-row click lib-set" + (isOpen ? " open" : "") + (x.active ? " on" : ""));
const pick = el("button", "lib-radio" + (x.active ? " on" : ""));
pick.setAttribute("role", "radio");
pick.setAttribute("aria-checked", x.active ? "true" : "false");
pick.title = x.active ? t("The agents switched on below read this set") : t("Switch the agents to this set");
pick.onclick = (e) => {
e.stopPropagation();
if (x.active) return;
const c = { activate: x.id };
const tx = unsavedTexts();
if (Object.keys(tx).length) c.texts = tx;
change("instructions/save", c, t("The agents read {name} now", { name: setName(x) })).then((ok) => { if (ok) for (const k of Object.keys(tx)) delete texts[k]; });
};
const who = el("div", "who");
who.append(el("div", "name", setName(x)));
const first = text.split("\n").find((l) => l.trim()) || "";
who.append(el("div", "sub", first ? first.replace(/^#+\s*/, "") : t("Empty")));
const tags = el("div", "lib-tags");
if (x.active) tags.append(tag(t("In use"), "", t("The agents switched on below read this set")));
if (x.file) tags.append(tag(t("Your file"), "", t("Kept in {path}, not in the library: edits there reach the agents, and Save writes there", { path: tilde(x.file) })));
if (text !== x.text) tags.append(tag(t("Not saved yet"), "warn"));
const chev = el("span", "chev");
chev.append(svg(CHEV_R, 11, 1.7));
row.append(pick, who, tags, chev);
row.onclick = () => { openSet = isOpen ? null : x.id; removingSet = null; render(); };
if (!isOpen) return [row];
const det = el("div", "lib-detail");
const nm = input(setName(x), t("Name"));
nm.dataset.lib = "setname:" + x.id;
nm.className = "lib-setname";
const rename = () => {
const v = nm.value.trim();
if (!v || v === setName(x)) { nm.value = setName(x); return; }
change("instructions/save", { rename: { id: x.id, name: v } }, t("Renamed to {name}", { name: v }));
};
nm.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") nm.blur(); else if (e.key === "Escape") { nm.value = setName(x); nm.blur(); } };
nm.onblur = rename;
const ta = el("textarea", "lib-text small");
ta.dataset.lib = "set:" + x.id;
ta.spellcheck = false;
ta.value = text;
ta.placeholder = t("What every agent should know — how you like code written, the stack you work in, the commands that run your tests…");
ta.oninput = () => { texts[x.id] = ta.value; renderSaveBars(); };
ta.onkeydown = (e) => { e.stopPropagation(); if ((e.metaKey || e.ctrlKey) && e.key === "s") { e.preventDefault(); saveInstructions(); } };
autosize(ta, 150);
det.append(nm);
if (x.file) {
// a set kept in a file of the user's own (~/.agents/AGENTS.md): what
// the page shows is that file, and Save writes to it
const where = el("div", "note lib-setfile");
where.append(t("Kept in") + " ", pathLink(x.file));
det.append(where);
// Droid and omp read ~/.agents/AGENTS.md themselves: given it by
// magpie too, they'd read it twice
const twice = /[\\/]\.agents[\\/]AGENTS\.md$/.test(x.file) ? lib.instructions.agents.filter((a) => a.on && ["droid", "omp"].includes(a.agent)) : [];
if (twice.length) det.append(el("p", "lib-aside lib-twice", t(twice.length > 1 ? "{agents} read this file themselves too: switch them off below so they don't read it twice." : "{agents} reads this file itself too: switch it off below so it doesn't read it twice.", { agents: twice.map((a) => a.name).join(", ") })));
}
det.append(ta);
const acts = el("div", "lib-acts");
if (!x.active) acts.append(button(t("Switch the agents to this set"), "action lib-use", () => pick.onclick({ stopPropagation() {} })));
if (x.id !== "default") {
// its text goes with it, so a second click says so and does it
const sure = removingSet === x.id;
const rm = button(sure ? (x.file ? t("Remove {name} — the file stays", { name: setName(x) }) : t("Remove {name} and its text", { name: setName(x) })) : t("Remove"), sure ? "primary danger-fill" : "action danger", () => {
if (!sure) { removingSet = x.id; render(); return; }
removingSet = null;
delete texts[x.id];
openSet = null;
change("instructions/save", { remove: x.id }, t("{name} removed", { name: setName(x) }));
});
if (x.active) { rm.disabled = true; rm.title = t("Switch the agents to another set before removing this one"); }
acts.append(rm);
if (sure) acts.append(button(t("Cancel"), "", () => { removingSet = null; render(); }));
}
if (acts.childElementCount) det.append(acts);
det.onclick = (e) => e.stopPropagation();
return [row, det];
}
function newSetRow() {
const row = el("div", "row lib-row lib-set lib-setnew");
const nm = input("", t("Name, e.g. Work"));
nm.dataset.lib = "newset";
nm.className = "lib-setname grow";
const create = async () => {
const name = nm.value.trim();
if (!name) return;
const id = "s" + Date.now().toString(36);
// the set in use empty, the new one is read from then on (as the
// library does it)
const inUse = (iv().sets || []).find((x) => x.active);
const said = !inUse || (inUse.text || "").trim() ? t("{name} added — switch the agents to it when it's ready", { name }) : t("{name} added — the agents read it", { name });
const create = { id, name };
if (file && file.value.trim()) create.file = file.value.trim();
if (await change("instructions/save", { create }, said)) {
addingSet = false;
openSet = id;
render();
}
};
const cancel = () => { addingSet = false; render(); };
nm.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") create(); else if (e.key === "Escape") cancel(); };
queueMicrotask(() => nm.focus());
// a set can be kept in a file of the user's own instead, one that other
// tools keep or read too: ~/.agents/AGENTS.md (新v学员 on Discord)
let file = null;
const link = button(t("Keep in a file…"), "action lib-setlink", () => {
file = input("~/.agents/AGENTS.md", t("Full path of a Markdown file"));
file.value = "~/.agents/AGENTS.md";
file.dataset.lib = "newsetfile";
file.className = "lib-setname lib-setfile-in grow";
file.onkeydown = nm.onkeydown;
if (!nm.value.trim()) nm.value = "AGENTS.md";
link.replaceWith(file);
file.focus();
});
row.append(nm, link, button(t("Cancel"), "", cancel), button(t("Add"), "primary", create));
return row;
}
// An agent in a stopped WSL distro (asleep) is its row as magpie last saw
// it, greyer: its file isn't read or shown in the file manager, either of
// which would start WSL (#3896), and a switch is written there the next
// time it runs. One whose file magpie never saw (unseen) is listed only
// while it is on, its switch kept as it is (#4182).
function instructionsRow(a) {
const isOpen = open.has(a.agent);
const row = el("div", "row lib-row click" + (isOpen ? " open" : "") + (a.asleep ? " asleep" : ""));
const who = el("div", "who");
const name = el("div", "name", a.name);
who.append(name);
const sub = el("div", "sub");
if (a.asleep) { if (a.path) sub.append(el("span", "lib-path", tilde(a.path))); }
else sub.append(pathLink(a.path));
who.append(sub);
const tags = el("div", "lib-tags");
const extra = extras[a.agent] ?? a.extra;
if (isHidden({ id: a.agent })) tags.append(tag(t("Hidden"), "", t("Hidden on the Agents page: switch it off here to take the shared instructions out of its file")));
if (a.on && extra) tags.append(tag(t("+ its own"), "", t("{agent} gets something of its own after the shared text", { agent: a.name })));
if (a.edited) tags.append(tag(t("edited in the file"), "warn", t("magpie's part of this file was changed there; magpie leaves it until the library's text changes")));
if (a.own) tags.append(tag(a.own === 1 ? t("1 line of its own") : t("{n} lines of its own", { n: a.own }), "", t("The file has instructions besides magpie's part — they stay, and the agent reads both")));
const chev = el("span", "chev");
chev.append(svg(CHEV_R, 11, 1.7));
const sw = toggle(a.on, t("{agent} reads the shared instructions", { agent: a.name }), (on) => {
if (a.unseen) return;
const agents = lib.instructions.agents.filter((x) => (x.agent === a.agent ? on : x.on)).map((x) => x.agent);
let done = t("Taken out of {agent}'s file", { agent: a.name });
if (on && dirty()) done = t("{agent} is on — save to write the new text into its file", { agent: a.name });
else if (on && !iv().shared.trim() && !(a.extra || "").trim()) {
const sets = iv().sets || [], inUse = sets.find((x) => x.active) || sets[0];
done = inUse && sets.some((x) => (x.text || "").trim())
? t("{agent} is on, but it reads {name}, which is empty — switch the agents to the set they should read", { agent: a.name, name: setName(inUse) })
: t("{agent} is on — it gets the shared instructions once there are some", { agent: a.name });
}
else if (on) done = t("{agent} reads the shared instructions now", { agent: a.name });
if (a.asleep) done = asleepSaid;
change("instructions/save", { agents }, done);
});
const asleepSaid = a.asleep && t("WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.", { distro: a.asleep });
if (a.unseen) { sw.setAttribute("aria-disabled", "true"); sw.title = t("WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this", { distro: a.asleep, agent: a.name }); }
else if (a.asleep) sw.title = asleepSaid;
row.append(icon(a.icon), who, tags, sw, chev);
row.onclick = () => { if (isOpen) open.delete(a.agent); else open.add(a.agent); render(); };
if (!isOpen) return [row];
const det = el("div", "lib-detail");
if (a.override) {
const w = el("div", "lib-warn");
w.append(el("span", "", t("{agent} reads {file} instead of this file while it has anything in it.", { agent: a.name, file: tilde(a.override) }) + " "), pathLink(a.override));
det.append(w);
}
if (a.agent === "opencode" || a.agent === "mimocode" || a.agent === "deveco") det.append(el("p", "lib-aside", t("{agent} reads Claude Code's CLAUDE.md when it has no AGENTS.md of its own.", { agent: a.name })));
if (a.agent === "agy") det.append(el("p", "lib-aside", t("Antigravity reads Gemini CLI's ~/.gemini/GEMINI.md as well as this file, so text given to both is read twice.")));
if (a.profile) det.append(el("p", "lib-aside", t("This file is {agent}'s profile of you: magpie adds its part after yours and leaves your own lines in it. A USER.md in a workspace is read instead of this one.", { agent: a.name })));
const lab = el("label", "lib-lab", t("Only for {agent}, after the shared text", { agent: a.name }));
const ta = el("textarea", "lib-text small");
ta.dataset.lib = "extra:" + a.agent;
ta.spellcheck = false;
ta.value = extra;
ta.placeholder = t("Anything only {agent} should be told", { agent: a.name });
ta.oninput = () => { extras[a.agent] = ta.value; renderSaveBars(); };
ta.onkeydown = (e) => { e.stopPropagation(); if ((e.metaKey || e.ctrlKey) && e.key === "s") { e.preventDefault(); saveInstructions(); } };
autosize(ta, 64);
det.append(lab, ta);
if (!a.on && extra) det.append(el("p", "lib-aside", t("Switch {agent} on for it to read this.", { agent: a.name })));
const acts = el("div", "lib-acts");
if (a.own && !a.profile) {
const b = button(t("Move its own into the shared text"), "action", () => change("instructions/import", { name: a.agent }, t("Moved into the shared instructions — {agent} reads the same as before", { agent: a.name })));
b.title = t("Takes the {n} lines out of the file, adds them to the shared text, and switches {agent} on — so it reads what it read before, and the other agents can too", { n: a.own, agent: a.name });
acts.append(b);
}
if (a.edited) {
const b = button(t("Write the library's text again"), "action", () => change("instructions/save", { rewrite: [a.agent] }, t("{agent}'s file has the library's text again", { agent: a.name })));
b.title = t("Replaces what was changed in magpie's part of the file; the file is kept aside first");
acts.append(b);
}
if (acts.childElementCount) det.append(acts);
det.onclick = (e) => e.stopPropagation();
return [row, det];
}
function renderSaveBars() {
const bar = page.querySelector(".lib-savebar");
if (bar) bar.hidden = !dirty();
}
function tag(text, kind, title) {
const s = el("span", "lib-tag " + (kind || ""), text);
if (title) s.title = title;
return s;
}
// ---------- MCP servers ----------
function serverLine(s) {
if (s.transport === "stdio") return [s.command, ...(s.args || [])].map(quote).join(" ");
return s.url;
}
// quote: an argument as this system's shell reads it, and words() reads
// back. On Windows that is cmd's double quotes, and a \ is a path's, not an
// escape: sh's 'C:\…\npx.cmd' read as quotes magpie had added to the
// command (fremontdango on Discord), and a path typed as it is lost its \
// and : on save (#2685).
const WIN_LINE = /^Win/.test(navigator.platform);
function quote(a) {
if (WIN_LINE) return a && !/[\s"'&|<>^%]/.test(a) ? a : '"' + a.replace(/"/g, '""') + '"';
return /^[\w@%+=:,./-]+$/.test(a) ? a : "'" + a.replace(/'/g, `'\\''`) + "'";
}
function sseBlocked(s) {
return (a) => {
if (remote(s) && a.noRemote) return t("{agent} runs only a command from its settings — add a remote server in its Connectors instead", { agent: a.name });
if (s.transport === "sse" && a.noSSE) return t("{agent} can't reach a server over SSE — only a command or streamable HTTP", { agent: a.name });
// #1250: written there as it is, the agent would send the text
// itself; written with the value, the token would be in its file
return envRefs(s) && a.noEnvRefs ? t("{agent} can't read {ref} from its settings — given this server, the token would be written there as plain text", { agent: a.name, ref: "${NAME}" }) : "";
};
}
// envRefs says whether the server's headers (remote) or environment
// (command) reference a variable: ${NAME}, as the library writes one
const envRef = /\$\{[A-Za-z_][A-Za-z0-9_]*\}/;
const envRefs = (s) => Object.values((remote(s) ? s.headers : s.env) || {}).some((v) => envRef.test(v));
// reaches(s) says whether an agent can be given the server
const remote = (s) => s.transport === "http" || s.transport === "sse";
const reaches = (s) => (a) => !a || (!(remote(s) && a.noRemote) && !(s.transport === "sse" && a.noSSE) && !(envRefs(s) && a.noEnvRefs));
function renderServers(body) {
body.append(intro(agentless()
? t("Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key.")
: t("Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads.")));
const all = mcpAgents();
pickingFor("servers", lib.servers);
if (!lib.servers.length) {
const add = button(t("+ Add a server"), "action", () => editServer(null));
body.append(empty(t("No servers in the library yet"), lib.foundServers.length && !agentless() ? t("Add one, or bring in those your agents already have, below.") : t("Paste a server's JSON from its README, or fill it in."), add));
// with no agent, the router is what the page is for: there to turn
// on before the first server
if (agentless()) body.append(...hubPart());
} else {
const list = el("div", "list lib-list");
// in the order the reader picked (#481), A→Z till then
const fill = () => list.replaceChildren(...[...lib.servers].sort(byName(sortOf("libServers"))).map((s) => serverRow(s, all)));
// one heading over the list, with what the skills' has (#1027): the
// order, Select, every server on or off for every agent shown, one
// agent's (#475, or out of a hidden one) and every server out
const many = lib.servers.length > 1, by = byAgentRows("servers").length;
if (many || by) {
const rh = el("div", "row-head lib-serverhead");
rh.append(el("span", "label", t("In the library")), el("span", "grow"));
if (many) rh.append(sortBy("libServers", NAME_SORTS, fill));
// the rest under ⋯, as the skills' (ryanpascal on Discord)
if (many && all.length) rh.append(pickButton("servers"));
rh.append(barMore([
...many && all.length ? everyButtons("servers", all).map((b) => [b, GLYPH.power]) : [],
by && [byAgentButton("servers"), GLYPH.person],
null,
many && [removeEveryButton("servers"), GLYPH.trash],
]));
body.append(rh);
}
fill();
body.append(list);
if (picking) body.append(pickBar(all));
const after = el("div", "after-list");
after.append(button(t("+ Add server"), "", () => editServer(null)));
body.append(after);
// kept while picking too, as Add server is: the page stays as tall,
// so Select doesn't move under the pointer (library-servers-bulk)
body.append(...hubPart());
// each server is checked once a session, and again only once it
// changed; once the rows are on the page, for them to show it. One
// that no agent and no project has is started for nobody, so it is
// checked only when the reader clicks its status (#1597, xiaozhu1337),
// and again once it changed after that: a sign-in since isn't left
// beside "needs sign-in" (新v学员 on Discord)
// With no agent, the router is what starts them, so on it checks them too
const unchecked = lib.servers.filter((s) => (inUse(s) || (agentless() && lib.mcpHub && inHub(s)) || health.has(s.name)) && health.get(s.name)?.key !== healthKey(s));
queueMicrotask(() => checkHealth(unchecked));
}
// an agent's own servers (Codex's node_repl, added each time it starts)
// aren't listed: magpie leaves them as they are
const found = agentless() ? [] : lib.foundServers.filter((f) => !f.own);
if (found.length) {
const rh = el("div", "row-head");
rh.append(el("span", "label", t("In your agents")), el("span", "grow"), el("span", "note", t("not in the library — bring one in to manage it here")));
body.append(rh);
body.append(foldedFound("mcp", found.map(foundServerRow)));
}
if (!agentless() && (lib.servers.length || lib.projects.length)) renderProjects(body, "mcp");
const skip = shownAgents().filter((a) => !a.mcp);
if (skip.length) body.append(el("p", "lib-aside", t("{agents} has no MCP servers magpie can write.", { agents: skip.map((a) => a.name).join(", ") })));
if (!gatewayPage()) body.append(...asleepAsides());
// WorkBuddy connects a server only once it is trusted there, again
// after its command or address changes (#1266)
for (const wb of shownAgents().filter((a) => (a.id === "workbuddy" || a.id === "workbuddy-ai") && a.mcp)) {
if (lib.servers.some((s) => s.agents?.includes(wb.id))) {
body.append(el("p", "lib-aside lib-wb-trust", t("{agent} connects a server only once you trust it: switch it on in {agent}'s MCP settings, and again after its command or address changes.", { agent: wb.name })));
}
}
body.append(discover("mcp"));
}
// The MCP hub (#2679): magpie as each agent's one MCP server, handing
// each call on to the library's servers ticked for it, and one address
// for any other app with every server in the library. A switch, off
// till turned on; on, what it serves, the address with Connect, and the
// agents that keep each server's own entry, with why.
function hubPart() {
const list = el("div", "list lib-list lib-hublist");
const row = el("div", "row lib-row lib-hub");
const who = el("div", "who");
who.append(el("div", "name", t("MCP router")));
who.append(el("div", "sub wraps", agentless()
? (lib.mcpHub ? t("Any app connects at the address below for every server in the library, as server__tool.") : t("Serve every server in the library at one address, for any app to connect to."))
: lib.mcpHub
? t("Each agent is given one server, magpie, in place of these. magpie runs each server once for all of them and hands each call to it, as server__tool. Restart an agent for it to read the change.")
: t("Serve every server through magpie: each agent is given one server, magpie, in place of these, and any other app connects at one address.")));
if (lib.mcpHub) who.append(el("div", "sub lib-hubstats", hubStats()));
row.append(hubMark(), who, toggle(!!lib.mcpHub, t("MCP router"), (on) =>
change("servers/hub", { on }, agentless()
? (on ? t("The MCP router is on: apps can connect at its address") : t("The MCP router is off"))
: on
? t("The agents are given magpie's one MCP server — restart them to use it")
: t("The agents are given each server's own entry again — restart them to use it"))));
list.append(row);
const out = [list];
if (!lib.mcpHub) return out;
// the one address any other app connects at
const at = el("div", "row lib-row lib-hubat");
const aw = el("div", "who");
// what it is, not who: the hub's address (the owner: "Other apps" over
// an address read as nonsense); who connects there is in the tooltip
aw.append(el("div", "name", t("Router address")));
aw.title = t("Any other app, as Cursor or VS Code, connects here for every server in the library");
const u = el("div", "sub mono lib-hubURL", hubURL());
u.title = hubURL();
aw.append(u);
const connect = button(t("Connect…"), "", () => connectHub());
connect.classList.add("lib-hubconnect");
at.append(glyph(GLYPH.web), aw, copyBtn(hubURL(), t("Address")), connect);
list.append(at);
list.append(hubNoteRow(), hubToolsRow());
const names = (why) => hubAgents().filter((a) => a.hub === why).map((a) => a.name).join(", ");
const why = [
["no-remote", "{agents} reaches no MCP server over HTTP, so it keeps each server's own entry."],
["taken", "A server in the library is called magpie, so {agents} keeps each server's own entry: give that server another name for the router to be used."],
["own", "{agents} has an MCP server called magpie of its own, which magpie leaves as it is, so it keeps each server's own entry."],
];
for (const [k, text] of why) {
const n = names(k);
if (n) {
const p = el("p", "lib-aside lib-hub-why", t(text, { agents: n }));
p.dataset.why = k;
out.push(p);
}
}
return out;
}
// What the router says of itself to the agents (packinggoodsllc_07668 on
// Discord: one magpie in China and one in Los Angeles serve the same
// tools, and an agent fetching Google should pick Los Angeles): before
// each tool's description and in what it tells an agent connecting.
// Empty, an agent on another computer is told this computer's name,
// shown as the placeholder. Saved on Enter or leaving the field, this
// computer's own (settings' routerNote).
function hubNoteRow() {
const row = el("div", "row lib-row lib-hubnoterow");
const who = el("div", "who");
who.append(el("div", "name", t("Router name")));
who.append(el("div", "sub wraps", t("Agents connected to more than one router tell them apart by it. Empty, agents on other computers are told this computer's name.")));
const f = el("input", "lib-filter lib-hubname");
f.type = "text";
f.value = lib.hubNote || "";
f.placeholder = lib.hubName || "";
f.maxLength = 80;
f.spellcheck = false;
f.autocomplete = "off";
f.setAttribute("aria-label", t("Router name"));
let saved = lib.hubNote || "";
const save = () => {
const note = f.value.trim().replace(/\s+/g, " ");
if (note === saved) return;
const was = saved;
saved = note;
// a change of settings, not of the agents' files: no result to report
change("servers/hub-note", { note }).then((ok) => {
if (!ok) { saved = was; return; }
status(note
? t("Agents are told this router is {name} — restart them to read it", { name: note })
: t("Agents on other computers are told this computer's name — restart them to read it"), "ok");
});
};
f.onkeydown = (e) => {
e.stopPropagation();
// an Enter that ends an input method's composition is the IME's
if (e.isComposing || e.keyCode === 229) return;
if (e.key === "Enter") { e.preventDefault(); f.blur(); }
if (e.key === "Escape") { e.preventDefault(); f.value = saved; f.blur(); }
};
f.onblur = save;
row.append(glyph(GLYPH.doc), who, f);
return row;
}
// Tools on demand (ArvinCharl on X: the router's tools filled the
// context): on, the default, an agent that doesn't search its MCP tools
// itself and is given more than a few is given two in their place, one
// finding a tool and one running it (gateway.hubOnDemand). Off gives
// every agent every tool whole (settings' routerAllTools).
function hubToolsRow() {
const row = el("div", "row lib-row lib-hubtoolsrow");
const who = el("div", "who");
who.append(el("div", "name", t("Tools on demand")));
who.append(el("div", "sub wraps", t("An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.")));
const on = !lib.hubAllTools;
row.append(glyph(GLYPH.search), who, toggle(on, t("Tools on demand"), (v) =>
change("servers/hub-tools", { on: !v }).then((ok) => {
if (ok) status(v
? t("Agents are given the router's tools on demand — restart them to use it")
: t("Agents are given every tool of the router — restart them to use it"), "ok");
})));
return row;
}
// every server is behind the hub, magpie's own image server too, but one
// the user keeps direct (#4382): each agent's own entry (inHub in
// mcp_hub.go)
const inHub = (s) => s.hub !== "direct";
// the servers each agent is given directly, by name, for the hub's lines
const directNames = () => lib.servers.filter((s) => !inHub(s)).map((s) => s.name).join(", ");
// what the hub serves: its servers, their tools as far as checked, and
// the agents given it
function hubStats() {
const servers = lib.servers.filter(inHub);
const parts = [servers.length === 1 ? t("1 server") : t("{n} servers", { n: servers.length })];
const known = servers.filter((s) => health.get(s.name)?.h?.state === "ok");
if (known.length) {
const n = known.reduce((sum, s) => sum + Math.max(0, (health.get(s.name).h.tools || 0) - (s.disabledTools?.length || 0)), 0);
parts.push(n === 1 ? t("1 tool") : t("{n} tools", { n }));
}
const given = hubAgents().filter((a) => a.hub === "on").map((a) => a.name);
if (given.length) parts.push(t("in {agents}", { agents: given.length > 3 ? t("{first} and {n} more", { first: given.slice(0, 2).join(", "), n: given.length - 2 }) : given.join(", ") }));
// the owner, counting two servers and seeing one: where the other went
const direct = agentless() ? "" : directNames();
if (direct) parts.push(t("{name} is given to each agent directly", { name: direct }));
return parts.join(" · ");
}
const hubURL = () => mcpAddress(state.settings || {}, lib.hubPath.replace(/\/+$/, ""));
// Connect to the hub (#2679): two tabs. Agents: every agent magpie looks
// after, in three groups, each a switch of its own. Not connected
// comes first, then connected, then the agents that keep each server's
// own entry, with why. Over them is one line of how many go through
// magpie, and in the bar a Connect all for the rest. With many agents,
// the connected and the kept fold to one row each and a search narrows
// them all. Other apps: the one address, and a row per app with what
// adds it, by its install link (servers/hub-open, which the app
// confirms) or by copying its entry. The agents are magpie's to
// connect, never a command for the user to run; Cursor is among them
// when it's here.
let hubTab = "agents";
const hubFold = { on: true, kept: true };
function connectHub() {
const url = hubURL();
const json = (o) => JSON.stringify(o, null, 2);
const served = () => lib.servers.filter(inHub);
const ed = el("div", "editor lib-editor lib-hubsheet");
const head = el("div", "ehead");
head.append(hubMark(), el("b", "", t("Connect an app")));
ed.append(head);
const pane = el("div", "lib-hubpane");
const bar = el("div", "bar");
let busy = false, changed = false, q = "";
const why = new Set();
if (!mcpAgents().length) hubTab = "apps";
if (mcpAgents().length) ed.append(segs([["agents", t("Agents")], ["apps", t("Other apps")]], hubTab, (k) => { hubTab = k; draw(); }));
ed.append(pane, bar);
// posts agents-all for some agents, on or off, and says what came of it
const give = async (ids, on, b) => {
if (busy) return;
busy = true;
for (const x of ed.querySelectorAll(".lib-hubpane button, .bar button")) x.disabled = true;
b?.classList.add("busy");
const named = mcpAgents().filter((a) => ids.includes(a.id));
try {
take(await api("library/servers/agents-all", { agents: ids, on }));
changed = true;
const now = mcpAgents().filter((a) => ids.includes(a.id));
const failed = now.filter((a) => on ? a.hub !== "on" : a.hub === "on");
if (failed.length) status(t("{agent} couldn't be connected", { agent: failed.map((a) => a.name).join(", ") }), "warn", 8000);
else if (!on) status(t("{agent} no longer has the library's servers — restart it to read the change", { agent: named[0]?.name || "" }), "ok");
else if (named.length === 1) status(t("{agent} is connected — restart it to use magpie's tools", { agent: named[0].name }), "ok");
else status(t("{n} agents are connected — restart them to use magpie's tools", { n: named.length }), "ok");
render();
} catch (e) {
status(e.message, "err", 6000);
}
busy = false;
if (ed.isConnected) draw();
};
// an agent's row: a switch, or, kept, why in a word and in full
const agentRow = (a) => {
const st = a.hub || (a.noRemote ? "no-remote" : "");
const row = el("div", "row lib-row lib-hubagent");
row.dataset.agent = a.id;
row.dataset.state = st || "none";
const who = el("div", "who");
who.append(el("div", "name", a.name));
if (a.aside && st !== "no-remote") who.append(el("div", "sub", a.aside));
row.append(agentIcon(a.icon), who);
if (st === "on" || !st) {
const sw = toggle(st === "on", t("{agent} through magpie", { agent: a.name }), (on) => give([a.id], on, sw));
if (!st && !served().length) { sw.disabled = true; sw.title = t("The library has no MCP servers yet"); }
row.append(sw);
return [row];
}
row.classList.add("lib-hubkept");
row.append(el("span", "lib-hubtag", { "no-remote": t("No HTTP"), own: t("Has its own magpie"), taken: t("Name taken") }[st]));
const open = why.has(a.id);
const i = el("button", "lib-hubinfo");
i.type = "button";
i.setAttribute("aria-expanded", open ? "true" : "false");
i.setAttribute("aria-label", t("Why"));
i.title = t("Why");
i.append(svg("M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11z M8 7.2v3.6 M8 5.2v.1", 14, 1.3));
i.onclick = (e) => { e.stopPropagation(); open ? why.delete(a.id) : why.add(a.id); draw(); };
row.append(i);
if (!open) return [row];
const p = el("p", "lib-hubwhy", {
"no-remote": t("It reaches no MCP server over HTTP, so it keeps each server's own entry"),
own: t("It has a server called magpie of its own, which magpie leaves as it is"),
taken: t("A server in the library is called magpie: give it another name to connect"),
}[st]);
p.dataset.why = st;
return [row, p];
};
// a group: its name and count, a fold when there are many, its rows
const group = (key, title, list, many) => {
if (!list.length) return [];
const sec = el("div", "lib-hubgrp");
sec.dataset.group = key;
const h = el("div", "lib-hubsec");
h.append(el("span", "", title), el("span", "lib-hubn", String(list.length)));
const folds = many && key !== "off" && !q;
const folded = folds && hubFold[key];
if (folds) {
const f = button(folded ? t("Show all") : t("Hide"), "lib-hubfold", () => { hubFold[key] = !hubFold[key]; draw(); });
f.setAttribute("aria-expanded", folded ? "false" : "true");
h.append(f);
}
const box = el("div", "list lib-list lib-hubagents");
if (folded) {
// one row for them all: a few icons, a couple of names, how many
const row = el("button", "row lib-row lib-hubfolded");
row.type = "button";
const stack = el("span", "lib-hubstack");
for (const a of list.slice(0, 4)) stack.append(agentIcon(a.icon));
const names = list.length > 2
? t("{first} and {n} more", { first: list.slice(0, 2).map((a) => a.name).join(", "), n: list.length - 2 })
: list.map((a) => a.name).join(", ");
row.append(stack, el("span", "name", names), svg("M6 3.5l4.5 4.5L6 12.5", 12, 1.6));
row.onclick = (e) => { e.stopPropagation(); hubFold[key] = false; draw(); };
box.append(row);
} else box.append(...list.flatMap(agentRow));
sec.append(h, box);
return [sec];
};
const drawAgents = () => {
const all = hubAgents();
const st = (a) => a.hub || (a.noRemote ? "no-remote" : "");
const can = all.filter((a) => st(a) === "on" || !st(a));
const on = can.filter((a) => st(a) === "on");
const kept = all.filter((a) => !can.includes(a));
const many = all.length > 8;
// agents → magpie → servers, and the one line of where things stand
const flow = el("div", "lib-hubflow");
const route = el("div", "lib-hubroute");
const ends = (items, more) => {
const s = el("span", "lib-hubstack");
s.append(...items);
if (more > 0) s.append(el("span", "ic lib-hubmore", "+" + more));
return s;
};
// magpie itself in the middle: the bird the sidebar shows, on a plain tile
const node = el("span", "lib-hubnode");
node.innerHTML = '';
const srv = served();
route.append(ends(on.slice(0, 3).map((a) => agentIcon(a.icon)), on.length - 3), el("span", "lib-hubwire"), node, el("span", "lib-hubwire"),
ends(srv.slice(0, 3).map((s) => mark(s.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web)), srv.length - 3));
flow.append(route);
flow.append(el("p", "lib-hublead", !srv.length ? t("The library has no MCP servers yet")
: can.length === 1 ? t(on.length ? "{agent} uses the library's servers through magpie" : "{agent} can use the library's servers through magpie", { agent: can[0].name })
: t("{on} of {all} agents use the library's servers through magpie", { on: on.length, all: can.length })));
const left = can.length - on.length;
const sub = [left ? t("{n} more can be connected", { n: left }) : t("Each server runs once, for all of them")];
if (kept.length) sub.push(kept.length === 1 ? t("1 keeps each server's own entry") : t("{n} keep each server's own entry", { n: kept.length }));
const direct = directNames();
if (direct) sub.push(t("{name} is given to each agent directly", { name: direct }));
// each part whole on its line, the dot kept with the part before it
const line = el("p", "lib-hubsub");
sub.forEach((x, i) => line.append(...(i ? [" "] : []), el("span", "", x + (i < sub.length - 1 ? "\u00a0·" : ""))));
flow.append(line);
const out = [flow];
if (many) {
const box = el("label", "lib-hubsearch");
box.append(svg("M7 2.5a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9z M10.3 10.3l3.2 3.2", 13, 1.5));
const inp = el("input");
inp.type = "search";
inp.id = "lib-hubq";
inp.placeholder = t("Find an agent");
inp.setAttribute("aria-label", t("Find an agent"));
inp.value = q;
inp.oninput = () => { q = inp.value.trim(); draw(); };
box.append(inp);
out.push(box);
}
const m = (a) => !q || a.name.toLowerCase().includes(q.toLowerCase());
const groups = [
...group("off", t("Not connected"), can.filter((a) => !st(a) && m(a)), many),
...group("on", t("Connected"), on.filter(m), many),
...group("kept", t("Keep each server's own entry"), kept.filter(m), many),
];
out.push(...(groups.length ? groups : [el("p", "lib-hubnone", t("No agent called “{q}”", { q }))]));
return out;
};
// any other app: the address, and a row per app with what adds it
const drawApps = () => {
const out = [el("p", "lib-hublead lib-hubapps", t("Any app that speaks MCP connects at this address"))];
const addr = el("div", "lib-hubaddr");
addr.append(el("code", "", url), copyBtn(url, t("Address")));
out.push(addr, el("p", "lib-hubcap", t("From another computer, use the address magpie is reached at there, with a gateway key: Authorization: Bearer .")));
const apps = [
...(mcpAgents().some((a) => a.id === "cursor") ? [] : [{ id: "cursor", icon: "cursor", name: "Cursor", link: true, where: t("Or add it to ~/.cursor/mcp.json"), text: json({ mcpServers: { magpie: { url } } }) }]),
{ id: "vscode", icon: "vscode", name: "VS Code", link: true, where: t("Or add it to .vscode/mcp.json, or to your user mcp.json"), text: json({ servers: { magpie: { type: "http", url } } }) },
{ id: "windsurf", icon: "windsurf", name: "Windsurf", where: t("Paste it into ~/.codeium/windsurf/mcp_config.json"), text: json({ mcpServers: { magpie: { serverUrl: url } } }) },
{ id: "json", icon: "generic", name: t("Other"), where: t("Cline, LM Studio and any app that takes MCP servers as JSON"), text: json({ mcpServers: { magpie: { type: "http", url } } }) },
];
const sec = el("div", "lib-hubgrp");
sec.append(el("div", "lib-hubsec", t("Add to an app")));
const box = el("div", "list lib-list lib-hubappl");
for (const a of apps) {
const row = el("div", "row lib-row lib-hubapp");
row.dataset.app = a.id;
const who = el("div", "who");
const link = a.link && !web;
who.append(el("div", "name", a.name), el("div", "sub", link ? t("{app} asks you to confirm, then it's ready", { app: a.name }) : a.where));
row.append(icon(a.icon), who);
if (link) {
const go = button(t("Add"), "lib-hubpill lib-hubadd", async () => {
go.disabled = true;
try {
await api("library/servers/hub-open", { app: a.id });
status(t("{app} asks you to confirm adding magpie", { app: a.name }));
} catch (e) { status(e.message, "err"); }
go.disabled = false;
});
go.title = t("Add to {app}", { app: a.name });
row.append(go);
}
const cp = button(t("Copy entry"), "lib-hubpill lib-hubcopy", () => copy(a.text, a.name, cp, t("{app}'s entry copied", { app: a.name })));
cp.title = a.text;
if (link) cp.classList.add("quiet");
row.append(cp);
box.append(row);
}
sec.append(box);
out.push(sec);
return out;
};
const done = button(t("Done"), "", () => closeLibModal(true));
const draw = () => {
const top = pane.scrollTop;
const focus = document.activeElement?.id === "lib-hubq";
pane.replaceChildren(...(hubTab === "agents" ? drawAgents() : drawApps()));
pane.scrollTop = top;
if (focus) { const i = pane.querySelector("#lib-hubq"); i.focus(); i.setSelectionRange(i.value.length, i.value.length); }
// the one primary action: Connect all while there are agents to connect
const rest = hubTab === "agents" && served().length ? hubAgents().filter((a) => !a.hub && !a.noRemote) : [];
bar.replaceChildren(el("span", "grow lib-hubnote", changed ? t("Restart an agent for it to read the change") : ""), done);
done.className = "text" + (rest.length ? "" : " primary");
done.disabled = false;
if (rest.length) {
const all = button(t("Connect all"), "primary lib-huball", (e, b) => give(rest.map((a) => a.id), true, b));
all.title = rest.map((a) => a.name).join(", ");
bar.append(all);
}
};
draw();
modal = { save: () => (bar.querySelector(".lib-huball") || done).click() };
openLib(ed);
}
// a row's line under its name: the user's note when there is one, in
// the place of what it would say (a skill's description, a server's
// command), which its tooltip then gives after the note. A row keeps its
// height either way
function noteSub(note, sub, said) {
if (!note) return sub;
const n = el("div", "sub lib-subnote", note);
n.title = said ? note + "\n\n" + said : note;
return n;
}
function serverRow(s, all) {
const row = el("div", "row lib-row click lib-server");
const who = el("div", "who");
const nm = el("div", "name mono", s.name);
if (s.signIn?.dead) nm.append(tag(t("Sign-in ran out"), "warn", t("Open it to sign in again")));
else if (s.signIn?.signedIn) nm.append(tag(t("Signed in"), "lib-signed", t("The agents given it use magpie's sign-in")));
// kept to this computer: sync carries it nowhere (huhuy72219405 on X)
// a plugin's tools say whose they are, where they are turned off too
if (s.plugin) nm.append(tag(t("Plugin"), "lib-local lib-plugin", t("{plugin}'s tools. Plugins can hide them from every agent, keeping the plugin; sync never carries them to your other computers", { plugin: s.plugin })));
else if (s.local) nm.append(tag(t("Not synced"), "lib-local", s.bridge ? bridgedWhy() : t("Sync never carries it to your other computers")));
// out of the hub, each agent's own entry (#4382): said only while the hub is on
if (lib.mcpHub && s.hub === "direct") nm.append(tag(t("Not through the router"), "lib-direct", t("Each agent is given its own entry for it, as with the MCP router off")));
// its status beside the name, not in it: the name is still the name
who.classList.add("lib-srvwho");
who.append(nm, healthEl(s.name));
const sub = el("div", "sub mono", serverLine(s));
sub.title = serverLine(s);
who.append(noteSub(s.note, sub, serverLine(s)), toolsEl(s.name));
row.append(mark(s.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web), who, ...removeAct(() => confirmRemoveServer(s)),
// no agent to give it to: other apps reach it through the router
...(agentless() ? [] : [agentChips(withGone(all, s.agents), s.agents, chipsChange("servers/agents", s.name, "servers", (x) => serverRow(x, all)), { problems: s.problems, blocked: sseBlocked(s), all: true })]));
if (picking) return pickRow(row, s.name);
// a line of its own under the row, not in the name's column (tao0194)
if (s.name === "magpie-browser" && !s.agents?.length) row.append(browserAsk(row));
row.onclick = () => editServer(s);
row.title = t("Edit {name}", { name: s.name });
return row;
}
// Magpie Browser connected and given to no agent: it is added opt-in, so
// until an agent is ticked the router offers it to none, and an agent
// asked to use the browser reached for something else (AppleScript).
// Once the extension connects, its row asks which agents may use it,
// each a button that clicks that agent's chip in the row; the first one
// taken, it says nothing more. Read again every few seconds while the
// row is shown, so connecting the extension shows it without a reload.
let browserSeen = null; // { at, link } — the last read of the extension's state, shared by redrawn rows
function browserLink() {
if (browserSeen && Date.now() - browserSeen.at < 2500) return browserSeen.link;
const link = api("library/browser").then((b) => !!b?.connected, () => false);
browserSeen = { at: Date.now(), link };
return link;
}
function browserAsk(row) {
const ask = el("div", "lib-browserask");
ask.hidden = true;
ask.onclick = (e) => e.stopPropagation();
const draw = () => {
const chips = [...row.querySelectorAll(":scope > .lib-agents > .lib-ag[data-agent]")].filter((c) => !cannot(c) && !c.classList.contains("gone"));
const picks = el("div", "lib-browserask-picks");
for (const c of chips) {
const b = button("", "lib-browserask-pick", () => { c.click(); ask.remove(); });
b.dataset.agent = c.dataset.agent;
b.append(agentIcon(agentOf(c.dataset.agent)?.icon), el("span", "", nameOf(c.dataset.agent)));
picks.append(b);
}
ask.replaceChildren(el("span", "lib-browserask-dot"), el("span", "lib-browserask-q", t("Connected to your browser. Which agents may use it? They act in your tabs, signed in as you are.")), picks);
};
const look = async () => {
if (!ask.isConnected && ask.dataset.drawn) return;
ask.dataset.drawn = "1";
const on = await browserLink();
if (on && ask.hidden) draw();
ask.hidden = !on;
row.classList.toggle("lib-asking", on);
setTimeout(look, 3000);
};
requestAnimationFrame(look);
return ask;
}
// A server's or a hook's own Remove on its row, as a skill's has (#2364,
// szoxidy: a server turned off for every agent stayed in the list, its
// only Remove inside the editor its row opens). It asks first in the
// page, naming the one it takes and what goes with it. While picking,
// the bar's Remove is the one, and the row keeps the room it had.
function removeAct(run) {
if (picking) return [];
const acts = el("div", "lib-rowacts");
const rm = button("", "lib-icon danger lib-rm", run);
rm.append(svg(GLYPH.trash, 13, 1.4));
rm.title = t("Remove");
acts.append(rm);
return [acts];
}
function confirmRemoveOne(kind, name, title, lines) {
const ed = el("div", "editor lib-editor lib-rmone");
const head = el("div", "ehead");
head.append(glyph(GLYPH.trash), el("b", "", title));
ed.append(head);
for (const l of lines) if (l) ed.append(el("p", "lib-confirm", l));
const bar = el("div", "bar");
const go = button(t("Remove"), "primary danger-fill", async () => {
go.disabled = true;
if (await change(kind + "/remove", { name }, t("{name} removed", { name }))) closeLibModal(true);
else go.disabled = false;
});
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
openLib(ed);
}
const takenFromOne = (x) => x.agents?.length
? t("It is taken out of the library and out of {agents}.", { agents: x.agents.map(nameOf).join(", ") })
: t("It is taken out of the library; no agent has it.");
function confirmRemoveServer(s) {
const projects = (lib.projects || []).filter((p) => p.servers?.[s.name]?.length).length;
confirmRemoveOne("servers", s.name, t("Remove the MCP server {name}?", { name: s.name }), [
takenFromOne(s),
projects && t("It is taken out of the {n} projects magpie placed it in too.", { n: projects }),
s.signIn?.signedIn && t("magpie's sign-in to it is forgotten too."),
t("Servers your agents have that aren't in the library stay as they are."),
]);
}
function confirmRemoveHook(h) {
confirmRemoveOne("hooks", h.name, t("Remove the hook {name}?", { name: h.name }), [
takenFromOne(h),
t("Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file."),
]);
}
// Whether a server works, as magpie found by connecting to it: started
// (or reached) and asked for its tools. Its row shows it as a dot and a
// few words, the whole reason in its tooltip; a click checks it again.
// A server that listed its tools shows them instead, by name and what
// each says it does (nf1qaz2w on Discord), with Check again under them.
const health = new Map(); // name → { key: the server as checked, h: what was found, null while checking }
const toolsOpen = new Set(); // the servers whose tools are shown
// a command is started where its agents run, this computer or a WSL
// distro (mcp_check_wsl.go): agents moved between them is a check anew,
// and so is the router taking it or leaving it to the agents, which
// start it in their project and the router in home (inProject)
const healthKey = (s) => JSON.stringify([s.transport, s.command, s.args, s.env, s.url, s.headers, s.signIn,
s.transport === "stdio" ? [...new Set((s.agents || []).map((a) => a.split("@wsl:")[1] || ""))].sort() : null,
s.transport === "stdio" && !!lib.mcpHub && s.hub !== "direct"]);
const toolList = (name) => { const h = health.get(name)?.h; return h?.state === "ok" ? h.toolList || [] : []; };
// whether an agent the page shows gets the server, here or in a project
// magpie keeps whose folder is there. The library keeps every agent it
// gave a server to, those the page leaves out too: one hidden on the
// Agents page, one no longer installed, one with no MCP of its own. A
// server on only for those has every chip off, and isn't started for
// them on its own (#1597, xiaozhu1337: ida-pro-mcp and windbg-mcp were)
const inUse = (s) => {
const shown = new Set(mcpAgents().map((a) => a.id)), inProjects = new Set(projectMCPAgents().map((a) => a.id));
return (s.agents || []).some((id) => shown.has(id))
|| (lib.projects || []).some((p) => !p.missing && (p.servers?.[s.name] || []).some((id) => inProjects.has(id)));
};
// whether the library has it on for anyone at all, shown here or not
const onAnywhere = (s) => !!s.agents?.length || (lib.projects || []).some((p) => p.servers?.[s.name]?.length);
// a click checks a server again, or for the first time one in no use;
// not while it is being checked
function recheck(name) {
const s = lib.servers.find((x) => x.name === name), e = health.get(name);
if (s && (!e || e.h)) checkHealth([s], true);
}
function healthEl(name) {
const b = el("button", "lib-health");
b.type = "button";
b.dataset.server = name;
b.onclick = (e) => {
e.stopPropagation(); // the row opens the editor
// a server that asks for a sign-in is signed in to from its status
// (the owner: a click on "needs sign-in" signs in)
const s = lib.servers.find((x) => x.name === name);
if (mcpSigning?.name === name && mcpSigning.id) return editServer(s); // under way: its dialog has Cancel
if (canSignIn(s)) return signInFromRow(s);
if (!toolList(name).length) return recheck(name);
if (toolsOpen.has(name)) toolsOpen.delete(name); else toolsOpen.add(name);
paintHealth(name);
};
paintHealth(b);
return b;
}
// toolsEl is the list a server's status opens: filled by paintHealth
function toolsEl(name) {
const box = el("div", "lib-tools");
box.dataset.server = name;
box.hidden = true;
box.onclick = (e) => e.stopPropagation(); // reading or selecting it opens no editor
paintTools(box);
return box;
}
function paintTools(box) {
const name = box.dataset.server, list = toolList(name);
// while it is checked again the list stays as it was, so nothing under
// the click moves until the answer comes
if (health.get(name) && !health.get(name).h && !box.hidden) return;
box.hidden = !(toolsOpen.has(name) && list.length);
if (box.hidden) return box.replaceChildren();
const ul = el("ul", "lib-toollist");
const off = toolsOffOf(name);
for (const tl of list) {
const li = el("li", "lib-tool" + (off.includes(tl.name) ? " off" : ""));
const txt = el("div", "lib-tooltxt");
txt.append(el("span", "lib-toolname mono", tl.name));
if (tl.description) txt.append(el("span", "lib-tooldesc", tl.description));
li.append(txt, toolSwitch(name, tl.name, !off.includes(tl.name)));
ul.append(li);
}
const parts = [ul];
// the agents given it that can't leave out a single tool get them all,
// which is said here rather than shown as off for them too
const cant = (lib.servers.find((s) => s.name === name)?.agents || []).map(agentOf).filter((a) => a && a.mcp && !a.toolsOff);
if (cant.length) parts.push(el("p", "lib-toolcant", t("{agents} can't turn off single tools: they get every tool of the server.", { agents: cant.map((a) => a.name).join(", ") })));
const foot = el("div", "lib-toolfoot");
const h = health.get(name).h;
if (h.tools > list.length) foot.append(el("span", "note", t("{n} more not shown", { n: h.tools - list.length })));
foot.append(el("span", "grow"), button(t("Check again"), "", () => recheck(name)));
parts.push(foot);
box.replaceChildren(...parts);
}
// Each tool has a switch (nf1qaz2w on Discord): one turned off is left
// out by the agents given the server that can leave out a single tool.
// A click flips its own switch at once and nothing else on the page, so
// the list doesn't move under it; quick clicks are sent as one.
const toolsSending = new Map(); // server → { want: the tools off, as last clicked }
const toolsOffOf = (name) => toolsSending.get(name)?.want || lib.servers.find((s) => s.name === name)?.disabledTools || [];
function toolSwitch(name, tool, on) {
const s = toggle(on, t("{tool} on", { tool }), () => {});
s.dataset.tool = tool;
s.onclick = (e) => {
e.stopPropagation();
const now = s.getAttribute("aria-checked") !== "true";
s.classList.toggle("on", now);
s.setAttribute("aria-checked", String(now));
s.closest("li")?.classList.toggle("off", !now);
const cur = toolsOffOf(name);
setToolsOff(name, now ? cur.filter((x) => x !== tool) : [...new Set([...cur, tool])].sort());
};
return s;
}
async function setToolsOff(name, want) {
const w = toolsSending.get(name);
if (w) { w.want = want; return; }
const me = { want };
toolsSending.set(name, me);
let sent = null, v = null;
try {
while (!sent || sent.join("\n") !== me.want.join("\n")) {
sent = me.want;
v = await api("library/servers/tools", { name, names: sent });
}
toolsSending.delete(name);
take(v);
report(v, t("Tools of {name} saved", { name }));
} catch (e) {
toolsSending.delete(name);
status(e.message, "err");
// the switches go back to what the library has
for (const box of page.querySelectorAll(`.lib-tools[data-server="${CSS.escape(name)}"]`)) {
const off = toolsOffOf(name);
for (const s of box.querySelectorAll(".lib-switch[data-tool]")) {
const on = !off.includes(s.dataset.tool);
s.classList.toggle("on", on);
s.setAttribute("aria-checked", String(on));
s.closest("li")?.classList.toggle("off", !on);
}
}
}
}
async function checkHealth(list, fresh) {
if (!list.length) return;
const keys = new Map(list.map((s) => [s.name, healthKey(s)]));
for (const [name, key] of keys) { health.set(name, { key, h: null }); paintHealth(name); }
let got = {}, failed = null;
try { got = (await api("library/mcp/check", { names: [...keys.keys()], fresh: !!fresh })).servers || {}; } catch (e) { failed = e.message; }
let signIns = false;
for (const [name, key] of keys) {
// a server changed while it was checked has been asked for again
if (health.get(name)?.key !== key) continue;
const h = got[name] || (failed ? { state: "error", why: "request", detail: failed } : null);
// the check found magpie's sign-in run out (the server refused even
// a renewed token): the row's tag says so, not "Signed in" beside
// "needs sign-in" (新v学员 on Discord)
const s = lib.servers.find((x) => x.name === name);
if (h?.signIn && s && (!!h.signIn.signedIn !== !!s.signIn?.signedIn || !!h.signIn.dead !== !!s.signIn?.dead)) {
s.signIn = h.signIn;
health.set(name, { key: healthKey(s), h });
signIns = true;
continue;
}
if (h) health.set(name, { key, h }); else health.delete(name);
paintHealth(name);
}
if (signIns) render();
}
function healthWords(h, s) {
const more = (x) => (h.detail ? x + "\n" + h.detail : x);
const count = (n) => (n === 1 ? t("1 tool") : t("{n} tools", { n }));
// it exits in home and lists its tools in a project folder, where an
// agent starts it (fff-mcp, math_milian on Discord): fine for agents
// that start it themselves, not those magpie runs it for, in home
if (h.state === "ok" && h.project) return [count(h.tools), more(t("It started in a project folder and listed its tools, as an agent starts it there. It exits when started in your home folder"))];
if (h.state === "ok") return [count(h.tools), t("It started and listed its tools")];
// an agent signed in to it on its own (Claude Code's /mcp, in WSL too)
// uses it, though magpie's check, without that sign-in, was asked for
// one: the row says who, not "needs sign-in" (CyberCaius on Discord)
if (h.state === "auth" && h.agentSignIn?.length) {
const names = h.agentSignIn.map(nameOf);
const text = t("signed in in {agent}", { agent: names[0] }) + (names.length > 1 ? " +" + (names.length - 1) : "");
return [text, t("{agents}: signed in to it on its own, and uses it. magpie's check doesn't have that sign-in, so it can't list the tools: open it to sign in once in magpie too", { agents: names.join(", ") })];
}
if (h.state === "auth") {
const why = h.oauth
? (s?.transport === "http" ? t("The server asks for a sign-in — open it to sign in once in magpie") : t("The server asks for a sign-in"))
: t("The server refused magpie (HTTP {code}) — a key in its headers may be missing or wrong", { code: h.code || 401 });
return [t("needs sign-in"), h.detail ? why + "\n" + h.detail : why];
}
switch (h.why) {
case "home": return [t("won't start in home"), more(t("It exits when started in your home folder, where magpie runs it for the agents given it, and works in a project folder. Turn off Through the MCP router in its editor, so each agent starts it in its own project"))];
case "notfound": return [t("can't start: {cmd} not found", { cmd: h.detail }), t("Can't start it: there is no {cmd} on the PATH magpie has", { cmd: h.detail })];
case "start": return [t("can't start"), more(t("Can't start it"))];
case "exited": return [h.code ? t("exited ({code})", { code: h.code }) : t("exited"), more(h.code ? t("It exited with code {code} before listing its tools", { code: h.code }) : t("It exited before listing its tools"))];
// which step went unanswered, and for how long (#1467): a slow server
// lists its tools long after it initialized
case "timeout": {
const n = Math.round((h.waited || 0) / 1000);
if (!h.step) return [t("no answer"), more(t("No answer in {n} seconds", { n }))];
return [t("no answer to {step}", { step: h.step }), more(t("No answer to {step} in {n} seconds", { step: h.step, n }))];
}
case "http": return ["HTTP " + h.code, t("The server answered {status}", { status: h.detail })];
case "refused": return [t("connection refused"), more(t("Nothing is listening at that address"))];
case "unreachable": return [t("can't reach"), more(t("Can't reach the server"))];
case "protocol": return [t("bad reply"), more(t("It answered, but not as an MCP server does"))];
// a ${NAME} magpie's own environment hasn't; an agent started from a
// shell that has it still gets it
case "novar": return [t("{names} not set", { names: h.detail }), t("magpie can't check it: {names} isn't set where magpie runs. An agent started where it is set still gets it", { names: h.detail })];
// the agents given it run in a WSL distro that isn't running, which
// a check doesn't start: nothing is known of the server
case "wsldown": return [t("WSL {distro} not running", { distro: h.detail }), t("magpie can't check it: the agents given it run in WSL {distro}, which isn't running, and a check doesn't start it", { distro: h.detail })];
default: return [t("couldn't check"), more(t("magpie couldn't check it"))];
}
}
// paintHealth fills a row's status in place, by the button or the
// server's name, so a check ending moves nothing on the page
function paintHealth(x) {
// the hub's count of tools follows each check
const stats = page.querySelector(".lib-hubstats");
if (stats) stats.textContent = hubStats();
const boxes = typeof x === "string" ? page.querySelectorAll(`.lib-health[data-server="${CSS.escape(x)}"]`) : [x];
for (const b of boxes) {
const e = health.get(b.dataset.server);
b.removeAttribute("aria-expanded");
if (!e) {
// one in no use waits for a click (#1597); one in use is about
// to be checked
const s = lib.servers.find((x) => x.name === b.dataset.server);
b.hidden = !s || inUse(s);
b.className = "lib-health idle";
b.replaceChildren(el("span", "", t("not checked")));
b.title = t(s && onAnywhere(s) ? "No agent shown here has it on, so it isn't checked on its own" : "No agent has it, so it isn't checked on its own") + "\n" + t("Click to check it");
continue;
}
b.hidden = false;
const sg = mcpSigning?.name === b.dataset.server ? mcpSigning : null;
if (sg && (sg.state === "starting" || sg.state === "waiting")) {
b.className = "lib-health auth";
b.replaceChildren(el("span", "", sg.state === "starting" ? t("Opening the sign-in…") : t("Finish signing in in your browser…")));
b.title = t("Click to see the sign-in");
continue;
}
if (!e.h) {
b.className = "lib-health checking";
b.replaceChildren(el("span", "", t("checking…")));
b.title = t("Connecting to it to list its tools");
continue;
}
let [text, tip] = healthWords(e.h, lib.servers.find((s) => s.name === b.dataset.server));
// a command agents in WSL start is checked where they run: the tip
// says where, and a failure which place it was (loong on Discord)
const places = (e.h.checked || []).map((p) => (p ? "WSL " + p : "Windows"));
if (places.length && e.h.state === "ok") tip += "\n" + t("Checked in: {places}", { places: places.join(", ") });
else if (places.length) {
text += " · " + places[places.length - 1];
tip += "\n" + t("Failed in: {place}", { place: places[places.length - 1] });
}
// a check magpie couldn't make for want of a variable only the
// agent's own launch sets says nothing of the server, so it isn't
// painted as broken (#2308, ASD-max: Codex's host-only codex_app,
// whose pipe Codex itself hands it)
b.className = "lib-health " + (e.h.state === "ok" || e.h.agentSignIn?.length ? "ok" : e.h.state === "auth" ? "auth" : e.h.why === "novar" || e.h.why === "wsldown" ? "unknown" : "err");
b.replaceChildren(el("span", "", text));
if (toolList(b.dataset.server).length) {
const open = toolsOpen.has(b.dataset.server);
b.classList.add("has-list");
b.setAttribute("aria-expanded", String(open));
b.title = tip + "\n" + (open ? t("Click to hide them") : t("Click to see them"));
} else b.title = tip + "\n" + (canSignIn(lib.servers.find((s) => s.name === b.dataset.server)) ? t("Click to sign in") : t("Click to check again"));
}
const name = typeof x === "string" ? x : x.dataset.server;
for (const box of page.querySelectorAll(`.lib-tools[data-server="${CSS.escape(name)}"]`)) paintTools(box);
}
// magpie's sign-in to a remote server (#615): signed in once here, and
// every agent given the server reaches it through magpie, with it
let mcpSigning = null; // { name, id, state, error } while one is under way
let signDraw = null; // the open dialog's sign-in box, drawn as a sign-in moves
function signMoved(name) {
if (signDraw && !signDraw.box.isConnected) signDraw = null;
signDraw?.draw();
if (name) paintHealth(name);
}
// one the row's status signs in to: a remote server that asked for a
// sign-in, unless an agent's own sign-in already uses it
function canSignIn(s) {
const h = s && health.get(s.name)?.h;
return !!h && s.transport === "http" && h.state === "auth" && !!h.oauth && !h.agentSignIn?.length;
}
// a sign-in from a row's status, as the dialog's Sign in starts one; the
// dialog opens when the user has something to do there: the browser
// didn't open (the link to open by hand) or the sign-in failed
async function signInFromRow(s) {
const name = s.name;
mcpSigning = { name, state: "starting" };
signMoved(name);
try {
const st = await api("library/mcp-signin", { name });
if (mcpSigning?.name !== name || mcpSigning.id) return; // canceled
if (web && st.url) api("open", { url: st.url }).catch(() => {});
mcpSigning = { ...st, name };
signMoved(name);
if (st.openError) editServer(s);
followSignIn(st.id, name);
} catch (e) {
if (mcpSigning?.name !== name) return;
mcpSigning = { name, state: "failed", error: t(e.message) };
signMoved(name);
editServer(s);
}
}
// followed with the dialog closed too, for the row to say it's signed in
async function followSignIn(id, name) {
while (mcpSigning?.id === id) {
await new Promise((r) => setTimeout(r, 800));
let st;
try { st = await api("library/mcp-signin/" + id); } catch { continue; }
if (mcpSigning?.id !== id) return;
if (st.state === "waiting") continue;
if (st.state === "done") {
mcpSigning = null;
await api("library").then(take, () => {});
status(t("Signed in to {name} — the agents given it use magpie's sign-in", { name }), "ok");
render();
} else mcpSigning = st.state === "canceled" ? null : { ...st, name };
signMoved(name);
return;
}
}
// name is the server as saved ("" for one being added); ready saves what
// the editor shows when it isn't that (a URL changed to the one that
// signs in, as Exa's ?login) and gives the name it's saved as, for the
// sign-in to be to the server the form shows. ready.saves says it would
// save, and the button then says so; box.redraw draws it again as the
// form changes
function signInBox(name, ready) {
const box = el("div", "lib-signin");
const draw = () => {
box.replaceChildren();
const cur = lib.servers.find((x) => x.name === name)?.signIn || {};
const sg = mcpSigning?.name === name ? mcpSigning : null;
const line = el("div", "lib-signin-line");
if (sg && (sg.state === "starting" || sg.state === "waiting")) {
line.append(el("span", "note", sg.state === "starting" ? t("Opening the sign-in…") : t("Finish signing in in your browser…")),
button(t("Cancel"), "", async () => {
if (sg.id) await api("library/mcp-signin/" + sg.id + "/cancel", {}).catch(() => {});
mcpSigning = null;
draw();
signMoved(name);
}));
} else if (cur.signedIn && !cur.dead) {
line.append(tag(t("Signed in"), "lib-signed"), el("span", "note", t("The agents given it use magpie's sign-in")), el("span", "grow"), button(t("Sign out"), "", signOut));
} else {
if (cur.dead) line.append(tag(t("Sign-in ran out"), "warn"));
line.append(button(ready?.saves?.() ? t("Save and sign in") : cur.dead ? t("Sign in again") : t("Sign in"), "action", start));
}
box.append(line);
// the browser didn't start (#2043): the page to open by hand, rather
// than waiting on one that never opened until the sign-in times out
if (sg?.state === "waiting" && sg.openError && sg.url) {
box.append(el("div", "lib-signin-err", t("magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.", { error: sg.openError })));
const link = el("div", "lib-signin-link");
const u = el("code", "", sg.url);
u.title = sg.url;
const cp = copyBtn(sg.url, t("Sign-in link"));
cp.title = t("Copy link");
link.append(u, cp);
box.append(link);
}
if (sg?.state === "failed") box.append(el("div", "lib-signin-err", sg.error));
};
async function start() {
const was = name;
mcpSigning = { name, state: "starting" };
draw();
try {
if (ready) {
const saved = await ready();
// canceled while it was saved
if (mcpSigning?.name !== was || mcpSigning.id) return;
name = saved;
mcpSigning = { name, state: "starting" };
}
const st = await api("library/mcp-signin", { name });
if (web && st.url) api("open", { url: st.url }).catch(() => {});
mcpSigning = { ...st, name };
draw();
followSignIn(st.id, name);
} catch (e) {
if (!mcpSigning) return; // canceled
// magpie's words in the reader's language, where it has them
mcpSigning = { name, state: "failed", error: t(e.message) };
draw();
ready?.failed?.(e.message);
}
}
async function signOut() {
try {
take(await api("library/mcp-signout", { name }));
status(t("Signed out of {name} — the agents are given the server's own address again", { name }), "ok");
render();
draw();
} catch (e) { status(e.message, "err", 6000); }
}
box.redraw = draw;
signDraw = { box, draw };
draw();
return box;
}
function foundServerRow(f) {
const s = f.server;
const row = el("div", "row lib-row");
const who = el("div", "who");
const nm = el("div", "name mono", s.name);
who.append(nm);
const sub = el("div", "sub mono", serverLine(s));
sub.title = serverLine(s);
who.append(sub);
const have = el("div", "lib-have");
for (const id of s.agents) { const a = agentOf(id); if (a) { const i = icon(a.icon); i.title = a.name; have.append(i); } }
row.append(mark(f.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web), who, have);
if (f.others?.length) row.append(tag(t("differs in {agents}", { agents: f.others.map(nameOf).join(", ") }), "warn", t("{agents} has another server by this name; bringing this one in leaves that one as it is", { agents: f.others.map(nameOf).join(", ") })));
const b = button(t("Bring in"), "action", () => change("servers/import", { name: s.name }, t("{name} is in the library now", { name: s.name })));
b.title = t("Keeps it in the library: {agents} go on having it, and you can give it to the others", { agents: s.agents.map(nameOf).join(", ") });
// gone from the agents' own MCP settings without bringing it in first
// (#1618), as a skill of their own is (#1303)
const rm = button("", "lib-icon danger", () => confirmRemoveFoundServer(f));
rm.append(svg(GLYPH.trash, 13, 1.4));
rm.title = t("Remove");
row.append(b, rm);
return row;
}
function confirmRemoveFoundServer(f) {
const s = f.server;
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead");
head.append(glyph(GLYPH.trash), el("b", "", t("Remove {name}?", { name: s.name })));
ed.append(head);
const agents = s.agents.map(nameOf).filter(Boolean);
ed.append(el("p", "lib-confirm", t("It is taken out of the MCP settings of {agents}. Each file is copied to magpie's backups before it changes.", { agents: agents.join(", ") })));
if (f.others?.length) ed.append(el("p", "lib-confirm", t("{agents} has another server by this name; that one stays.", { agents: f.others.map(nameOf).join(", ") })));
const bar = el("div", "bar");
const go = button(t("Remove"), "primary danger-fill", async () => { if (await change("servers/remove-found", { name: s.name }, t("{name} removed", { name: s.name }))) closeLibModal(true); });
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
openLib(ed);
}
// A command line split the way a shell would, quotes and all.
function words(s) {
const out = [];
let cur = "", q = "", any = false;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (q) {
// on Windows "" in quotes is one ", as quote() writes it
if (c === q && WIN_LINE && q === '"' && s[i + 1] === '"') cur += s[++i];
else if (c === q) q = "";
else if (c === "\\" && q === '"' && !WIN_LINE && i + 1 < s.length) cur += s[++i];
else cur += c;
} else if (c === "'" || c === '"') { q = c; any = true; }
else if (c === "\\" && !WIN_LINE && i + 1 < s.length) { cur += s[++i]; any = true; }
else if (/\s/.test(c)) { if (cur || any) out.push(cur); cur = ""; any = false; }
else cur += c;
}
if (cur || any) out.push(cur);
return out;
}
// The servers in JSON the user pasted: a README's {"mcpServers": {...}},
// one server's entry, or VS Code's {"servers": {...}}.
function serversIn(text) {
let v;
try { v = JSON.parse(text.trim().replace(/,\s*([}\]])/g, "$1")); } catch {
try { v = JSON.parse("{" + text.trim().replace(/,\s*$/, "") + "}"); } catch { return null; }
}
if (!v || typeof v !== "object") return null;
const map = v.mcpServers || v.servers || v.mcp || v.context_servers || null;
const one = (name, e) => {
if (!e || typeof e !== "object") return null;
const url = e.url || e.serverUrl || e.httpUrl || e.uri;
const s = { name: (name || "").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, ""), env: {}, headers: {} };
if (url) {
s.transport = e.type === "sse" || e.transport === "sse" || /\/sse\/?$/.test(url) ? "sse" : "http";
s.url = url;
s.headers = { ...(e.headers || e.http_headers || {}) };
} else if (e.command) {
s.transport = "stdio";
const cmd = Array.isArray(e.command) ? e.command : [e.command];
s.command = String(cmd[0]);
s.args = [...cmd.slice(1), ...(e.args || [])].map(String);
s.env = { ...(e.env || e.environment || {}) };
} else return null;
return s;
};
if (map && typeof map === "object") {
return Object.entries(map).map(([n, e]) => one(n, e)).filter(Boolean);
}
if (v.command || v.url || v.serverUrl || v.httpUrl) { const s = one(v.name || "", v); return s ? [s] : null; }
const entries = Object.entries(v).filter(([, e]) => e && typeof e === "object" && (e.command || e.url || e.serverUrl || e.httpUrl));
return entries.length ? entries.map(([n, e]) => one(n, e)).filter(Boolean) : null;
}
// Key–value rows for a server's environment or headers.
function pairs(obj, keyHint, valHint, onChange) {
const box = el("div", "lib-pairs");
const rows = Object.entries(obj || {});
const emit = () => onChange(Object.fromEntries(rows.filter(([k]) => k.trim()).map(([k, v]) => [k.trim(), v])));
const draw = () => {
box.replaceChildren();
rows.forEach((r, i) => {
const line = el("div", "lib-pair");
const k = field2(r[0], keyHint, (v) => { r[0] = v; emit(); });
const v = field2(r[1], valHint, (x) => { r[1] = x; emit(); });
const x = button("", "lib-x", () => { rows.splice(i, 1); emit(); draw(); });
x.append(svg("M4.5 4.5l7 7M11.5 4.5l-7 7", 11, 1.6));
x.title = t("Remove");
line.append(k, v, x);
box.append(line);
});
box.append(button(t("+ Add"), "lib-addpair", () => { rows.push(["", ""]); draw(); box.querySelectorAll(".lib-pair input")[rows.length * 2 - 2]?.focus(); }));
};
draw();
return box;
}
function field2(value, placeholder, onInput) {
const i = el("input");
i.type = "text";
i.value = value || "";
i.placeholder = placeholder || "";
i.spellcheck = false;
i.autocomplete = "off";
i.oninput = () => onInput(i.value);
// an Enter or Escape that ends an input method's composition (a
// Chinese description, #2011) is the IME's, not a save or a close
i.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter" && modal?.save) { e.preventDefault(); modal.save(); } };
return i;
}
// lineBox is a command line in a box that wraps, so a long one (npx
// with a database's host, user, password and name, hema_17384 on
// Discord) is read and edited whole. It is still one line: Enter saves,
// and a line break is a space between words, a shell's \ before it too.
function lineBox(value, placeholder, onInput) {
const ta = el("textarea", "lib-text small mono lib-cmd");
ta.rows = 1;
ta.value = value || "";
ta.placeholder = placeholder || "";
ta.spellcheck = false;
ta.setAttribute("autocapitalize", "off");
ta.setAttribute("autocorrect", "off");
ta.oninput = () => onInput(WIN_LINE ? ta.value : ta.value.replace(/\\\r?\n/g, " "));
ta.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter" && modal?.save) { e.preventDefault(); modal.save(); } };
autosize(ta, 27);
return ta;
}
// noteBox is the user's note on a server or a skill (youyo.p on Discord:
// with many, which is which and when to use it). One line of at most 200
// characters, as a hook's description (#2011); the library alone keeps
// it, and no agent is given it.
const NOTE_MAX = 200;
function noteBox(value, placeholder, onInput) {
const ta = el("textarea", "lib-text small lib-notein");
ta.rows = 1;
ta.value = value || "";
ta.placeholder = placeholder;
ta.maxLength = NOTE_MAX;
ta.oninput = () => onInput(ta.value);
ta.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter" && modal?.save) { e.preventDefault(); modal.save(); } };
autosize(ta, 27);
return ta;
}
const noteHint = () => t("Optional: what it's for and when to use it, in any language. Only the library keeps it; no agent is given it");
// refHint: how a value is read from a variable (#1250)
const refHint = () => t("A value can name a variable, as {ref}: each agent is given it in its own way, so the token stays out of its settings", { ref: "${NAME}" });
// the start of mcpauth.ErrNoRegistration
const NO_REGISTRATION = "the server's sign-in doesn't let an app register itself";
// a server's own OAuth app, to tell a changed one: "" for none
const appOf = (x) => (x?.transport === "http" && x.oauth?.clientId ? JSON.stringify([x.oauth.clientId, x.oauth.clientSecret || "", x.oauth.callbackPort || 0]) : "");
function editServer(s, prefill) {
const all = mcpAgents();
const d = prefill || (s ? structuredClone(s) : { name: "", transport: "stdio", command: "", args: [], env: {}, url: "", headers: {}, agents: all.map((a) => a.id) });
if (!d.env) d.env = {};
if (!d.headers) d.headers = {};
d.local = !!d.local;
d.note = d.note || "";
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead lib-serverhead");
head.append(mark(s?.icon, d.transport === "stdio" ? GLYPH.cmd : GLYPH.web), el("b", "", s ? s.name : t("New MCP server")));
if (!s) head.append(el("span", "note", t("or paste its JSON anywhere here")));
// the form, or the server as JSON (hema_17384 on Discord), in Claude
// Code's .mcp.json shape, as Copy config gives it: read whole, edited,
// pasted over. The note, the agents and sync are the library's own and
// stay in the form below it
let view = "form", jsonBad = "";
const viewBox = el("div", "lib-viewpick");
const viewSegs = () => segs([["form", t("Form")], ["json", "JSON"]], view, (v) => {
if (v === "form" && jsonBad) { err.textContent = jsonBad; viewBox.replaceChildren(viewSegs()); return; }
view = v;
err.textContent = "";
draw();
(view === "json" ? top.querySelector(".lib-json") : name).focus();
});
viewBox.append(viewSegs());
head.append(viewBox);
ed.append(head);
const err = el("div", "editor-error");
let signBox = null; // the sign-in's, for its button to say it saves
// a sign-in saves the form first only to sign in to another server than
// the saved one; see ready
ready.saves = () => !s || d.name !== s.name || d.transport !== s.transport || d.url !== (s.url || "") || appOf(d) !== appOf(s);
// a server whose sign-in doesn't let magpie register itself (GitHub's,
// 新v学员 on Discord): the fields for the user's own app open
ready.failed = (msg) => {
if (!msg.startsWith(NO_REGISTRATION) || !appBox) return;
appOpen = true;
drawApp();
appBox.querySelector("input")?.focus();
};
let appOpen = !!d.oauth?.clientId, appBox = null, appHint = null;
// the user's own OAuth app, by Claude Code's names (--client-id,
// --client-secret, --callback-port)
function drawApp() {
appBox.replaceChildren();
const hint = appHint;
if (!appOpen) {
appBox.append(button(t("Use your own OAuth app"), "lib-addpair", () => { appOpen = true; drawApp(); appBox.querySelector("input")?.focus(); }));
if (hint) hint.textContent = t("For a server whose sign-in doesn't let magpie register itself, as GitHub's");
return;
}
const a = () => (d.oauth ||= { clientId: "", clientSecret: "", callbackPort: 0 });
const id = field2(d.oauth?.clientId, t("Client ID"), (v) => { a().clientId = v.trim(); signBox?.redraw(); });
const secret = field2(d.oauth?.clientSecret, t("Client secret"), (v) => { a().clientSecret = v.trim(); signBox?.redraw(); });
secret.type = "password";
const port = field2(d.oauth?.callbackPort || "", t("Callback port"), (v) => {
port.value = v.replace(/\D/g, "").slice(0, 5);
a().callbackPort = Number(port.value) || 0;
signBox?.redraw();
if (hint) hint.textContent = callback();
});
port.inputMode = "numeric";
port.classList.add("port");
for (const [i, l] of [[id, t("Client ID")], [secret, t("Client secret")], [port, t("Callback port")]]) i.setAttribute("aria-label", l);
const x = button("", "lib-x", () => { d.oauth = s?.oauth ? null : undefined; appOpen = false; drawApp(); signBox?.redraw(); });
x.append(svg("M4.5 4.5l7 7M11.5 4.5l-7 7", 11, 1.6));
x.title = t("Remove");
appBox.append(id, secret, port, x);
if (hint) hint.textContent = callback();
}
const callback = () => t("Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL", { url: "http://localhost" + (d.oauth?.callbackPort ? ":" + d.oauth.callbackPort : "") + "/callback" });
const name = field2(d.name, t("e.g. github"), (v) => { d.name = v.trim(); signBox?.redraw(); });
const kindOf = () => segs([["stdio", t("Command")], ["http", "HTTP"], ["sse", "SSE"]], d.transport, (v) => { d.transport = v; draw(); });
const kindBox = el("div");
kindBox.append(kindOf());
const nameF = field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it")), kindF = field(t("Runs as"), kindBox);
const top = el("div", "lib-slot");
ed.append(top);
const note = noteBox(d.note, t("e.g. The shop's database, read only"), (v) => { d.note = v; });
ed.append(...field(t("Note"), note, noteHint()));
const slot = el("div", "lib-slot");
ed.append(slot);
const agentsBox = el("div");
ed.append(...field(t("Agents"), agentsBox));
// kept to this computer: a sync neither carries it to the others nor
// takes it away here (huhuy72219405 on X)
const hereBox = el("div", "lib-localbox");
// said as sync, on while it syncs: "This computer only" read as a
// sharing switch (bin.90 on Discord). local keeps its meaning: on is
// kept here, so the switch shows and saves its opposite.
const drawHere = () => hereBox.replaceChildren(toggle(!d.local, t("Sync to your other computers"), (on) => { d.local = !on; drawHere(); }));
drawHere();
// a Remote magpie's server holds this computer's key for it and goes
// with it, so it is never synced: the switch says so, off and held,
// where it showed on and went back off once saved (treeman_26897)
const bridged = !!d.bridge;
if (bridged) {
const sw = hereBox.firstChild;
sw.setAttribute("aria-disabled", "true");
sw.onclick = (e) => e.stopPropagation();
}
ed.append(...field(t("Sync to your other computers"), hereBox, bridged ? bridgedWhy() : t("Off keeps it on this computer: sync never carries it to your other computers, and a sync from them neither removes it nor puts theirs in its place")));
// with the hub on, a server can stay each agent's own entry (#4382,
// cuipengcx90): one that reads its project from the folder it starts
// in, or keeps a session's state. Shown while the hub is on, and for a
// server the check found won't start in home, where magpie runs it for
// Codex too (inHome)
d.hub = d.hub === "direct" ? "direct" : "";
if (lib.mcpHub || (s && health.get(s.name)?.h?.why === "home")) {
const hubBox = el("div", "lib-hubbox");
const drawHub = () => hubBox.replaceChildren(toggle(d.hub !== "direct", t("Through the MCP router"), (on) => { d.hub = on ? "" : "direct"; drawHub(); }));
drawHub();
ed.append(...field(t("Through the MCP router"), hubBox, t("Off gives each agent its own entry for it, as with the router off: for a server that reads its project from the folder it starts in, or keeps a session's state")));
}
ed.append(err);
function drawAgents() {
agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, blocked: sseBlocked(d), all: true }));
}
// the server as Copy config's Claude Code entry has it (fmtClaude)
function jsonOf() {
const e = d.transport === "stdio"
? { type: "stdio", command: d.command || "", args: d.args || [], env: d.env || {} }
: { type: d.transport, url: d.url || "", ...(Object.keys(d.headers || {}).length ? { headers: d.headers } : {}) };
return JSON.stringify({ mcpServers: { [d.name]: e } }, null, 2);
}
// what is typed is read as a paste is (serversIn): each valid edit is
// the form's at once; one that isn't keeps the dialog from saving or
// going back to the form until it is
function jsonBox() {
const ta = el("textarea", "lib-text small mono lib-json");
ta.value = jsonOf();
ta.spellcheck = false;
ta.setAttribute("autocapitalize", "off");
ta.setAttribute("autocorrect", "off");
ta.oninput = () => {
const found = serversIn(ta.value);
jsonBad = !found?.length ? t("This isn't an MCP server's JSON") : found.length > 1 ? t("Only one server here; paste several outside this box to add them") : "";
ta.setAttribute("aria-invalid", String(!!jsonBad));
err.textContent = jsonBad;
if (jsonBad) return;
const f = found[0];
Object.assign(d, { transport: f.transport, command: f.command || "", args: f.args || [], env: f.env || {}, url: f.url || "", headers: f.headers || {} });
if (f.name) d.name = f.name;
name.value = d.name;
kindBox.replaceChildren(kindOf());
drawAgents();
};
// a newline is the box's; ⌘/Ctrl-Enter saves, Escape closes
ta.onkeydown = (e) => {
e.stopPropagation();
if (e.isComposing || e.keyCode === 229) return;
if (e.key === "Escape") closeLibModal();
else if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && modal?.save) { e.preventDefault(); modal.save(); }
};
autosize(ta, 160);
return ta;
}
function draw() {
slot.replaceChildren();
if (view === "json") {
signBox = appBox = null;
top.replaceChildren(...field("JSON", jsonBox(), t("As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here", { ref: "${NAME}" })));
head.firstChild.replaceWith(mark(s && d.transport === s.transport ? s.icon : "", d.transport === "stdio" ? GLYPH.cmd : GLYPH.web));
drawAgents();
return;
}
top.replaceChildren(...nameF);
slot.append(...kindF);
const g = el("div", "lib-grid");
if (d.transport === "stdio") {
const line = lineBox([d.command, ...(d.args || [])].filter((x, i) => i > 0 || x).map(quote).join(" "), "npx -y @modelcontextprotocol/server-github", (v) => { const w = words(v); d.command = w[0] || ""; d.args = w.slice(1); });
g.append(...field(t("Command"), line, t("The command and its arguments, as you'd type them")));
g.append(...field(t("Environment"), pairs(d.env, "GITHUB_TOKEN", t("value"), (v) => { d.env = v; drawAgents(); }), refHint()));
} else {
const url = field2(d.url, "https://example.com/mcp", (v) => { d.url = v.trim(); signBox?.redraw(); });
url.classList.add("mono");
g.append(...field("URL", url));
g.append(...field(t("Headers"), pairs(d.headers, "Authorization", "Bearer …", (v) => { d.headers = v; drawAgents(); }), refHint()));
// Sign in saves the form first when it is of another server than
// the saved one, so a URL just changed (or a server just added) is
// the one signed in to
signBox = d.transport === "http" ? signInBox(s ? s.name : "", ready) : null;
if (signBox) {
appBox = el("div", "lib-app");
const f = field(t("OAuth app"), appBox, " ");
appHint = f[1].querySelector(".hint");
g.append(...f);
g.append(...field(t("Sign-in"), signBox, t("For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in")));
} else appBox = null;
}
// how long the agents that take one (Codex's startup_timeout_sec)
// wait for it to start, shown only when one of them is here (#3168)
const slow = [...new Set(all.filter((a) => a.startup).map((a) => a.name))];
if (slow.length) {
const wait = field2(d.startupTimeout || "", "30", (v) => {
wait.value = v.replace(/\D/g, "").slice(0, 5);
d.startupTimeout = Number(wait.value) || 0;
});
wait.inputMode = "numeric";
wait.classList.add("lib-startup");
wait.setAttribute("aria-label", t("Startup timeout"));
g.append(...field(t("Startup timeout"), wait, t("Seconds {agents} waits for it to start and list its tools. Empty leaves {agents}'s own 30; a value you wrote in its config.toml by hand is kept", { agents: slow.join(", ") })));
}
slot.append(g);
if (appBox) drawApp();
// its own icon while it runs as it did; another way of running is another server
head.firstChild.replaceWith(mark(s && d.transport === s.transport ? s.icon : "", d.transport === "stdio" ? GLYPH.cmd : GLYPH.web));
drawAgents();
}
draw();
const bar = el("div", "bar");
if (s) bar.append(button(t("Remove from the library"), "danger", async () => {
if (!await confirmRemoval(s.name, "It will be removed from the library and the agents it was given to.")) return;
if (await change("servers/remove", { name: s.name }, t("{name} is out of the library and the agents it was given to", { name: s.name }))) closeLibModal(true);
}));
if (s && projectMCPAgents().length) bar.append(copyConfigButton([s.name]));
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal));
// send saves the form; s is then the server as saved, for a save after
// a sign-in's to be of it
const send = async () => {
const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents, startupTimeout: d.startupTimeout || 0, local: !!d.local, hub: d.hub || "", note: d.note || "" } };
if (d.transport === "stdio") Object.assign(body.server, { command: d.command, args: d.args, env: d.env });
else Object.assign(body.server, { url: d.url, headers: d.headers, oauth: d.transport === "http" && d.oauth?.clientId ? d.oauth : null });
take(await api("library/servers/save", body));
const was = s;
s = lib.servers.find((x) => x.name === d.name) || s;
return was;
};
const save = async () => {
if (jsonBad) { err.textContent = jsonBad; return; }
err.textContent = "";
try {
const was = await send();
report(lib.result, was ? t("{name} saved", { name: d.name }) : "");
closeLibModal(true);
render();
} catch (e) { err.textContent = e.message; }
};
// before a sign-in: the form saved, the dialog left open, only when
// the sign-in is to another server than the saved one (a new one, a
// name or URL changed). It never saves the rest of the form on its
// own: a header removed, then Sign in, then Cancel left the header
// removed (新v学员 on Discord). A save says so on the button ("Save and
// sign in"), and what it saved is what Cancel then keeps
async function ready() {
if (!ready.saves()) return s.name;
err.textContent = "";
const was = await send();
report(lib.result, was ? t("{name} saved", { name: d.name }) : "");
ok.textContent = t("Save");
original = JSON.stringify(d);
render();
return s.name;
}
const ok = button(s ? t("Save") : t("Add"), "primary", save);
bar.append(ok);
ed.append(bar);
// a README's JSON pasted anywhere in the dialog fills it in
ed.addEventListener("paste", (e) => {
if (e.target.closest?.(".lib-json")) return; // the JSON box's own
const text = e.clipboardData?.getData("text") || "";
if (!/[{]/.test(text)) return;
const found = serversIn(text);
if (!found?.length) return;
e.preventDefault();
if (found.length === 1) {
const f = found[0];
Object.assign(d, { transport: f.transport, command: f.command || "", args: f.args || [], env: f.env || {}, url: f.url || "", headers: f.headers || {} });
if (f.name && (!d.name || !s)) d.name = f.name;
name.value = d.name;
kindBox.replaceChildren(kindOf());
draw();
status(t("Filled in from what you pasted"), "ok");
} else pasteMany(found, d.agents);
});
let original = JSON.stringify(d);
modal = { save, dirty: () => !!jsonBad || JSON.stringify(d) !== original };
openLib(ed);
if (!s) requestAnimationFrame(() => name.focus());
}
// Several servers pasted at once: pick those to add.
function pasteMany(found, agents) {
const all = mcpAgents();
const have = new Set(lib.servers.map((s) => s.name));
const pick = new Set(found.filter((f) => f.name && !have.has(f.name)).map((f) => f.name));
let who = [...agents];
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead");
head.append(glyph(GLYPH.cmd), el("b", "", t("{n} servers in what you pasted", { n: found.length })));
ed.append(head);
const list = el("div", "lib-picks");
for (const f of found) {
const r = el("label", "lib-pick" + (have.has(f.name) ? " dim" : ""));
const c = el("input");
c.type = "checkbox";
c.checked = pick.has(f.name);
c.disabled = !f.name || have.has(f.name);
c.onchange = () => { if (c.checked) pick.add(f.name); else pick.delete(f.name); go.textContent = label(); go.disabled = !pick.size; };
const w = el("span", "who");
w.append(el("span", "name mono", f.name || t("(no name)")), el("span", "sub mono", serverLine(f)));
r.append(c, w);
if (have.has(f.name)) r.append(tag(t("in the library"), ""));
list.append(r);
}
ed.append(list);
const agentsBox = el("div");
const drawAgents = () => agentsBox.replaceChildren(agentChips(all, who, (n) => { who = n; drawAgents(); }, { names: true, all: true }));
drawAgents();
ed.append(...field(t("Agents"), agentsBox));
const err = el("div", "editor-error");
ed.append(err);
const bar = el("div", "bar");
const label = () => (pick.size === 1 ? t("Add 1 server") : t("Add {n} servers", { n: pick.size }));
const go = button(label(), "primary", async () => {
go.disabled = true;
let last = null;
for (const f of found.filter((x) => pick.has(x.name))) {
try {
last = await api("library/servers/save", { old: "", server: { ...f, agents: who.filter((id) => reaches(f)(agentOf(id))) } });
} catch (e) { err.textContent = f.name + ": " + e.message; go.disabled = false; if (last) { take(last); render(); } return; }
}
take(last);
report(lib.result, t("Added {n} servers", { n: pick.size }));
closeLibModal(true);
render();
});
go.disabled = !pick.size;
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
openLib(ed);
}
// ---------- hooks ----------
// A hook (#1790, AllenReder) is a command an agent runs at a point of
// its turn: a phone notification when it ends, a formatter after it
// edits a file. It is kept once and written into each agent picked, in
// that agent's own file and shape (hooks.go). An event is one every
// agent has, under its own name, or one agent's own, for it alone.
const HOOK_EVENTS = () => [
["turn-end", t("When a turn ends")],
["after-tool", t("After a tool runs")],
["before-tool", t("Before a tool runs")],
["prompt", t("When a prompt is sent")],
["session-start", t("When a session starts")],
];
const HOOK_TOOLS = () => [["", t("Any tool")], ["shell", t("Shell commands")], ["edit", t("File edits")]];
// the starts a session-start hook can be narrowed to (#5604, NEKO-CwC),
// in Claude Code's words for them, which library.HookStarts keeps
const HOOK_STARTS = () => [
["", t("Any start")],
["startup", t("A fresh session")],
["resume", t("A resumed session")],
["clear", t("After /clear")],
["compact", t("After the context is compacted")],
["fork", t("A forked session")],
["startup|resume|clear|compact", t("Any start but a fork")],
];
const STARTS = ["startup", "resume", "clear", "compact", "fork"];
// a matcher of starts in library.HookStarts' order, as each agent's
// view lists the ones it takes
const startsOf = (m) => STARTS.filter((s) => m.split("|").includes(s)).join("|");
const toolEvent = (ev) => ev === "after-tool" || ev === "before-tool";
// the choices an event can be narrowed by, or null
const narrowsOf = (ev) => toolEvent(ev) ? HOOK_TOOLS() : ev === "session-start" ? HOOK_STARTS() : null;
const hookAgentOf = (id) => (lib.hookAgents || []).find((x) => x.id === id);
// the agents the tab shows a chip for: every one shown, those magpie
// can't give a hook greyed, saying why
const hookAgents = () => shownAgents().filter((a) => hookAgentOf(a.id));
// why a can't be given h, or ""
const hookBlocked = (h) => (a) => {
const ha = hookAgentOf(a.id);
if (!ha || ha.no) return ha?.wsl ? t("magpie gives hooks only to agents on this computer, not yet to {agent} in WSL", { agent: a.name }) : t("{agent} has no hooks magpie can write", { agent: a.name });
const own = h.event?.includes(":") && h.event.split(":")[0];
if (own && own !== a.id) return t("{event} is {agent}'s own event: only it can run this hook", { event: h.event.slice(own.length + 1), agent: nameOf(own) });
// narrowed to starts this agent can't single out: never widened to
// every start, nor written to match none (hooks.go, startMatcher)
if (h.event === "session-start" && h.matcher && !(ha.starts || []).includes(startsOf(h.matcher))) {
if (!ha.startSources?.length) return t("{agent} runs a session-start hook at every start: it can't be narrowed", { agent: a.name });
if (!h.matcher.split("|").some((s) => ha.startSources.includes(s))) return t("{agent} never starts a session that way", { agent: a.name });
return t("{agent} can't tell those starts apart from its others", { agent: a.name });
}
return "";
};
function hookEventLabel(h) {
const i = h.event.indexOf(":");
if (i > 0) return nameOf(h.event.slice(0, i)) + " · " + h.event.slice(i + 1);
return HOOK_EVENTS().find(([v]) => v === h.event)?.[1] || h.event;
}
function hookLine(h) {
let s = hookEventLabel(h);
if (h.matcher) s += " · " + (h.event.includes(":") ? h.matcher : (narrowsOf(h.event) || []).find(([v]) => v === h.matcher)?.[1] || h.matcher);
return s;
}
function renderHooks(body) {
body.append(intro(t("A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.")));
const all = hookAgents();
const hooks = lib.hooks || [];
pickingFor("hooks", hooks);
if (!hooks.length) {
body.append(empty(t("No hooks in the library yet"), t("Add one, and pick the agents that run it."), button(t("+ Add a hook"), "action", () => editHook(null))));
} else {
if (hooks.length > 1) {
const rh = el("div", "row-head lib-hookhead");
rh.append(el("span", "label", t("In the library")), el("span", "grow"));
if (all.length) rh.append(pickButton("hooks"));
rh.append(removeEveryButton("hooks"));
body.append(rh);
}
const list = el("div", "list lib-list");
list.append(...[...hooks].sort((a, b) => a.name.localeCompare(b.name)).map((h) => hookRow(h, all)));
body.append(list);
if (picking) body.append(pickBar(all));
const after = el("div", "after-list");
after.append(button(t("+ Add hook"), "", () => editHook(null)));
body.append(after);
}
const given = (id) => hooks.some((h) => h.agents?.includes(id));
for (const a of all) {
const ha = hookAgentOf(a.id);
if (ha.off && given(a.id)) body.append(el("p", "lib-aside lib-hooks-off", t("{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.", { agent: a.name })));
}
// Codex runs a hook only once it is trusted there, again after it
// changes (codex-rs/hooks: trusted_hash)
if (given("codex")) body.append(el("p", "lib-aside lib-hooks-codex", t("Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.")));
// Cursor runs Claude Code's hooks as well as its own
if (hooks.some((h) => h.agents?.includes("cursor") && h.agents?.includes("claude"))) body.append(el("p", "lib-aside lib-hooks-twice", t("Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.")));
// the agents greyed: Claude Code, Codex, Gemini CLI and Cursor are the
// ones whose hooks files magpie knows
const skip = all.filter((a) => hookAgentOf(a.id).no);
if (skip.length) body.append(el("p", "lib-aside lib-hooks-no", t("magpie can't give hooks to {agents} yet: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") })));
}
function hookRow(h, all) {
const row = el("div", "row lib-row click lib-hook");
const who = el("div", "who");
who.append(el("div", "name mono", h.name));
// what it is for, in the user's own words (#2011)
if (h.description) who.append(el("div", "lib-hookdesc", h.description));
who.append(el("div", "sub lib-hookev", hookLine(h)));
const cmd = el("div", "sub mono lib-hookcmd", h.command);
cmd.title = h.command;
who.append(cmd);
row.append(glyph(GLYPH.hook), who, ...removeAct(() => confirmRemoveHook(h)),
agentChips(withGone(all, h.agents), h.agents, chipsChange("hooks/agents", h.name, "hooks", (x) => hookRow(x, all)), { problems: h.problems, blocked: hookBlocked(h), all: true }));
if (picking) return pickRow(row, h.name);
row.onclick = () => editHook(h);
row.title = t("Edit {name}", { name: h.name });
return row;
}
function editHook(h) {
const all = hookAgents();
const d = h ? { name: h.name, description: h.description || "", event: h.event, matcher: h.matcher || "", command: h.command, timeout: h.timeout || 0, agents: [...(h.agents || [])] }
: { name: "", description: "", event: "turn-end", matcher: "", command: "", timeout: 0, agents: [] };
if (!h) d.agents = all.filter((a) => !hookBlocked(d)(a)).map((a) => a.id);
const ed = el("div", "editor lib-editor lib-hookedit");
const head = el("div", "ehead");
head.append(glyph(GLYPH.hook), el("b", "", h ? h.name : t("New hook")));
ed.append(head);
const err = el("div", "editor-error");
const name = field2(d.name, t("e.g. notify"), (v) => { d.name = v.trim(); });
ed.append(...field(t("Name"), name, t("Letters, digits, - and _")));
// a box that wraps, so a long description is read whole while it is
// written (#2085). It is kept as one paragraph (library.SaveHook joins
// its lines), so Enter still saves, as in every other field here
const desc = el("textarea", "lib-text small lib-hookdescin");
desc.value = d.description;
desc.placeholder = t("e.g. Tell me when a turn ends");
desc.spellcheck = false;
desc.rows = 3;
desc.maxLength = 200;
desc.oninput = () => { d.description = desc.value; };
desc.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter" && modal?.save) { e.preventDefault(); modal.save(); } };
autosize(desc, 64);
ed.append(...field(t("Description"), desc, t("Optional: what it's for, in any language. Only the library keeps it")));
// the event and the tools it is narrowed to: menus, never a