// 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 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 regrouping = false; // the skills' repositories fetched to group them again let modal = null; // what the library has open in the dialog 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 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", }; 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. const shownAgents = () => lib.agents.filter((a) => !isHidden(a)); 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); 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")); } // 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; } 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.getAttribute("aria-pressed") === "true").map((x) => x.dataset.agent); } // What a click leaves as it was: an agent not shown, and one that has the // item whatever is ticked, whose chip can't be clicked. function keptOf(box, all, on) { const fixed = [...box.children].filter((x) => x.classList.contains("always")).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)).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)); 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:" }[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) { 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; rtk = null; // asked again when its tab is drawn: an agent may have been installed since 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; // 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 || []; if (had.length || skipped.length) { const n = res.installed?.length || 0, parts = []; if (n) parts.push(n === 1 ? t("1 skill installed") : t("{n} skills installed", { n })); 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() { const list = lib.problems || []; 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 (p.own && p.what.startsWith("skill:") && p.agent) { 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) && !p.own); 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")), el("span", "grow")); if (failed) { const again = button(t("Try again"), "action", () => change("all/sync", {})); again.title = t("Writes the library into every agent again"); ttl.append(again); } 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") }; 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; } // 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" }[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 === "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 { 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(); 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([ ["instructions", t("Instructions")], ["mcp", t("MCP servers") + n("mcp")], ["skills", t("Skills") + n("skills")], ["hooks", t("Hooks") + n("hooks")], ["rtk", "RTK"], ], 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: matchMedia("(prefers-reduced-motion: reduce)").matches ? "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"); acts.append(go); } const more = button("", "lib-more", () => lib && reveal(lib.dir)); more.append(glyph(GLYPH.folder, "lib-mini"), el("span", "", 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"))); 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 = []; const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length }); page.append(head); head.classList.toggle("stuck", top > 0); if (!lib.agents.length) { page.append(empty(t("No agents to write to"), t("Install Claude Code, Codex, Gemini CLI, OpenCode… and the library can give them the same instructions, MCP servers and skills."))); return; } // 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 === "hooks") renderHooks(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); 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 })) : t("magpie can't tell how this RTK was installed — update it the way you installed it"); 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 }))); 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)); 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); 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")); // its hook calls an rtk that isn't there: switching it off still works if (a.on && !rtk.path) row.append(tag(t("RTK missing"), "warn", 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 && rtk.offPath) row.append(tag(t("Not on PATH"), "warn", 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 }))); // OpenCode 2 won't load rtk's plugin (written for OpenCode 1): it can't // be switched on, and one already there can be switched off // an agent RTK has no hook for (DeepSeek Harness): listed, with why if (a.noHook) row.append(tag(t("No RTK hook"), "warn", 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: a.name }))); else if (a.blocked && a.id !== "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 }))); else if (a.blocked) row.append(tag(t("Not for OpenCode 2"), "warn", a.on ? t("RTK's plugin is written for OpenCode 1, and OpenCode 2 refuses to load it. Switch this off until RTK supports OpenCode 2.") : t("RTK's plugin is written for OpenCode 1, and OpenCode 2 refuses to load it. It can be switched on once RTK supports OpenCode 2."))); const sw = toggle(a.on, t("{agent} runs its commands through RTK", { agent: a.name }), (on) => setRTK(a, on)); if ((!rtk.path && !a.on) || (a.blocked && !a.on) || rtkBusy.has(a.id) || rtkInstalling || 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); } 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(); } // 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(); } let rtkInstalling = false; async function installRTK() { rtkInstalling = true; render(); try { rtk = await api("library/rtk/install", {}); status(t("RTK is installed — switch it on for your agents below"), "ok", 6000); } catch (e) { 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 ---------- function autosize(ta, min) { const fit = () => { ta.style.height = "auto"; ta.style.height = Math.max(min, ta.scrollHeight + 2) + "px"; }; 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); const skip = shownAgents().filter((a) => !a.instructions); 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(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; } function instructionsRow(a) { const isOpen = open.has(a.agent); const row = el("div", "row lib-row click" + (isOpen ? " open" : "")); const who = el("div", "who"); const name = el("div", "name", a.name); who.append(name); const sub = el("div", "sub"); 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)); row.append(icon(a.icon), who, tags, toggle(a.on, t("{agent} reads the shared instructions", { agent: a.name }), (on) => { 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 }); change("instructions/save", { agents }, done); }), 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."))); 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) { 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; } function quote(a) { 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(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 ? 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)); } 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)); if (many && all.length) rh.append(pickButton("servers"), ...everyButtons("servers", all)); if (by) rh.append(byAgentButton("servers")); if (many) rh.append(removeEveryButton("servers")); 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); // 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) const unchecked = lib.servers.filter((s) => (inUse(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 = 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); const list = el("div", "list lib-list"); for (const f of found) list.append(foundServerRow(f)); body.append(list); } if (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(", ") }))); // 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")); } 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"))); // 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(sub, toolsEl(s.name)); row.append(mark(s.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web), who, agentChips(all, 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); row.onclick = () => editServer(s); row.title = t("Edit {name}", { name: s.name }); return row; } // 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 const healthKey = (s) => JSON.stringify([s.transport, s.command, s.args, s.env, s.url, s.headers, s.signIn]); 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 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) { if (h.state === "ok") return [h.tools === 1 ? t("1 tool") : t("{n} tools", { n: h.tools }), t("It started and listed its tools")]; 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]; } const more = (x) => (h.detail ? x + "\n" + h.detail : x); switch (h.why) { 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 })]; 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) { 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; 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; } const [text, tip] = healthWords(e.h, lib.servers.find((s) => s.name === b.dataset.server)); b.className = "lib-health " + (e.h.state === "ok" ? "ok" : e.h.state === "auth" ? "auth" : "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" + 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 // 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(); })); } 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(); follow(st.id); } 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); } } // followed with the dialog closed too, for the row to say it's signed in async function follow(id) { 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 }; draw(); return; } } 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; 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) { if (c === q) q = ""; else if (c === "\\" && q === '"' && i + 1 < s.length) cur += s[++i]; else cur += c; } else if (c === "'" || c === '"') { q = c; any = true; } else if (c === "\\" && 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; } // 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 = {}; const ed = el("div", "editor lib-editor"); const head = el("div", "ehead"); 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"))); 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(); }); ed.append(...field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it"))); const kindOf = () => segs([["stdio", t("Command")], ["http", "HTTP"], ["sse", "SSE"]], d.transport, (v) => { d.transport = v; draw(); }); const kindBox = el("div"); kindBox.append(kindOf()); ed.append(...field(t("Runs as"), kindBox)); const slot = el("div", "lib-slot"); ed.append(slot); const agentsBox = el("div"); ed.append(...field(t("Agents"), agentsBox)); ed.append(err); function drawAgents() { agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, blocked: sseBlocked(d), all: true })); } function draw() { slot.replaceChildren(); const g = el("div", "lib-grid"); if (d.transport === "stdio") { const line = field2([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); }); line.classList.add("mono"); 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; } 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 } }; 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 () => { 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) => { 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: () => 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")]]; const toolEvent = (ev) => ev === "after-tool" || ev === "before-tool"; 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) }); 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 : HOOK_TOOLS().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, agentChips(all, 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