// Library: one set of instructions, MCP servers and skills, written into // every agent that should have them (#29). magpie keeps the library in its // own folder and writes each agent's files from it; what the user has in // those files besides stays theirs, and every file is kept aside before // magpie writes it. Everything shown here comes from /api/library. // // A page the Library plugin adds to the window (kernel.js): mount wires it // up, open and relang read the library again, redraw draws it again as it // is, and close, dirty and discard are what app.js asks of it before the // reader leaves it. magpie.plugin("library", (ctx) => { let page = null; let loading = null; // the read open started, which server waits for let lib = null; // the page, as /api/library gives it let taken = 0; // how many times lib was set, for a read to tell a newer answer came first let tab = "instructions"; let shown = ""; // the tab the page last drew, which fades in only when it changes let fits = []; // textareas to fit before the page is painted try { tab = localStorage.getItem("magpie.libTab") || tab; } catch {} const texts = {}; // set → its shared instructions as typed, while not saved let openSet = null; // the set of instructions opened to edit let addingSet = false; // a new set being named let removingSet = null; // a set whose Remove was clicked once const extras = {}; // agent → its own additions as typed, while not saved const open = new Set(); // agents whose instructions row is open let probe = null; // skills found at a source: { source, candidates, pick:Set, agents:Set } let probing = false; let checking = false; // asking GitHub which skills it has changed let autoChecked = false; // the page checked by itself, as the server said it was due (#1449) let updatingAll = false; // Update all, picked from the bar's menu let regrouping = false; // the skills' repositories fetched to group them again let modal = null; // what the library has open in the dialog const hid = new Set(); // the write failures the reader hid, by agent and what (#3745) const GLYPH = { cmd: "M3 4.5h10v7H3z M5.5 7l1.5 1.2-1.5 1.3 M8.5 9.5h2", // two arrows closing on a line: billion-context folding a context fold: "M8 2v4 M6 4.2 8 6l2-1.8 M8 14v-4 M6 11.8 8 10l2 1.8 M3 8h10", web: "M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11z M2.5 8h11 M8 2.5c1.6 1.7 2.3 3.5 2.3 5.5S9.6 11.8 8 13.5 M8 2.5C6.4 4.2 5.7 6 5.7 8s.7 3.8 2.3 5.5", skill: "M4 2.5h6.5L12 4v9.5H4z M6 6h4 M6 8.5h4 M6 11h2.5", doc: "M4 2.5h5.5L12 5v8.5H4z M9.5 2.5V5H12", folder: "M2.5 4.5h4l1.2 1.3h5.8v6.7h-11z", up: "M8 12.5v-9 M4.5 7 8 3.5 11.5 7", down: "M8 3.5v9 M4.5 9 8 12.5 11.5 9", trash: "M3.5 4.5h9 M6.5 4.5V3h3v1.5 M4.5 4.5l.6 8.5h5.8l.6-8.5", search: "M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M10 10l3 3", out: "M9.5 3.5h3v3 M12.5 3.5 7.5 8.5 M11 9.5v3H3.5V5h3", key: "M10 2.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4z M7.8 8.2 3 13 M4.5 11.5 6 13", person: "M8 3a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z M3.5 13.5c.6-2.4 2.3-3.6 4.5-3.6s3.9 1.2 4.5 3.6", back: "m9.5 4.5-3 3.5 3 3.5", hook: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9", // a person with a second, smaller one it hands work to subagent: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4", // a clock with an arrow going back round it, as macOS draws backups backup: "M3.2 8a4.8 4.8 0 1 0 1.4-3.4 M2.8 2.6v2.4h2.4 M8 5.3V8l1.9 1.2", power: "M8 2.5v5 M4.7 4.6a4.8 4.8 0 1 0 6.6 0", }; const tilde = (p) => (lib?.home && p?.startsWith(lib.home) ? "~" + p.slice(lib.home.length) : p || ""); const agentOf = (id) => lib.agents.find((a) => a.id === id); const nameOf = (id) => agentOf(id)?.name || id; // An agent with no MCP of its own (Pi) reads its servers through an // extension, which each of its chips says. // An agent hidden on the Agents page is left out here too (#71): what it // already has stays with it, and a new server or skill isn't given to it. // One gone from this computer (gone: uninstalled, or its CLI) is listed // only on the rows of what it still has (withGone), for that to be taken // out: an agent that isn't installed was on every row (@jiahao_jayden). // An agent in a stopped WSL distro (asleep) is listed by what magpie last // knew of it, its ticks kept for when the distro next runs; one whose // places magpie never saw (unseen) only on the rows that name it, like // a gone one, its chip greyed out: opening its files would start WSL // (#3896, cybercaius on Discord). // In gateway mode (gatewaymode.go) none is shown: the page is the // MCP servers the router gives other computers' apps. const shownAgents = () => gatewayPage() ? [] : lib.agents.filter((a) => !a.gone && !a.unseen && !isHidden(a)); // With no agent to write to, none on this computer or gateway mode, the // library is its MCP servers alone, served to any app through the router // (treeman_26897 on Discord: magpie on a server, an MCP entry point for // remote clients, had no way to turn the router on). const gatewayPage = () => typeof gatewayMode !== "undefined" && !!gatewayMode; const agentless = () => !!lib && (gatewayPage() || !lib.agents.length); const withGone = (all, on) => [...all, ...lib.agents.filter((a) => (a.gone || a.unseen && !isHidden(a)) && (on || []).includes(a.id) && !all.some((x) => x.id === a.id))]; const mcpAgents = () => shownAgents().filter((a) => a.mcp) .map((a) => a.mcpVia ? { ...a, aside: t("{agent} reads MCP servers through the {ext} extension", { agent: a.name, ext: a.mcpVia }) } : a); const skillAgents = () => shownAgents().filter((a) => a.skills); // the MCP hub's agents: not a stopped distro's, whose files say what it // has of the hub, and can't be read without starting it const hubAgents = () => mcpAgents().filter((a) => !a.asleep); // one line for each stopped WSL distro the page lists agents of: they // show what magpie last saw, and a change waits for the distro to run. // The Instructions page passes its own rows' agents ({asleep, unseen, // name}). function asleepAsides(seen = lib.agents.filter((a) => a.asleep && !isHidden(a))) { return [...new Set(seen.map((a) => a.asleep))].map((d) => { const unseen = seen.filter((a) => a.asleep === d && a.unseen).map((a) => a.name); const p = el("p", "lib-aside lib-asleep", t("WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.", { distro: d })); if (unseen.length) p.append(" " + t("{agents} can be changed once it runs.", { agents: unseen.join(", ") })); p.dataset.distro = d; return p; }); } // the hub's mark: magpie's bird, the one server each agent is given, // its tail three lines out to three servers (the owner's pick, 10-31) function hubMark() { const g = el("span", "lib-glyph lib-hubmark"); g.innerHTML = ''; return g; } function glyph(d, cls = "lib-glyph") { const g = el("span", cls); g.append(svg(d, 16, 1.3)); return g; } // A row's mark: the thing's own icon where the market knows it, else a // glyph for what it is — never a made-up picture. function mark(url, d) { if (!url) return glyph(d); const box = logo(url, ""); box.classList.add("lib-logo"); box.querySelector("img").onerror = () => box.replaceWith(glyph(d)); return box; } function button(text, cls, onclick) { const b = el("button", "text " + (cls || ""), text); b.onclick = (e) => { e.stopPropagation(); onclick(e, b); }; return b; } // a path shown on the page: a click shows it in the file manager function pathLink(p) { const b = el("button", "lib-path", tilde(p)); b.title = t("Show in {fm}", { fm: fileManager() }); b.onclick = (e) => { e.stopPropagation(); reveal(p); }; return b; } function fileManager() { return /^Mac/.test(navigator.platform) ? "Finder" : /^Win/.test(navigator.platform) ? "Explorer" : t("the file manager"); } // the app's webview opens no new windows: a link goes to the system browser function browse(u) { api("open", { url: u }).catch((e) => status(e.message, "err")); } function reveal(p) { api("library/reveal", { path: p }).catch((e) => status(e.message, "err")); } const bridgedWhy = () => t("Added from a Remote magpie with this computer's key for it, so it stays on this computer"); // A switch: on or off, nothing between. function toggle(on, label, onChange) { const s = el("button", "lib-switch" + (on ? " on" : "")); s.setAttribute("role", "switch"); s.setAttribute("aria-checked", on ? "true" : "false"); s.setAttribute("aria-label", label); s.append(el("i")); s.onclick = (e) => { e.stopPropagation(); onChange(!on); }; return s; } // An agent's icon, made once and copied: a list of hundreds of skills has // a chip for each agent on every row, and making each icon afresh (its // image, and a probe of whether it loads) was most of drawing the list. // One whose picture didn't load is let go, so the next row makes it // afresh: kept, its copies would all be empty until the page was loaded // again (as Claude Code's were seen to, in the skills list). // It's made apart from the Providers page's kept icons, which are its // own rows' to take back. const icons = new Map(); function agentIcon(name) { let i = icons.get(name); if (!i) { const kept = keptIcons; keptIcons = null; try { i = icon(name); } finally { keptIcons = kept; } icons.set(name, i); const im = i.querySelector(":scope > img"); if (im) im.onerror = () => { if (icons.get(name) === i) icons.delete(name); }; greyIcon(i); } return i.cloneNode(true); } // A copy already drawn whose picture failed asks for it again, a few // times and a little later each time; the grey copy is left to the filter. document.addEventListener("error", (e) => { const im = e.target; if (im.tagName !== "IMG" || im.classList.contains("grey") || !im.parentElement?.classList.contains("ic") || !im.closest("#view-library, #modal.lib")) return; const n = +(im.dataset.tries || 0); if (n >= 3) return; im.dataset.tries = n + 1; setTimeout(() => { if (im.isConnected) im.src = srcOf(im) + "?try=" + (n + 1); }, 400 * (n + 1)); }, true); const srcOf = (im) => (im.getAttribute("src") || "").split("?")[0]; // A chip's icon is grey while its agent hasn't the item. A filter made it // so on every paint of every chip — most of what a scroll through // hundreds of skills painted — so it's made grey once instead: a picture // gets a grey copy (by the filter's own sum), which stands in for // it once ready, and an icon drawn in the text's colour takes that colour // grey (library.css). Until then, or if it can't be, the filter does it. function greyIcon(i) { if (i.querySelector(":scope > .mask, :scope > svg")) { i.classList.add("flat"); return; } const src = i.querySelector(":scope > img") && srcOf(i.querySelector(":scope > img")); if (!src) return; greyCopy(src).then((url) => { if (!url) return; const add = (ic) => { if (ic.classList.contains("baked")) return; const g = el("img", "grey"); g.src = url; g.alt = ""; g.draggable = false; ic.append(g); ic.classList.add("baked"); }; add(i); for (const x of document.querySelectorAll(".lib-ag > .ic:not(.baked) > img")) if (srcOf(x) === src) add(x.parentElement); }, () => {}); } // grayscale(1)'s own sum: each colour's red, green and blue become this const lum = (r, g, b) => Math.round(r * .2126 + g * .7152 + b * .0722); let tint; function greyColour(v) { tint ||= document.createElement("canvas").getContext("2d"); // a colour in any spelling, read back as #rrggbb or rgba(…); anything // else (none, url(#…), currentColor) is left as it is if (/^\s*(none|currentcolor|inherit|transparent|url\()/i.test(v)) return v; tint.fillStyle = "#010203"; tint.fillStyle = v; const c = tint.fillStyle; let m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(c); if (m) { if (c === "#010203" && !/010203/.test(v)) return v; const y = lum(parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)).toString(16).padStart(2, "0"); return "#" + y + y + y; } m = /^rgba?\(\s*([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\s*\)$/.exec(c); if (!m) return v; const y = lum(+m[1], +m[2], +m[3]); return `rgba(${y}, ${y}, ${y}, ${m[4] ?? 1})`; } async function greyCopy(src) { const r = await fetch(src); if (!r.ok) return null; let blob; if (/svg/.test(r.headers.get("content-type") || "") || /\.svg$/.test(src)) { // the drawing with each of its colours made grey — the same as the // filter, which is a sum over each colour (blending and gradients // mix colours in sRGB, as the filter does, so they come out the same) // and drawn as sharp as the drawing itself // (a name inside another, as data-fill, is left: checked by hand, as a // lookbehind in the pattern is a syntax error before Safari 16.4, #220) const inWord = (s, at) => /[\w-]/.test(s[at - 1] || ""); const s = (await r.text()).replace(/(fill|stroke|stop-color|flood-color|lighting-color|color)(\s*=\s*)(["'])([^"']*)\3/g, (all, k, eq, q, v, at, s) => inWord(s, at) ? all : k + eq + q + greyColour(v) + q) .replace(/(fill|stroke|stop-color|flood-color|lighting-color|color)(\s*:\s*)([^;"'}]+)/g, (all, k, eq, v, at, s) => inWord(s, at) ? all : k + eq + greyColour(v)); if (/<(image|feColorMatrix|feComponentTransfer|feTurbulence)\b/.test(s)) return null; // a colour the sum can't reach blob = new Blob([s], { type: "image/svg+xml" }); } else { // a picture made grey pixel by pixel const im = new Image(); im.src = URL.createObjectURL(await r.blob()); await im.decode(); const c = document.createElement("canvas"); c.width = im.naturalWidth; c.height = im.naturalHeight; const x = c.getContext("2d"); x.drawImage(im, 0, 0); URL.revokeObjectURL(im.src); const d = x.getImageData(0, 0, c.width, c.height), p = d.data; for (let k = 0; k < p.length; k += 4) p[k] = p[k + 1] = p[k + 2] = p[k] * .2126 + p[k + 1] * .7152 + p[k + 2] * .0722; x.putImageData(d, 0, 0); blob = await new Promise((done) => c.toBlob(done)); if (!blob) return null; } const url = URL.createObjectURL(blob); const t = new Image(); t.src = url; await t.decode(); // ready before it stands in, so nothing blinks return url; } // Agent chips for a server or a skill: each agent that could have it, lit // when it does. A chip whose agent couldn't be given it says why. One that // has it whatever is ticked (opts.always: a skill kept in ~/.agents/skills, // which the agent reads itself, #595) is lit, can't be clicked, and says // why; it is left out of what a click sends, and keeps what it had. function agentChips(all, on, onChange, opts = {}) { on ||= []; const box = el("div", "lib-agents"); box.style.setProperty("--lib-agent-count", all.length); // the row it is put in says so (.with-agents), for its name's room: // Safari before 15.4 has no :has(). Every caller appends it at once. queueMicrotask(() => box.parentElement?.classList.contains("lib-row") && box.parentElement.classList.add("with-agents")); for (const [i, a] of all.entries()) { const always = opts.always?.(a) || ""; const has = on.includes(a.id) || !!always; const c = el("button", "lib-ag" + (has ? " on" : "") + (always ? " always" : "")); c.dataset.agent = a.id; // how many chips are to its right, how far it slides into the hand c.style.setProperty("--k", all.length - 1 - i); c.append(agentIcon(a.icon)); if (opts.names) c.append(el("span", "n", a.name)); const problem = !always && opts.problems?.[a.id]; const blocked = always || opts.blocked?.(a); const via = !has && opts.via?.(a); let tip = has ? t("{agent} has it — click to take it away", { agent: a.name }) : t("Give it to {agent}", { agent: a.name }); if (via) { c.classList.add("via"); tip = t("{agent} reads it through {other} — click to give it its own", { agent: a.name, other: via }); } if (problem) { c.classList.add("warn"); tip = a.name + ": " + problem; } // not disabled: a disabled button tells nothing on a click, and // WebKit shows it no tooltip either — 蓝猫 clicked Claude Desktop's // grey chip for a remote server and nothing said why if (blocked) { c.classList.add("blocked"); c.setAttribute("aria-disabled", "true"); tip = blocked; } if (a.gone) { c.classList.add("gone"); tip = t("{agent} isn't installed here — click to take it away", { agent: a.name }); } if (a.unseen) { c.classList.add("asleep", "unseen", "blocked"); c.setAttribute("aria-disabled", "true"); tip = t("WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this", { distro: a.asleep, agent: a.name }); } else if (a.asleep) { c.classList.add("asleep"); const v = { distro: a.asleep, agent: a.name }; if (!problem && !blocked) tip = has ? t("WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs", v) : t("WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs", v); } c.title = a.aside && !problem && !blocked ? tip + "\n" + a.aside : tip; c.setAttribute("aria-pressed", has ? "true" : "false"); // What's lit is read off the chips clicked, not the list they were // drawn with: a row's chips change in place, several clicks before // magpie has answered the first, and take on the handlers of chips // drawn for them (morphChips). An agent not shown keeps what it has. c.onclick = (e) => { e.stopPropagation(); const me = e.currentTarget; if (cannot(me)) { status(me.title, "warn", 8000); return; } const lit = litOf(me.parentElement); const kept = keptOf(me.parentElement, all, on); onChange([...kept, ...(lit.includes(a.id) ? lit.filter((x) => x !== a.id) : [...lit, a.id])], me); }; box.append(c); } if (opts.all) allChip(box, all, on, onChange); return box; } // cannot says a chip's agent can't be given the item, or has it whatever // is ticked: a click says why rather than switching it const cannot = (c) => c.getAttribute("aria-disabled") === "true"; // The agents a row's chips have lit by a click: not one lit because it // has the item whatever is ticked. function litOf(box) { return [...box.children].filter((x) => x.dataset.agent && !x.classList.contains("always") && !x.classList.contains("unseen") && x.getAttribute("aria-pressed") === "true").map((x) => x.dataset.agent); } // What a click leaves as it was: an agent not shown, one that has the // item whatever is ticked, whose chip can't be clicked, and one in a // stopped distro magpie can't show the ticks of (unseen). function keptOf(box, all, on) { const fixed = [...box.children].filter((x) => x.classList.contains("always") || x.classList.contains("unseen")).map((x) => x.dataset.agent); return on.filter((id) => !all.some((x) => x.id === id) || fixed.includes(id)); } // All, ahead of a row's chips: one click gives the item to every agent // shown that can take it (not those a chip is greyed out for: no SSE, no // remote server), and when they all have it, takes it from every one. // An agent not shown keeps what it has, as with a chip. The pickers that // choose the agents before an item is added (installing skills, adding or // bringing in servers) have it too (#1531): most start with every agent // lit, and one agent alone was a click on each of the others. function allChip(box, all, on, onChange) { const can = [...box.children].filter((c) => !cannot(c) && !c.classList.contains("gone")).map((c) => c.dataset.agent); if (can.length < 2) return; const c = el("button", "lib-ag all", t("All")); c.dataset.all = "1"; c.onclick = (e) => { e.stopPropagation(); const me = e.currentTarget; const lit = litOf(me.parentElement); const kept = keptOf(me.parentElement, all, on); onChange(can.every((id) => lit.includes(id)) ? kept : [...new Set([...kept, ...lit, ...can])], me); }; box.prepend(c); paintAll(box); } // the All chip shows whether every agent that can take the item has it function paintAll(box) { const c = box.querySelector(":scope > .lib-ag.all"); if (!c) return; const can = [...box.children].filter((x) => x.dataset.agent && !cannot(x) && !x.classList.contains("gone")); const n = can.length, full = can.every((x) => x.getAttribute("aria-pressed") === "true"); c.classList.toggle("on", full); c.setAttribute("aria-pressed", full ? "true" : "false"); c.title = full ? t("Every agent that can take it has it — click to take it from all {n}", { n }) : t("Give it to all {n} agents that can take it", { n }); } // A row's chips switched in place: the page isn't drawn again, which // lost the chips' hover (they folded back together and spread again under // the pointer) and blinked their icons (#69). The chip shows the click at // once and the next click needn't wait: a row writes one list at a time, // and clicks made meanwhile are sent together once it's answered, so the // last click is what the agents end up with. What magpie wrote is then // painted onto the same buttons — or, when it couldn't, what it has, which // takes back the clicks it refused. Nothing else on the page is drawn // again for it: the rest is drawn from the new answer when the page next is. const writing = new Map(); // path + name → { list, name, want, box } while a row's agents are written let refused = 0; // when a row's write last failed, whose error another row's "Written" doesn't cover function chipsChange(path, name, list, rowOf) { return async (next, c) => { // All lights or darkens every chip of the row, a chip only itself const every = !!c.dataset.all; for (const x of every ? [...c.parentElement.children].filter((y) => y.dataset.agent && !y.classList.contains("always")) : [c]) { const on = next.includes(x.dataset.agent); x.classList.toggle("on", on); if (on || x === c) x.classList.remove("via"); x.setAttribute("aria-pressed", on ? "true" : "false"); } paintAll(c.parentElement); const key = path + "\n" + name; const w = writing.get(key); if (w) { w.want = next; w.box = c.parentElement; w.every = every; take(lib); return; } const me = { list, name, want: next, box: c.parentElement, every }; writing.set(key, me); take(lib); let sent = null, failed = false; try { // clicks that came back to what was sent aren't sent again const same = () => [...sent].sort().join() === [...me.want].sort().join(); while (!sent || !same()) { sent = me.want; const v = await api("library/" + path, { name, agents: sent }); take(v); if (same() && me.every && Date.now() - refused > 6000) { reportAll(v, me); continue; } if (same() && Date.now() - refused > 6000) report(v.result, null, sent); } } catch (e) { failed = true; refused = Date.now(); status(e.message, "err", 6000); } writing.delete(key); syncProblems(); // the page held the clicks: what magpie really has is read again if (failed) await api("library").then(take, () => {}); const x = lib[list].find((y) => y.name === name); const fresh = x && rowOf(x).querySelector(":scope > .lib-agents"); if (!me.box.isConnected) { if (failed) render(); } // drawn again meanwhile, from the clicks else if (fresh && !morphChips(me.box, fresh)) me.box.replaceWith(fresh); }; } // What All did, said of the item: on for how many of the agents it went // to, and which of them couldn't be given it, and why. function reportAll(v, me) { const what = ({ servers: "mcp:", hooks: "hook:", subagents: "subagent:" }[me.list] || "skill:") + me.name; const shown = [...me.box.children].filter((x) => x.dataset.agent && !cannot(x)).map((x) => x.dataset.agent); const n = shown.filter((id) => me.want.includes(id)).length; const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent)); if (!bad.length) { status(n ? t("{name} is on for all {n} agents", { name: me.name, n }) : t("{name} is off for every agent", { name: me.name }), "ok"); return; } const p = bad[0]; status((n ? t("{name} is on for {ok} of {n} agents", { name: me.name, ok: n - bad.length, n }) : t("{name} couldn't be taken from every agent", { name: me.name })) + " — " + t("{agent}: {error}", { agent: nameOf(p.agent), error: p.error }) + (bad.length > 1 ? " " + t("(and {n} more)", { n: bad.length - 1 }) : ""), "warn", 8000); } // take is the page as magpie answered it, with the rows still being // written kept as they were last clicked. A server or skill added, // removed or renamed changes what the market calls added (#300): one gone // from the library loses its mark at once, and the market is asked again. function take(v) { // What the reader hid stays hidden while it still fails and nothing // else does: every change writes every agent again, so a file magpie // can't stat fails at each one (#3745). A failure not hidden brings the // card back whole, and an item written meanwhile is new when it fails // again. v.problems is everything that stands, whatever answered. const failing = new Set((v.problems || []).filter(failure).map(problemKey)); for (const k of hid) if (!failing.has(k)) hid.delete(k); if ([...failing].some((k) => !hid.has(k))) hid.clear(); const was = lib && shelf(); lib = v; taken++; for (const w of writing.values()) { const x = lib[w.list].find((y) => y.name === w.name); if (x) x.agents = w.want; } if (!was || shelf() === was) return; for (const [kind, list] of [["mcp", lib.servers], ["skills", lib.skills]]) { const m = market[kind]; if (!m.items) continue; const names = new Set((list || []).map((x) => x.name)); for (const x of m.items) if (x.have && !names.has(x.have)) x.have = ""; drawMarket(kind); fetchMarket(kind); } } function morphChips(box, fresh) { const was = [...box.children], now = [...fresh.children]; if (was.length !== now.length || was.some((c, i) => c.dataset.agent !== now[i].dataset.agent)) return false; was.forEach((c, i) => { const n = now[i]; c.className = n.className; c.title = n.title; if (cannot(n)) c.setAttribute("aria-disabled", "true"); else c.removeAttribute("aria-disabled"); c.setAttribute("aria-pressed", n.getAttribute("aria-pressed")); c.onclick = n.onclick; }); return true; } // ---------- loading and changing ---------- // quiet is a read on coming back to the window: the page is drawn again // only when the library changed meanwhile, so a click that brings the // window forward doesn't redraw what it clicked on. // The first read is a glance: the page but for the skills the agents // have of their own and which copies are out of date, which take reading // their skill folders through, and on a machine with many big skills // that took minutes before anything showed (0day404, #541). It is drawn // at once, and the whole page after it; only the Skills tab shows what // the glance left out, so the others aren't drawn again for it. async function load(quiet) { let glanced = false; if (!lib) { renderLoading(); const at = taken; try { const g = await api("library?glance=1"); if (!lib && taken === at) { take(g); glanced = true; render(); } } catch {} } try { const at = taken; const v = await api("library"); // a change answered meanwhile, with the library as it is after it if (taken !== at) return; const was = lib && seen(lib); take(v); if (glanced && tab !== "skills") return; if ((quiet === true || glanced) && seen(lib) === was) return; // opening the page (its nav clicked, while on it too) draws it again // only for a change, or for RTK's tab, which is asked again: a page // drawn over again replaced the row under the reader's pointer (#3099) if (quiet === "open" && seen(lib) === was && tab !== "rtk" && tab !== "bili" && page.querySelector(":scope > .lib-body")) return; rtk = null; // asked again when its tab is drawn: an agent may have been installed since bili = null; piView = null; render(); } catch (e) { status(e.message, "err"); } } // the library as the page shows it: what a change did is said once, not shown const seen = (v) => JSON.stringify({ ...v, result: undefined }); // Every change answers with the page as it is after it, and what it did; // one to the instructions with them alone, the rest kept as it is (#1624). // One change is on its way at a time: while it is, the page's buttons // can't be pressed and the one pressed says it is saving, so a second // click doesn't make or remove a set twice (Hipple, #1624: a minute a // click with nothing to show for it). let changing = false; async function change(path, body, done) { if (changing) return false; changing = true; const ev = window.event; const pressed = ev?.type === "click" && ev.target?.closest?.("button:not(.lib-switch):not(.lib-radio)"); const held = [...document.querySelectorAll("#view-library button, #modal.lib button")].filter((b) => !b.disabled); for (const b of held) b.disabled = true; page.setAttribute("aria-busy", "true"); if (pressed && pressed.textContent.trim()) saving(pressed, t("Saving…")); status(t("Saving…"), "", 120000); let ok = false; try { const v = await api("library/" + path, body); take(v.part === "instructions" ? { ...lib, instructions: v.instructions, problems: v.problems, result: v.result } : v); status(""); // what it did, said next, or nothing for one that says nothing report(v.result, done); ok = true; return true; } catch (e) { status(e.message, "err", 6000); return false; } finally { changing = false; page.removeAttribute("aria-busy"); for (const b of held) b.disabled = false; if (pressed) doneSaving(pressed); if (ok) render(); } } // given, for a row's agent chips, is the agents that have it now: an // agent written that isn't one of them had it taken out (#332). function report(res, done, given) { if (!res) return; // an update that found its source without the skill: said so, not // as done or failed (スライム on Discord) if (res.gone?.length) { status(goneSaid(res.gone), "warn", 10000); return; } // skills installed together (lc on Discord): those the library had // already, and those left out because another by that name is in the // way, are named, beside how many were installed const had = res.had || [], skipped = res.skipped || [], linked = res.linked || []; if (had.length || skipped.length || linked.length) { const n = res.installed?.length || 0, parts = []; if (n) parts.push(n === 1 ? t("1 skill installed") : t("{n} skills installed", { n })); // a skill from a folder, linked to the one installed (skill_link.go) if (linked.length) parts.push(t("updates from GitHub now: {names}", { names: linked.join(", ") })); if (res.linkedKept?.length) parts.push(t("files of their own kept with the backups: {names}", { names: res.linkedKept.join(", ") })); if (had.length) parts.push(t("already in the library: {names}", { names: had.join(", ") })); for (const p of skipped) parts.push(t("{name} skipped: {error}", { name: p.what.replace(/^skill:/, ""), error: p.error })); status(parts.join(" · "), skipped.length ? "warn" : "ok", skipped.length ? 12000 : 6000); return; } if (res.problems?.length) { const p = res.problems[0]; status(t("{agent}: {error}", { agent: tilde(nameOf(p.agent)), error: p.error }) + (res.problems.length > 1 ? " " + t("(and {n} more)", { n: res.problems.length - 1 }) : ""), "warn", 8000); return; } const n = res.changed?.length || 0; const out = given ? (res.changed || []).filter((id) => !given.includes(id)).length : 0; if (done) status(done, "ok"); else if (out && out === n) status(n === 1 ? t("Removed from {agent}", { agent: nameOf(res.changed[0]) }) : t("Removed from {n} agents", { n }), "ok"); else if (out) status(t("{n} agents updated", { n }), "ok"); else if (n) status(n === 1 ? t("Written to {agent}", { agent: nameOf(res.changed[0]) }) : t("Written to {n} agents", { n }), "ok"); else status(t("Saved — the agents already had it"), "ok"); } // What the last change couldn't write, whole: a chip's amber dot holds // only its own item's, so an agent's instructions, its MCP file, a // project or a skill that wouldn't update were said once in a toast // ("see Library") and shown nowhere. // Each is listed on the tab it is about; another tab says only how many // wait where, with a button to go there: Claude Desktop's own skills // listed one by one on the MCP servers tab read as duplicated servers // (#1896). An agent's own skills in the library's way are one row for // the agent, settled together, not a write that failed: Try again, which // can't change them, is offered only beside a write that did fail. function problemsCard() { // the write failures the reader hid are left out while they are all // that fails; an agent's own skills, still to settle, stay const all = lib.problems || []; const quiet = all.some(failure) && all.filter(failure).every((p) => hid.has(problemKey(p))); const list = quiet ? all.filter((p) => !failure(p)) : all; if (!list.length) return null; const here = list.filter((p) => !problemTab(p.what) || problemTab(p.what) === tab); const away = {}; for (const p of list) if (!here.includes(p)) away[problemTab(p.what)] = (away[problemTab(p.what)] || 0) + 1; const owns = new Map(); // agent → its own skills by the library's names const rest = []; for (const p of here) { if (!failure(p)) { if (!owns.has(p.agent)) owns.set(p.agent, []); owns.get(p.agent).push(p.what.slice("skill:".length)); } else rest.push(p); } const card = el("div", "lib-problems"); card.setAttribute("role", "status"); const ttl = el("div", "lib-problems-head"); const failed = rest.length || list.some((p) => !here.includes(p) && failure(p)); ttl.append(el("span", "lib-problems-dot"), el("b", "", failed ? t("Some of the Library couldn't be written") : t("Some agents have skills of their own by the library's names"))); if (failed) { const again = button(t("Try again"), "action", () => change("all/sync", {})); again.title = t("Writes the library into every agent again"); // the reader who can't mend it here, or won't now, puts it away; a // change's toast still says what failed, and something new that // can't be written brings it back (#3745) const hide = button("", "lib-x", () => hideFailed(card)); hide.append(svg("M4.5 4.5l7 7M11.5 4.5l-7 7", 11, 1.6)); hide.title = t("Hide until something new can't be written"); ttl.append(again, hide); } card.append(ttl); const ul = el("ul"); for (const p of rest) { const li = el("li"); const who = p.what.startsWith("project:") ? tilde(p.agent) : p.agent ? nameOf(p.agent) : ""; if (who) li.append(el("b", "", who), el("span", "lib-problems-sep", " · ")); li.append(el("span", "", problemWhat(p.what)), el("span", "lib-problems-err", p.error)); ul.append(li); } // an agent's own skills in the library's way are settled right here: // the library's in their place (the agent's kept aside), or the agent's for (const [id, names] of owns) { const li = el("li", "lib-problems-own"); const who = nameOf(id), name = names.join(", "); const one = names.length === 1; li.append(el("b", "", who), el("span", "lib-problems-sep", " · "), el("span", "", one ? t("Skill {name}", { name }) : t("Skills {names}", { names: name }))); // Claude Desktop's are Anthropic's built in or made in Desktop, listed // in its manifest: kept, never put aside for the library's const desktop = id === "claude-desktop"; li.append(el("span", "lib-problems-err", desktop ? (one ? t("Claude Desktop has its own {name}, so it doesn't get the library's", { name }) : t("Claude Desktop has its own of these, so it doesn't get the library's")) : (one ? t("{agent} has a skill of its own called {name}, not the same as the library's", { agent: who, name }) : t("{agent} has skills of its own by these names, not the same as the library's", { agent: who })))); const body = one ? { name: names[0], agent: id } : { names, agent: id }; const fix = el("div", "lib-problems-fix"); if (!desktop) { const use = button(t("Use the library's"), "action", () => change("skills/use-library", body, one ? t("{agent} has the library's {name} now; its own is kept with the backups", { agent: who, name }) : t("{agent} has the library's {names} now; its own are kept with the backups", { agent: who, names: name }))); use.title = one ? t("Sets {agent}'s own {name} aside with the backups and gives it the library's in its place", { agent: who, name }) : t("Sets {agent}'s own {names} aside with the backups and gives it the library's in their place", { agent: who, names: name }); fix.append(use); } const keep = button(t("Keep {agent}'s", { agent: who }), "action", () => change("skills/keep-own", body, one ? t("{agent} keeps its own {name}", { agent: who, name }) : t("{agent} keeps its own {names}", { agent: who, names: name }))); keep.title = one ? t("{agent} keeps its own {name}, and the library no longer gives it this skill", { agent: who, name }) : t("{agent} keeps its own {names}, and the library no longer gives it these skills", { agent: who, names: name }); fix.append(keep); li.append(fix); ul.append(li); } if (ul.childElementCount) card.append(ul); const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), subagents: t("Subagents"), plugins: t("Claude plugins") }; const others = Object.keys(away).filter((k) => k in tabNames); if (others.length) { const more = el("div", "lib-problems-away"); for (const k of others) { const go = button(t("{tab}: {n} more", { n: away[k], tab: tabNames[k] }), "action", () => openTab(k)); go.dataset.tab = k; more.append(go); } card.append(more); } return card; } // a write that failed, as against an agent's own skill in the library's // way, which is the agent's to settle function failure(p) { return !(p.own && p.what.startsWith("skill:") && p.agent); } // a failure is the same from one sync to the next by its agent and its // item: the error can name a temp file new at each write (edit.WriteAtomic) function problemKey(p) { return p.agent + "\n" + p.what; } function hideFailed(card) { const focused = card.contains(document.activeElement); for (const p of lib.problems || []) if (failure(p)) hid.add(problemKey(p)); // the view keeps its scroll, as render keeps it for Try again: // Chromium's scroll anchoring would move it as the card goes const top = page.scrollTop; syncProblems(); page.scrollTop = top; // the keyboard's place: the card's next button, or the tab open if (focused) (page.querySelector(":scope > .lib-problems button") || page.querySelector(".lib-tabs .opt.on"))?.focus({ preventScroll: true }); } // the tab a problem is about; "" is one shown on every tab function problemTab(what) { return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", subagent: "subagents", plugin: "plugins" }[what.split(":")[0]] || ""; } function problemWhat(what) { const [kind, ...rest] = what.split(":"); const name = rest.join(":"); if (kind === "instructions") return t("Instructions"); if (kind === "mcp") return name ? t("MCP server {name}", { name }) : t("MCP servers"); if (kind === "skill") return t("Skill {name}", { name }); if (kind === "hook") return t("Hook {name}", { name }); if (kind === "subagent") return t("Subagent {name}", { name }); if (kind === "project") return name ? t("Skill {name}", { name }) : t("The project"); return what; } // a chip's write changes the list without drawing the page again: the // card is put right in place (the chip clicked is held where it is on the // screen by app.js, as for any click) function syncProblems() { const was = page.querySelector(":scope > .lib-problems"); const card = problemsCard(); if (!was && !card) return; if (was && card && was.textContent === card.textContent) return; if (was && card) was.replaceWith(card); else if (was) was.remove(); else page.querySelector(":scope > .lib-head")?.after(card); } // Until the library comes, the page is drawn as it will be: the real tabs // (one can be picked already) and, for the tab open, its rows in outline, // so nothing moves when they're filled in. The outline shows only if the // wait is long enough to see it. function renderLoading() { page.replaceChildren(); shown = ""; page.append(libHead(null), skeleton(tab)); } function skeleton(which) { const box = el("div", "lib-body lib-skel"); box.setAttribute("aria-busy", "true"); const bar = (w, h, cls = "") => { const b = el("span", "skeleton " + cls); b.style.cssText = `width:${w};height:${h}px`; return b; }; // name and path lengths vary, as they will const widths = [[34, 46], [22, 40], [30, 52], [26, 38], [38, 44], [20, 36], [28, 48]]; const rows = (n, sw) => { const list = el("div", "list lib-list"); for (let i = 0; i < n; i++) { const [a, b] = widths[i % widths.length]; const row = el("div", "row lib-row"); const who = el("div", "who"); who.append(bar(a + "%", 10), bar(b + "%", 8)); row.append(bar("26px", 26, "lib-sk-icon"), who, el("span", "grow")); if (sw) row.append(bar("34px", 20, "lib-sk-switch")); list.append(row); } return list; }; const head = (w) => { const rh = el("div", "row-head"); rh.append(bar(w, 8)); return rh; }; const intro = el("div", "lib-intro lib-sk-intro"); intro.append(bar("min(520px, 80%)", 9)); box.append(intro); if (which === "instructions") { const card = el("div", "list lib-list"); const ch = el("div", "row lib-row"); ch.append(bar("26px", 26, "lib-sk-icon"), bar("150px", 11)); card.append(ch, rows(1, false).firstChild); box.append(card, head("60px"), rows(6, true)); } else if (which === "rtk" || which === "bili") { box.append(rows(1, false), head("60px"), rows(which === "rtk" ? 5 : 3, true)); } else if (which === "memory") { box.append(rows(1, true), rows(6, false)); } else if (which === "pi") { box.append(head("60px"), rows(4, true)); } else { box.append(rows(5, true)); } return box; } function openTab(id) { tab = id; try { localStorage.setItem("magpie.libTab", id); } catch {} // RTK's count read afresh each time its tab is opened: an agent run // since adds to it (#741); the page keeps the last one until then if (id === "rtk" && rtk) loadRTK(); // and which agents have billion-context's plugin: bili switched outside magpie if (id === "bili" && bili) loadBili(); // Pi's extensions too: one installed or changed outside magpie since if (id === "pi" && piView) loadPi(); // memory too: agents save to it while the page is open if (id === "memory" && mem) loadMemory(); if (!lib) return page.querySelector(":scope > .lib-skel")?.replaceWith(skeleton(id)); render(); syncLists(); } // the tabs and the Library folder; without the library yet (lib is null // while it loads) the tabs have no counts and the folder waits function libHead(counts) { const head = el("div", "lib-head"); const n = (k) => (counts?.[k] ? " · " + counts[k] : ""); const tabs = segs(agentless() ? [["mcp", t("MCP servers") + n("mcp")]] : [ ["instructions", t("Instructions")], ["memory", t("Memory")], ["mcp", t("MCP servers") + n("mcp")], ["skills", t("Skills") + n("skills")], ["hooks", t("Hooks") + n("hooks")], ["subagents", t("Subagents") + n("subagents")], ["plugins", t("Claude plugins") + n("plugins")], ["rtk", "RTK"], ["bili", "billion-context"], ...(hasPi() ? [["pi", t("Pi packages")]] : []), ], tab, openTab); tabs.classList.add("lib-tabs"); head.append(tabs); // the buttons keep together at the end, on a line of their own when the // window is too narrow for the tabs and them const acts = el("span", "lib-headacts"); // The market sits under everything the tab lists, many screens down with // dozens of skills (#1348): the strip that stays at the top goes to it. if (lib && (tab === "mcp" || tab === "skills")) { const go = button("", "lib-discover", (e) => { const mk = page.querySelector(`.mk[data-market="${tab}"]`); if (!mk || !window.scrollOnPurpose?.(e, 1500)) return; // its heading just under the strip, however many lines that takes const top = mk.getBoundingClientRect().top - page.getBoundingClientRect().top + page.scrollTop - head.getBoundingClientRect().height - 8; page.scrollTo({ top, behavior: calm() ? "auto" : "smooth" }); mk.querySelector("input")?.focus({ preventScroll: true }); }); go.append(glyph(GLYPH.search, "lib-mini"), el("span", "", t("Discover"))); go.title = tab === "mcp" ? t("Go to the MCP servers you can add, under the list") : t("Go to the skills you can add, under the list"); // a narrow window's title bar shows the icon alone (app.css // .tools-tight): the name stays the button's, not only its tooltip's go.setAttribute("aria-label", t("Discover")); acts.append(go); } const more = button("", "lib-more", () => lib && reveal(lib.dir)); more.append(glyph(GLYPH.folder, "lib-mini"), el("span", "", t("Library folder"))); more.setAttribute("aria-label", t("Library folder")); if (lib) more.title = tilde(lib.dir); else more.disabled = true; // magpie's backups beside it, on every tab: at the foot of a long // page they were hard to find (Dade on Discord: 备份在最底部) const back = button("", "lib-backups", () => lib && reveal(lib.backups)); back.append(glyph(GLYPH.backup, "lib-mini"), el("span", "", t("Backups"))); back.setAttribute("aria-label", t("Backups")); if (lib) back.title = t("magpie keeps a copy of every file before it writes it.") + "\n" + tilde(lib.backups); else back.disabled = true; acts.append(more, back); head.append(acts); return head; } // ---------- the page ---------- function render() { if (!lib) return; const top = page.scrollTop; const focus = document.activeElement?.dataset?.lib; // keep the caret where the reader is typing const caret = focus ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null; page.replaceChildren(); fits = []; // the MCP servers alone with no agent to write to; the tab the reader // last picked is kept for when there is one if (agentless()) tab = "mcp"; // Pi's tab only while a Pi is here; the pick is kept for when one is else if (tab === "pi" && !hasPi()) tab = "instructions"; const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length, plugins: (lib.plugins || []).length }); page.append(head); head.classList.toggle("stuck", top > 0); // what changed in a tab is drawn in place: only another tab (or the // first one after the skeleton) fades in const problems = problemsCard(); if (problems) page.append(problems); const body = el("div", "lib-body" + (shown !== tab ? " enter" : "")); shown = tab; if (tab === "instructions") renderInstructions(body); else if (tab === "mcp") renderServers(body); else if (tab === "rtk") renderRTK(body); else if (tab === "bili") renderBili(body); else if (tab === "memory") renderMemory(body); else if (tab === "pi") renderPi(body); else if (tab === "hooks") renderHooks(body); else if (tab === "subagents") renderSubagents(body); else if (tab === "plugins") renderPlugins(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); } // ---------- memory ---------- // What the agents know about the user and their projects, shared by all // of them (internal/memory): agents search it and save to it through the // Magpie Memory server, and the ones ticked for instructions read its // digest. A memory an agent only guessed waits under Suggested until the // user keeps it. let mem = null; // /api/memory let dist = null; // /api/memory/distill: conversations read into memory let distPoll = 0; let sem = null; // /api/memory/semantic: search by meaning (memembed) let semPoll = 0; let memRank = null; // {q, status, ids}: the search's ranking by meaning, best first let rankT = 0; let memLoading = false; let memQ = ""; // the search typed let memStatus = "active"; let memScope = ""; // "" every scope let memOpen = null; // the memory open to edit, or "new" let memDraft = null; // its fields as typed let memRemoving = null; // the memory whose Delete was clicked once // Select (RealZeroP27 on X): a box on each memory shown, and a bar that // keeps, archives, restores or deletes the ones picked at once let memPicking = false; const memPicked = new Set(); // ids let memAnchor = null; // the one picked or unpicked last: a Shift-click's range starts there let memSure = false; // the bar's Delete was clicked once let memShown = []; // the memories listed, in their order const MEM_KINDS = ["profile", "preference", "rule", "reference", "fact", "procedure", "episode"]; const kindName = (k) => ({ profile: t("About you"), preference: t("Preference"), rule: t("Rule"), reference: t("Reference"), fact: t("Fact"), procedure: t("How-to"), episode: t("Decision") })[k] || k; function scopeName(s) { if (!s || s === "global") return t("Everywhere"); if (s.startsWith("project:")) { const k = s.slice(8), p = mem?.projects?.[k]; return p?.name || k; } if (s.startsWith("agent:")) return t("Only {agent}", { agent: nameOf(s.slice(6)) }); return s; } async function loadMemory() { if (memLoading) return; memLoading = true; try { [mem, dist, sem] = await Promise.all([api("memory"), api("memory/distill").catch(() => null), api("memory/semantic").catch(() => null)]); } catch (e) { status(e.message, "err"); } memLoading = false; if (tab === "memory" && mem) render(); distWatch(); semWatch(); rankSoon(); } function memDirty() { if (!memOpen || !memDraft) return false; const m = mem?.memories.find((x) => x.id === memOpen); if (!m) return !!memDraft.text.trim(); return memDraft.text !== m.text || memDraft.why !== (m.why || "") || memDraft.tags !== (m.tags || []).join(", ") || memDraft.kind !== m.kind || memDraft.scope !== m.scope; } let memBusy = false; async function memChange(path, body, done) { if (memBusy) return false; memBusy = true; page.setAttribute("aria-busy", "true"); try { const v = await api(path, body); mem = v; if (v.problem) status(v.problem, "err", 10000); else if (done) status(done, "", 4000); return true; } catch (e) { status(e.message, "err", 6000); return false; } finally { memBusy = false; page.removeAttribute("aria-busy"); render(); } } // a picker: the app's menu, never a const evBtn = el("button", "sess-pick lib-menu lib-hookevent"); evBtn.type = "button"; evBtn.setAttribute("aria-haspopup", "menu"); evBtn.setAttribute("aria-expanded", "false"); evBtn.onclick = (e) => { e.stopPropagation(); const opts = HOOK_EVENTS().map(([v, n]) => ({ v, name: n, literalName: true, note: "every agent, in its own name for it", always: true })); // an agent's own events, for it alone for (const a of all) { const ha = hookAgentOf(a.id); if (ha.no) continue; for (const ev of ha.events || []) opts.push({ v: a.id + ":" + ev, name: a.name + " · " + ev, literalName: true, note: t("{agent}'s own event", { agent: a.name }) }); } openProtoMenu(evBtn, opts, d.event, (v) => { d.event = v; if (v.includes(":")) d.agents = [v.split(":")[0]]; // a tool kept from one tool event to the other; nothing else if (v.includes(":") || !(narrowsOf(v) || []).some(([m]) => m === d.matcher)) d.matcher = ""; draw(); }, "When it runs", "", "left", false, "Find an event"); }; ed.append(...field(t("When it runs"), evBtn)); const slot = el("div", "lib-slot"); ed.append(slot); const cmd = field2(d.command, "curl -s https://api.day.app/KEY/done", (v) => { d.command = v; }); cmd.classList.add("mono"); ed.append(...field(t("Command"), cmd, t("Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input"))); const to = field2(d.timeout ? String(d.timeout) : "", t("the agent's own"), (v) => { d.timeout = Math.max(0, parseInt(v, 10) || 0); }); to.inputMode = "numeric"; to.classList.add("lib-hooktimeout"); ed.append(...field(t("Timeout (seconds)"), to)); 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: hookBlocked(d), all: true })); } function draw() { evBtn.replaceChildren(el("span", "", hookEventLabel(d)), svg(CHEV, 11, 1.6)); slot.replaceChildren(); if (d.event.includes(":")) { const m = field2(d.matcher, t("every tool"), (v) => { d.matcher = v.trim(); }); m.classList.add("mono", "lib-hookmatcher"); slot.append(...field(t("Matcher"), m, t("The agent's own matcher, as its hooks file has it; empty for all"))); } else if (narrowsOf(d.event)) { const tools = toolEvent(d.event); const opts = narrowsOf(d.event); const mb = el("button", "sess-pick lib-menu " + (tools ? "lib-hooktool" : "lib-hookstart")); mb.type = "button"; mb.setAttribute("aria-haspopup", "menu"); mb.setAttribute("aria-expanded", "false"); // one written by hand into library.json shows as it is mb.append(el("span", "", opts.find(([v]) => v === d.matcher)?.[1] || d.matcher), svg(CHEV, 11, 1.6)); const title = tools ? "For which tools" : "At which starts"; mb.onclick = (e) => { e.stopPropagation(); // an agent that can't run it at just those greys, saying why, // and is left out when it is saved openProtoMenu(mb, opts.map(([v, n]) => ({ v, name: n, literalName: true, note: "" })), d.matcher, (v) => { d.matcher = v; draw(); }, title); }; slot.append(...field(t(title), mb, t("Each agent's own names for them"))); } drawAgents(); } draw(); const bar = el("div", "bar"); if (h) bar.append(button(t("Remove from the library"), "danger", async () => { if (!await confirmRemoval(h.name, "It will be removed from the library and the agents it was given to.")) return; if (await change("hooks/remove", { name: h.name }, t("{name} is out of the library and the agents it was given to", { name: h.name }))) closeLibModal(true); })); bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal)); const save = async () => { err.textContent = ""; try { const hook = { name: d.name, description: d.description.trim(), event: d.event, matcher: d.matcher, command: d.command, timeout: d.timeout, agents: d.agents.filter((id) => !hookBlocked(d)(agentOf(id) || { id })) }; take(await api("library/hooks/save", { old: h ? h.name : "", hook })); report(lib.result, h ? t("{name} saved", { name: d.name }) : ""); closeLibModal(true); render(); } catch (e) { err.textContent = e.message; } }; bar.append(button(h ? t("Save") : t("Add"), "primary", save)); ed.append(bar); const original = JSON.stringify(d); modal = { save, dirty: () => JSON.stringify(d) !== original }; openLib(ed); if (!h) requestAnimationFrame(() => name.focus()); } function confirmRemoveEveryHook(some) { const hooks = (some || lib.hooks || []).slice(), names = hooks.map((x) => x.name), n = names.length; confirmRemoveEvery("hooks", names, !some ? t("Remove all {n} hooks?", { n }) : n === 1 ? t("Remove {name}?", { name: names[0] }) : t("Remove {n} hooks?", { n }), [ takenFrom(hooks), t("Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file."), ], !!some); } // ---------- subagents ---------- // A subagent (#2283, chuanchinatest) is a helper with a prompt of its // own that an agent hands a task to. It is kept once and written into // each agent picked, as that agent's own file in its own folder and // shape (subagents.go). Its skills and MCP servers go only into the // files that can name them: skills into Claude Code's, servers into // Claude Code's and Droid's. Every other agent gets its prompt alone. // Its model goes only into Codex's role file (luckymanjc on Discord: a // routing group named for a subagent, which ran on its lead's model). const subagentAgentOf = (id) => (lib.subagentAgents || []).find((x) => x.id === id); const subagentAgents = () => shownAgents().filter((a) => subagentAgentOf(a.id)); // why a can't be given a subagent, or "" const subagentBlocked = (a) => { const sa = subagentAgentOf(a.id); if (!sa || sa.no) return sa?.wsl ? t("magpie gives subagents only to agents on this computer, not yet to {agent} in WSL", { agent: a.name }) : t("{agent} reads no subagents magpie can write", { agent: a.name }); return ""; }; // the agents of all that take what s binds, by kind: who can't bind them const unbound = (all, ids, kind) => all.filter((a) => ids.includes(a.id) && !subagentBlocked(a) && !subagentAgentOf(a.id)[kind]); // the name of a model a subagent may run on, its id when it is no longer one const subagentModelName = (id) => (lib.subagentModels || []).find((m) => m.id === id)?.name || id; function subagentLine(s) { const parts = []; if (s.model) parts.push(t("Model: {name}", { name: subagentModelName(s.model) })); if (s.skills?.length) parts.push(t("Skills: {names}", { names: s.skills.join(", ") })); if (s.mcp?.length) parts.push(t("MCP servers: {names}", { names: s.mcp.join(", ") })); return parts.join(" · "); } function renderSubagents(body) { body.append(intro(t("A subagent is a helper with a prompt of its own that an agent hands a task to — a reviewer, a test writer. Add it once and magpie writes it into each agent you pick, as that agent's own subagent file."))); const all = subagentAgents(); const subs = lib.subagents || []; pickingFor("subagents", []); if (!subs.length) { body.append(empty(t("No subagents in the library yet"), t("Add one, and pick the agents that can hand it a task."), button(t("+ Add a subagent"), "action", () => editSubagent(null)))); } else { const list = el("div", "list lib-list"); list.append(...[...subs].sort((a, b) => a.name.localeCompare(b.name)).map((s) => subagentRow(s, all))); body.append(list); const after = el("div", "after-list"); after.append(button(t("+ Add subagent"), "", () => editSubagent(null))); body.append(after); } // what each agent does with what a subagent binds: said only when one // binds something that an agent it is given to can't const given = (kind) => [...new Set(subs.filter((s) => s[kind]?.length).flatMap((s) => unbound(all, s.agents || [], kind)))]; const noSkills = given("skills"), noMCP = given("mcp"); const noModel = [...new Set(subs.filter((s) => s.model).flatMap((s) => unbound(all, s.agents || [], "model")))]; if (noSkills.length) body.append(el("p", "lib-aside lib-subagents-noskills", t("{agents} can't bind skills to a subagent: theirs gets its prompt, and every skill the agent has.", { agents: noSkills.map((a) => a.name).join(", ") }))); if (noMCP.length) body.append(el("p", "lib-aside lib-subagents-nomcp", t("{agents} can't bind MCP servers to a subagent: theirs gets its prompt, and every server the agent has.", { agents: noMCP.map((a) => a.name).join(", ") }))); if (noModel.length) body.append(el("p", "lib-aside lib-subagents-nomodel", t("{agents} can't be given a subagent's model: theirs runs on the model the agent picks.", { agents: noModel.map((a) => a.name).join(", ") }))); // Cursor's app reads ~/.cursor/agents; its cursor-agent CLI reads // only a project's .cursor/agents if (subs.some((s) => s.agents?.includes("cursor"))) body.append(el("p", "lib-aside lib-subagents-cursor", t("The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents."))); const skip = all.filter((a) => subagentAgentOf(a.id).no); if (skip.length) body.append(el("p", "lib-aside lib-subagents-no", t("magpie can't give subagents to {agents} yet: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") }))); } function subagentRow(s, all) { const row = el("div", "row lib-row click lib-subagent"); const who = el("div", "who"); who.append(el("div", "name mono", s.name)); who.append(el("div", "lib-subagentdesc", s.description)); const line = subagentLine(s); if (line) who.append(el("div", "sub lib-subagentuses", line)); row.append(glyph(GLYPH.subagent), who, agentChips(all, s.agents, chipsChange("subagents/agents", s.name, "subagents", (x) => subagentRow(x, all)), { problems: s.problems, blocked: subagentBlocked, all: true })); row.onclick = () => editSubagent(s); row.title = t("Edit {name}", { name: s.name }); return row; } // a menu of names to tick, for a subagent's skills or servers: the app // menu, never a