// magpie — one state object per view, rendered into a list. No framework. const $ = (s) => document.querySelector(s); const $$ = (s) => document.querySelectorAll(s); const params = new URLSearchParams(location.search); const mode = params.get("mode") || "window"; // The panel loads Wails for ExecJS readiness, but stays attached to the tray. // On Linux it is dragged by its header like the window: a Wayland window // can't be put by the icon, so KWin places it, and since it has no KWin // title bar (#1283) the header is the only handle it has (#1430). if (mode === "panel" && !document.body.classList.contains("linux")) $("header.top").style.setProperty("--wails-draggable", "no-drag"); // `magpie web`: the page in a browser tab, with no window of the app's // around it — it opens links itself, and what is the desktop's is left out const web = !!window.bootPrefs?.web; // layout.js applies the mode and platform before the header can paint. // Gateway mode (gatewaymode.go): magpie web on a server that is only the // gateway for other computers' agents leaves out this computer's agents' // pages — Agents, Sessions, Library — and their settings; Settings › // General turns it off, and they are back. let gatewayMode = web && !!window.bootPrefs?.gateway; const GATEWAY_HIDES = ["agents", "library"]; // The window is dragged by its header, and only where the header says so // (--wails-draggable), so the tabs and buttons in it stay plain clicks. // Outside the app — a browser on the gateway's page, or on `magpie web` — // there is no runtime, and it isn't asked for (a 404 in the browser's // console, Jorben on Discord). // The panel also needs runtime readiness to drain Go's queued ExecJS calls. const winRuntime = !web ? import("/wails/runtime.js").catch(() => null) : Promise.resolve(null); // theme.js already applied the theme and text size before the first paint. if (window.bootPrefs) setLocale(window.bootPrefs.lang); let state = { agents: [], profiles: [], catalog: "", settings: {} }; let prefs = null; // the settings page: theme, lang, version, dir, gateway let providers = null; // { providers, presets, gateway } let view = "agents"; let showAllAgents = false; // the agents no one has set anything on, folded away let showHiddenAgents = false; // under them, the ones hidden by hand: a fold of their own, shut until asked let period = "today"; // usage window let usage = null; // last usage summary let usageHidOpen = false; // the Usage page's hidden agents shown under their line let pick = null; // { agent, field, options, items, cursor, anchor } let editing = null; // provider id being edited; { preset } or { custom: true } for a new one let draft = null; // the editor's working copy let naming = null; // the provider whose models' names and levels are open in its editor let adding = false; // the preset sheet is open // the partners counted as shown since the sheet opened: once an opening, // however often it is drawn (countPartner) let partnersCounted = null; let importing = null; // a magpie://import link waiting for a yes: { provider, error, replaces } let importingApps = null; // the Import from other apps dialog: { sources, picks } let providerDiscovery = []; // only opaque fingerprints and app names, never credentials let discoveryAt = 0, discoveryRun = 0, discoveryPending = false; let discoveryIgnored = new Set(); try { discoveryIgnored = new Set(JSON.parse(localStorage.getItem("magpie.discoveryIgnored") || "[]")); } catch {} // the gateway tab's choices, kept per machine let flavor = params.get("flavor") || localStorage.getItem("magpie.flavor") || "openai"; // which API the snippets speak let lang = params.get("lang") || localStorage.getItem("magpie.lang") || "shell"; // which snippet let snipOS = localStorage.getItem("magpie.snipOS") || ""; // the shell the Shell and curl snippets are for (#1514) let exampleModel = localStorage.getItem("magpie.model") || ""; // the model in the snippets let decideModel = localStorage.getItem("magpie.decideModel") || ""; // the System One snippets' decision model let connectFolded = false; // Connect folded away under its heading try { connectFolded = localStorage.getItem("magpie.gwConnectFolded") === "1"; } catch {} const expandedCalls = new Set(); // recent-call ids whose wire bodies are open const callBodies = new Map(); // callRow → its bodies, read when it is opened (#1521) const CALLS_PAGE = 20; let callsShown = CALLS_PAGE; // recent calls drawn a page at a time // a streamed reply's body is read as its reply, its events or as it came; // the pick is one for every call and kept, the events drawn per call let sseView = "events"; try { sseView = localStorage.getItem("magpie.sseView") || "events"; } catch {} const sseShown = new Map(); // call id → how many events are drawn let savedModelFavorites = []; try { savedModelFavorites = JSON.parse(localStorage.getItem("magpie.modelFavorites") || "[]"); } catch {} const modelFavorites = new Set(Array.isArray(savedModelFavorites) ? savedModelFavorites : []); // A model through magpie is starred as its catalog id, which is the same in // every agent; the agent's own models by their value. Stars kept by value // before still count. const favoriteKey = (o) => o.ref || o.value; const isFavorite = (o) => modelFavorites.has(favoriteKey(o)) || modelFavorites.has(o.value); // heads, when given, is shown the answer's headers (loadQuotas' X-Magpie-Reading); // signal, when given, cancels the request (a read the reader moved on from) async function api(path, body, heads, signal) { if (web && path === "open") { window.open(body.url, "_blank", "noopener"); return null; } // a segment may be an agent id, and omp's named profiles are omp#: // left raw, the browser reads #work as the fragment and the request // reaches the default omp row (#1187). Only # is encoded: ? = & stay a // query string, which encodeURIComponent would turn into a 404. path = path.replace(/#/g, "%23"); const res = await fetch("/api/" + path, { method: body === undefined ? "GET" : "POST", headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), signal, }); heads?.(res.headers); if (res.status === 204) return null; // a body that isn't JSON (a proxy's or a plain http.Error) is the error // itself, not WebKit's "did not match the expected pattern" const text = await res.text(); let data; try { data = text ? JSON.parse(text) : null; } catch { throw new Error(text.trim().slice(0, 200) || `${res.status} ${res.statusText}`); } if (!res.ok) { const err = new Error(data?.error || `${res.status} ${res.statusText}`); if (data?.code === "runtime_unavailable") { err.code = data.code; if (data.offline === "stage" || data.offline === "disconnect") err.offline = data.offline; } // magpie has no models to connect an agent to yet: said in the // reader's language if (data?.code === "no_models") err.message = t("Add a provider or subscription in magpie first, then connect {agent}", { agent: data.agent }); if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language // an account the agent is signed in to, refused removal while it has // another: said in the reader's language if (data?.code === "signed_in") { err.code = data.code; err.message = t("{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one", { agent: { codex: "Codex", claude: "Claude Code" }[data.agent] || data.agent, user: data.user }); } // a text Import can't add as a routing group (laincatx on X) if (data?.code === "share") { err.code = data.code; err.message = { newer: t("This group was shared from a newer magpie (format {n}): update magpie to import it", { n: data.format }), no_format: t("This shared group says no format it is in: copy it again with Copy to share"), unreadable: t("This shared group can't be read: copy it again with Copy to share"), none_here: t("None of the group's models is in your magpie: {models}", { models: data.models }), }[data.share] || t("This is not a routing group shared from magpie: copy one with Copy to share in a group's menu"); } // an agent's npm update whose global folder (Program Files) needs an // administrator, or RTK's winget for every user, the prompt declined or // not to be had (新v学员 on Discord): what to do, in the reader's language if (data?.code === "needs_admin") { err.code = data.code; const v = { agent: data.agent, prefix: data.prefix, cmd: data.command, why: data.reason || "" }; const where = data.prefix ? (data.canceled ? t("{agent} is installed in {prefix}, which only an administrator can change, and the administrator prompt was declined.", v) : t("{agent} is installed in {prefix}, which only an administrator can change, and magpie couldn't ask Windows for one ({why}).", v)) : (data.canceled ? t("{agent} needs an administrator here, and the administrator prompt was declined.", v) : t("{agent} needs an administrator here, and magpie couldn't ask Windows for one ({why}).", v)); err.message = where + " " + (data.via === "winget" ? t("Try again and allow it, or run {cmd} in a terminal opened as administrator.", v) : t("Update again and allow it, run {cmd} in a terminal opened as administrator, or move npm's global folder to one of your own (npm config set prefix \"%APPDATA%\\npm\") and install {agent} again.", v)); } throw err; } // the accounts it names, for Hide accounts to know them (#568); a // session's or a library's words aren't looked through if (data && typeof data === "object" && !/^(sessions|library|skills|plugins|market)/.test(path)) noteAccounts(data); return data; } function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; } // replaceKeeping is parent.replaceChildren(...nodes) that leaves a node // already in parent where it is, rather than taking it out and putting it // back. A filter redrawn from its own input event is one: taken out of the // page while an IME commits, it gets the text twice (#1055: 1, 2 → 1122). function replaceKeeping(parent, nodes) { const keep = new Set(nodes); for (const n of [...parent.childNodes]) if (!keep.has(n)) n.remove(); let at = parent.firstChild; for (const n of nodes) { if (n === at) at = at.nextSibling; else parent.insertBefore(n, at); } } function svg(d, size = 12, stroke = 1.6) { const s = document.createElementNS("http://www.w3.org/2000/svg", "svg"); s.setAttribute("viewBox", "0 0 16 16"); s.setAttribute("width", size); s.setAttribute("height", size); s.innerHTML = ``; return s; } const CHEV = "m5.5 6.5 2.5 2.5 2.5-2.5"; // three dots, a row's actions (drawn with a thick round stroke) const DOTS = "M3.5 8h.01M8 8h.01M12.5 8h.01"; const CHEV_R = "m6.5 4.5 3 3.5-3 3.5"; const CHECK = "m3.5 8.5 3 3 6-7"; const CROSS = "M4.5 4.5l7 7M11.5 4.5l-7 7"; const PLUS = "M8 3.5v9M3.5 8h9"; const OUT = "M6.5 3.5h-3v9h9v-3M9 3.5h3.5V7M12.5 3.5 7.5 8.5"; const COPY_ICON = "M5.5 5.5V3.5h7v7h-2M3.5 5.5h7v7h-7z"; const PENCIL = "M3.5 12.5l.5-2.5 6.8-6.8a1.2 1.2 0 0 1 1.7 0l.3.3a1.2 1.2 0 0 1 0 1.7L6 12z M9.8 4.2l2 2"; const PUZZLE = "M6.2 2.8h2.3a1.3 1.3 0 1 1 2.5 0h2.2V5a1.3 1.3 0 1 0 0 2.6v5.6H3V7.6a1.3 1.3 0 1 1 0-2.6V2.8z"; // A brand icon: colour logos are images, mono logos take the text colour. // Nothing is ever invented: a model with no known vendor keeps the slot // empty, and a custom provider shows a plain outline ("generic"). // A page redrawn whole (the Providers page, as a dialog opens or closes) // hands its icons to keptIcons first and the new rows take them back: a // logo made afresh loads its picture again and blinks out for a moment. let keptIcons = null; function keepIcons(...roots) { keptIcons = new Map(); for (const r of roots) for (const e of r.querySelectorAll(".ic[data-icon]")) { if (!keptIcons.has(e.dataset.icon)) keptIcons.set(e.dataset.icon, []); keptIcons.get(e.dataset.icon).push(e); } } // A mono logo is a CSS mask, and a mask is not an : a row drawn again // makes its span afresh, and nothing but the spans on the page keeps the // picture, so between the old row going and the new one painting the // engine may let it go and paint the new one empty until it has loaded it // again: the logo blinks, where an beside it doesn't (#1847). Every // mask picture that has loaded is kept by a span of its own on a hidden // shelf for as long as the page is open, so a logo drawn again paints at // once on any page. Each picture is tried once, not once per logo: a // probe made for every logo asked for the file again on a redraw. const maskLoads = new Map(); let maskShelf = null; function maskSpan(src, failed) { const m = el("span", "mask"); m.style.setProperty("--i", `url(${src})`); let load = maskLoads.get(src); if (!load) { load = new Promise((done) => { const probe = new Image(); probe.onload = () => done(true); probe.onerror = () => done(false); probe.src = src; }); load.then((ok) => { if (!ok) return; if (!maskShelf) { maskShelf = el("div", "mask-shelf"); maskShelf.setAttribute("aria-hidden", "true"); document.body.append(maskShelf); } const k = el("span", "mask"); k.style.setProperty("--i", `url(${src})`); maskShelf.append(k); }); maskLoads.set(src, load); } if (failed) load.then((ok) => ok || failed()); return m; } const pngIcons = new Set(["crush", "zcode", "alma", "hanako", "cindy", "typesafe", "atomcode", "snow", "mlx-serve"]); function icon(name) { const kept = keptIcons?.get(name || "")?.shift(); if (kept) { kept.removeAttribute("title"); return kept; } const e = el("span", "ic"); e.dataset.icon = name || ""; if (name === "generic") { e.classList.add("generic"); e.append(svg("M8 2.2 13.2 5.1v5.8L8 13.8 2.8 10.9V5.1Z M8 8v5.8 M2.8 5.1 8 8l5.2-2.9", 16, 1.4)); return e; } if (name?.startsWith("file:")) { // a picture the user gave their own provider const img = el("img"); img.src = "/api/icons/" + encodeURIComponent(name.slice(5)); img.alt = ""; img.draggable = false; img.onerror = () => e.replaceWith(icon("generic")); e.append(img); return e; } if (name) { if (name.endsWith("-color") || pngIcons.has(name)) { const img = el("img"); img.src = `icons/${name}.${pngIcons.has(name) ? "png" : "svg"}`; img.alt = ""; img.draggable = false; e.append(img); } else { // a mask that fails to load draws nothing, and says nothing e.append(maskSpan(`icons/${name}.svg`, () => { e.classList.add("generic"); e.replaceChildren(...icon("generic").childNodes); })); } return e; } e.classList.add("blank"); return e; } function status(msg, kind = "", ms = kind === "err" ? 8000 : 3500) { const s = $("#status"); s.textContent = msg; s.title = msg; s.className = "status " + kind; s.setAttribute("role", kind === "err" ? "alert" : "status"); // with a dialog open the footer is under its scrim: the pill floats over both const m = $("#modal"); s.classList.toggle("lift", !!msg && !m.hidden && !m.classList.contains("out")); clearTimeout(status.t); if (msg) status.t = setTimeout(() => { s.textContent = ""; s.className = "status"; }, ms); } // ---------- agents view ---------- function optionFor(field, value) { return field.options.find((o) => o.value === value); } // directSaid: a model the agent asks its own vendor for itself, magpie not // in the way (Claude Code on its own sign-in), so its config names no magpie // endpoint — which read as magpie having failed to set it up function directSaid(a, opt) { if (!opt?.direct) return ""; return t("Not through magpie: {agent} asks {vendor} for it directly, with its own sign-in or key, so {path} has no magpie endpoint — that is expected.", { agent: a.name, vendor: opt.direct, path: a.path }); } // Rows in the shape of the list while magpie first reads the agents; a // reload keeps the rows it has until the new ones are in. function renderAgentsLoading() { const page = $("#view-agents"); page.classList.add("loading"); page.setAttribute("aria-busy", "true"); const list = $("#agents"); list.replaceChildren(); for (let i = 0; i < 5; i++) { const row = el("div", "row agent ag-sk-row"); const who = el("div", "who"); who.append(el("span", "skeleton ag-sk-name")); // the panel says what is set in words at the right; the window has two // setting columns const rest = el("div", mode === "panel" ? "ag-sk-sum" : "fields"); if (mode === "panel") rest.append(el("span", "skeleton ag-sk-value"), el("span", "skeleton ag-sk-bars")); else rest.append(el("span", "skeleton ag-sk-field"), el("span", "skeleton ag-sk-field")); row.append(el("span", "skeleton ag-sk-icon"), who, rest); list.append(row); } fit(); // the panel as tall as the rows, not as it was } let agentArranging = false, agentRenderPending = false; function renderAgents() { renderCodexMemories(); // Settings' row is the same field if (agentArranging) { agentRenderPending = true; return; } if (unhideCleared()) return; // it renders again with the hiding dropped const page = $("#view-agents"); page.classList.remove("loading"); page.removeAttribute("aria-busy"); const list = $("#agents"); list.replaceChildren(); agentsLead(list); if (!state.agents.length) { const e = el("div", "empty-state"); e.append(el("b", "", t("No agents found")), el("span", "", t("Install Claude Code, Codex, Gemini CLI, OpenCode… and magpie will list them here."))); list.append(e); } const { shown: used, folded } = arrangeAgents(); if (mode === "panel") $("#ptabN").textContent = state.agents.length || ""; const agentRow = (a, inFold) => { const row = el("div", "row agent"); row.dataset.id = a.id; row.title = a.path; row.oncontextmenu = (ev) => { ev.preventDefault(); openAgentMenu(row.querySelector(".ag-handle"), a, inFold); }; const who = el("div", "who"); who.append(el("div", "name", a.name)); // the model picker takes the wide column, everything else the narrow one, // so the controls line up down the list const fields = el("div", "fields"); const wide = (f) => f.label === "model" || f.label === "large" || f.label === "executor" || f.label === "planner"; // an effort or ultracode the model has none of (Claude Code on Haiku // 4.5, ultracode short of xhigh) isn't drawn at all, nor are subagents // with no model to go on, or a sign-in with no other to take (Claude // Code's, until it runs through magpie where magpie takes any key), or // a small model with none to pick (Snow CLI's, on a profile of the // user's own) // nor Aside's account with one account only (#1499) const none = (f) => (f.key === "effort" || f.key === "ultracode" || f.label === "subagents" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === MEMORIES || f.label === "sign-in" || f.key === "small" || asideAccount(a, f)) && !f.options.length && !f.value; const shownFields = a.fields.filter((f) => !grouped(a, f) && !none(f)); const tiers = tierMenu(a); if (tiers) shownFields.push(tiers); const sorted = shownFields.sort((x, y) => wide(y) - wide(x) || extra(x) - extra(y)); const plain = sorted.filter((f) => !extra(f)).length; // the squares share one cell, side by side: two (Codex's subagents and // sign-in) wrapped the second under the first const extras = el("span", "extras-cell"); const fieldBtn = (f, cls) => { const b = el("button", "field " + cls); const opt = optionFor(f, f.value); b.title = t("{label}: {value}", { label: t(f.label), value: f.value || t("agent default") }) + (opt?.note ? ` · ${opt.note}` : ""); if (f.value && opt?.direct) b.title += "\n" + directSaid(a, opt); const effort = f.key === "effort" || f.label === "effort" || f.label === "thinking" || TIER_EFFORTS.includes(f.label); if (opt?.icon || opt?.icons?.length) b.append(optionIcon(opt)); // a field with no logo of its own still leads with an icon: how much // effort, or the agent's own for its default, as the picker shows it else if (effort) b.append(effortIcon(f)); else if (!f.value && !f.menu && a.icon) b.append(icon(a.icon)); else if (!wide(f) || !f.value) b.append(el("span", "k", t(f.label))); if ((f.label === "executor" || f.label === "planner") && !b.querySelector(".k")) b.append(el("span", "k", t(f.label))); const shown = f.menu ? f.summary : effort ? effortName(opt || { value: f.value }) : (opt?.label || f.value || t(FOLLOWS_MODEL.includes(f.label) ? "same as model" : "default")); if (f.menu) b.title = f.options.map((o) => `${o.label}: ${o.note}`).join("\n"); b.append(el("span", "v" + (f.value || f.custom ? "" : " empty"), shown)); if (f.value && opt?.fast) b.append(fastTag()); const c = el("span", "chev"); c.append(svg(CHEV, 11, 1.7)); b.append(c); b.dataset.key = f.key; const fieldState = a.native?.fields?.[f.key]; if (fieldState?.detail) b.title += "\n" + t(fieldState.detail); if (fieldState?.status === "unavailable") b.classList.add("drifted"); b.onclick = (ev) => openPicker(a, f, b, ev); return b; }; for (const f of sorted) { if (extra(f)) { extras.append(extraField(a, f)); continue; } fields.append(fieldBtn(f, plain === 1 ? "solo" : wide(f) ? "main" : "side")); } // an agent that takes the gateway only from its environment (agy): a // square that copies the command starting it on magpie // one with nothing else to set (Cursor Private Inference) has the // command as its one control, in words const launchOnly = !!a.launch && !a.fields.length && !a.import; if (a.launch && !launchOnly) extras.append(launchButton(a)); if (extras.childNodes.length) fields.append(extras); // an app that takes magpie by a link of its own (Cindy) has nothing to // pick: its row opens the link, and the app asks to add magpie if (a.import && mode !== "panel") fields.append(importButton(a)); if (launchOnly && mode !== "panel") fields.append(launchSolo(a)); // the panel shows what's set as words, and a row's controls only // once it's opened: one row at a time, in place let sum = null, openBox = null; const effortOf = (f) => f.key === "effort" || f.label === "effort" || f.label === "thinking"; if (mode === "panel" && (a.import || launchOnly)) { // in words like the rest, the row itself the link (or the command) const act = a.import ? importButton(a) : launchSolo(a); sum = el("span", "ag-sum"); sum.append(a.import ? el("span", "v" + (a.added ? "" : " empty"), a.added ? "magpie" : t("Add magpie")) : el("span", "v empty", t("Copy launch command")), el("span")); const c = el("span", "chev"); c.append(a.import ? svg(OUT, 10, 1.6) : svg(LAUNCH_GLYPH, 10, 1.5)); sum.append(c); row.title = act.title; row.onclick = (ev) => { if (ev.target.closest(".ag-handle, .ag-fix, .ag-show")) return; act.click(); }; } else if (mode === "panel") { sum = el("span", "ag-sum"); const main = sorted.find((f) => !extra(f) && !f.menu && !effortOf(f)); const opt = main && optionFor(main, main.value); // the model in words, its logo coming in beside them on hover const v = el("span", "v" + (main?.value ? "" : " empty")); if (main?.value && (opt?.icon || opt?.icons?.length)) { const mi = el("span", "mi"); mi.setAttribute("aria-hidden", "true"); mi.append(el("span", "mi-in")); mi.firstChild.append(optionIcon(opt)); // its width to open to, read as the pointer comes onto the row: // before :hover is styled, so the box eases open from nothing row.addEventListener("pointerenter", () => { if (!mi.style.getPropertyValue("--w")) mi.style.setProperty("--w", mi.firstChild.offsetWidth + "px"); }); v.append(mi); } v.append(el("span", "vt", menuFromList(a) ? menuSaid(a.models) : main ? (opt?.label || main.value || t("default")) : "")); sum.append(v); // how much effort as three bars, in a column of its own down the list: // none lit for the default, off, none or auto, or for an agent that has // no such setting const ef = a.fields.find(effortOf); sum.append(effortBars(ef)); const c = el("span", "chev"); c.append(svg(CHEV, 10, 1.6)); sum.append(c); // opened: each setting on a line of its own, named, and the effort as // its levels side by side // .ag-in clips while the row opens or closes, .ag-body holds the lines openBox = el("div", "ag-open"); const body = el("div", "ag-body"); openBox.append(el("div", "ag-in")); openBox.firstChild.append(body); for (const b of [...fields.querySelectorAll(":scope > .field")]) { const f = sorted.find((x) => x.key === b.dataset.key) || (b.dataset.key === "tiers" ? tiers : null); if (f && effortOf(f)) { body.append(effortSeg(a, f)); continue; } if (f && !b.querySelector(":scope > .k")) b.prepend(el("span", "k", t(f.label))); body.append(b); } // Claude Desktop's: which models its own menu lists, under its // provider if (menuFromList(a)) { const m = menuButton(a, "main"); m.prepend(el("span", "k", t("Models"))); body.append(m); } if (extras.childNodes.length) body.append(extras); row.classList.toggle("open", panelOpenAgent === a.id); row.setAttribute("aria-expanded", String(panelOpenAgent === a.id)); row.onclick = (ev) => { if (ev.target.closest(".ag-open, .ag-handle, .ag-fix, .ag-show")) return; const open = panelOpenAgent !== a.id; panelOpenAgent = open ? a.id : null; // the rows ease open and shut, and the panel's edge moves with them: // it goes now to where they will be, over the same time and curve let grow = open ? openBox.querySelector(".ag-body").offsetHeight : 0; for (const r of $("#agents").querySelectorAll(".row.agent.open")) { grow -= r.querySelector(".ag-in")?.offsetHeight || 0; r.classList.remove("open"); r.setAttribute("aria-expanded", "false"); } row.classList.toggle("open", open); row.setAttribute("aria-expanded", String(open)); fit(grow, open ? ROW_OPEN : ROW_CLOSE); const settle = (ev) => { if (ev.target !== openBox || ev.propertyName !== "grid-template-rows") return; openBox.removeEventListener("transitionend", settle); fit(); }; openBox.addEventListener("transitionend", settle); }; } // one hidden by hand gives its way back in words, rather than being a // greyed row whose way back is its menu. One nothing is set on isn't // hidden: setting something on it brings it up the list. if (inFold && isHidden(a)) { row.classList.add("put-away"); const back = el("button", "ag-show"); back.type = "button"; back.title = t("Hidden by you · show it in the list again"); back.append(svg(EYE, 12, 1.5), el("span", "", t("Show"))); back.onclick = (e) => { e.stopPropagation(); setAgentHidden(a, false); }; who.append(back); } // on the name's own line, so the row keeps its height and the pickers // their columns // a row with 「接入」 says it on its line under the name instead const kind = mode !== "panel" ? connectKind(a) : ""; if (a.drift) { row.classList.add("drifted"); if (!kind) who.append(driftFix(a)); } // the CLI's version, and an update when one is out (#202); the panel's // name column has no room for it if (mode !== "panel") who.append(cliTag(a)); // which of magpie's models its lists show, on a line under the name if (mode !== "panel" && a.models && !kind) { const line = el("div", "ag-models-line"); line.append(modelsEntry(a)); who.append(line); who.classList.add("with-models"); } // connected to magpie or not, said under the name, with where the agent // picks among magpie's models itself const sw = connectable(a) ? connectSwitch(a) : null; if (kind) { // Claude Code's tiers and subagents have rows of their own when opened if (a.id === "claude") { for (const f of a.fields.filter((f) => TIERS.includes(f.label) || f.label === "subagents")) extras.querySelector(`[data-key="${CSS.escape(f.key)}"]`)?.remove(); extras.querySelector('[data-key="tiers"]')?.remove(); } row.append(agentHandle(a, row, inFold), who); connectRow(a, row, who, { fields, extras, fieldBtn, sw, kind }); return row; } if (sw && openBox) { const line = el("div", "ag-conn-row"); line.append(el("span", "k", t("magpie")), el("span", "ag-conn-said", connectSaid(a)), sw); openBox.querySelector(".ag-body").prepend(line); } row.append(agentHandle(a, row, inFold), who); if (sum) row.append(sum, ...(openBox ? [openBox] : [])); else row.append(fields, ...(sw ? [sw] : [])); return row; }; // the extras column is there for every row once any agent has one, so the // pickers keep lining up down the list list.classList.toggle("extras", state.agents.some((a) => a.fields.some(extra) || tierMenu(a) || a.launch)); // as wide as the row with the most squares list.style.setProperty("--extras", Math.max(1, ...state.agents.map((a) => a.fields.filter((f) => extra(f) && !grouped(a, f)).length + (tierMenu(a) ? 1 : 0) + (a.launch ? 1 : 0)))); if (!folded.length) { for (const a of used) list.append(agentRow(a)); } else { // the ones in use stay put; the rest unroll beneath them like a scroll for (const a of used) list.append(agentRow(a)); const fold = el("div", "agent-fold" + (showAllAgents ? " open" : "")); const inner = el("div", "agent-fold-inner"); inner.inert = !showAllAgents; fold.style.setProperty("--n", folded.length); // the ones nothing is set on, then, last and least, the ones hidden by // hand (0xZaTe on Discord: listed first, right under the agents in use, // hidden read as pinned, 反而更显眼了). Under the others the hidden ones // are a disclosure of their own, shut until it is opened, as a Finder // sidebar section is; with nothing else folded, the fold is theirs. const byHand = folded.filter(isHidden), unset = folded.filter((a) => !isHidden(a)); if (!byHand.length) showHiddenAgents = false; let i = 0; const rows = (group, into) => { for (const a of group) { const row = agentRow(a, true); row.style.setProperty("--i", i++); into.append(row); } }; const cap = (text) => { const c = el("div", "agent-fold-cap", text); c.style.setProperty("--i", i); inner.append(c); }; if (unset.length) { cap(t("Not set up")); rows(unset, inner); } if (byHand.length && !unset.length) { cap(t("Hidden")); rows(byHand, inner); } else if (byHand.length) { const line = el("button", "agent-fold-cap agent-hid-line"); line.type = "button"; line.style.setProperty("--i", i); line.title = t("Hidden by you · click to see them"); const hc = el("span", "chev"); hc.append(svg(CHEV, 9, 1.8)); line.append(el("span", "", t("Hidden ({n})", { n: byHand.length })), hc); const hf = el("div", "agent-hid-fold" + (showHiddenAgents ? " open" : "")); const hi = el("div", "agent-hid-inner"); hi.inert = !showHiddenAgents; hf.id = "agentsHidden"; line.setAttribute("aria-controls", hf.id); line.setAttribute("aria-expanded", String(showHiddenAgents)); rows(byHand, hi); hf.append(hi); hf.addEventListener("transitionend", (e) => { if (e.target === hf) fit(); }); line.onclick = (e) => { showHiddenAgents = !showHiddenAgents; const room = hi.scrollHeight; fit(showHiddenAgents ? room : -room, showHiddenAgents ? UNROLL : ROLLUP); hf.classList.toggle("open", showHiddenAgents); hi.inert = !showHiddenAgents; line.setAttribute("aria-expanded", String(showHiddenAgents)); if (showHiddenAgents) unrollInView(hf, line, e); }; inner.append(line, hf); } fold.append(inner); const more = el("button", "agent-more"); more.dataset.unrolls = ""; // it goes down with the rows it opens const label = el("span", "", ""); const chev = el("span", "chev"); chev.append(svg(CHEV, 10, 1.8)); more.append(label, chev); const labelFor = () => { // what is folded, and how many of them were hidden by hand label.textContent = showAllAgents ? t("Show less") : !unset.length ? t("{n} hidden agents", { n: byHand.length }) : t("Show {n} more", { n: unset.length }); more.setAttribute("aria-expanded", String(showAllAgents)); }; labelFor(); // settled: the soft edge goes, and a folded scroll gives the panel its room // back. A hidden window never ends its transition, so a timer backs it up. let settle; const settled = () => { clearTimeout(settle); fold.classList.remove("moving"); fit(); }; fold.addEventListener("transitionend", (e) => { if (e.target === fold) settled(); }); more.onclick = (e) => { showAllAgents = !showAllAgents; // a fold of hidden ones only is the hidden ones' disclosure: Show on // one of them leaves the rest open under their own line if (!unset.length) showHiddenAgents = showAllAgents; // the panel's edge moves with the scroll, on the same beat and curve const room = inner.scrollHeight; fit(showAllAgents ? room : -room, showAllAgents ? UNROLL : ROLLUP); clearTimeout(settle); settle = setTimeout(settled, 900); fold.classList.add("moving"); fold.classList.toggle("open", showAllAgents); inner.inert = !showAllAgents; labelFor(); if (!matchMedia("(prefers-reduced-motion: reduce)").matches) { label.animate([{ opacity: 0, transform: "translateY(3px)" }, { opacity: 1, transform: "none" }], { duration: 260, easing: "cubic-bezier(.22, 1, .36, 1)" }); } if (showAllAgents) unrollInView(fold, more, e); }; // the button, then what it unrolls: the rest come in under it, and the // rows above stay where they are (the scroll unrolling above the button // pushed it off the foot of a panel at its tallest, or, held there, drew // the whole list up past it) list.append(more, fold); } agentsManageButton(list); confirmAsk?.refreshAgents?.(); paintUpdateAll(); paintInstalls(); renderProfiles(); fit(0, agentsGlide); agentsGlide = null; } // renderProfiles draws the saved profiles as chips, a chip whose save, // update or use is on its way dimmed until the answer is in. A click on a // chip shows what the profile holds, and its Apply applies it (#467): it was // applied at once, so what it held could be seen only by applying it over // the setup in use. function renderProfiles() { const chips = $("#profiles"); if (!state.profiles.some((p) => p.name === profileOpen)) profileOpen = null; chips.replaceChildren(); $(".profiles > .chip-input")?.remove(); // a name field open goes with the list it was for $(".profiles").classList.remove("naming", "detailed"); $("#save").textContent = t("+ Save current"); // the panel's button names the profile in use, as a pop-up button shows // what is picked, else how many there are (superhtoooth on X: it read // 方案 1, 方案 2, a count taken for the name the profile was saved under, // and nothing said which one was in use) const cur = state.profiles.find((p) => p.inUse); const n = $("#profN"); n.textContent = cur ? cur.name : state.profiles.length || ""; n.classList.toggle("cur", !!cur); n.title = cur ? t("In use") : ""; if (!state.profiles.length) chips.append(el("span", "hint", t("none yet · save the setup to switch back in one click"))); for (const p of state.profiles) { const c = el("button", "chip"); c._profile = p.name; if (profilePending.has(p.name)) c.classList.add("pending"); const lib = profileLibrary(p.library); c.title = [p.inUse && t("In use"), p.summary, lib].filter(Boolean).join("\n"); // the one the setup is now, ticked as a menu ticks the item in effect if (p.inUse) { c.classList.add("cur"); c.setAttribute("aria-current", "true"); c.append(el("span", "cur-tick", "✓")); } c.append(el("span", "", p.name)); if (lib) c.append(el("span", "lib")); // the setup as it is now, saved over this profile; it, and ×, on a // second click (#478) const u = el("span", "x"); u._arm = "save"; u.onclick = (ev) => { ev.stopPropagation(); armOrDo(p.name, "save"); }; const x = el("span", "x"); x._arm = "delete"; x.onclick = (ev) => { ev.stopPropagation(); armOrDo(p.name, "delete"); }; c.append(u, x); paintArm(c); c.setAttribute("aria-expanded", "false"); c.onclick = () => toggleProfile(c, p); chips.append(c); } const open = state.profiles.find((p) => p.name === profileOpen); if (open) showProfile([...chips.children].find((c) => c._profile === open.name), open); } // profileArm is a chip's ↻ or × clicked once: it then reads "Overwrite?" // or "Delete?", and a second click does it (#478: either acted on the first // click, so a slip overwrote or deleted a profile). It goes after a few // seconds, on Escape, or when the other one is clicked. let profileArm = null; const ARM = { save: { glyph: "↻", title: "Update to the current setup", armed: "Overwrite?", armedTitle: "Click again to update {name} to the current setup" }, delete: { glyph: "×", title: "Delete profile", armed: "Delete?", armedTitle: "Click again to delete {name}" }, }; function armOrDo(name, action) { if (profileArm?.name === name && profileArm.action === action) { disarmProfile(); profileAction(action, name, action === "save"); return; } clearTimeout(profileArm?.timer); profileArm = { name, action, timer: setTimeout(disarmProfile, 3500) }; for (const c of $("#profiles").children) paintArm(c); } function disarmProfile() { if (!profileArm) return false; clearTimeout(profileArm.timer); profileArm = null; for (const c of $("#profiles").children) paintArm(c); return true; } // paintArm draws a chip's ↻ and × as profileArm has them. function paintArm(c) { for (const s of c.querySelectorAll?.(":scope > .x") || []) { const a = ARM[s._arm], on = profileArm?.name === c._profile && profileArm.action === s._arm; s.classList.toggle("arm", on); s.textContent = on ? t(a.armed) : a.glyph; s.title = on ? t(a.armedTitle, { name: c._profile }) : t(a.title); } } // profileOpen is the profile whose details are shown, by name. However they // close — a second click on the chip, their ×, Escape, Apply, the panel's // list closed — they stay closed, the list opening again on the chips alone // (#478: closed by hand they came back with the list). let profileOpen = null; function toggleProfile(chip, p) { if (profileOpen === p.name) closeProfileDetail(); else { profileOpen = p.name; showProfile(chip, p); fit(); } } // closeProfileDetail closes the details shown, if any: false if none were. // Details on the page close whether or not profileOpen still names them. function closeProfileDetail() { if (!profileOpen && !$("#profiles > .prof-detail")) return false; profileOpen = null; $("#profiles > .prof-detail")?.remove(); $(".profiles").classList.remove("detailed"); for (const c of $("#profiles").querySelectorAll(".chip.on")) { c.classList.remove("on"); c.setAttribute("aria-expanded", "false"); } fit(); return true; } // profileEscape is Escape for the profiles: it takes back a ↻ or × waiting // for its second click, else closes the details, else the panel's list — // one at a time, and never the tray panel with them (#478: Escape on the // details hid the whole panel). False if there was nothing to close. function profileEscape() { if (disarmProfile()) return true; const chip = $("#profiles .chip.on"); if (closeProfileDetail()) { chip?.focus({ preventScroll: true }); return true; } if (mode === "panel" && profBox.classList.contains("open")) { closeProfiles(); profBtn.focus({ preventScroll: true }); return true; } return false; } // showProfile draws what a profile holds, by agent, under its chip's line; // in the panel, where the list opens upward from its foot, over it, its // Apply at its foot by the chip, so the chip clicked stays where it is as the // details come in. function showProfile(chip, p) { const chips = $("#profiles"), box = $(".profiles"); chips.querySelector(":scope > .prof-detail")?.remove(); box.classList.remove("detailed"); for (const c of chips.querySelectorAll(".chip.on")) { c.classList.remove("on"); c.setAttribute("aria-expanded", "false"); } if (!chip) return; chip.classList.add("on"); chip.setAttribute("aria-expanded", "true"); const panel = mode === "panel"; const was = chip.getBoundingClientRect().top; const line = [...chips.querySelectorAll(":scope > .chip")].filter((c) => c.offsetTop === chip.offsetTop); const d = profileDetail(p, panel); box.classList.add("detailed"); // the window's label and Save at the chips' first line if (panel) line[0].before(d); else line[line.length - 1].after(d); // grown past its height, the panel's list scrolls the details in above // the chip rather than the chip down if (panel) box.scrollTop += chip.getBoundingClientRect().top - was; } function profileDetail(p, footed) { const d = el("div", "prof-detail"); d.setAttribute("role", "group"); d.setAttribute("aria-label", p.name); const head = el("div", "pd-head"); const apply = el("button", "text primary pd-apply", t("Apply")); apply.type = "button"; apply.title = t("Apply {name} to the agents", { name: p.name }); apply.onclick = () => profileAction("use", p.name); const close = el("button", "pd-close", "×"); close.type = "button"; close.title = t("Close"); close.setAttribute("aria-label", t("Close")); close.onclick = () => { const chip = $("#profiles .chip.on"); closeProfileDetail(); chip?.focus({ preventScroll: true }); }; head.append(el("span", "pd-name", p.name)); if (p.inUse) head.append(el("span", "pd-cur", t("In use"))); head.append(apply, close); if (!footed) d.append(head); const groups = p.agents || []; if (!groups.length) d.append(el("div", "pd-none", t("No agent settings saved"))); for (const g of groups) { const sec = el("div", "pd-agent"); const gh = el("div", "pd-gh"); gh.append(icon(g.icon || "generic"), el("span", "pd-gn", g.name)); const rows = el("dl", "pd-fields"); const row = (label, value, cls) => { const v = el("dd", cls || "", value); v.title = value; rows.append(el("dt", "", label), v); }; for (const f of g.fields || []) { const effort = f.key === "effort" || f.label === "effort" || f.label === "thinking"; // a Claude Code tier left to follow the main model (#480), and to what const main = f.follows && g.fields.find((x) => x.key === f.follows && !x.hidden)?.value; if (f.hidden) row(t(f.label), "••••••", "pd-hidden"); else if (f.follows) row(t(f.label), main ? t("follows the main model ({model})", { model: main }) : t("follows the main model"), "pd-default"); else if (!f.value) row(t(f.label), t("agent default"), "pd-default"); else row(t(f.label), effort ? effortName({ value: f.value }) : f.value); } // the models its list shows, which applying it switches to (#1368) const m = g.models; if (m) row(t("Model list"), m.only ? t("only the {n} picked", { n: m.picked }) : m.hidden ? t("{n} hidden", { n: m.hidden }) : t("every model shown"), m.only || m.hidden ? "" : "pd-default"); if (g.servers?.length) row(t("MCP servers"), g.servers.join(t(", "))); if (g.skills?.length) row(t("Skills"), g.skills.join(t(", "))); if (g.instructions) row(t("Instructions"), t("on")); sec.append(gh, rows); d.append(sec); } if (groups.some((g) => g.fields?.some((f) => f.hidden))) d.append(el("div", "pd-none", t("•••••• looks like a key or a token, and is not shown"))); if (footed) { head.classList.add("pd-foot"); d.append(head); } return d; } // driftNote: under the name of an agent whose config something else // rewrote since magpie set it — the row still shows a magpie model while the // agent no longer reaches magpie, or it was put back on a model of its own — // what happened, and the one click that sets it again. // driftFix is the one thing a drifted agent shows: an amber pill after its // name that sets magpie's settings again. What is off is its tooltip; taking // the config as it is now is in the row's menu. // An agent whose config is right but whose address doesn't answer (#1013) // has nothing to set again: its pill says what has to listen there, unless // WSL now reaches Windows at another address, which it moves the config to. // Likewise one whose requests for magpie go through a proxy that doesn't // pass them on (proxied: Codex, Muma102kMichael on X). function driftFix(a, label = "Apply again") { const d = a.drift, f = a.fields.find((x) => x.key === d.field); const want = (f && optionFor(f, d.want)?.label) || d.want; const fix = el("button", "ag-fix"); fix.type = "button"; fix.title = `${t(DRIFT_WHY[d.kind] || DRIFT_WHY.unwired, { agent: a.name, model: want })}\n${d.detail}`; const deaf = d.kind === "unreachable" || d.kind === "proxied"; if (deaf && d.move) label = t("Use {url}", { url: d.move.replace(/^https?:\/\//, "") }); else if (deaf) label = "How to fix"; fix.setAttribute("aria-label", t(label)); fix.append(svg(deaf && !d.move ? INFO_I : REAPPLY, 11, 1.8), el("span", "", t(label))); fix.onclick = (e) => { e.stopPropagation(); if (deaf && !d.move) explainDrift(a); else reapplyAgent(a, fix); }; return fix; } // explainDrift: what has to listen at an address an agent can't reach // magpie by, or let it through a proxy — too long for the status line, so a // dialog of its own. Until it is fixed, Disconnect puts the agent's config // back as it was, one click away. function explainDrift(a) { const ed = el("div", "editor"); const head = el("div", "ehead"); head.append(el("b", "", t(DRIFT_WHY[a.drift.kind] || DRIFT_WHY.unreachable, { agent: a.name }))); ed.append(head); ed.append(el("p", "lib-confirm drift-why", a.drift.detail)); const bar = el("div", "bar"); const ok = el("button", "text primary", t("OK")); ok.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; bar.append(el("span", "grow")); if (a.wired) { const off = el("button", "text drift-off", t("Disconnect from magpie")); off.title = t(DISCONNECT_TIP, { agent: a.name }); off.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); askDisconnect(a); }; bar.append(off); } bar.append(ok); ed.append(bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); ok.focus({ preventScroll: true }); } const DRIFT_WHY = { unwired: "{agent} no longer goes through magpie — its config was changed", replaced: "{agent} was switched off {model} outside magpie", bypassed: "{agent} was used without going through magpie — restart it after applying", unreachable: "{agent} is set up, but nothing answers at the address it reaches magpie by", proxied: "{agent} reaches magpie through a proxy that doesn't pass its requests on", }; // an i in a circle: the pill that explains rather than acts const INFO_I = "M8 14.5a6.5 6.5 0 1 0 0-13 6.5 6.5 0 0 0 0 13zM8 7.25V11M8 5v.01"; const REAPPLY = "M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3.25h-3.25"; // An unplugged plug: the agent taken off magpie. const UNPLUG = "M6 2v3M10 2v3M4.5 5h7v2.5a3.5 3.5 0 0 1-7 0zM8 11v3M2 2l12 12"; const DISCONNECT_TIP = "Take out everything magpie wrote into {agent}'s config and put back what it had before"; // An agent is connected to magpie with a switch (the owner: the Agents page // connects an agent, and its models are picked in the agent): on, magpie is // its provider and its own model list has magpie's models (agent.Connect); // off, magpie takes out what it wrote (askDisconnect). An agent with none of // magpie's models to offer (Cursor, Copilot) has no switch. // the field magpie is picked in: the first, or Gemini CLI's model, its // first being how it signs in const connectField = (a) => a.fields.find((f) => f.options.some((o) => o.ref)) || a.fields.find((f) => f.options.some((o) => o.value === "magpie")); // connectable: magpie has models for it — in its pickers, or every one // hidden from its lists, which leave its pickers but not the way back (#356) function connectable(a) { return !a.import && (!!connectField(a) || !!a.models?.listed); } // PICKS_IN is where an agent picks a model itself, for the words under it. const PICKS_IN = { codex: "/model", claude: "/model", opencode: "/models", pi: "/model", droid: "/model", kimi: "/model", grok: "/model", "minimax-code": "/model", dsh: "/model", crush: "ctrl+p", omp: "/model", qwen: "/model", mimocode: "/model", deveco: "/models" }; function connectSaid(a) { if (!a.wired) return t("Not connected · {agent} uses its own settings", { agent: a.name }); if (menuFromList(a)) return t("Connected · {n} models in {agent}'s model menu", { n: a.models.shown, agent: a.name }); const at = PICKS_IN[a.id]; return at ? t("Connected · pick magpie's models with {cmd} in {agent}", { cmd: at, agent: a.name }) : t("Connected · magpie's models are in {agent}'s model list", { agent: a.name }); } // connectedSaid: what the switch connected an agent on, and why (#726: // switched on, Codex kept its last pick, Claude Code started on a Sonnet // through magpie and Antigravity on some model, with nothing to say why). // c is agent.Connection: how the model was chosen. const CONNECTED_HOW = { again: "{agent} is connected to magpie · back on {model}, what it was on when it was switched off", same: "{agent} is connected to magpie · on {model} through magpie, the model it was on", alike: "{agent} is connected to magpie · on {model} through magpie, the model it was on", default: "{agent} is connected to magpie · on {model} through magpie: it had no model set, so the first of its own", first: "{agent} is connected to magpie · on {model} through magpie: magpie doesn't serve the model it was on", }; function connectedSaid(a, c) { const plain = t("{agent} is connected to magpie", { agent: a.name }); if (a.native && c?.how === "joined") return t("{agent} is connected to magpie", { agent: a.name }); if (c?.how === "joined") return t("{agent} is connected to magpie · it stays on its own last pick; magpie's models join its {cmd}", { agent: a.name, cmd: PICKS_IN[a.id] || "/model" }); const now = state.agents.find((x) => x.id === a.id); const f = now && startField(now); const model = f?.value ? optionFor(f, f.value)?.label || f.value : ""; return CONNECTED_HOW[c?.how] && model ? t(CONNECTED_HOW[c.how], { agent: a.name, model }) : plain; } function connectSwitch(a) { const s = el("button", "lib-switch ag-conn" + (a.wired ? " on" : "")); s.type = "button"; s.setAttribute("role", "switch"); s.setAttribute("aria-checked", a.wired ? "true" : "false"); s.setAttribute("aria-label", t("Connect {agent} to magpie", { agent: a.name })); s.title = a.wired ? t("Connected · switch off to put back what {agent} had before magpie", { agent: a.name }) : t("Switch on and {agent}'s model list gets magpie's models", { agent: a.name }); s.append(el("i")); s.onclick = async (e) => { e.stopPropagation(); if (a.wired) { askDisconnect(a); return; } if (s.disabled) return; s.disabled = true; s.classList.add("on"); try { state = await api("agents/connect/" + a.id, {}); renderAgents(); const msg = connectedSaid(a, state.connected); if (state.notice) status(withNotice(msg, state.notice), "warn", 9000); else if (msg !== t("{agent} is connected to magpie", { agent: a.name })) status(msg, "ok", 7000); else status(msg, "ok"); } catch (err) { s.disabled = false; s.classList.remove("on"); status(t(err.message), "err"); } }; return s; } // ---------- 「接入」 in the window (the owner's design boards) ---------- // A row there answers one thing: does the agent go through magpie. Its // switch stands where the model and effort pickers stood, a line under the // name says what it runs on and where it picks a model, and a connected // one opens to what else there is: when it takes effect, which models it // lists, what a new session starts on, the files magpie changed, and the // way back. // agents with no way onto magpie: no switch, the reason instead const NATIVE_ONLY = { cursor: "Only Cursor's own models", copilot: "Only GitHub Copilot's own models", goose: "Only Goose's own providers", devin: "Only Devin's own models", }; // agents that pick no model once started: the one they start on stays in // the row const NO_PICKER = new Set(["gemini", "hermes", "morph", "agy", "muse"]); // agents whose own model menu is the list picked here: no one model to // start on, but which of magpie's it offers (Claude Desktop and Cursor // Private Inference read /v1/models, and the user switches among them in it) const MENU_FROM_LIST = new Set(["claude-desktop", "cursor-local"]); // or the server says so (agent.ListsModels): ZCode, Pencil, T3 Code, // WorkBuddy's and Copilot in JetBrains put magpie's models in their own // picker (#1508) const listsMenu = (a) => MENU_FROM_LIST.has(a.id) || !!a.menu; const menuFromList = (a) => listsMenu(a) && a.wired && !!a.models; // menuSaid: the models such an agent lists, by name while they are few function menuSaid(c) { if (!c.shown) return t("No models"); const names = c.names || []; if (!names.length) return t("{n} models", { n: c.shown }); return names.slice(0, 2).join(", ") + (c.shown > 2 ? " +" + (c.shown - 2) : ""); } // menuButton: where the model picker stands in another agent's row, the // models its own menu lists, several picked at once (openAgentModels) function menuButton(a, cls = "ag-start") { const b = el("button", "field ag-menu " + cls); b.type = "button"; b.dataset.key = "models"; fillMenuButton(b, a); b.onclick = (ev) => openAgentModels(a, b, ev); holdAgentModels(a, b); return b; } function fillMenuButton(b, a) { const c = a.models; const k = b.querySelector(":scope > .k"); b.replaceChildren(...(k ? [k] : [])); b.append(icon("magpie")); b.append(el("span", "v" + (c.shown ? "" : " empty"), menuSaid(c))); const ch = el("span", "chev"); ch.append(svg(CHEV, 11, 1.7)); b.append(ch); const pick = t("Pick which models {agent} lists", { agent: a.name }); b.title = pick + "\n" + t("{agent} reads its model list as it starts: quit and reopen it after a change", { agent: a.name }); b.setAttribute("aria-label", pick + ": " + menuSaid(c)); } // what turning one on costs, said in its opened row const CONNECT_COST = { gemini: "Gemini CLI's requests all go through magpie; its Google sign-in is turned off first and comes back when you disconnect", }; // agents that read magpie's list only as they start: copies already // running keep the list they started with (agent.Stale) const STARTS_WITH = new Set(["codex", "claude"]); let agentExpanded = null; // the connected agent opened in the window const staleSeen = {}; // agent id → the running copies the reader was told of const previews = {}; // agent id → its disconnect preview, as last read const anyMagpieModels = () => state.agents.some((a) => connectField(a)?.options.some((o) => o.ref)); // connectKind: "ok" (a switch), "empty" (a switch for when magpie has // models), "no" (never), "link" (an app magpie is added to by a link of its // own: Cindy), "" (the row as it was) function connectKind(a) { if (a.import) return "link"; if (connectable(a)) return "ok"; if (NATIVE_ONLY[a.id]) return "no"; if (a.fields.length && !anyMagpieModels()) return "empty"; return ""; } // the models it lists the reader hasn't seen yet: counted once, said in // bold for a while, then counted as seen const SEEN_KEY = "magpie.agentModelsSeen"; let seenTimer = null; function newModels(a) { if (!a.wired || !a.models) return 0; let seen = {}; try { seen = JSON.parse(localStorage.getItem(SEEN_KEY) || "{}") || {}; } catch { /* none kept */ } const was = seen[a.id], now = a.models.shown; const keep = () => { try { seen[a.id] = now; localStorage.setItem(SEEN_KEY, JSON.stringify(seen)); } catch { /* not kept */ } }; if (was === undefined || now <= was) { if (was !== now) keep(); return 0; } clearTimeout(seenTimer); seenTimer = setTimeout(() => { keep(); renderAgents(); }, 12000); return now - was; } const staleNow = (a) => a.wired && a.stale > 0 && staleSeen[a.id] !== a.stale; // a running copy left on the old list (agent.StaleCopy's kind): what it // is, since when, and how it is reopened — the words, and the command or // key in them as code const STALE_HOW = { app: ["The {agent} app, started {when}: closing its window keeps it running. Quit it with {cmd} and open it again.", "⌘Q"], ide: ["{agent} in an editor (VS Code, Cursor…), started {when}: reload that editor's window."], daemon: ["{agent}'s background app-server, started {when}: restart it with {cmd}.", "codex app-server daemon restart"], // another app's own Codex (Agents Anywhere's), named by that app embedded: ["{app}'s own {agent}, started {when}: quit {app} and open it again."], cli: ["A {agent} in a terminal, started {when}: quit it and start it again."], }; // the folded row's words for the copies left on the old list (#1374): a // reopen of one kind doesn't end another, so "reopen Codex" sent the reader // to the app while the editor's Codex was the one left. One kind is named // with how it is reopened; more are counted, the row opened says which. const STALE_SHORT = { app: "Connected · quit and reopen the {agent} app", ide: "Connected · reload the editor's window", daemon: "Connected · restart {agent}'s app-server", embedded: "Connected · reopen {app}", cli: "Connected · restart {agent} in the terminal", }; function staleSaid(a) { const copies = a.staleCopies || []; if (!copies.length || copies.some((c) => !STALE_HOW[c.kind])) return { text: t("Connected · takes effect once {agent} is reopened", { agent: a.name }) }; // each copy whole, with its start, for the hover where the words are cut const title = copies.map((c) => t(STALE_HOW[c.kind][0], { agent: a.name, when: ago(c.since), app: c.app || "" }).replace("{cmd}", STALE_HOW[c.kind][1] || "")).join("\n"); const kinds = new Set(copies.map((c) => c.kind + "\0" + (c.app || ""))); if (kinds.size > 1) return { text: t("Connected · {n} copies of {agent} to reopen", { n: copies.length, agent: a.name }), title }; return { text: t(STALE_SHORT[copies[0].kind], { agent: a.name, app: copies[0].app || "" }), title }; } // connectLine: the dot and the words under an agent's name function connectLine(a, kind) { const line = el("div", "ag-st"); const dot = el("span", "ag-dot"); const words = el("span", "ag-st-t"); line.append(dot, words); const say = (s, cls) => { words.textContent = s; if (cls) line.classList.add(cls); }; if (kind === "no") { say(t(NATIVE_ONLY[a.id])); return line; } if (kind === "link") { if (a.added) say(t("Added · magpie is a provider in {agent}", { agent: a.name }), "on"); else say(t("Not added · {agent} asks to add magpie when its link opens", { agent: a.name })); return line; } if (kind === "empty") { say(t("Add a key or a subscription first; then there are models to connect")); return line; } if (!a.wired && a.native && a.native.provider !== "disconnected") { say(t(a.native.detail), "bad"); if (a.native.provider === "invalid") line.append(driftFix(a, "Reconnect")); return line; } if (!a.wired) { const src = a.source || ""; if (a.id === "agy") say(t("Not connected · once connected, start it with magpie's command")); // not connected, yet through magpie for account failover (#1385): it // read as Codex on its own while magpie served every request, so the // line says why, and the accounts that turn it off are a click away else if (a.failover) { say(t("Not connected · goes through magpie only to fail over to your other ChatGPT accounts")); words.title = t("magpie set openai_base_url in {agent}'s config.toml, so a request the ChatGPT account {agent} is signed in to has no allowance for goes on to your other ChatGPT accounts on in magpie. {agent} keeps to its own models. To stop it, tick Only switch {agent}'s sign-in under Providers › Codex, or switch those accounts off; connecting {agent} adds magpie's models.", { agent: a.name }); const go = el("button", "ag-acc", t("ChatGPT accounts")); go.type = "button"; go.title = words.title; go.onclick = (e) => { e.stopPropagation(); openProvider("codex"); }; line.append(go); } else if (src === "sub") say(t("Not connected · now on its Claude subscription")); else if (src === "chatgpt") say(t("Not connected · now signed in with ChatGPT · OpenAI's models stay available once connected")); else if (src === "key") say(t("Not connected · now on an API key of its own")); else if (src.startsWith("providers:")) say(t("Not connected · now has {n} providers of its own", { n: src.slice(10) })); else say(t("Not connected · {agent} uses its own settings", { agent: a.name })); return line; } if (a.native) { say(connectSaid(a), "on"); return line; } if (a.drift) { say(t(DRIFT_WHY[a.drift.kind] || DRIFT_WHY.unwired, { agent: a.name, model: a.drift.want }), "bad"); words.title = a.drift.detail || ""; line.append(driftFix(a, "Reconnect")); return line; } line.classList.add("on"); if (staleNow(a)) { if (a.id === "claude") say(t("Connected · new sessions take it")); else { const { text, title } = staleSaid(a); say(text, "wait"); if (title) words.title = title; } return line; } const fresh = newModels(a); if (fresh) { const [pre, post] = t("Connected · {n} models · {new} show in new {agent} sessions", { n: a.models.shown, agent: a.name }).split("{new}"); words.append(pre, el("b", "", t("{n} new", { n: fresh })), post || ""); return line; } const at = PICKS_IN[a.id]; if (menuFromList(a)) say(connectSaid(a)); else if (a.id === "claude") say(t("Connected · switch the opus · sonnet · haiku tiers in /model")); else if (NO_PICKER.has(a.id)) say(t("Connected · starts on the model picked here")); else if (at && a.models) say(t("Connected · {n} models in {agent}'s {cmd}", { n: a.models.shown, agent: a.name, cmd: at })); else say(connectSaid(a)); return line; } // expandLink opens a connected agent's row, and closes it again function expandLink(a) { const open = agentExpanded === a.id; const b = el("button", "ag-link" + (open ? " open" : "")); b.type = "button"; b.setAttribute("aria-expanded", String(open)); b.append(el("span", "", open ? t("Collapse") : a.id === "claude" ? t("Tiers") : a.models && !listsMenu(a) ? t("Models {n}", { n: a.models.shown }) : t("Details"))); if (!open) { const c = el("span", "chev"); c.append(svg(CHEV_R, 10, 1.6)); b.append(c); } b.onclick = (e) => { e.stopPropagation(); const shut = document.querySelector("#agents .row.agent.expanded > .ag-exp"); agentExpanded = open ? null : a.id; const want = agentExpanded; // the one open slides shut first, then the list is drawn again sheet(shut, false, () => { if (agentExpanded !== want) return; renderAgents(); if (want) sheet(document.querySelector(`#agents .row.agent[data-id="${CSS.escape(want)}"] > .ag-exp`), true); }); }; return b; } // sheet slides a row's opened part open or shut, as a sheet moves on iOS: // its height on iOS's own curve, what is in it fading in a little below function sheet(box, open, done) { if (!box || !box.animate || matchMedia("(prefers-reduced-motion: reduce)").matches) { done?.(); return; } const cs = getComputedStyle(box); const full = { height: box.offsetHeight + "px", paddingTop: cs.paddingTop, paddingBottom: cs.paddingBottom, marginTop: cs.marginTop, marginBottom: cs.marginBottom, borderTopWidth: cs.borderTopWidth, opacity: 1 }; const none = { height: "0px", paddingTop: "0px", paddingBottom: "0px", marginTop: "0px", marginBottom: "0px", borderTopWidth: "0px", opacity: 0 }; const ease = "cubic-bezier(.32, .72, 0, 1)"; box.style.overflow = "hidden"; const run = box.animate(open ? [none, full] : [full, none], { duration: open ? 460 : 340, easing: ease, fill: open ? "none" : "forwards" }); for (const c of box.children) c.animate(open ? [{ opacity: 0, transform: "translateY(-6px)" }, { opacity: 1, transform: "none" }] : [{ opacity: 1 }, { opacity: 0 }], { duration: open ? 420 : 200, delay: open ? 60 : 0, easing: open ? ease : "ease-out", fill: "backwards" }); run.onfinish = () => { if (open) box.style.overflow = ""; done?.(); }; run.oncancel = run.onfinish; } // startField: the field an agent's model is picked in (Gemini CLI's model, // not how it signs in). Its model is that field whatever the providers // on: one switched off changes only what it lists, so Codex's model with // none of magpie's left isn't traded for its subagent model, which still // has a ChatGPT account's (#1582). A model with nothing to list (Ante's, // magpie's only) leaves the field it connects through. function startField(a) { return a.fields.find((f) => f.key === "model" && f.options.length) || connectField(a); } // startButton picks the model an agent starts on, from the row. It says // what the agent is on, connected or not, its Default or a model, and // lists every choice: the agent's own models with magpie's. A magpie model // picked while it isn't connected connects it and starts it on it. Not // connected, only Claude Code said its model, the others Pick a model // beside it (EZN7L2C3, #834: 这里似乎需要统一); and Claude Code's list had // lost the one picked. A field that isn't a model (a provider) still // offers magpie's models alone. function startButton(a, f, fieldBtn) { const b = fieldBtn(f, "ag-start"); if (!a.wired && !a.native && f.key !== "model" && !f.options.some((o) => o.direct)) { b.replaceChildren(el("span", "v empty", t("Pick a model"))); const c = el("span", "chev"); c.append(svg(CHEV, 11, 1.7)); b.append(c); b.title = t("Pick one of magpie's models: {agent} is connected and starts on it", { agent: a.name }); b.onclick = (ev) => openPicker(a, f, b, ev, (o) => !!o.ref); } else if (!a.wired) { b.title += "\n" + t("Pick one of magpie's models: {agent} is connected and starts on it", { agent: a.name }); } else if (!f.value && a.id !== "claude") { b.querySelector(".v").textContent = t("Its last pick"); b.title = t("Unset, {agent} starts on its own last pick", { agent: a.name }); } // Codex's is the very value its /model picks: one choice if (a.wired && a.id === "codex") b.title += "\n" + t("The same choice as {agent}'s {cmd}: change it here or there", { agent: a.name, cmd: PICKS_IN.codex }); return b; } // connectRow finishes a window row that has 「接入」 function connectRow(a, row, who, { fields, extras, fieldBtn, sw, kind }) { // its list open, what was picked there until the state has it if (agentModels?.a.id === a.id && agentModels.count) a.models = agentModels.count; row.classList.add("conn"); row.classList.toggle("unplugged", kind === "ok" && !a.wired); who.classList.add("with-models"); who.append(connectLine(a, kind)); // a hidden one's Show stands in the row, centred as its picker and switch // are, not up on the name's line above its middle (Hu9956, #842: 其余里 // 的显示歪了偏上了) const back = who.querySelector(":scope > .ag-show"); if (back) row.append(back); // the model it starts on, one click away beside the switch (the owner: // both ways at once): picked here, it is connected first if it wasn't const start = kind === "ok" && !listsMenu(a) ? startField(a) : null; if (start) fields.querySelector(`:scope > [data-key="${CSS.escape(start.key)}"]`)?.remove(); if (kind === "ok") { if (a.wired) row.append(expandLink(a)); // the square copying the command that starts it on magpie (agy), the // only way it takes magpie: on the row, before the model const launch = a.wired && fields.querySelector(".field.launch"); if (launch) row.append(launch); if (start) row.append(startButton(a, start, fieldBtn)); // Claude Desktop's: which models its own menu lists else if (menuFromList(a)) row.append(menuButton(a)); row.append(sw); } else if (kind === "empty") { const add = el("button", "ag-add", t("Add a provider")); add.type = "button"; add.onclick = (e) => { e.stopPropagation(); addProviderFromAgents(); }; const off = el("button", "lib-switch ag-conn"); off.type = "button"; off.disabled = true; off.setAttribute("role", "switch"); off.setAttribute("aria-checked", "false"); off.setAttribute("aria-label", t("Connect {agent} to magpie", { agent: a.name })); off.title = t("Add a key or a subscription first; then there are models to connect"); off.append(el("i")); row.append(add, off); } else if (kind === "link") { // its link where the others' model stands, and nothing to switch: the // switch's room kept, so the button lines up with the pickers (the // owner: the old row's wide button sat apart from every other) const b = importButton(a); b.classList.add("ag-start"); row.append(b, el("span", "ag-conn-gap")); } else row.append(el("span", "ag-cant", t("Can't connect"))); if (kind === "ok" && a.wired && agentExpanded === a.id) { row.classList.add("expanded"); row.append(connectPanel(a, { fields: fields.querySelector(".field") ? fields : null, extras, fieldBtn })); } } // agentsLead: above the window's list, what 「接入」 does, said once in a // line; while no agent is connected, as a welcome, with a way to add a // provider when magpie has no models to give function agentsLead(list) { let lead = $("#agentsLead"); if (!lead) { lead = el("div", "ag-lead"); lead.id = "agentsLead"; list.before(lead); } lead.replaceChildren(); // a new user's first view: the Get started card in the welcome's place, // in the panel as in the window const g = guideShown(); lead.classList.toggle("guiding", !!g); if (g) { lead.hidden = false; lead.classList.remove("welcome"); lead.append(guideCard(g)); return; } const kinds = mode === "panel" ? [] : state.agents.map(connectKind); lead.hidden = !kinds.some((k) => k === "ok" || k === "empty"); if (lead.hidden) return; const first = !state.agents.some((a) => a.wired); lead.classList.toggle("welcome", first); if (!first) { const [pre, post] = t("Switch an agent on and the models you set up in magpie show up as the {magpie} provider in its own model list; or pick its model right here.").split("{magpie}"); lead.append(pre, el("b", "", "magpie"), post || ""); return; } lead.append(el("b", "ag-lead-h", t("Let your agents use the models you set up in magpie"))); lead.append(el("p", "", t("Switch an agent on and your models show up as the magpie provider in its own model list, to change in the agent. Or pick a model right here: the agent is connected and starts on it. Switch it off and it goes back to how it was."))); if (!anyMagpieModels()) { const add = el("button", "text primary", t("Add a provider")); add.type = "button"; add.onclick = () => addProviderFromAgents(); lead.append(add); } } // ---------- Get started (wangye1644294 on X) ---------- // A new user is shown three steps above the agents: add a model source, // connect an agent (those magpie found here listed, each connected in a // click), and, optionally, a routing group made of their own models in a // click (provider.Templates). Each step is ticked from what is so — the // models magpie serves (state.served), an agent wired, a group of the // user's own — never from having been seen. The card goes once the first // two are done, or when put away (settings.GuideHidden, saved on the // server so the panel and the window agree). // the templates offered as a starter, most harmless first: each behind // the other changes no model the agent asked for until one fails const GUIDE_TEMPLATES = ["steady", "thrifty", "smart"]; const GUIDE_TEMPLATE_NAMES = { smart: "Hard to strong, easy to cheap", thrifty: "Cheap first", steady: "Never stuck" }; const GUIDE_TEMPLATE_SAYS = { smart: "A hard task goes to the strongest model, an easy one and compaction to a cheap one", thrifty: "A cheap model first; the strongest for high reasoning, or when the cheap ones fail", steady: "The strongest model of each provider, each behind the other: one down doesn't stop the agent", }; const GUIDE_X = "M4.5 4.5l7 7M11.5 4.5l-7 7"; const GUIDE_CHIPS = 6; // agents named on the card; the rest are in the list under it // guideGroups: /api/groups as the card last read it, and for which served // count, read again when the models change or a group is added let guideGroups = null, guideGroupsFor = null, guideGroupsBusy = false; let guideBusy = ""; // what the card is doing: "hide", "template", an agent's id // guideShown: the steps' state when the card is to be shown, else null function guideShown() { if (gatewayMode || !state || state.settings?.guideHidden) return null; const source = (state.served || 0) > 0 || anyMagpieModels(); const agent = state.agents.some((a) => a.wired); if (source && agent) return null; const own = guideGroups?.groups?.filter((x) => !x.auto) || []; return { source, agent, routing: own.length > 0, own }; } function guideStep(n, done, title, say) { const li = el("li", "guide-step" + (done ? " done" : "")); const tick = el("span", "guide-tick"); tick.setAttribute("aria-hidden", "true"); if (done) tick.append(svg(CHECK, 12, 2)); else tick.textContent = String(n); const body = el("div", "guide-body"); const h = el("b", "guide-title", title); body.append(h); if (say) body.append(el("span", "guide-say", say)); li.append(tick, body); li.setAttribute("aria-label", (done ? t("Done") + ": " : "") + title); return { li, body }; } function guideCard(g) { const card = el("section", "guide"); card.setAttribute("aria-label", t("Get started")); const head = el("div", "guide-head"); const steps = [g.source, g.agent]; head.append(el("b", "guide-h", t("Get started")), el("span", "guide-n", t("{n} of {m} done", { n: steps.filter(Boolean).length, m: steps.length }))); const x = el("button", "guide-x"); x.type = "button"; x.title = t("Hide Get started"); x.setAttribute("aria-label", x.title); x.append(svg(GUIDE_X, 12, 1.6)); x.disabled = guideBusy === "hide"; x.onclick = (e) => { e.stopPropagation(); hideGuide(); }; head.append(x); card.append(head); const list = el("ol", "guide-steps"); // 1: a model source const one = guideStep(1, g.source, t("Add a model source"), g.source ? t("{n} models ready to use", { n: state.served || 0 }) : t("A subscription you already pay for, a provider, or an API key")); one.li.dataset.step = "source"; if (!g.source) { const add = el("button", "text primary guide-go", t("Add a provider")); add.type = "button"; add.onclick = (e) => { e.stopPropagation(); if (mode === "window") addProviderFromAgents(); else api("window/main?view=providers", {}).catch((err) => status(err.message, "err")); }; one.body.append(add); } list.append(one.li); // 2: an agent, those found here named, each connected in a click const found = state.agents.filter((a) => connectKind(a) === "ok" || connectKind(a) === "empty"); const two = guideStep(2, g.agent, t("Connect an agent"), g.agent ? "" : found.length ? t("magpie found these on this computer. Click one to connect it:") : t("Install Claude Code, Codex, Gemini CLI, OpenCode… and magpie will list them here.")); two.li.dataset.step = "agent"; if (!g.agent && found.length) { const chips = el("div", "guide-agents"); for (const a of found.slice(0, GUIDE_CHIPS)) { const b = el("button", "guide-agent"); b.type = "button"; b.dataset.id = a.id; b.append(icon(a.icon), el("span", "", a.name)); const ready = connectKind(a) === "ok"; b.disabled = !ready || !!guideBusy; b.classList.toggle("busy", guideBusy === a.id); b.title = ready ? t("Switch on and {agent}'s model list gets magpie's models", { agent: a.name }) : t("Add a key or a subscription first; then there are models to connect"); b.onclick = (e) => { e.stopPropagation(); guideConnect(a); }; chips.append(b); } if (found.length > GUIDE_CHIPS) chips.append(el("span", "guide-more", t("+{n} more below", { n: found.length - GUIDE_CHIPS }))); two.body.append(chips); } list.append(two.li); // 3, optional: a routing group of the user's own models const three = guideStep(3, g.routing, t("Set up routing (optional)"), g.routing ? g.own.map((x) => x.name || x.id).join(", ") : t("A routing group sends each request to the right model, and to the next one when a model fails")); three.li.dataset.step = "routing"; three.li.classList.add("optional"); if (!g.routing && g.source) { guideLoadGroups(); const acts = el("div", "guide-acts"); const tp = GUIDE_TEMPLATES.map((k) => guideGroups?.templates?.find((x) => x.kind === k && !x.need && x.group?.members?.length)).find(Boolean); if (tp) { const name = t(GUIDE_TEMPLATE_NAMES[tp.kind] || tp.group.name); const add = el("button", "text primary guide-go guide-tpl", t("Add “{name}”", { name })); add.type = "button"; add.dataset.kind = tp.kind; add.title = t(GUIDE_TEMPLATE_SAYS[tp.kind] || "") + "\n" + tp.group.members.join(" → "); add.disabled = !!guideBusy; add.onclick = (e) => { e.stopPropagation(); guideTemplate(tp, name); }; acts.append(add); } const open = el("button", "text guide-open", t("Open Routing")); open.type = "button"; open.onclick = (e) => { e.stopPropagation(); if (mode === "window") show("routing"); else api("window/main?view=routing", {}).catch((err) => status(err.message, "err")); }; acts.append(open); three.body.append(acts); if (tp) three.body.append(el("span", "guide-say guide-tpl-say", t(GUIDE_TEMPLATE_SAYS[tp.kind] || ""))); } list.append(three.li); card.append(list); return card; } // guideLoadGroups reads the groups and templates for step 3, once for // each count of models served, and draws the card again with them function guideLoadGroups(again) { const key = String(state.served || 0); if (guideGroupsBusy || (!again && guideGroupsFor === key)) return; guideGroupsBusy = true; guideGroupsFor = key; api("groups").then((gs) => { guideGroups = gs; }, () => { /* the step links to Routing still */ }) .finally(() => { guideGroupsBusy = false; if (view === "agents" || mode === "panel") guideRedraw(); }); } // guideRedraw draws the lead again, and the panel to its height function guideRedraw() { const list = $("#agents"); if (!list || !state) return; agentsLead(list); fit(); } async function guideConnect(a) { if (guideBusy) return; guideBusy = a.id; guideRedraw(); try { state = await api("agents/connect/" + a.id, {}); guideBusy = ""; renderAgents(); const msg = connectedSaid(a, state.connected); if (state.notice) status(withNotice(msg, state.notice), "warn", 9000); else status(msg, "ok", 7000); } catch (err) { guideBusy = ""; guideRedraw(); status(t(err.message), "err"); } } async function guideTemplate(tp, name) { if (guideBusy) return; guideBusy = "template"; guideRedraw(); try { guideGroups = await api("groups/template", { kind: tp.kind, name }); guideBusy = ""; status(t("Added {name}", { name }), "ok"); // the agents' pickers list the new group state = await api("state"); renderAgents(); } catch (err) { guideBusy = ""; guideRedraw(); status(t(err.message), "err"); } } async function hideGuide() { if (guideBusy) return; guideBusy = "hide"; guideRedraw(); try { prefs = await writingPrefs(api("settings/guide", { hidden: true })); state.settings = prefs; guideBusy = ""; renderAgents(); } catch (err) { guideBusy = ""; guideRedraw(); status(t(err.message), "err"); } } async function addProviderFromAgents() { if (!await show("providers")) return; // the list not read yet (the page's first opening): clicked before it is // in, the button drew a list of nothing and threw; read, an empty list // opens the sheet itself if (!providers) { try { await loadProviders(); } catch { return; } } if (!adding) $("#addProvider")?.click(); } // desktopLongestLine: Claude Desktop lists a model of 1M or more twice, the // plain one and a "1M context window" one of its own; switched on, magpie // lists it by its 1M id alone, one entry each (#1272). Desktop reads the // list as it starts. function desktopLongestLine() { const on = !!state.settings?.desktopLongest; const l = el("label", "ag-vl ag-longest"); const b = el("button", "lib-switch use-credits" + (on ? " on" : "")); b.type = "button"; b.setAttribute("role", "switch"); b.setAttribute("aria-checked", String(on)); b.append(el("i")); const say = el("span", "ag-longest-say", t("Only each model's largest window")); b.setAttribute("aria-label", say.textContent); const hint = el("span", "ag-hint", t("A model of 1M or more is listed once, as its 1M entry. Quit and reopen Claude Desktop after a change.")); l.append(b, say, hint); b.onclick = async (e) => { e.stopPropagation(); e.preventDefault(); if (b.disabled) return; b.disabled = true; try { prefs = await writingPrefs(api("settings/desktop-longest", { on: !on })); state.settings = prefs; status(t("Saved — quit and reopen Claude Desktop to see it"), "ok"); renderAgents(); } catch (err) { b.disabled = false; status(t(err.message), "err"); } }; return l; } // daemonRestart: the button that restarts Codex's background app-server // left on the old list, then shows the row as it is after function daemonRestart() { const go = el("button", "ag-quiet accent", t("Restart")); go.type = "button"; go.title = "codex app-server daemon restart"; go.onclick = async () => { go.disabled = true; go.classList.add("busy"); try { await api("codex/daemon/restart", {}); state = await api("state"); renderAgents(); status(t("Codex's background service restarted")); } catch (e) { go.disabled = false; go.classList.remove("busy"); status(e.message, "err"); } }; return go; } // connectPanel: a connected agent's row, opened function connectPanel(a, { fields, fieldBtn }) { const box = el("div", "ag-exp"); const settings = el("div", "ag-settings"); box.append(settings); box.onclick = (e) => e.stopPropagation(); const kv = (k, ...v) => { const r = el("div", "ag-kv"); const val = el("div", "ag-v"); val.append(...v); r.append(el("div", "ag-k", k), val); settings.append(r); return val; }; const line = (...parts) => { const l = el("div", "ag-vl"); l.append(...parts); return l; }; const code = (s) => el("code", "ag-code", s); // where it picks, and when the copies running take it const at = PICKS_IN[a.id]; if (at || STARTS_WITH.has(a.id)) { const parts = []; // the command in the words as code, wherever the language puts it const said = (s, cmd) => { const [pre, post] = t(s, { agent: a.name }).split("{cmd}"); return line(pre, code(cmd), post || ""); }; if (a.id === "claude") parts.push(said("New sessions take it; switch the tiers in {cmd}.", "/model")); // its own models still there beside magpie's (Codex on ChatGPT) else if (a.joined) parts.push(said("Reopen {agent}: its own models stay in {cmd}, and magpie's join them.", at)); else if (STARTS_WITH.has(a.id)) parts.push(said("Reopen {agent}, then pick any model in {cmd}.", at)); else parts.push(said("Pick any model in {agent}'s {cmd}.", at)); if (staleNow(a)) { const w = line(); w.classList.add("ag-warn"); w.append(el("span", "ag-dot"), el("span", "", t(a.stale === 1 ? "1 running {agent} still has the old list" : "{n} running {agent} still have the old list", { n: a.stale, agent: a.name }))); const later = el("button", "ag-quiet", t("Got it")); later.type = "button"; later.onclick = () => { staleSeen[a.id] = a.stale; renderAgents(); }; w.append(later); parts.push(w); // which copy is left, and how it is reopened: a reopen of one kind // doesn't end another (the Codex app keeps running on macOS when its // window is closed; an editor's Codex and the CLI's daemon run on) for (const c of a.staleCopies || []) { const how = STALE_HOW[c.kind]; if (!how) continue; const [pre, post] = t(how[0], { agent: a.name, when: ago(c.since), app: c.app || "" }).split("{cmd}"); const l = line(pre, ...(how[1] ? [code(how[1]), post || ""] : [])); l.classList.add("ag-stale-copy"); // Codex's daemon, which magpie restarts itself while no codex // session is on it: with one on, here, when the user says (open // sessions of Codex 0.162 reconnect to the new one) if (c.kind === "daemon" && a.id === "codex") l.append(daemonRestart()); parts.push(l); } } kv(t("In {agent}", { agent: a.name }), ...parts); } else if (menuFromList(a)) { kv(t("In {agent}", { agent: a.name }), line(t("{agent}'s model menu lists the models picked here; switch among them there. It reads the list as it starts: quit and reopen it after a change.", { agent: a.name }))); } // Claude Code's tiers, each with the /model that picks it if (a.id === "claude") { const tiers = a.fields.filter((f) => TIERS.includes(f.label) && f.options.length); const hint = { opus: "/model opus", sonnet: "/model sonnet", haiku: "/model haiku", fable: "/model fable" }; const also = { sonnet: " · " + t("the default tier"), haiku: " · " + t("also for small background tasks") }; const rows = tiers.map((f) => { const l = line(el("span", "ag-tier", f.label[0].toUpperCase() + f.label.slice(1)), fieldBtn(f, "ag-pick")); // the tier's own effort (#536), while there are levels to pick; // unset, it runs at the effort Claude Code asks for const e = a.fields.find((x) => x.label === f.label + " effort" && (x.options.length || x.value)); if (e) { const b = fieldBtn(e, "ag-eff"); b.title = t("{label}: {value}", { label: t(e.label), value: e.value ? effortName(optionFor(e, e.value) || { value: e.value }) : t("the effort Claude Code asks for") }); b.setAttribute("aria-label", b.title); l.append(b); } l.append(el("span", "ag-hint", (hint[f.label] || "") + (also[f.label] || ""))); return l; }); const sub = a.fields.find((f) => f.label === "subagents" && (f.options.length || f.value)); if (sub) rows.push(line(el("span", "ag-tier", t("Subagents")), fieldBtn(sub, "ag-pick"))); if (rows.length) kv(t("Tiers"), ...rows); const main = a.fields.find((f) => f.key === "model"); const hasSub = main?.options.some((o) => (o.ref || "").startsWith("claude/")); if (hasSub) kv(t("Claude models"), line(t("Your Claude subscription is in magpie; picking a claude-* model goes through it as before"))); else { const add = el("button", "ag-quiet accent", t("Add a Claude subscription")); add.type = "button"; add.onclick = () => addProviderFromAgents(); kv(t("Claude models"), line(t("claude-* models need a Claude subscription in magpie"), add)); } } // which of magpie's models it lists, by whose they are if (a.models) { const chips = line(); chips.classList.add("ag-chips"); for (const g of a.models.by || []) { const c = el("span", "ag-chip"); if (g.icons?.length) c.append(optionIcon({ icons: g.icons })); else if (g.icon) c.append(icon(g.icon)); c.append(el("span", "", g.name === ROUTING_GROUPS ? t(g.name) : g.name), el("span", "n", String(g.n))); chips.append(c); } const hidden = a.models.listed - a.models.shown; if (hidden > 0) chips.append(el("span", "ag-hint", t("{n} hidden", { n: hidden }))); const pick = el("button", "ag-quiet"); pick.type = "button"; pick.append(el("span", "", t("Pick"))); const c = el("span", "chev"); c.append(svg(CHEV_R, 10, 1.6)); pick.append(c); pick.onclick = (ev) => openAgentModels(a, pick, ev); holdAgentModels(a, pick); chips.append(pick); const v = kv(t("Model list"), chips); // the Codex app's menu reaches only so many of them (#1262) if (a.id === "codex" && a.models.shown > CODEX_APP_MENU) { const w = line(); w.classList.add("ag-warn", "ag-menu-cap"); w.append(el("span", "ag-dot"), el("span", "", t("The Codex app's model menu shows only the first {max}: the last {n} models can't be picked there (the Codex CLI's /model lists them all). In Pick, turn off the ones you don't use, or drag the ones you use to the front under Order.", { max: CODEX_APP_MENU, n: a.models.shown - CODEX_APP_MENU }))); v.append(w); } if (a.id === "claude-desktop") v.append(desktopLongestLine()); } // what a new session starts on: optional, the agent's own last pick // unset; Codex's is the very value its /model picks, so one choice // the model it starts on is on the row; what goes with it here if (fields) { // each setting named, as the tray panel's opened rows name them. On the // row a setting nobody has picked is the agent's own logo for want of // room, which says nothing about which setting it is, and four of them // laid side by side all read as one for (const b of fields.querySelectorAll(":scope > .field")) { const f = a.fields.find((x) => x.key === b.dataset.key); if (f && !b.querySelector(":scope > .k")) b.prepend(el("span", "k", t(f.label))); } // Cursor Private Inference's are magpie's own, its effort asked on // every request it sends from then on, not what a new session starts // with (#1003) kv(t(a.id === "cursor-local" ? "Settings" : "New sessions"), line(fields)); } if (a.native) for (const [key, detail] of Object.entries(a.native.fields || {})) { if (detail.detail) { const f = a.fields.find((x) => x.key === key); kv(t(f?.label || key), line(t(detail.detail))); } } if (CONNECT_COST[a.id]) kv(t("Once connected"), line(t(CONNECT_COST[a.id]))); if (a.launch) { const cp = el("button", "ag-quiet", t("Copy")); cp.type = "button"; cp.onclick = () => copy(a.launch, t("Launch command"), null, t("Copied — run it to start {name} on magpie", { name: a.name })); kv(t("Start it with"), line(code(a.launch), cp)); } // the files magpie changed, and the way back const foot = el("div", "ag-foot"); const files = el("span", "ag-files"); const view = el("button", "ag-quiet"); view.type = "button"; view.hidden = true; const diff = el("div", "ag-diff-box"); diff.hidden = true; view.onclick = () => { diff.hidden = !diff.hidden; view.firstChild.textContent = diff.hidden ? t("View") : t("Hide changes"); view.classList.toggle("open", !diff.hidden); }; view.append(el("span", "", t("View"))); const vc = el("span", "chev"); vc.append(svg(CHEV_R, 10, 1.6)); view.append(vc); const off = el("button", "ag-quiet red", t("Disconnect and restore")); off.type = "button"; off.onclick = () => askDisconnect(a); foot.append(files, view, el("span", "grow"), off); box.append(foot, diff); const fill = (changes) => { if (!changes?.length) return; files.replaceChildren(t("Changed ")); changes.forEach((c, i) => { if (i) files.append(" · "); files.append(el("span", "ag-path", i ? c.path.split("/").pop() : c.path)); }); view.hidden = false; diff.replaceChildren(changesList(changes)); }; if (previews[a.id]) fill(previews[a.id]); loadPreview(a).then((preview) => fill(preview.changes), () => {}); return box; } async function loadPreview(a) { const r = await api("agents/preview/" + a.id); if (r?.error) throw new Error(r.error); previews[a.id] = r?.changes || []; return { changes: previews[a.id], revision: typeof r?.revision === "string" ? r.revision : "" }; } // changesList: what disconnecting does to each file, line by line function changesList(changes) { const box = el("div", "ag-diff"); for (const c of changes) { const f = el("div", "ag-diff-file"); const h = el("div", "ag-diff-path"); h.append(el("span", "", c.path)); if (c.removed) h.append(el("span", "ag-tag del", t("Deleted"))); if (c.created) h.append(el("span", "ag-tag", t("Created"))); f.append(h); const line = (l) => { const r = el("div", "ag-diff-line " + (l.op === "-" ? "del" : "back")); // the indent shows where it was, and isn't struck through const code = el("code"), ind = l.text.match(/^\s*/)[0]; code.append(el("span", "ind", ind), el("span", "t", l.text.slice(ind.length))); r.append(el("span", "op", l.op === "-" ? "−" : "↺"), code); if (l.op !== "-") r.append(el("span", "ag-tag", t("value before connecting"))); if (l.op === "~" && l.was) r.title = t("Now: {line}", { line: l.was }); return r; }; // a list magpie wrote whole (Claude Code's modelPicker, Codex's // catalog) is a few lines and the rest on asking const lines = c.lines || [], FEW = 8; f.append(...lines.slice(0, FEW).map(line)); if (lines.length > FEW + 2) { const rest = el("button", "ag-diff-more", t("{n} more lines", { n: lines.length - FEW })); rest.type = "button"; rest.onclick = () => rest.replaceWith(...lines.slice(FEW).map(line)); f.append(rest); } else f.append(...lines.slice(FEW).map(line)); box.append(f); } return box; } // askDisconnect takes magpie out of an agent's config once asked: every // field magpie set, and its endpoint and key, give way to what the agent // had before magpie (agent.Disconnect). Picking Default isn't that: it is // the agent as installed. function askDisconnect(a) { const ed = el("div", "editor disconnect-ask"); const head = el("div", "ehead"); head.append(icon(a.icon), el("b", "", t("Disconnect {agent} from magpie?", { agent: a.name }))); ed.append(head); ed.append(el("p", "lib-confirm", t("{agent} goes back to how it was before it was connected; these are the places put back.", { agent: a.name }))); // what changes, line by line, read from a dry run on a copy (preview.go); // where none can be had, the old words const said = el("p", "lib-confirm", t("magpie takes out everything it wrote into {agent}'s config — its endpoint, key, models and effort — and puts back the settings {agent} had before. magpie's providers and accounts stay as they are.", { agent: a.name })); const body = el("div", "ag-diff-wrap"); const show = (changes) => { if (changes?.length) body.replaceChildren(changesList(changes)); else body.replaceChildren(said); }; if (previews[a.id]) show(previews[a.id]); else body.append(el("div", "ag-diff-loading", t("Reading what changes…"))); let previewBlocked = !!a.native, revision = "", offline = false; loadPreview(a).then((preview) => { show(preview.changes); revision = preview.revision; previewBlocked = !!a.native && !revision; go.disabled = previewBlocked; }, (err) => { if (!a.native) { show(null); return; } previewBlocked = true; go.disabled = true; body.replaceChildren(el("p", "lib-confirm", t(err.message))); }); ed.append(body); if (a.id === "codex") ed.append(el("p", "ag-note", t("magpie's provider table stays, so sessions opened on magpie's models still open"))); const bar = el("div", "bar"); const go = el("button", "text primary danger-fill", t("Disconnect and restore")); go.disabled = previewBlocked; go.onclick = async (e) => { e.stopPropagation(); if (previewBlocked) return; go.disabled = true; go.classList.add("busy"); try { state = await api("agents/" + (offline ? "disconnect-offline/" : "disconnect/") + a.id, offline ? { revision } : {}); closeConfirmAsk(); delete previews[a.id]; if (agentExpanded === a.id) agentExpanded = null; renderAgents(); const msg = t(offline ? "Saved settings restored; magpie was removed from {agent}" : "{agent} no longer goes through magpie; its own settings are back", { agent: a.name }); if (state.notice) status(withNotice(msg, state.notice), "warn", 9000); else status(msg, "ok"); } catch (err) { go.disabled = false; go.classList.remove("busy"); if (!offline && err.code === "runtime_unavailable" && err.offline === "disconnect" && revision) { offline = true; head.querySelector("b").textContent = t("Restore saved settings and remove magpie?"); ed.querySelector(".lib-confirm").textContent = t("Restore saved settings and remove magpie without contacting Aside? Close Aside first if it is running."); go.textContent = t("Restore saved settings and remove magpie"); cancel.focus({ preventScroll: true }); return; } status(t(err.message), "err"); } }; const cancel = el("button", "text", t("Cancel")); cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; bar.append(STARTS_WITH.has(a.id) ? el("span", "ag-bar-note", t("Running {agent} copies take it once reopened", { agent: a.name })) : el("span"), el("span", "grow"), cancel, go); ed.append(bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); cancel.focus({ preventScroll: true }); } async function keepAgent(a) { try { state = await api("agents/keep/" + a.id, {}); renderAgents(); } catch (e) { status(e.message, "err"); } } // reapplyAgent writes what magpie set on the agent into its config again. async function reapplyAgent(a, btn) { btn?.classList.add("busy"); try { state = await api("agents/reapply/" + a.id, {}); renderAgents(); document.querySelector(`.agent[data-id="${CSS.escape(a.id)}"] .field`)?.classList.add("flash"); const msg = t("{agent} goes through magpie again", { agent: a.name }); if (state.notice) status(withNotice(msg, state.notice), "warn", 9000); else status(msg, "ok"); } catch (e) { btn?.classList.remove("busy"); status(e.message, "err"); } } // ---------- the agents' CLIs (#202) ---------- // Each agent's CLI shows its version after its name, faint; when a newer one // is out and magpie knows how the CLI was installed (its own updater, npm, // bun, pnpm, Homebrew), a pill beside it updates it. The versions come after // the rows are drawn, never holding them up; one magpie can't tell how it // was installed shows its version alone. let cliInfo = {}; // agent id → { version, latest, via, command, update } const cliBusy = new Set(); // the ones being updated now const CLI_UP = "M8 2.5v8M4.5 7 8 10.5 11.5 7M3.5 13.5h9"; const CLI_SPIN = "M13.5 8a5.5 5.5 0 1 1-5.5-5.5"; function cliTag(a) { const box = el("span", "ag-cli"); // its settings are here, its CLI isn't: uninstalled, its folder left // behind (#843); Install another agent has it again if (a.cliMissing) { const m = el("span", "ag-missing", t("CLI not found")); m.title = t("{agent}'s settings are still here ({path}), but its command-line program isn't found: it may have been uninstalled. Install another agent, below the list, has its install command.", { agent: a.name, path: a.path }); box.append(m); return box; } const c = cliInfo[a.id]; if (!c?.version && !c?.app) return box; if (c.version) { // beside its desktop app's version, the CLI's says it is the CLI's const v = el("span", "ag-ver", c.app ? t("CLI {v}", { v: c.version }) : c.version); v.title = !c.via ? t("{agent} {v} · magpie can't tell how it was installed — update it the way you installed it", { agent: a.name, v: c.version }) : c.update ? t("{agent} {v} is installed · {latest} is out", { agent: a.name, v: c.version, latest: c.latest }) : t("{agent} {v} · up to date", { agent: a.name, v: c.version }); box.append(v); // found in a folder magpie adds to its own PATH that a terminal's // doesn't have (an npm install under a Node nvm no longer uses): // listed though `which` finds nothing, so it says where it is // (悠悠哥 on Discord: Codex 0.162.1 with no codex on PATH); where the // row is too tight for the note, the version's tip says it if (c.offPath && c.path) { const o = el("span", "ag-missing ag-offpath", t("Not on your terminal's PATH")); o.title = v.title = t("magpie found {agent} {v} at {path}. That folder is one magpie looks in, but your terminal's PATH doesn't have it, so a terminal won't find {agent} there. If it was left behind by an uninstall, delete it.", { agent: a.name, v: c.version, path: c.path }); box.append(o); } } if (c.update || cliBusy.has(a.id)) { const b = el("button", "ag-up"); b.type = "button"; // npm's global folder under Program Files: Windows asks first b.title = c.admin ? t("Updates with {cmd}, as administrator: Windows asks first", { cmd: c.command }) : t("Updates with {cmd}", { cmd: c.command }); paintCLIButton(b, c, cliBusy.has(a.id)); b.onclick = (e) => { e.stopPropagation(); updateCLI(a, b); }; box.append(b); } // the desktop app (the Codex app, #1334): its version, which updates // itself; one connection serves the app and the CLI if (c.app) { const v = el("span", "ag-ver ag-app", t("App {v}", { v: c.app })); v.title = t("The {agent} app {v}. It reads the same settings as the CLI: connecting {agent} here connects both", { agent: a.name, v: c.app }); box.append(v); } return box; } function paintCLIButton(b, c, busy) { b.classList.toggle("busy", busy); b.setAttribute("aria-busy", String(busy)); const text = busy ? t("Updating…") : t("Update to {v}", { v: c.latest }); // named even where a tight row shows only the arrow b.setAttribute("aria-label", text); b.replaceChildren(svg(busy ? CLI_SPIN : CLI_UP, 11, 1.8), el("span", "", text)); } // paintCLI draws an agent's CLI again where it is, the row left as it is function paintCLI(id) { const a = state?.agents?.find((x) => x.id === id); if (!a) return; for (const old of document.querySelectorAll(`#agents .row.agent[data-id="${CSS.escape(id)}"] .ag-cli`)) old.replaceWith(cliTag(a)); } let cliLoading = null; async function loadCLIs(again = 0) { if (mode === "panel" || cliLoading) return; cliLoading = (async () => { let r; try { r = await api("agents/cli"); } catch { return; } // it just isn't shown const next = r?.agents || {}; const was = cliInfo; cliInfo = next; for (const id of new Set([...Object.keys(was), ...Object.keys(next)])) { if (JSON.stringify(was[id]) !== JSON.stringify(next[id])) paintCLI(id); } paintUpdateAll(); // some were still being asked: they are ready in a moment if (r?.pending && again < 3) setTimeout(() => loadCLIs(again + 1), 4000); })(); try { await cliLoading; } finally { cliLoading = null; } } // updateCLI updates one agent's CLI; "" when it went well, else why not. // Quiet (Update all) leaves the saying to the caller. Each version it went // from and to is said once (37FlowAI on X: "Pi 从 v1.0x 更新到 v1.10"). async function updateCLI(a, btn, quiet = false) { if (cliBusy.has(a.id)) return t("{agent} is already being updated", { agent: a.name }); const from = cliInfo[a.id]?.version; cliBusy.add(a.id); if (btn) paintCLIButton(btn, cliInfo[a.id] || {}, true); // in place: what was clicked stays else paintCLI(a.id); paintUpdateAll(); try { const c = await api("agents/cli/" + encodeURIComponent(a.id), {}); cliInfo[a.id] = c; if (cliAll && quiet) cliAll.changed.push(versionChange(a.name, from, c.version)); if (!quiet) status(from && from !== c.version ? t("{agent} updated: {from} → {v}", { agent: a.name, from, v: c.version }) : t("{agent} updated to {v}", { agent: a.name, v: c.version }), "ok"); return ""; } catch (e) { if (!quiet) status(e.message, "err", 12000); cliBusy.delete(a.id); await loadCLIs(); // what it is now return e.message; } finally { cliBusy.delete(a.id); paintCLI(a.id); paintUpdateAll(); } } // "Pi 1.0.9 → 1.1.0", or the name and the version now when the one before // isn't known or is the same const versionChange = (name, from, to) => from && to && from !== to ? `${name} ${from} → ${to}` : [name, to].filter(Boolean).join(" "); // ---------- Update all (#727) ---------- // With two or more agents' CLIs behind, a line above the list updates them // all, one after another (two global npm installs at once can trip over // each other's folders), each row's pill turning busy in its turn. Once // shown, the line stays until the agents are read again (a reload, the // window coming back), saying how the run went or what is left, so the // list under it never jumps for a click — Update all's or a row's pill's. let cliAll = null; // { n, done, now, failed: [{ name, msg }], changed: ["Pi 1.0.9 → 1.1.0"] } once Update all is clicked const updatable = () => (state?.agents || []).filter((a) => cliInfo[a.id]?.update && !cliBusy.has(a.id)); // fresh: the agents were read again, so a line with nothing to offer goes function paintUpdateAll(fresh = false) { const list = $("#agents"); if (mode === "panel" || !list) return; let bar = $("#agentsUpdates"); const ups = updatable(); const running = !!cliAll && cliAll.done < cliAll.n; if (!running && ups.length < 2 && (fresh || !bar)) { bar?.remove(); return; } if (!bar) { bar = el("div", "ag-updates"); bar.id = "agentsUpdates"; bar.setAttribute("role", "status"); list.before(bar); } const say = el("span", "ag-updates-say"); const parts = [say]; bar.classList.toggle("failed", !running && !!cliAll?.failed.length); if (running) { say.textContent = t("Updating {agent}… ({i} of {n})", { agent: cliAll.now, i: cliAll.done + 1, n: cliAll.n }); const b = el("button", "ag-up ag-up-all busy"); b.type = "button"; b.setAttribute("aria-busy", "true"); b.append(svg(CLI_SPIN, 11, 1.8), el("span", "", t("Updating…"))); parts.push(b); } else if (cliAll) { say.textContent = updatedSay(); // one line, cut short when narrow: every change and error in full here say.title = [...cliAll.changed, ...cliAll.failed.map((f) => f.msg)].join("\n"); } else { // what is behind now, the ones being updated by their own pill too const behind = (state?.agents || []).filter((a) => cliInfo[a.id]?.update || cliBusy.has(a.id)); say.textContent = behind.length >= 2 ? t("{n} agents have updates: {names}", { n: behind.length, names: behind.map((a) => a.name).join(", ") }) : behind.length ? t("{agent} has an update", { agent: behind[0].name }) : t("Every agent is up to date"); } if (!running && ups.length >= 2) { const b = el("button", "ag-up ag-up-all"); b.type = "button"; b.title = ups.map((a) => `${a.name}: ${cliInfo[a.id].version} → ${cliInfo[a.id].latest}`).join("\n"); b.append(svg(CLI_UP, 11, 1.8), el("span", "", t("Update all"))); b.onclick = (e) => { e.stopPropagation(); updateAllCLIs(); }; parts.push(b); } bar.replaceChildren(...parts); } async function updateAllCLIs() { if (cliAll && cliAll.done < cliAll.n) return; const ups = updatable(); if (!ups.length) return; cliAll = { n: ups.length, done: 0, now: ups[0].name, failed: [], changed: [] }; for (const a of ups) { cliAll.now = a.name; paintUpdateAll(); const err = await updateCLI(a, null, true); if (err) cliAll.failed.push({ name: a.name, msg: err }); cliAll.done++; } paintUpdateAll(); if (!cliAll.failed.length) status(updatedSay(), "ok"); else status(cliAll.failed.map((f) => f.msg).join(" · "), "err", 12000); } // how an Update all went, with each agent's versions from and to function updatedSay() { const ok = cliAll.n - cliAll.failed.length, list = cliAll.changed.join(", "); if (!cliAll.failed.length) return t("{n} agents updated: {list}", { n: ok, list }); const names = cliAll.failed.map((f) => f.name).join(", "); return ok ? t("{ok} of {n} agents updated: {list} · {failed} didn't: {names}", { ok, n: cliAll.n, list, failed: cliAll.failed.length, names }) : t("{ok} of {n} agents updated · {failed} didn't: {names}", { ok, n: cliAll.n, failed: cliAll.failed.length, names }); } // ---------- installing the agents not here (#727) ---------- // Under the list, the agents magpie knows that aren't on this machine, each // with its vendor's install commands to copy into a terminal: the vendor's // installer first, then Homebrew's or npm's. magpie doesn't run them — a // new computer may have no Node.js for npm yet, and an installer may ask // for things in the terminal. Folded unless no agent is here at all. let installInfo = []; // [{ id, name, icon, commands: [{ via, command }] }] let installsOpen = null; // null: as the list has it (open with no agents) const VIA = { script: "Installer", powershell: "PowerShell", brew: "Homebrew", npm: "npm" }; async function loadInstalls() { if (mode === "panel") return; let r; try { r = await api("agents/install"); } catch { return; } // it just isn't shown installInfo = Array.isArray(r) ? r : []; paintInstalls(); } // installNote: what the commands want. With no Node.js on this machine the // server gives each npm command Node's install first (node: nvm, nvm-mac // or winget), and the note says so, and what may still be asked for. function installNote(items) { // npm's global folder is Node.js's own under Program Files (新v学员 on // Discord): npm install -g there wants a terminal opened as administrator const admin = items.flatMap((x) => x.commands).find((c) => c.admin)?.admin; const note = installNoteFor(items); return admin ? note + " " + t("npm installs into {prefix} here, which only an administrator can change: run the npm commands in a terminal opened as administrator, or first move npm's global folder to one of your own (npm config set prefix \"%APPDATA%\\npm\").", { prefix: admin }) : note; } function installNoteFor(items) { const node = items.flatMap((x) => x.commands).find((c) => c.node)?.node; const after = t("Run a command in a terminal, then come back: magpie lists the agent here once it is installed."); if (node === "winget") return t("No Node.js was found here, so the npm commands install it with winget first; run them in PowerShell. If npm isn't found after Node.js is installed, open a new terminal and run the npm install again.") + " " + after; if (node) { const s = t("No Node.js was found here, so the npm commands install it with nvm first.") + " " + after; return node === "nvm-mac" ? s + " " + t("On a Mac, nvm needs Xcode's Command Line Tools: if it asks for them, run xcode-select --install, then the command again.") : s; } return t("Run a command in a terminal, then come back: magpie lists the agent here once it is installed. The npm commands need Node.js (nodejs.org)."); } function paintInstalls() { const list = $("#agents"); if (mode === "panel" || !list) return; let box = $("#agentsInstall"); const here = new Set((state?.agents || []).map((a) => a.id)); // one listed above by its settings alone, its CLI gone (#843), is // offered again too const items = installInfo.filter((x) => x.missing || !here.has(x.id)); if (!items.length) { box?.remove(); return; } if (!box) { box = el("section", "ag-install"); box.id = "agentsInstall"; list.after(box); } const open = installsOpen ?? !(state?.agents || []).length; const head = el("button", "ag-install-head"); head.type = "button"; head.setAttribute("aria-expanded", String(open)); head.dataset.unrolls = ""; // it stays put, and its commands open beneath it const chev = el("span", "chev"); chev.append(svg(CHEV, 10, 1.8)); head.append(el("span", "", t("Install another agent ({n})", { n: items.length })), chev); head.onclick = (e) => { e.stopPropagation(); installsOpen = !open; paintInstalls(); $("#agentsInstall .ag-install-head")?.focus({ preventScroll: true }); }; const parts = [head]; if (open) { parts.push(el("p", "ag-install-note", installNote(items))); for (const x of items) { const r = el("div", "ag-install-row"); r.dataset.id = x.id; const who = el("div", "ag-install-who"); // one whose settings are left (#843) says so under its name const name = el("span", "ag-install-name"); name.append(el("b", "", x.name)); if (x.missing) { const m = el("span", "ag-install-missing", t("CLI not found")); m.title = t("{agent}'s settings are still here, but its command-line program isn't found", { agent: x.name }); name.append(m); } who.append(icon(x.icon || x.id), name); const cmds = el("div", "ag-install-cmds"); for (const c of x.commands) { const line = el("div", "ag-install-cmd"); line.append(el("span", "ag-install-via", c.node ? t("Node.js + npm") : t(VIA[c.via] || c.via)), el("code", "", c.command), copyBtn(c.command, t("{agent}'s install command", { agent: x.name }))); cmds.append(line); } r.append(who, cmds); parts.push(r); } } box.replaceChildren(...parts); } // ---------- the agents' order, and the ones put away ---------- // Kept in magpie's own settings (agentOrder, agentsHidden, agentsShown), // never in an agent's files. An agent the order doesn't name — one // installed since — follows the ordered ones, in magpie's own order. let agentsGlide = null; // how the panel's edge moves after the next render let panelOpenAgent = null; // the one agent row the panel has opened // set up: a model, a provider, a role given one — what magpie is there for. // How the agent's own model is run (ultracode, an effort) is not: turning // Claude Code's ultracode on folded every other agent away under Show more. // One with 「接入」's switch is set up when it is connected, and only then // (#726): its fields are read from its own files, so one not connected kept // its row up for a model of its own (Antigravity, DeepSeek Harness), and a // connected Codex starting on its last choice, no model set, went under // Not set up. One magpie connected that has come apart (drift) stays up // too, to be put right. One with no switch (Cursor, an app's own models) // goes by what is set on it, as before, though while an agent can be // connected it doesn't start the folding (arrangeAgents): its values are // its own files' too, and a Cursor on auto would fold every agent not // connected yet away on a fresh magpie. const tweak = (f) => f.key === "ultracode" || f.key === "effort" || f.key.endsWith("_effort"); const onMagpie = (a) => !!(a.added || a.wired || a.drift); // one whose only control is its launch command (Cursor Private Inference) // has nothing set to tell by, and stays up while it is there const agentUsed = (a) => onMagpie(a) || (!connectable(a) && a.fields.some((f) => f.value && !tweak(f))) || (!!a.launch && !a.fields.length && !a.import); // importButton: the one control of an app magpie is added to by its import // link: magpie, once the app has it, or an offer to add it function importButton(a) { const b = el("button", "field solo import"); b.type = "button"; b.title = a.added ? t("{name} has magpie as a provider · click to add it again", { name: a.name }) : t("Opens {name} to add magpie as a provider — confirm it there", { name: a.name }); b.append(icon("magpie"), el("span", "v" + (a.added ? "" : " empty"), a.added ? "magpie" : t("Add magpie"))); const c = el("span", "chev"); c.append(svg(OUT, 11, 1.6)); b.append(c); b.onclick = (ev) => { ev.stopPropagation(); if (web) location.href = a.import; else api("open", { url: a.import }); }; return b; } // unhid: the agents whose hiding unhideCleared dropped here. A state answered // while that was being saved (a pick's, which is read once the agent's files // are written) can still name them hidden; they stay shown unless hidden by // hand again. const unhid = new Set(); const hiddenIds = () => (state.settings?.agentsHidden || []).filter((id) => !unhid.has(id)); const isHidden = (a) => hiddenIds().includes(a.id); // unhideCleared: a hidden agent whose settings change so that nothing is set // on it any more goes under Not set up, its hiding dropped (Hu9956, #842): // put back to its defaults it kept Hidden and its Show until the switch was // turned on and off. One hidden while nothing was set on it stays hidden // until something on it changes. True when the arrangement is saved, which // renders the list again. const agentSeen = new Map(); // each agent's settings when last rendered const agentSig = (a) => JSON.stringify([!!a.wired, !!a.added, !!a.drift, a.fields.filter((f) => !tweak(f)).map((f) => [f.key, f.value || ""])]); function unhideCleared() { const hidden = hiddenIds(); const cleared = []; for (const a of state.agents || []) { const was = agentSeen.get(a.id), now = agentSig(a); agentSeen.set(a.id, now); if (was !== undefined && was !== now && hidden.includes(a.id) && !agentUsed(a)) cleared.push(a); } if (!cleared.length) return false; for (const a of cleared) unhid.add(a.id); saveArrangement(state.settings?.agentOrder || [], hiddenIds(), []); status(t("{agent} has nothing set on it now · it is under Not set up, no longer hidden", { agent: cleared.map((a) => a.name).join(", ") }), "ok", 4000); return true; } // arrangeAgents: the rows in view, in order, and the folded rest. Folded is // what was hidden by hand, and what nothing is set on — noise in a picker — // unless none is set up yet (a fresh magpie has nothing to show // otherwise). function arrangeAgents() { const s = state.settings || {}; const order = s.agentOrder || [], hidden = new Set(hiddenIds()); const rank = (a) => { const i = order.indexOf(a.id); return i < 0 ? order.length : i; }; const all = state.agents.map((a, i) => [a, i]).sort(([x, i], [y, j]) => rank(x) - rank(y) || i - j).map(([a]) => a); // with 「接入」 there to use, folding starts once one is on magpie, not for a // model an agent not connected has in its own files (#726); with magpie // having nothing to connect, once any is set const counts = all.some(connectable) ? onMagpie : agentUsed; const anyUsed = all.some((a) => !hidden.has(a.id) && counts(a)); // what is set on it alone decides where one not hidden goes: pinned in view // by hand, one cleared stayed up among the set ones with nothing to say why const inView = (a) => !hidden.has(a.id) && (!anyUsed || agentUsed(a)); return { all, shown: all.filter(inView), folded: all.filter((a) => !inView(a)) }; } async function saveArrangement(order, hidden, shown) { const prev = state.settings; state.settings = { ...prev, agentOrder: order, agentsHidden: hidden, agentsShown: shown }; renderAgents(); try { const s = await api("agents/arrange", { order, hidden, shown }); state.settings = { ...state.settings, agentOrder: s.agentOrder || [], agentsHidden: s.agentsHidden || [], agentsShown: s.agentsShown || [] }; } catch (e) { state.settings = prev; renderAgents(); status(e.message, "err"); } } // Bulk visibility changes only magpie's arrangement, never agent configs. let agentsVisibilitySaving = false; // Ignore state reads begun before a completed visibility write. A fresh read // still owns the truth, including changes made by the tray or another window. let agentsVisibilityRevision = 0; function agentsManageButton(list) { if (mode === "panel" || !state.agents.length) return; let bar = $("#agentsManage"); if (!bar) { bar = el("div", "ag-manage-bar"); bar.id = "agentsManage"; const more = list.querySelector(":scope > .agent-more"); if (more) { more.before(bar); bar.append(more); } else list.append(bar); const button = el("button", "ag-manage-button"); button.type = "button"; button.append(svg("M2 3.5h2M6 3.5h8M2 8h2M6 8h8M2 12.5h2M6 12.5h8", 14, 1.5), el("span", "", t("Manage"))); button.setAttribute("aria-label", t("Manage agents")); button.title = t("Manage agents"); button.onclick = openAgentsManager; bar.append(button); } bar.querySelector(".ag-manage-button").disabled = agentsVisibilitySaving; } function openAgentsManager() { if (agentsVisibilitySaving) return; const selected = new Set(); const ed = el("div", "editor ag-manager"); const head = el("div", "ehead"); head.append(el("b", "", t("Manage agents"))); const note = el("p", "lib-confirm", t("Hiding only changes this list, not an agent's connection or settings. Unhidden agents may stay under Not set up.")); const search = el("input", "words ag-manage-search"); search.type = "search"; search.placeholder = t("Search agents…"); search.setAttribute("aria-label", t("Search agents…")); const actions = el("div", "ag-manage-actions"); const rows = el("div", "ag-manage-rows"); const count = el("span", "ag-manage-count"); const result = el("p", "ag-manage-result"); result.setAttribute("role", "status"); const bar = el("div", "bar"); const button = (label, run, parent = actions) => { const b = el("button", "text", t(label)); b.type = "button"; b.onclick = run; parent.append(b); return b; }; const matching = () => arrangeAgents().all.filter((a) => (a.name + " " + a.id).toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())); button("Select search results", () => { matching().forEach((a) => selected.add(a.id)); draw(); }); button("Invert search selection", () => { matching().forEach((a) => selected.has(a.id) ? selected.delete(a.id) : selected.add(a.id)); draw(); }); button("Select unconnected agents", () => { selected.clear(); matching().filter((a) => !onMagpie(a)).forEach((a) => selected.add(a.id)); draw(); }); button("Clear selection", () => { selected.clear(); draw(); }); const hide = button("Hide selected", () => save(true), bar); const show = button("Unhide selected", () => save(false), bar); bar.append(el("span", "grow")); button("Done", () => closeConfirmAsk(), bar); const controls = () => { ed.querySelectorAll("button, input").forEach((b) => { b.disabled = agentsVisibilitySaving; }); hide.disabled ||= ![...selected].some((id) => !hiddenIds().includes(id)); show.disabled ||= ![...selected].some((id) => hiddenIds().includes(id)); count.textContent = t(selected.size === 1 ? "{n} agent selected" : "{n} agents selected", { n: selected.size }); }; // Update status in place: a state refresh must keep search, selection and // keyboard focus on the control the reader is using. ed.refreshAgents = () => { const hidden = new Set(hiddenIds()); for (const row of rows.querySelectorAll(".ag-manage-row")) { row.querySelector(".ag-manage-state").textContent = t(hidden.has(row.dataset.id) ? "Hidden" : "Not hidden"); } controls(); }; function draw() { rows.replaceChildren(); for (const a of matching()) { const row = el("label", "ag-manage-row"); row.dataset.id = a.id; const check = el("input"); check.type = "checkbox"; check.checked = selected.has(a.id); check.setAttribute("aria-label", a.name); check.onchange = () => { check.checked ? selected.add(a.id) : selected.delete(a.id); controls(); }; row.append(check, icon(a.icon), el("span", "ag-manage-name", a.name), el("span", "ag-manage-state", t(isHidden(a) ? "Hidden" : "Not hidden"))); rows.append(row); } if (!rows.children.length) rows.append(el("p", "lib-confirm", t("No matching agents"))); controls(); } async function save(hidden) { if (agentsVisibilitySaving) return; const ids = [...selected].filter((id) => hiddenIds().includes(id) !== hidden); if (!ids.length) return; const next = new Set(hiddenIds()); ids.forEach((id) => hidden ? next.add(id) : next.delete(id)); agentsVisibilitySaving = true; controls(); result.textContent = ""; agentsManageButton($("#agents")); try { // Commit once, then publish only the arrangement returned by the server. // A failed save leaves both the visible list and selection unchanged. const s = await api("agents/arrange", { order: state.settings?.agentOrder || [], hidden: [...next], shown: state.settings?.agentsShown || [], }); if (hidden) ids.forEach((id) => unhid.delete(id)); agentsVisibilityRevision++; state.settings = { ...state.settings, agentOrder: s.agentOrder || [], agentsHidden: s.agentsHidden || [], agentsShown: s.agentsShown || [] }; selected.clear(); result.textContent = hidden ? t(ids.length === 1 ? "{n} agent hidden" : "{n} agents hidden", { n: ids.length }) : t(ids.length === 1 ? "{n} agent unhidden" : "{n} agents unhidden", { n: ids.length }); renderAgents(); } catch (e) { result.textContent = e.message; } finally { agentsVisibilitySaving = false; agentsManageButton($("#agents")); draw(); } } search.oninput = draw; ed.append(head, note, search, actions, count, rows, result, bar); draw(); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); } // moveAgent puts the agent at index `to` among the rows in view; the folded // ones keep their places after them. function moveAgent(id, to) { const { shown, folded } = arrangeAgents(); const ids = shown.map((a) => a.id); const from = ids.indexOf(id); if (from < 0 || to < 0 || to >= ids.length || to === from) return; ids.splice(to, 0, ...ids.splice(from, 1)); const s = state.settings || {}; saveArrangement([...ids, ...folded.map((a) => a.id)], hiddenIds(), []); } function setAgentHidden(a, hide) { const s = state.settings || {}; const { all } = arrangeAgents(); let hidden = hiddenIds().filter((x) => x !== a.id); if (hide) { hidden.push(a.id); unhid.delete(a.id); } // the rows that change go on the panel's edge, as the fold does agentsGlide = hide ? ROLLUP : UNROLL; saveArrangement(all.map((x) => x.id), hidden, []); // hidden, it says where it went, since the row goes out of sight; shown // with nothing set on it, it stays folded under Not set up, and says why: // one with a switch until it is connected const still = !hide && arrangeAgents().folded.includes(a); const until = connectable(a) ? "{agent} is no longer hidden · it stays under Not set up until it is connected" : "{agent} is no longer hidden · it stays under Not set up until a model is picked for it"; status(t(hide ? "{agent} hidden · find it under Hidden at the bottom" : still ? until : "{agent} shown", { agent: a.name }), "ok", hide || still ? 4000 : 1800); } const ALT = /^Mac/.test(navigator.platform) ? "⌥" : "Alt+"; const SHIFT = /^Mac/.test(navigator.platform) ? "⇧" : "Shift+"; // the arrows of a row menu's Move up and Move down (agents, routing groups) const MOVE_UP = "M8 12.5v-9M4 7.25l4-3.75 4 3.75", MOVE_DOWN = "M8 3.5v9M4 8.75l4 3.75 4-3.75"; // Move to Top and Move to Bottom: the arrow to a bar (a provider row's menu) const MOVE_TOP = "M8 13v-7.5M4.5 9l3.5-3.5 3.5 3.5M3.5 2.75h9", MOVE_BOTTOM = "M8 3v7.5M4.5 7l3.5 3.5 3.5-3.5M3.5 13.25h9"; const EYE_OFF = "M6.6 3.7A6.9 6.9 0 0 1 8 3.5c3.75 0 6.25 4.5 6.25 4.5a11 11 0 0 1-1.5 2M4.4 4.4C2.7 5.55 1.75 8 1.75 8S4.25 12.5 8 12.5c1.2 0 2.25-.45 3.1-1.05M6.75 6.75a1.75 1.75 0 0 0 2.5 2.5M2 2l12 12"; const EYE = "M1.75 8S4.25 3.5 8 3.5 14.25 8 14.25 8 11.75 12.5 8 12.5 1.75 8 1.75 8ZM8 9.75a1.75 1.75 0 1 0 0-3.5 1.75 1.75 0 0 0 0 3.5Z"; // agentHandle is the row's logo, which is also its handle: drag it to move // the row, click it (or right-click the row) for Move up, Move down and // Hide; Alt+↑/↓ moves it from the keyboard. The grip that says so is drawn // in the row's margin on hover (app.css), not over the logo. function agentHandle(a, row, inFold) { const b = el("button", "ag-handle"); b.type = "button"; b.setAttribute("aria-label", t("Arrange {agent}", { agent: a.name })); b.setAttribute("aria-haspopup", "menu"); b.title = inFold ? t(isHidden(a) ? "Show {agent}" : "Hide {agent}", { agent: a.name }) : t(a.wired ? "Drag to reorder · click to move, hide or disconnect from magpie" : "Drag to reorder · click to move or hide"); b.append(icon(a.icon)); b.onkeydown = (e) => { if (inFold || !e.altKey || (e.key !== "ArrowUp" && e.key !== "ArrowDown")) return; e.preventDefault(); const { shown } = arrangeAgents(); const i = shown.findIndex((x) => x.id === a.id); moveAgent(a.id, i + (e.key === "ArrowUp" ? -1 : 1)); // the rows were drawn anew: keep the keyboard on this one $(`#agents .row.agent[data-id="${CSS.escape(a.id)}"] .ag-handle`)?.focus(); }; b.onclick = (e) => { if (!b.dataset.dragged) openAgentMenu(b, a, inFold); delete b.dataset.dragged; }; if (!inFold) b.onpointerdown = (e) => dragAgent(e, b, row); return b; } // dragAgent moves a row in view up and down the list with the pointer; the // others make room as it passes, and letting go keeps the new order. function dragAgent(e, handle, row) { if (agentArranging) return; const list = $("#agents"); agentArranging = dragRows(e, handle, row, list, [...list.children].filter((r) => r.classList.contains("agent")), (to) => moveAgent(row.dataset.id, to), closeAgentMenu, () => { agentArranging = false; if (agentRenderPending) { agentRenderPending = false; renderAgents(); } }); } // Shared pointer sorter. Measure once, move only transforms on animation frames, // and commit once on release. No DOM rebuilds or network calls during a drag. // The same primitive serves agent handles and handle-free account rows. function dragRows(e, handle, row, list, rows, commit, start = () => {}, idle = () => {}) { if (e.button !== 0 || e.isPrimary === false || rows.length < 2) return false; const from = rows.indexOf(row); if (from < 0) return false; const rects = rows.map((r) => r.getBoundingClientRect()); const tops = rects.map((r) => r.top), heights = rects.map((r) => r.height), h = heights[from]; let scroll = list.parentElement; while (scroll && !/(auto|scroll)/.test(getComputedStyle(scroll).overflowY)) scroll = scroll.parentElement; scroll ||= document.scrollingElement; const bounds = scroll.getBoundingClientRect(), scroll0 = scroll.scrollTop; let dragging = false, ended = false, to = from, y = e.clientY, frame = 0, lastTime = 0; const y0 = y, pointer = e.pointerId; const paint = (time) => { frame = 0; if (!row.isConnected) return finish(false); if (!dragging) return; const dt = Math.min(32, lastTime ? time - lastTime : 16); lastTime = time; const edge = 36; const speed = y < bounds.top + edge ? -Math.min(1, (bounds.top + edge - y) / edge) : y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0; if (speed) scroll.scrollTop += speed * dt * .6; const dy = y - y0 + scroll.scrollTop - scroll0; const lo = tops[0] - tops[from], hi = tops.at(-1) + heights.at(-1) - h - tops[from]; const d = Math.max(lo, Math.min(hi, dy)); row.style.transform = `translateY(${d}px)`; const mid = tops[from] + d + h / 2; to = from; if (d > 0) { while (to < rows.length - 1 && mid >= tops[to + 1] + heights[to + 1] / 2) to++; } else { while (to > 0 && mid <= tops[to - 1] + heights[to - 1] / 2) to--; } // held at the top or the foot it goes there, though the first row is a // pixel shorter than the rest (they have a border over them) and its // middle was out of reach (#499) if (d <= lo && from > 0) to = 0; else if (d >= hi && from < rows.length - 1) to = rows.length - 1; rows.forEach((r, i) => { if (i === from) return; const shift = i > from && i <= to ? -h : i < from && i >= to ? h : 0; r.style.transform = shift ? `translateY(${shift}px)` : ""; }); if (speed) frame = requestAnimationFrame(paint); }; const move = (ev) => { if (ev.pointerId !== pointer) return; if (!row.isConnected || !handle.isConnected) return finish(false, ev); y = ev.clientY; if (!dragging) { if (Math.abs(y - y0) < 4) return; dragging = true; handle.dataset.dragged = "1"; start(); list.classList.add("sorting"); row.classList.add("dragging"); getSelection()?.removeAllRanges(); handle.setPointerCapture(pointer); } ev.preventDefault(); if (!frame) frame = requestAnimationFrame(paint); }; const finish = (save, ev) => { if (ended || (ev?.pointerId != null && ev.pointerId !== pointer)) return; if (save && dragging && ev) { y = ev.clientY; cancelAnimationFrame(frame); paint(performance.now()); } if (ended) return; ended = true; cancelAnimationFrame(frame); document.removeEventListener("pointermove", move); document.removeEventListener("pointerup", up); document.removeEventListener("pointercancel", cancel); document.removeEventListener("keydown", keys, true); handle.removeEventListener("lostpointercapture", cancel); removeEventListener("blur", cancel); removeEventListener("resize", cancel); if (handle.hasPointerCapture(pointer)) handle.releasePointerCapture(pointer); list.classList.remove("sorting"); row.classList.remove("dragging"); rows.forEach((r) => { r.style.transform = ""; }); if (save && dragging && to !== from) commit(to); idle(); // The click dispatched after pointerup must not rename, toggle or remove. setTimeout(() => delete handle.dataset.dragged, 0); }; const up = (ev) => finish(true, ev); const cancel = (ev) => finish(false, ev); const keys = (ev) => { if (ev.key === "Escape") { ev.preventDefault(); ev.stopImmediatePropagation(); finish(false); } }; document.addEventListener("pointermove", move, { passive: false }); document.addEventListener("pointerup", up); document.addEventListener("pointercancel", cancel); document.addEventListener("keydown", keys, true); handle.addEventListener("lostpointercapture", cancel); addEventListener("blur", cancel); addEventListener("resize", cancel); return true; } // dragCards is dragRows for cards laid out in a grid: the card follows the // pointer both ways, the slot nearest its middle is where it goes, and the // cards between move a slot over to make room. function dragCards(e, handle, card, list, cards, commit, idle = () => {}) { if (e.button !== 0 || e.isPrimary === false || cards.length < 2) return false; const from = cards.indexOf(card); if (from < 0) return false; const rects = cards.map((c) => c.getBoundingClientRect()); let scroll = list.parentElement; while (scroll && !/(auto|scroll)/.test(getComputedStyle(scroll).overflowY)) scroll = scroll.parentElement; scroll ||= document.scrollingElement; const bounds = scroll.getBoundingClientRect(), scroll0 = scroll.scrollTop; let dragging = false, ended = false, to = from, x = e.clientX, y = e.clientY, frame = 0, lastTime = 0; const x0 = x, y0 = y, pointer = e.pointerId; const r0 = rects[from]; const paint = (time) => { frame = 0; if (!card.isConnected) return finish(false); if (!dragging) return; const dt = Math.min(32, lastTime ? time - lastTime : 16); lastTime = time; const edge = 36; const speed = y < bounds.top + edge ? -Math.min(1, (bounds.top + edge - y) / edge) : y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0; if (speed) scroll.scrollTop += speed * dt * .6; const dx = x - x0, dy = y - y0 + scroll.scrollTop - scroll0; card.style.transform = `translate(${dx}px, ${dy}px)`; const cx = r0.left + r0.width / 2 + dx, cy = r0.top + r0.height / 2 + dy; let best = Infinity; rects.forEach((r, i) => { const d = (cx - r.left - r.width / 2) ** 2 + (cy - r.top - r.height / 2) ** 2; if (d < best) { best = d; to = i; } }); cards.forEach((c, i) => { if (i === from) return; const j = i > from && i <= to ? i - 1 : i < from && i >= to ? i + 1 : i; c.style.transform = j !== i ? `translate(${rects[j].left - rects[i].left}px, ${rects[j].top - rects[i].top}px)` : ""; }); if (speed) frame = requestAnimationFrame(paint); }; const move = (ev) => { if (ev.pointerId !== pointer) return; if (!card.isConnected || !handle.isConnected) return finish(false, ev); x = ev.clientX; y = ev.clientY; if (!dragging) { if (Math.hypot(x - x0, y - y0) < 4) return; dragging = true; handle.dataset.dragged = "1"; list.classList.add("sorting"); card.classList.add("dragging"); getSelection()?.removeAllRanges(); handle.setPointerCapture(pointer); } ev.preventDefault(); if (!frame) frame = requestAnimationFrame(paint); }; const finish = (save, ev) => { if (ended || (ev?.pointerId != null && ev.pointerId !== pointer)) return; if (save && dragging && ev) { x = ev.clientX; y = ev.clientY; cancelAnimationFrame(frame); paint(performance.now()); } if (ended) return; ended = true; cancelAnimationFrame(frame); document.removeEventListener("pointermove", move); document.removeEventListener("pointerup", up); document.removeEventListener("pointercancel", cancel); document.removeEventListener("keydown", keys, true); handle.removeEventListener("lostpointercapture", cancel); removeEventListener("blur", cancel); removeEventListener("resize", cancel); if (handle.hasPointerCapture(pointer)) handle.releasePointerCapture(pointer); list.classList.remove("sorting"); card.classList.remove("dragging"); cards.forEach((c) => { c.style.transform = ""; }); if (save && dragging && to !== from) commit(to); idle(); setTimeout(() => delete handle.dataset.dragged, 0); }; const up = (ev) => finish(true, ev); const cancel = (ev) => finish(false, ev); const keys = (ev) => { if (ev.key === "Escape") { ev.preventDefault(); ev.stopImmediatePropagation(); finish(false); } }; document.addEventListener("pointermove", move, { passive: false }); document.addEventListener("pointerup", up); document.addEventListener("pointercancel", cancel); document.addEventListener("keydown", keys, true); handle.addEventListener("lostpointercapture", cancel); addEventListener("blur", cancel); addEventListener("resize", cancel); return true; } // ---------- an agent's model list ---------- // CODEX_APP_MENU is how many models the Codex app's model menu reaches: it // asks Codex's app-server for model/list with limit 100 and never for the // next page (ChatGPT.app 26.930), so a model past them can't be picked // there; the Codex CLI's /model asks for every one (#1262). const CODEX_APP_MENU = 100; // modelsEntry: the line under an agent's name counting the models its // lists show ("All 41 models", or "Showing 5 / 32 models"); it opens the // list to take models out of them and put them back. function modelsEntry(a) { const b = el("button", "ag-models"); b.type = "button"; fillModelsEntry(b, a); b.onclick = (ev) => openAgentModels(a, b, ev); if (holdAgentModels(a, b) && agentModels.count) { a.models = agentModels.count; fillModelsEntry(b, a); } return b; } function fillModelsEntry(b, a) { const c = a.models; b.replaceChildren(); // the words in one box, so the flex line keeps the spaces round the number const words = el("span"); if (c.shown >= c.listed) words.append(t("All {n} models", { n: c.listed })); else { const [pre, post] = t("Showing {shown} / {listed} models", { listed: c.listed }).split("{shown}"); words.append(pre, el("b", "", String(c.shown)), post || ""); } b.append(words); const ch = el("span", "chev"); ch.append(svg(CHEV_R, 10, 1.6)); b.append(ch); b.title = t("Pick which models {agent} lists", { agent: a.name }); } const ctxShort = (n) => !n ? "" : n >= 1e6 ? (n % 1e6 ? (n / 1e6).toFixed(1) : n / 1e6) + "M" : Math.round(n / 1e3) + "K"; let agentModels = null; // the list being fetched, before its box is up: a second click on the line // takes it back, as it would close the box, and another open or a close // supersedes it — each fetch that came back drew a box of its own, and the // one agentModels no longer held stayed on the screen, nothing closing it let agentModelsLoading = null; function closeAgentModels() { agentModelsLoading?.drop(); const m = agentModels; if (!m) return; agentModels = null; m.anchor.classList.remove("open"); popGhost(m.box); m.box.remove(); document.removeEventListener("mousedown", m.outside, true); document.removeEventListener("keydown", m.keys, true); document.removeEventListener("scroll", m.scrolled, true); removeEventListener("resize", closeAgentModels); if (!m.changed) return; // its pickers drop what was taken out at once, so the one opened next // (the mousedown on it is what closed the list) has it gone (#927); what // was put back comes with the state if (m.hidden) for (const f of m.a.fields || []) f.options = f.options.filter((o) => !o.ref || !m.hidden.has(o.ref) || o.value === f.value); // the agent's own, left out, go as the server leaves them out // (agent.Picks): from a picker of magpie's models, but its default and // the one it is set to if (m.ownHidden) { for (const f of m.a.fields || []) { if (f.options.some((o) => o.ref)) f.options = f.options.filter((o) => o.ref || !o.value || o.value === f.value); } } // the agents' pickers list what's left once the writes are in m.saving.then(async () => { state = await api("state"); renderAgents(); }).catch(() => {}); } // holdAgentModels: a button that opens an agent's list, drawn again while // that list is open or still loading. The list stays, held to the new // button: one loading came up at the old one, gone from the page, so a // redraw while it loaded (a refresh, or the state re-read after a changed // list) dropped the click. Says whether the list is open. function holdAgentModels(a, b) { if (agentModelsLoading?.id === a.id) agentModelsLoading.anchor = b; if (agentModels?.a.id !== a.id) return false; b.classList.add("open"); agentModels.anchor = b; return true; } async function openAgentModels(a, anchor, ev) { ev.stopPropagation(); const again = agentModels?.a.id === a.id || agentModelsLoading?.id === a.id; closeAgentModels(); closePicker(); if (again) return; // a click elsewhere while it loads is one away from it, as it is once open const loading = agentModelsLoading = { id: a.id, anchor, away: (e) => { if (!loading.anchor.contains(e.target)) loading.drop(); }, drop() { if (agentModelsLoading === loading) agentModelsLoading = null; document.removeEventListener("mousedown", loading.away, true); }, }; document.addEventListener("mousedown", loading.away, true); // every agent's list goes in the order dragged here (Codex's, #855; the // others', #1052) // only: the agent is shown only the models ticked for it, a new one off // until it is ticked (#1337), not every one not taken out // own: its pickers offer models the agent reaches on its own beside // magpie's (DeepSeek Harness's), which ownHidden leaves out (#1642) let models, ordered = false, only = false, own = false, ownHidden = false; try { ({ models, ordered, only = false, own = false, ownHidden = false } = await api("agent-models/" + encodeURIComponent(a.id))); } catch (e) { if (agentModelsLoading === loading) { loading.drop(); status(e.message, "err"); } return; } if (agentModelsLoading !== loading) return; loading.drop(); // the button as it is drawn now anchor = loading.anchor; if (!anchor.isConnected) return; const box = el("div", "pop am-pop"); box.setAttribute("role", "dialog"); box.setAttribute("aria-label", t("{agent}'s model list", { agent: a.name })); const head = el("div", "am-head"); head.append(el("div", "am-t", t("{agent}'s model list", { agent: a.name })), el("div", "am-d", t("Models turned off don't show in {agent}'s model picker; other agents can still use them.", { agent: a.name }))); // the models the agent reaches itself, not through magpie, shown in its // picker beside magpie's or left out (MizuIro-H, #1642): not in the list // below, which is magpie's catalog, so a switch of their own const ownBox = el("label", "am-own"); const ownSw = el("button", "lib-switch use-credits" + (ownHidden ? "" : " on")); ownSw.type = "button"; ownSw.setAttribute("role", "switch"); ownSw.setAttribute("aria-checked", String(!ownHidden)); ownSw.append(el("i")); const ownSay = el("span", "", t("Show {agent}'s own models", { agent: a.name })); ownSw.setAttribute("aria-label", ownSay.textContent); ownBox.title = t("The models {agent} reaches itself, not through magpie. Off: its model picker offers magpie's alone; the one it is set to stays", { agent: a.name }); ownBox.append(ownSw, ownSay); if (own) head.append(ownBox); const tools = el("div", "am-tools"); const search = el("label", "am-search"); search.innerHTML = ''; const q = el("input"); q.type = "text"; q.spellcheck = false; q.autocomplete = "off"; q.placeholder = t("Search models"); search.append(q); const seg = el("div", "am-seg"); const segAll = el("button", "on", t("All")), segOn = el("button", "", t("Shown")), segOrder = el("button", "", t("Order")); segAll.type = segOn.type = segOrder.type = "button"; seg.append(segAll, segOn, segOrder); tools.append(search, seg); const list = el("div", "am-list"); const foot = el("div", "am-foot"); // every one at once, the model in use aside const hideAll = el("button", "am-reset am-hide", t("Hide all")); const reset = el("button", "am-reset", t("Show all")); hideAll.type = reset.type = "button"; const unorder = el("button", "am-reset", t("Default order")); unorder.type = "button"; const footNote = el("span", ""); // whether a model that comes later is shown, or stays off until ticked: // the agent's own switch, not every agent's (nianlee-official, #1337) const onlyBox = el("label", "am-only"); const onlySw = el("button", "lib-switch use-credits" + (only ? " on" : "")); onlySw.type = "button"; onlySw.setAttribute("role", "switch"); onlySw.setAttribute("aria-checked", String(only)); onlySw.append(el("i")); const onlySay = el("span", "", t("Only models I pick")); onlySw.setAttribute("aria-label", onlySay.textContent); onlyBox.title = t("Off: new models are shown. On: only the models ticked here are shown, and a model added later, of any provider, stays off until you tick it"); onlyBox.append(onlySw, onlySay); // takes back a first click on Hide all or Show all (twice, below) let disarm = () => {}; foot.append(onlyBox, el("span", "sp"), hideAll, el("span", "am-dot", "·"), reset); // groups as the catalog has them, routing groups first; a long one // starts folded, unless the agent is set to a model in it const groups = []; const regroup = () => { groups.length = 0; for (const m of models) { let g = groups.find((x) => x.name === m.group); if (!g) groups.push(g = { name: m.group, icon: m.icon, models: [] }); g.models.push(m); } groups.sort((x, y) => (y.name === ROUTING_GROUPS) - (x.name === ROUTING_GROUPS)); }; regroup(); const shut = new Set(groups.filter((g) => groups.length > 1 && g.models.length > 8 && !g.models.some((m) => m.inUse)).map((g) => g.name)); // with a few providers, a rail of them down the left: one picked shows // its models alone, so a long list is one click away rather than a // scroll down past the others (蓝猫 on Discord); a search looks in all const railed = groups.length > 2 && innerWidth >= 600; let pick = ""; const rail = el("div", "am-rail"); if (railed) { const body = el("div", "am-body"); body.append(rail, list); box.classList.add("railed"); box.append(head, tools, body, foot); } else box.append(head, tools, list, foot); const drawRail = () => { if (!railed) return; const top = rail.scrollTop; rail.replaceChildren(); const item = (name, label, lead, on, n) => { const b = el("button", "am-ri" + (pick === name ? " on" : "")); b.type = "button"; b.setAttribute("aria-pressed", String(pick === name)); b.append(lead, el("span", "rn", label), el("span", "c", `${on}/${n}`)); b.title = label; b.onclick = () => { pick = name; q.value = ""; list.scrollTop = 0; draw(); }; rail.append(b); }; const all = el("span", "ic"); all.append(svg("M3 4.5h10M3 8h10M3 11.5h10", 14, 1.5)); item("", t("All providers"), all, models.filter((m) => !m.hidden).length, models.length); for (const g of groups) { const route = g.name === ROUTING_GROUPS; item(g.name, route ? t(g.name) : g.name, route ? svg(FAN, 14, 1.5) : icon(g.icon || "generic"), g.models.filter((m) => !m.hidden).length, g.models.length); } rail.scrollTop = top; }; // under "Shown", one just turned off stays until the view changes let onlyShown = false, kept = new Set(); // under "Order", the models shown, as the agent lists them let ordering = false; const me = agentModels = { a, anchor, box, saving: Promise.resolve(), changed: false }; const save = () => { me.changed = true; const hidden = models.filter((m) => m.hidden).map((m) => m.id); me.hidden = new Set(hidden); // by whose they are, as the state counts them, for a connected row's chips const by = []; for (const m of models) { if (m.hidden) continue; let g = by.find((x) => x.name === m.group); if (!g) by.push(g = m.group === ROUTING_GROUPS ? { name: m.group, icons: m.icons, n: 0 } : { name: m.group, icon: m.icon, n: 0 }); g.n++; } const names = models.filter((m) => !m.hidden).slice(0, 3).map((m) => m.name); const count = { shown: models.length - hidden.length, listed: models.length, by, names }; me.count = a.models = count; // the line under the name counts them, a menu's button names them; an // opened row is drawn again if (me.anchor.classList.contains("ag-models")) fillModelsEntry(me.anchor, a); else if (me.anchor.classList.contains("ag-menu")) { fillMenuButton(me.anchor, a); const row = me.anchor.closest(".row.agent"); for (const said of row?.querySelectorAll(".ag-st.on .ag-st-t, .ag-conn-said") || []) said.textContent = connectSaid(a); row?.querySelector(".ag-sum .vt")?.replaceChildren(menuSaid(count)); } else renderAgents(); // shown only its picks, the ones ticked are what is sent: a model that // came since the list was opened isn't among them, so it stays off const body = only ? { shown: models.filter((m) => !m.hidden).map((m) => m.id) } : { hidden }; me.saving = me.saving.then(() => api("agent-models/" + encodeURIComponent(a.id), body)) .catch((e) => status(e.message, "err")); }; onlySw.onclick = (e) => { e.preventDefault(); disarm(); only = !only; onlySw.classList.toggle("on", only); onlySw.setAttribute("aria-checked", String(only)); me.changed = true; // the models shown stay as they are, so the list drawn needs nothing // new; what comes back is the same, but for one added meanwhile const want = only; me.saving = me.saving.then(() => api("agent-models/" + encodeURIComponent(a.id), { only: want })) .catch((err) => { status(err.message, "err"); if (only !== want) return; only = !want; onlySw.classList.toggle("on", only); onlySw.setAttribute("aria-checked", String(only)); }); }; ownSw.onclick = (e) => { e.preventDefault(); disarm(); ownHidden = !ownHidden; ownSw.classList.toggle("on", !ownHidden); ownSw.setAttribute("aria-checked", String(!ownHidden)); me.changed = true; me.ownHidden = ownHidden; const want = ownHidden; me.saving = me.saving.then(() => api("agent-models/" + encodeURIComponent(a.id), { ownHidden: want })) .catch((err) => { status(err.message, "err"); if (ownHidden !== want) return; me.ownHidden = ownHidden = !want; ownSw.classList.toggle("on", !ownHidden); ownSw.setAttribute("aria-checked", String(!ownHidden)); }); }; // the shown models as the agent lists them: as dragged, or, before any // drag, Codex's own (a ChatGPT account's) ahead of magpie's, as its // /model has them const inOrder = () => { const shown = models.filter((m) => !m.hidden); return ordered ? shown : [...shown.filter((m) => m.own), ...shown.filter((m) => !m.own)]; }; const saveOrder = (ids) => { me.changed = true; me.saving = me.saving.then(() => api("agent-models/" + encodeURIComponent(a.id), { order: ids })) .catch((e) => status(e.message, "err")); return me.saving; }; const moveTo = (id, to) => { const shown = inOrder(); const from = shown.findIndex((m) => m.id === id); to = Math.max(0, Math.min(shown.length - 1, to)); if (from < 0 || to === from) return false; shown.splice(to, 0, ...shown.splice(from, 1)); // the hidden after them, as they were; the groups keep the new order models.splice(0, models.length, ...shown, ...models.filter((m) => m.hidden)); for (const g of groups) g.models.sort((x, y) => models.indexOf(x) - models.indexOf(y)); ordered = true; saveOrder(shown.map((m) => m.id)); return true; }; const drawOrder = () => { const top = list.scrollTop; list.replaceChildren(); const body = el("div", "am-rows am-order"); body.setAttribute("role", "list"); const shown = inOrder(); shown.forEach((m, i) => { const r = el("div", "am-mr am-or"); r.tabIndex = 0; r.dataset.id = m.id; r.setAttribute("role", "listitem"); r.title = t("Drag to move · Alt+↑/↓ from the keyboard"); const lg = m.group === ROUTING_GROUPS ? svg(FAN, 14, 1.5) : icon(m.logo || m.icon || "generic"); lg.classList.add("lg"); r.append(el("span", "grip"), el("span", "ix", String(i + 1)), lg, el("span", "n", m.name), el("span", "x", m.group === ROUTING_GROUPS ? t(m.group) : m.group)); r.onkeydown = (e) => { if (!e.altKey || (e.key !== "ArrowUp" && e.key !== "ArrowDown")) return; e.preventDefault(); if (!moveTo(m.id, i + (e.key === "ArrowUp" ? -1 : 1))) return; draw(); list.querySelector(`.am-or[data-id="${CSS.escape(m.id)}"]`)?.focus({ preventScroll: true }); }; r.onpointerdown = (e) => dragRows(e, r, r, body, [...body.children], (to) => { moveTo(m.id, to); draw(); }); body.append(r); }); list.append(body); if (!shown.length) list.append(el("div", "am-none", t("No matches."))); list.scrollTop = top; unorder.disabled = !ordered; }; const draw = () => { if (ordering) return drawOrder(); const top = list.scrollTop; list.replaceChildren(); const words = q.value.trim().toLowerCase(); drawRail(); for (const g of groups) { if (pick && !words && g.name !== pick) continue; const rows = g.models.filter((m) => (!onlyShown || !m.hidden || kept.has(m.id)) && (!words || [m.name, m.id, g.name].some((s) => s.toLowerCase().includes(words)))); if (!rows.length) continue; const on = g.models.filter((m) => !m.hidden).length; const folded = !words && !pick && shut.has(g.name); const sec = el("section", "am-g" + (folded ? " shut" : "") + (g.name === ROUTING_GROUPS ? " routes" : "")); const gh = el("div", "am-gh"); const fold = el("button", "am-fold"); fold.type = "button"; fold.setAttribute("aria-expanded", String(!folded)); const tw = el("span", "tw"); tw.append(svg(CHEV, 10, 1.7)); fold.append(tw, g.name === ROUTING_GROUPS ? svg(FAN, 14, 1.5) : icon(g.icon || "generic"), el("span", "gn", g.name === ROUTING_GROUPS ? t(g.name) : g.name), el("span", "c", `${on} / ${g.models.length}`)); fold.onclick = () => { shut.has(g.name) ? shut.delete(g.name) : shut.add(g.name); draw(); }; const free = g.models.filter((m) => !m.inUse); const allOn = free.every((m) => !m.hidden); const all = el("button", "am-all", allOn ? t("Hide all") : t("Show all")); all.type = "button"; all.hidden = !free.length; all.onclick = () => { for (const m of free) { m.hidden = allOn; if (allOn) kept.add(m.id); } save(); draw(); }; gh.append(fold, all); sec.append(gh); if (!folded) { const body = el("div", "am-rows"); for (const m of rows) { const r = el("button", "am-mr" + (m.hidden ? " off" : "") + (m.inUse ? " lock" : "")); r.type = "button"; r.setAttribute("role", "menuitemcheckbox"); r.setAttribute("aria-checked", String(!m.hidden)); r.title = m.inUse ? t("{agent} is set to it, so it stays", { agent: a.name }) : m.id; const n = el("span", "n", m.name); if (m.inUse) n.append(el("span", "am-tag", t("Current"))); const ck = el("span", "ck"); if (!m.hidden) ck.append(svg("m3.5 8.5 3 3 6-7", 12, 1.9)); // a routing group: its providers' icons stacked, as everywhere // else, a lone one in a disc like them; a model: its maker's // logo, or an empty slot, so the names line up const route = g.name === ROUTING_GROUPS; let lg; if (route && m.icons?.length > 1) lg = stackIcon(m.icons); else if (route && m.icons?.length) { const d = el("span", "disc"); d.append(icon(m.icons[0] || "generic")); lg = el("span", "ic-stack"); lg.append(d); } else lg = m.logo && !route ? icon(m.logo) : el("span", "ic"); if (route && !m.icons?.length) lg.append(svg(FAN, 14, 1.5)); lg.classList.add("lg"); r.append(lg, n, el("span", "x", ctxShort(m.context)), ck); if (m.inUse) r.setAttribute("aria-disabled", "true"); else r.onclick = () => { m.hidden = !m.hidden; if (m.hidden) kept.add(m.id); save(); draw(); }; body.append(r); } sec.append(body); } list.append(sec); } if (!list.childNodes.length) list.append(el("div", "am-none", t("No matches."))); list.scrollTop = top; // anything else done in the list takes back a first click there disarm(); reset.disabled = !models.some((m) => m.hidden); hideAll.disabled = !models.some((m) => !m.hidden && !m.inUse); }; q.oninput = () => { list.scrollTop = 0; draw(); }; const view = (shown, order = false) => { onlyShown = shown; ordering = order; kept = new Set(); segAll.classList.toggle("on", !shown && !order); segOn.classList.toggle("on", shown && !order); segOrder.classList.toggle("on", order); // ordering is of the whole list: no search, no provider picked, and the // foot puts magpie's own order back rather than showing or hiding box.classList.toggle("ordering", order); // Codex's /model, in WSL too, lists them as handed (#855); another // agent is handed them in it, and one that sorts its own menu may sort // them again footNote.textContent = !order ? "" : a.id.split("@wsl:")[0] === "codex" ? t("Drag to put them in the order {agent} lists them; new models go last", { agent: a.name }) : t("Drag to put them in the order magpie hands them to {agent}; new models go last", { agent: a.name }); if (order) foot.replaceChildren(footNote, el("span", "sp"), unorder); else foot.replaceChildren(onlyBox, el("span", "sp"), hideAll, el("span", "am-dot", "·"), reset); list.scrollTop = 0; draw(); }; segAll.onclick = () => view(false); segOn.onclick = () => view(true); segOrder.onclick = () => view(false, true); unorder.onclick = async () => { unorder.disabled = true; const r = await saveOrder([]); ordered = false; // magpie's own order, as the list comes back if (r?.models) { const was = new Map(models.map((m) => [m.id, m])); models.splice(0, models.length, ...r.models.map((m) => was.get(m.id) || m)); regroup(); } draw(); }; // every model of every provider at once is a lot to pick again by hand, // and with one provider picked on the left it read as that one's (#920): // a first click says how many, of every provider, and a second does it const twice = (b, armed, go) => { b.onclick = () => { if (!b.dataset.armed) { disarm(); b.dataset.armed = "1"; b.textContent = armed(); onlyBox.hidden = true; b._t = setTimeout(disarm, 4000); return; } disarm(); go(); save(); draw(); }; }; disarm = () => { for (const [b, label] of [[hideAll, t("Hide all")], [reset, t("Show all")]]) { clearTimeout(b._t); if (!b.dataset.armed) continue; delete b.dataset.armed; b.textContent = label; } onlyBox.hidden = false; }; twice(reset, () => t("Show {n} hidden, of every provider? Click again", { n: models.filter((m) => m.hidden).length }), () => { for (const m of models) m.hidden = false; }); twice(hideAll, () => t("Hide {n}, of every provider? Click again", { n: models.filter((m) => !m.inUse && !m.hidden).length }), () => { for (const m of models) if (!m.inUse && !m.hidden) { m.hidden = true; kept.add(m.id); } }); draw(); document.body.append(box); // under the line, or over it where there's no room; the list scrolls const r = anchor.getBoundingClientRect(), pad = 8, top = popTop(pad); const w = Math.min(railed ? 580 : 380, innerWidth - pad * 2); box.style.width = w + "px"; const x = Math.max(pad, Math.min(r.left - 10, innerWidth - w - pad)); box.style.left = x + "px"; box.style.setProperty("--ox", Math.max(18, Math.min(w - 18, r.left + Math.min(r.width, 60) / 2 - x)) + "px"); const below = innerHeight - r.bottom - 8 - pad, above = r.top - 8 - top; const want = Math.min(560, box.scrollHeight); if (want > below && above > below) { box.classList.add("up"); box.style.bottom = innerHeight - r.top + 8 + "px"; box.style.maxHeight = Math.min(560, above) + "px"; } else { box.style.top = r.bottom + 8 + "px"; box.style.maxHeight = Math.min(560, below) + "px"; } anchor.classList.add("open"); me.outside = (e) => { if (!box.contains(e.target) && !me.anchor.contains(e.target)) closeAgentModels(); }; me.keys = (e) => { if (e.key !== "Escape") return; e.preventDefault(); e.stopPropagation(); closeAgentModels(); me.anchor.focus({ preventScroll: true }); }; me.scrolled = (e) => { if (scrollCloses(box, e)) closeAgentModels(); }; document.addEventListener("mousedown", me.outside, true); document.addEventListener("keydown", me.keys, true); document.addEventListener("scroll", me.scrolled, true); addEventListener("resize", closeAgentModels); q.focus({ preventScroll: true }); } let agentMenu = null; function closeAgentMenu() { if (!agentMenu) return; agentMenu.anchor.classList.remove("open"); agentMenu.box.remove(); document.removeEventListener("mousedown", agentMenu.outside, true); document.removeEventListener("keydown", agentMenu.keys, true); document.removeEventListener("scroll", agentMenu.scroll, true); removeEventListener("resize", closeAgentMenu); agentMenu = null; } function openAgentMenu(anchor, a, inFold) { if (!anchor) return; const again = agentMenu?.anchor === anchor; closeAgentMenu(); if (again) return; const { shown } = arrangeAgents(); const i = shown.findIndex((x) => x.id === a.id); const reapply = a.drift || a.fields.some((f) => optionFor(f, f.value)?.ref); const acts = inFold && isHidden(a) ? [{ name: "Show", icon: EYE, run: () => setAgentHidden(a, false) }] : inFold ? [{ name: "Hide", icon: EYE_OFF, run: () => setAgentHidden(a, true) }] : [ { name: "Move up", icon: MOVE_UP, key: ALT + "↑", off: i <= 0, run: () => moveAgent(a.id, i - 1) }, { name: "Move down", icon: MOVE_DOWN, key: ALT + "↓", off: i < 0 || i >= shown.length - 1, run: () => moveAgent(a.id, i + 1) }, // for a config rewritten in a way magpie can't see: set it again anyway ...(reapply ? [{ name: "Apply again", icon: REAPPLY, sep: true, run: () => reapplyAgent(a) }] : []), ...(a.drift?.kind === "replaced" ? [{ name: "Keep current settings", icon: CHECK, run: () => keepAgent(a) }] : []), // everything magpie wrote comes out, what the user had goes back (Fate on Discord) ...(a.wired ? [{ name: "Disconnect from magpie", icon: UNPLUG, sep: !reapply, tip: t(DISCONNECT_TIP, { agent: a.name }), run: () => askDisconnect(a) }] : []), { name: "Hide", icon: EYE_OFF, sep: true, run: () => setAgentHidden(a, true) }, ]; openRowMenu(anchor, acts); } // openRowMenu: a small menu of acts under anchor, the one an agent row's // right-click opens, and a model chip's function openRowMenu(anchor, acts) { const box = el("div", "pop row-menu"); box.setAttribute("role", "menu"); const items = []; for (const o of acts) { if (o.sep) box.append(el("div", "rm-sep")); const b = el("button", "rm-item"); b.type = "button"; b.setAttribute("role", "menuitem"); b.disabled = !!o.off; b.append(svg(o.icon, 13, 1.5), el("span", "rm-name", t(o.name))); if (o.key) b.append(el("span", "rm-key", o.key)); if (o.tip) b.title = o.tip; // an item that is off can say why, under its name and as its title if (o.why) { b.classList.add("has-why"); b.title = o.why; b.querySelector(".rm-name").append(el("span", "rm-why", o.why)); } b.onclick = (e) => { e.stopPropagation(); closeAgentMenu(); o.run(); }; b.onmouseenter = () => b.focus({ preventScroll: true }); box.append(b); if (!o.off) items.push(b); } document.body.append(box); placeMenu(box, anchor, "left", -4); anchor.classList.add("open"); const outside = (e) => { if (!box.contains(e.target) && !anchor.contains(e.target)) closeAgentMenu(); }; // a long menu scrolls inside itself; only a scroll outside it closes it const scroll = (e) => { if (scrollCloses(box, e)) closeAgentMenu(); }; const keys = (e) => { const k = items.indexOf(document.activeElement); if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeAgentMenu(); anchor.focus({ preventScroll: true }); } else if (e.key === "Tab") closeAgentMenu(); else if ((e.key === "ArrowDown" || e.key === "ArrowUp") && items.length) { e.preventDefault(); e.stopPropagation(); const n = items.length, at = k < 0 ? (e.key === "ArrowDown" ? n - 1 : 0) : k; items[(at + (e.key === "ArrowDown" ? 1 : n - 1)) % n].focus(); } }; document.addEventListener("mousedown", outside, true); document.addEventListener("keydown", keys, true); document.addEventListener("scroll", scroll, true); addEventListener("resize", closeAgentMenu); agentMenu = { box, anchor, outside, keys, scroll }; items[0]?.focus({ preventScroll: true }); } // Claude Code's opus/sonnet/haiku/fable can each have a model of their own // once it runs through magpie. They share one button, which lists the four; // picking one opens the model picker for it. const TIERS = ["opus", "sonnet", "haiku", "fable"]; // and each an effort of its own (#536), in the same menu, under its model const TIER_EFFORTS = TIERS.map((tier) => tier + " effort"); // fields that fall back to the agent's model when unset: omp's smol and // slow roles take the session's, as its subagents do ("smol", not "small": // other agents' small model is a picker of its own) const FOLLOWS_MODEL = [...TIERS, "subagents", "smol", "slow"]; // omp's roles share one square as Claude Code's tiers do (#1397), each // with its thinking level under its model: the level omp reads off the end // of the role's model ("…:high"). The roles after slow don't follow the // model; each says what omp does when it is unset: plan and vision are // omp's own pick, the advisor the slow role's model first, commit and tiny // the smol role's, memory the tiny role's (omp's chat roles, #1397) const OMP_UNSET = { plan: "omp's own pick", vision: "omp's own pick", advisor: "the slow role's model, else omp's own pick", commit: "the smol role's model", tiny: "the smol role's model", memory: "the tiny role's model, else the smol role's", }; const OMP_OWN_PICK = Object.keys(OMP_UNSET); const OMP_ROLES = ["subagents", "smol", "slow", ...OMP_OWN_PICK]; // omp, a named profile of it (omp#) or either in a WSL distro const ompAgent = (a) => a.id.split("@wsl:")[0].split("#")[0] === "omp"; // the roles an agent's square lists, and whether a field is one of them or // one of their levels const menuRoles = (a) => ompAgent(a) ? OMP_ROLES : TIERS; const roleLevel = (label) => TIER_EFFORTS.includes(label) || OMP_ROLES.some((r) => label === r + " thinking"); const grouped = (a, f) => menuRoles(a).includes(f.label) || roleLevel(f.label); // fields that take a model, as the model picker opens for them const ROLE_MODELS = [...FOLLOWS_MODEL, ...OMP_OWN_PICK]; // agents with no default model of their own, whose Default leaves the pick // to them (#709) const PICKS_ITSELF = ["pi", "omo", "prime-agent"]; // A field that follows the model unless set — Codex's subagents, Claude // Code's tiers, omp's roles — is a small square after the pickers rather // than a third picker, which a row has no room for: it wrapped onto a line // of its own. So is Codex's sign-in, ChatGPT or magpie as its provider, // and the effort its subagents start at (#469), and the model Codex writes // its memories with (Yc on Discord). const SUB_EFFORT = "subagent effort"; const MEMORIES = "memories"; // the model magpie puts every Codex subagent on, whatever its lead asked // for (willz on Discord): any model magpie serves (#1633); a subagent // whose task a ChatGPT-backed lead sealed stays on its own unless the one // set is a ChatGPT account's, the Routing page saying why const SUB_MODEL = "subagent model"; // Codex's subagents square is [agents] default_subagent_model, the model a // subagent starts on only when its lead names none in spawn_agent // (codex-rs core/src/agent/child_config.rs). Unset, a subagent isn't held to // the model: the lead may name another, and GPT-6.1-Sol's spawned GPT-6-Astra // (willz on Discord). So it says the lead picks, and points at the subagent // model square, which holds every subagent to one. const leadPicks = (a, f) => f.label === "subagents" && a.id.split("@wsl:")[0] === "codex"; const LEAD_PICKS = "Codex's lead may name another model for a subagent; set the subagent model to hold every subagent to one"; const extra = (f) => f.key === "tiers" || FOLLOWS_MODEL.includes(f.label) || f.label === "sign-in" || f.key === "ultracode" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === MEMORIES; const EXTRA_GLYPH = { subagents: "M4.5 2.75v10.5M4.5 9.25c0-2.2 1.6-3.75 3.9-3.75h3.35M9.9 3.6l1.9 1.9-1.9 1.9", // a feather for omp's smol role, an hourglass for its slow one smol: "M12.75 3.25c-4.5 0-8 3.5-8 8v1.5M12.75 3.25c0 4-2.75 7-6.75 7.25M4.75 12.75l-1.5 1.5", slow: "M4.5 2.5h7M4.5 13.5h7M5.25 2.5c0 3 5.5 3 5.5 5.5s-5.5 2.5-5.5 5.5M10.75 2.5c0 3-5.5 3-5.5 5.5s5.5 2.5 5.5 5.5", tiers: "M8 2.6 2.75 5.4 8 8.2l5.25-2.8zM2.75 8.1 8 10.9l5.25-2.8M2.75 10.8 8 13.6l5.25-2.8", "sign-in": "M8 2.5a2.75 2.75 0 1 1 0 5.5 2.75 2.75 0 0 1 0-5.5zM3 13.5c.4-2.4 2.4-3.9 5-3.9s4.6 1.5 5 3.9", ultracode: "M3 4.25h4M3 8h2.5M3 11.75h4M9.5 4.25l3.5 3.75-3.5 3.75", // the subagents' branch, with effort's rising bars after it [SUB_EFFORT]: "M3.25 2.75v10.5M3.25 9.25c0-2.2 1.6-3.75 3.9-3.75h.6M9.25 13.25v-2M11.5 13.25v-4M13.75 13.25v-6", // the subagents' branch, ending on a pin: their model, set by magpie [SUB_MODEL]: "M4 2.75v10.5M4 9.25c0-2.2 1.6-3.75 3.9-3.75h1.1M11.75 3.25a2.25 2.25 0 1 1 0 4.5 2.25 2.25 0 0 1 0-4.5zM11.75 7.75v4", // a notebook: Codex's memories [MEMORIES]: "M4.25 2.75h7.5v10.5h-7.5zM6.25 2.75v10.5M8.25 5.75h1.75M8.25 8h1.75", }; // what Codex writes its memories with when none is set (codex-rs // model-provider: memory_consolidation_preferred_model, _extraction_) const MEMORIES_DEFAULT = "Codex's own: gpt-5.6-terra, threads summed up with gpt-5.6-luna"; function extraField(a, f) { if (f.key === "ultracode") return ultracodeToggle(a, f); const set = !!(f.value || f.custom); const b = el("button", "field extra" + (set ? " set" : "")); b.append(svg(EXTRA_GLYPH[f.label] || EXTRA_GLYPH.tiers, 13, 1.5)); const opt = optionFor(f, f.value); b.title = f.label === SUB_EFFORT ? subEffortTitle(a, f, opt) : f.menu ? menuTitle(f) : t("{label}: {value}", { label: f.label === MEMORIES ? t("Codex memories model") : t(f.label), value: t(opt?.label || f.value || (f.label === MEMORIES ? MEMORIES_DEFAULT : f.label === SUB_MODEL ? "the model the lead asks for" : leadPicks(a, f) ? "the lead's pick, else same as model" : "same as model")) }) + (opt?.note && !FOLLOWS_MODEL.includes(f.label) ? "\n" + t(opt.note) : "") + (leadPicks(a, f) ? "\n" + t(LEAD_PICKS) : ""); b.setAttribute("aria-label", b.title); b.dataset.key = f.key; b.onclick = (ev) => openPicker(a, f, b, ev); return b; } // menuTitle: a menu square's title, its summary and then each of its entries function menuTitle(f) { return t("{label}: {value}", { label: t(f.label), value: f.summary }) + "\n" + f.options.map((o) => `${t(o.label)}: ${o.note}`).join("\n"); } // subEffortTitle: the effort subagents start at, and unset, what that means: // Codex runs one at the session's effort, or, given a model of its own, at // that model's default; Claude Code's (#536) at the effort it asks for function subEffortTitle(a, f, opt) { return t("{label}: {value}", { label: t(f.label), value: effortName(opt || { value: f.value }) }) + (f.value ? "" : "\n" + t(a.id === "claude" ? "the effort Claude Code asks for" : "the session's effort, or the subagent model's own default")); } // launchButton copies the command that starts an agent on magpie, for one // that takes the gateway only from its environment (agy) function launchButton(a) { const b = el("button", "field extra launch"); b.type = "button"; b.append(svg(LAUNCH_GLYPH, 13, 1.5)); b.title = t("{name} takes magpie only from its environment · click to copy the command that starts it:", { name: a.name }) + "\n" + a.launch; b.setAttribute("aria-label", b.title); b.onclick = (ev) => { ev.stopPropagation(); copy(a.launch, t("Launch command"), null, t("Copied — run it to start {name} on magpie", { name: a.name })); }; return b; } // launchSolo is the one control of an agent that takes magpie only from // how it is started and has nothing else to set: the command, in words function launchSolo(a) { const b = el("button", "field solo import launch-solo"); b.type = "button"; b.title = t("{name} takes magpie only from its environment · click to copy the command that starts it:", { name: a.name }) + "\n" + a.launch; b.append(icon("magpie"), el("span", "v empty", t("Copy launch command"))); const c = el("span", "chev"); c.append(svg(LAUNCH_GLYPH, 11, 1.5)); b.append(c); b.onclick = (ev) => { ev.stopPropagation(); copy(a.launch, t("Launch command"), null, t("Copied — run it to start {name} on magpie", { name: a.name })); }; return b; } const LAUNCH_GLYPH = "M2.5 3.5h11v9h-11zM5 6.5l2 1.75L5 10M8.5 10h2.5"; function tierMenu(a) { const omp = ompAgent(a); const tiers = a.fields.filter((f) => menuRoles(a).includes(f.label)); if (!tiers.length || !tiers.some((f) => f.options.length)) return null; // Claude Desktop has no model of its own here: a tier unset runs on a // Claude model of that tier magpie serves, else on the chat's model const main = a.fields.find((f) => f.key === "model"); const mainName = main && (optionFor(main, main.value)?.label || main.value); const unset = (f) => omp && OMP_OWN_PICK.includes(f.label) ? t(OMP_UNSET[f.label]) : main ? t("same as model ({model})", { model: mainName }) : t("a Claude model of the tier, else the chat's model"); // a tier's effort, offered while there are levels to pick (Claude Code // through magpie); unset, the tier runs at the effort Claude Code asks. // An omp role's thinking level, while the role is on one model; unset, // it runs at the session's level const effortOf = (f) => a.fields.find((e) => (e.label === f.label + " effort" || e.label === f.label + " thinking") && (e.options.length || e.value)); const level = (e) => e?.value ? effortName(optionFor(e, e.value) || { value: e.value }) : ""; const custom = tiers.filter((f) => f.value || effortOf(f)?.value); const name = (f) => optionFor(f, f.value)?.label || f.value; return { key: "tiers", label: omp ? "roles" : "tiers", value: "", menu: true, custom: custom.length > 0, summary: custom.length ? custom.map((f) => level(effortOf(f)) ? `${t(f.label)} (${level(effortOf(f))})` : t(f.label)).join(", ") : main ? t("same as model") : t("not set"), options: tiers.flatMap((f) => { const model = { value: f.key, label: t(f.label), icon: optionFor(f, f.value)?.icon || (main && optionFor(main, main.value)?.icon), note: f.value ? name(f) : unset(f), }; const e = effortOf(f); return e ? [model, { value: e.key, label: t(e.label), effortOf: e, note: level(e) || levelUnset(a) }] : [model]; }), }; } // levelUnset: what a role's level is when none is set const levelUnset = (a) => ompAgent(a) ? t("the session's thinking level") : t("the effort Claude Code asks for"); // The tray panel has no scrollbars to speak of, so it grows to fit instead. // The agents' scroll unrolls and rolls up on these, in app.css as in the // panel's own height. const UNROLL = { ms: 620, ease: ".22,1,.36,1" }; // A row opens and closes on a critically damped spring, as iOS moves things: // it sets off gently, not at a jump, and settles without a long tail. The // curve is that spring fitted to a cubic-bezier, which the panel's edge can // take too; app.css has the same (--row-spring). const ROW_OPEN = { ms: 480, ease: ".25,.3,.1,1" }; const ROW_CLOSE = { ms: 400, ease: ".25,.3,.1,1" }; const ROLLUP = { ms: 420, ease: ".4,0,.2,1" }; // tintPanel hands the colour the panel's page shows to the system, to paint // under the page, which then leaves its own background clear: the page is // drawn a frame or two after the panel grows, and what shows at the new edge // meanwhile is that colour, not a dark band. ms is how long a change of theme // fades. async function tintPanel(ms = 0) { if (mode !== "panel") return; const probe = tintPanel.probe || (tintPanel.probe = document.body.appendChild(el("div", "tint-probe"))); const c = document.createElement("canvas").getContext("2d", { willReadFrequently: true }); c.fillStyle = "#010203"; const none = c.fillStyle; c.fillStyle = getComputedStyle(probe).backgroundColor; if (c.fillStyle === none) return; // a colour the canvas can't read // what the page shows: its thin paint over the webview's white const paint = c.fillStyle; c.fillStyle = "#fff"; c.fillRect(0, 0, 1, 1); c.fillStyle = paint; c.fillRect(0, 0, 1, 1); const rgba = [...c.getImageData(0, 0, 1, 1).data].join(","); if (rgba === tintPanel.last) return; tintPanel.last = rgba; try { const r = await api("window/tint?c=" + rgba + "&ms=" + ms, {}); document.body.classList.toggle("tinted", !!r?.ok); } catch { tintPanel.last = null; document.body.classList.remove("tinted"); } } if (mode === "panel") { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => tintPanel(450)); } // tintTitleBar paints Windows' own title bar the window's page colour, dark // or light as the page is, so the bar and the page are one surface as on the // Mac, not a grey strip above it (light over a dark page). wait lets a change // of theme finish fading first: the colour read is where it ends. function tintTitleBar(wait = 0) { if (mode !== "window" || web || !document.documentElement.classList.contains("win")) return; clearTimeout(tintTitleBar.t); tintTitleBar.t = setTimeout(async () => { const c = document.createElement("canvas").getContext("2d", { willReadFrequently: true }); c.fillStyle = "#fff"; c.fillRect(0, 0, 1, 1); c.fillStyle = getComputedStyle(document.body).backgroundColor; c.fillRect(0, 0, 1, 1); const [r, g, b] = c.getImageData(0, 0, 1, 1).data; const rgba = [r, g, b, 255].join(","); if (rgba === tintTitleBar.last) return; tintTitleBar.last = rgba; // the bar's own text and buttons light on a dark page, dark on a light one const dark = 0.2126 * r + 0.7152 * g + 0.0722 * b < 128; try { await api("window/titlebar?c=" + rgba + "&dark=" + (dark ? 1 : 0), {}); } catch { tintTitleBar.last = null; } }, wait); } if (mode === "window") { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => tintTitleBar(460)); } // extra is room about to be taken (or given back), e.g. by agents unrolling; // glide moves the panel's edge there over time instead of at once. // The panel is as tall as its tallest tab, not the one showing, so it keeps // its height as the tabs change and a shorter tab leaves room below (#124): // every tab is laid out at once for the measure, before anything is drawn. function fit(extra = 0, glide) { if (mode !== "panel") return; const body = document.body, tab = body.dataset.ptab; delete body.dataset.ptab; // extra is only ever the agents' (a row opening, the scroll unrolling) const tallest = Math.max($("#agents").offsetHeight + extra, $("#panelQuota").offsetHeight, $("#panelRouting").offsetHeight, $("#panelUsage").offsetHeight); if (tab) body.dataset.ptab = tab; const h = $(".top").offsetHeight + $("#ptabs").offsetHeight + tallest + $(".foot").offsetHeight + 4; if (h === fit.last) return; fit.last = h; const still = !glide || matchMedia("(prefers-reduced-motion: reduce)").matches; api("window/fit?h=" + h + (still ? "" : "&ms=" + glide.ms + "&ease=" + glide.ease), {}); } // again: the window came back (focused, or shown again), which only reads // what is on the page anew. It must not put a page's skeleton up over what // it shows: under focus-follows-mouse (Hyprland; Zhenzhen on Discord) the // pointer crossing into the window blanked the Usage chart each time. async function load(again) { again = again === true; if (!load.done) renderAgentsLoading(); // the gateway page too waits for the state first: its skeleton, not a // blank page, until then (#123) if (view === "providers" && !providers) renderProvidersLoading(); if (view === "gateway" && !providers) renderGatewayLoading(); try { const since = prefsWrites, hid = hiddenIds().join(), visibilitySince = agentsVisibilityRevision; const asked = api("state"); // the first load draws the state magpie kept from its last read while // the fresh one is read (#1519, fatkun): reading every agent's config, // and a WSL distro's through \\wsl.localhost, took seconds after a // start or after light mode let the window go. The fresh state // replaces it the moment it is in, so an agent leaves the list only // once that says it is gone. let relang = false, shown = null; if (!load.done) { const last = await Promise.race([api("state?last=1").catch(() => null), asked.then(() => null, () => null)]); if (last?.last && !load.done) { state = shown = last; relang = applyPrefs(state.settings, state.fx); tintPanel(); tintTitleBar(); renderAgents(); } } let next = await asked; // a change made on the rows drawn from it answered with a state read // after this one was asked for: that one stands if (shown && state !== shown) next = state; // a setting changed while this was on its way (it can take seconds): // what came back is from before it, and would put the old theme back if (!prefsSettled(since) && load.done) next.settings = state.settings; if (visibilitySince !== agentsVisibilityRevision) { const { agentOrder, agentsHidden, agentsShown } = state.settings; next.settings = { ...next.settings, agentOrder, agentsHidden, agentsShown }; } state = next; load.done = true; // the library may have drawn itself before the saved language was known if (applyPrefs(state.settings, state.fx) || relang) { again = false; // the Usage page too is drawn again, in the new language if (view === "library") window.loadLibrary?.(); if (view === "plugins") window.loadPlugins?.(); if (view === "sessions") window.loadSessionsPage?.(); } // a Library drawn before the state came counted the hidden agents too else if (view === "library" && hiddenIds().join() !== hid) window.redrawLibrary?.(); tintPanel(); tintTitleBar(); renderAgents(); redrawSuffix(); redrawNoNames(); // Update all's outcome stays until the agents are read again if (cliAll && cliAll.done >= cliAll.n) cliAll = null; paintUpdateAll(true); loadCLIs(); // after the rows, never holding them up loadInstalls(); // the panel brought up on its Allowances tab is the reader opening // them (#1588); the page loaded while the panel is still put away is not if (mode === "panel") { renderPanelQuota(); panelTab === "usage" && !document.hidden && (again || document.hasFocus()) ? quotasOpened() : loadQuotas(); } // an open provider editor is someone typing: coming back to the window // must not rebuild it under them if ((view === "providers" || view === "gateway") && !(editing || adding)) await loadProviders(); // the window back on the Usage page reads the tab shown as its own timer // does: drawn again only on a change, with no skeleton between; on the // Overview, where the allowances are, that is opening them (#1588) if (view === "usage" && again && usageTab === "usage") quotasOpened(); if (view === "usage") await (again && usageDrawn() ? refreshUsage() : loadUsage()); // so is an open sync form (WebDAV, export, import): its passwords are // never sent back, so a rebuild would empty it if (view === "settings" && !syncOpen) await loadSettings(); } catch (e) { status(e.message, "err"); } renderUpdateBadge(); cliBehindOnce(); whatsNewOnce(); recoveredOnce(); } // recoveredOnce tells, once each, of a file of magpie's own a crash left // unreadable (all zero, #1505) that was read back from its last good copy: // the accounts in it are as they were then, a later change may be missing. const recoveredShown = new Set(); function recoveredOnce() { const fresh = (state?.recovered || []).filter((n) => !recoveredShown.has(n.path + "\n" + n.at)); if (!fresh.length) return; for (const n of fresh) recoveredShown.add(n.path + "\n" + n.at); const files = fresh.map((n) => n.file).join(", "); const bak = fresh.length === 1 && fresh[0].bak && !fresh[0].bak.startsWith("0001-") ? new Date(fresh[0].bak) : null; status(bak ? t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.", { file: files, time: bak.toLocaleString(intlLang()) }) : t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.", { file: files }), "warn", 20000); } // installFrom is what a restart to update tells the app: the window's tab, // for the new version to open its window there (Windows, Linux). function installFrom() { return mode === "window" ? { view } : {}; } // updateBusy says what a restart would cut short (#577): the agents' // requests in flight through the gateway, the Claude Code turns waiting on // their tool results. function updateBusyText(b) { const parts = []; if (b?.requests) parts.push(t("{n} in flight", { n: b.requests })); if (b?.tools) parts.push(t("{n} awaiting tool results", { n: b.tools })); return parts.join(" · "); } // updatePath asks for the update's state or the release notes in the // page's language: the notes follow Settings' language, Chinese where a // release has it (freecss on Discord). function updatePath(p) { return p + (p.includes("?") ? "&" : "?") + "lang=" + encodeURIComponent(locale); } // renderUpdateBadge shows the header's Update pill once a newer magpie is // downloaded (a click restarts into it) or, where magpie can't replace // itself, out (a click opens the release page). The user may keep it away: // for good (Settings), or for this version (its ×, or a right-click), until // a newer one is out. magpie still downloads it and puts it in on quitting. async function renderUpdateBadge() { const b = $("#update"), label = b.querySelector("span"); const u = await api(updatePath("update")).catch(() => null); // pulling: a click is downloading it again, and restarts once it's in const pulling = !!u && !!b.dataset.pulling && ["checking", "downloading", "ready"].includes(u.state); if (b.dataset.pulling && !pulling) { delete b.dataset.pulling; b.classList.remove("busy"); } const on = pulling || (!!u && !updatePillOff(u.latest) && (u.state === "ready" || u.state === "available" || (u.state === "error" && u.retry))); if (b.hidden !== !on) b.hidden = !on; if (!on) return; const hide = $("#updateHide"); hide.setAttribute("aria-label", t("Hide until the next version")); hide.onclick = b.oncontextmenu = (e) => { e.preventDefault(); skipUpdate(u.latest); }; const restart = async () => { b.classList.add("busy"); label.textContent = t("Restarting…"); // an answer means it didn't: the password prompt dismissed, the swap // failed, or a newer version is out and downloading first const a = await api("update/install", installFrom()).catch(() => ({})); if (!a) return backAsNew(u.current); if (a) { if (["checking", "downloading"].includes(a.state)) b.dataset.pulling = "1"; else b.classList.remove("busy"); if (a.waiting) b.dataset.armed = String(Date.now()); renderUpdateBadge(); } }; if (pulling) { if (u.state === "ready") { delete b.dataset.pulling; return restart(); } label.textContent = downloadingText(u); setTimeout(renderUpdateBadge, 700); return; } if (b.classList.contains("busy")) return; // a restart waiting for the gateway to be idle (#577): a click restarts // at once; one just after the click that armed it is taken as a double // click, not as "now" if (u.state === "ready" && u.waiting) { label.textContent = t("Waiting to update"); b.title = t("magpie restarts to update to {v} once the agents' requests through the gateway have finished: {busy}. Click to restart now.", { v: u.latest, busy: updateBusyText(u.busy) || "…" }); b.onclick = () => { if (Date.now() - (+b.dataset.armed || 0) < 1500) return; b.classList.add("busy"); label.textContent = t("Restarting…"); api("update/install", { ...installFrom(), when: "now" }).then((a) => { if (!a) return backAsNew(u.current); b.classList.remove("busy"); renderUpdateBadge(); }, () => backAsNew(u.current)); }; clearTimeout(b.waitPoll); b.waitPoll = setTimeout(() => { api(updatePath("update")).then(() => renderUpdateBadge(), () => backAsNew(u.current)); }, 1500); return; } // a swap that failed says so where it was clicked, not only in the tooltip label.textContent = u.state === "ready" && u.error ? t("Update failed") : t("Update"); b.title = u.state === "ready" ? t("Restart to update to {v}", { v: u.latest }) : u.state === "error" ? t("Couldn't download {v}", { v: u.latest }) + " · " + t("Click to try again") : u.stuck ? updateStuck(u) + " " + t("Click to open the download page.") : t("{v} is out", { v: u.latest }); if (u.error) b.title += "\n" + u.error; b.onclick = () => { // what changed is shown first, and a click there restarts (#844); one // that failed restarts again at once if (u.state === "ready") return u.error ? restart() : confirmUpdate(u, restart); if (u.state === "error") { b.dataset.pulling = "1"; b.classList.add("busy"); label.textContent = t("Downloading…"); return api("update/install", {}).then(renderUpdateBadge, renderUpdateBadge); } if (web && u.url) return window.open(u.url, "_blank", "noopener"); api("update/install", {}).catch(() => {}); }; } // downloadingText is the pill's word while an update downloads: its // percent once there is one. The answer leaves done out while it is 0, and // total too while the size isn't known yet, so the first reads have none — // they said "NaN%" (inaction on Discord). function downloadingText(u) { const p = u?.total > 0 ? Math.floor(((u.done || 0) / u.total) * 100) : NaN; return Number.isFinite(p) ? t("Downloading… {p}%", { p: Math.min(100, Math.max(0, p)) }) : t("Downloading…"); } // updatePillOff is whether the user keeps the Update pill away for v. function updatePillOff(v) { const s = state?.settings || {}; return !!s.noUpdatePill || (!!v && s.updateSkip === v); } // skipUpdate hides the Update pill until a version newer than v is out // ("" shows it again), and says where it can be brought back. async function skipUpdate(v) { $("#update").hidden = true; try { const ns = await writingPrefs(api("settings/update-skip", { version: v })); prefs = ns; if (state) state.settings = ns; if (v) status(t("Update hidden until the next version; Settings still has it"), "ok", 3000); } catch (e) { status(e.message, "err"); } renderUpdateBadge(); if (view === "settings" && prefs) renderSettings(); } // backAsNew waits, in magpie web, for the version the page restarted into // to answer in its place, and reloads the page from it (#111). async function backAsNew(was) { if (!web) return; for (let i = 0; i < 180; i++) { await new Promise((r) => setTimeout(r, 1000)); const u = await fetch("/api/update").then((r) => (r.ok ? r.json() : null)).catch(() => null); if (u && u.current !== was) return location.reload(); } } // updateStuck says why this magpie can't replace itself where it is: off // the Mac, a folder it may not write to, such as C:\ (#1277), or a // container, whose image is what gets updated. function updateStuck(u) { if (u.stuck === "container") return t("magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container."); if (u.stuck === "not-writable") return t("magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.", { dir: u.stuckDir || "" }); return u.stuck === "translocated" ? t("macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.") : t("magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there."); } // ---------- what's new ---------- // After an update the window (or magpie web's page) shows what changed in // every release since the one last run, once (a Discord user: to see if // their issue was fixed). Not in the tray's panel, where a dialog has no // room; Settings' version row opens it again, and with an update waiting, // that one's notes first. const ISSUES = "https://github.com/yetone/magpie/issues/"; let whatsNewAsked = false; // cliBehindOnce: the terminal's magpie is a copied file rather than the // installer's link, so it can't follow the app's updates (#531's lesson: a // stale command wedged the WebDAV sync). The window can't tell a stale copy // from a current one — that would mean running the old binary, whose // start-up migrates settings — so this is advice, shown once per load, only // in the window (the panel is too small), and dismissable until the next // version. let cliBehindAsked = false; function cliBehindOnce() { if (cliBehindAsked || mode === "panel" || !$("#modal").hidden) return; // another dialog owns the screen: the advice waits for the next load cliBehindAsked = true; if (!state?.cliBehind) return; const ed = el("div", "editor"); const head = el("div", "ehead"); head.append(el("b", "", t("The `magpie` command is a copy"))); ed.append(head); ed.append(el("p", "lib-confirm", t("The `magpie` command at {path} is a copied file, not the installer's link to the app: it won't follow the app's updates, and an old copy can break what a new one fixed. Re-run the installer, or link it by hand.", { path: state.cliBehind }))); const bar = el("div", "bar"); const quiet = el("button", "text", t("Hide until the next version")); quiet.onclick = async (e) => { e.stopPropagation(); try { await api("cli-behind/quiet", {}); } catch (err) { return status(err.message, "err"); } closeConfirmAsk(); }; const ok = el("button", "text primary", t("OK")); ok.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; bar.append(el("span", "grow"), quiet, ok); ed.append(bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); ok.focus({ preventScroll: true }); } async function whatsNewOnce() { if (whatsNewAsked || mode === "panel" || document.hidden || !$("#modal").hidden) return; whatsNewAsked = true; const w = await api(updatePath("whatsnew")).catch(() => null); // something else opened meanwhile: the notes wait for the next load if (!w?.show || !w.releases?.length || !$("#modal").hidden) { if (w?.show) whatsNewAsked = false; return; } api("whatsnew/seen", {}).catch(() => {}); showWhatsNew(w.releases, true); } // openWhatsNew is Settings' way back to the notes: the current version's (or // those since the last update), after the waiting update's when u has one. // The notes that couldn't be had (the site failing, #661) say so, with a // retry and the release page, apart from a version that has none. async function openWhatsNew(u, b) { if (b) { b.disabled = true; b.classList.add("busy"); } const w = await api(updatePath("whatsnew?all=1")).catch(() => null); if (b) { b.disabled = false; b.classList.remove("busy"); } const list = [...(w?.releases || [])]; if (u?.notes && u.latest && ["ready", "available", "downloading"].includes(u.state) && !list.some((r) => r.version === u.latest)) { list.unshift({ version: u.latest, notes: u.notes, url: u.url, pending: true }); } const failed = !w || !!w.error; if (!list.length && !w?.current) return status(t("Couldn't load the release notes"), "err"); showWhatsNew(list, false, { failed, current: w?.current, url: w?.url, retry: () => openWhatsNew(u) }); } // auto: shown by itself after an update, with "Don't show again today" // (#525: releases come many a day); Settings' row opens it without one. // more (from Settings): failed, the current version's notes couldn't be // had, retry asks again; current and url, the version and its release // page, for a dialog with no notes. function showWhatsNew(releases, auto, more = {}) { const ed = el("div", "editor whatsnew"); const head = el("div", "ehead"); head.append(el("b", "", t("What's new in {v}", { v: "v" + (releases[0]?.version || more.current) }))); ed.append(head); for (const r of releases) { const sec = el("section", "wn-rel"); const h = el("div", "wn-ver"); h.append(el("b", "", "v" + r.version)); if (r.pending) h.append(el("span", "badge", t("Not installed yet"))); sec.append(h, noteBlocks(r.notes)); ed.append(sec); } if (more.failed || !releases.length) { const sec = el("section", "wn-rel wn-none" + (more.failed ? " wn-failed" : "")); const h = el("div", "wn-ver"); if (more.current) h.append(el("b", "", "v" + more.current)); const p = el("p", "wn-msg", more.failed ? t("Couldn't load the release notes") : t("No release notes provided.")); const acts = el("div", "wn-acts"); if (more.failed && more.retry) { const again = el("button", "text", t("Try again")); again.onclick = async (e) => { e.stopPropagation(); again.disabled = true; again.classList.add("busy"); await more.retry(); }; acts.append(again); } if (more.url) acts.append(noteLink(t("Open the release page"), more.url)); sec.append(h, p, acts); ed.append(sec); } const bar = el("div", "bar"); const ok = el("button", "text primary", t("Close")); ok.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; if (auto) { // told at once, so Escape or a click outside keeps it as well as Close const [quiet, box] = tick(t("Don't show again today"), false); quiet.classList.add("wn-quiet"); box.onchange = () => api("whatsnew/today", { on: box.checked }).catch((e) => status(e.message, "err")); bar.append(quiet); } bar.append(el("span", "grow"), ok); ed.append(bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); ok.focus({ preventScroll: true }); } // noteBlocks draws a release's markdown as text: headings, bullets, // paragraphs, and inline bold, code and links. Nothing in it is taken as // HTML; #123 links the issue. function noteBlocks(md) { const box = el("div", "wn-notes"); let list = null; for (const line of String(md || "").split(/\r?\n/)) { const h = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line); const li = /^\s*[-*+]\s+(.*)$/.exec(line); if (h) { list = null; box.append(inlineMD(el("div", "wn-h wn-h" + Math.min(h[1].length, 4)), h[2])); } else if (li) { if (!list) box.append(list = el("ul")); list.append(inlineMD(el("li"), li[1])); } else if (!line.trim()) { list = null; } else if (list && /^\s{2,}\S/.test(line)) { inlineMD(list.lastElementChild, " " + line.trim()); } else { list = null; box.append(inlineMD(el("p"), line.trim())); } } return box; } // inlineMD appends text to e with **bold**, `code`, [links](https://…), // bare https:// links and #123 issue links; only http(s) addresses link. function inlineMD(e, s) { const re = /\*\*(.+?)\*\*|`([^`]+)`|\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s<>)]+)|(^|[\s(\[])#(\d+)\b/g; let at = 0, m; while ((m = re.exec(s))) { if (m.index > at) e.append(s.slice(at, m.index)); if (m[1] !== undefined) e.append(inlineMD(el("b"), m[1])); else if (m[2] !== undefined) e.append(el("code", "", m[2])); else if (m[3] !== undefined) e.append(noteLink(m[3], m[4])); else if (m[5] !== undefined) e.append(noteLink(m[5], m[5])); else e.append(m[6], noteLink("#" + m[7], ISSUES + m[7])); at = re.lastIndex; } if (at < s.length) e.append(s.slice(at)); return e; } // a link in the notes opens in the browser, as the app's other links do function noteLink(text, url) { const a = el("a", "wn-link", text); a.href = url; a.target = "_blank"; a.rel = "noopener"; a.onclick = (e) => { e.preventDefault(); e.stopPropagation(); api("open", { url }).catch(() => {}); }; return a; } // confirmUpdate shows what changed before an update downloaded is put in // (Hu9956, #844: every update came unseen, its notes three clicks away in // Settings › About): every release's notes after this one up to it, newest // first, with Restart to update and Later. The update's own notes show at // once; the releases between come in after. go restarts. The tray's panel, // with no room for a dialog, restarts as before. async function confirmUpdate(u, go) { if (mode === "panel" || !$("#modal").hidden) return go(); const ed = el("div", "editor whatsnew update-ask"); const head = el("div", "ehead"); const title = el("b", "", t("Update to {v}", { v: "v" + u.latest })); head.append(title); if (u.current) head.append(el("span", "wn-since", t("What changed since {v}", { v: "v" + u.current }))); const box = el("div", "wn-list"); const draw = (releases) => { box.replaceChildren(); for (const r of releases) { const sec = el("section", "wn-rel"); const h = el("div", "wn-ver"); h.append(el("b", "", "v" + r.version)); sec.append(h, noteBlocks(r.notes)); box.append(sec); } if (!releases.length) { const sec = el("section", "wn-rel wn-none"); sec.append(el("p", "wn-msg", t("No release notes provided."))); if (u.url) sec.append(noteLink(t("Open the release page"), u.url)); box.append(sec); } }; draw(u.notes ? [{ version: u.latest, notes: u.notes }] : []); const bar = el("div", "bar"); const later = el("button", "text", t("Later")); later.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; const ok = el("button", "text primary", t("Restart to update")); ok.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); go(); }; bar.append(el("span", "grow"), later, ok); ed.append(head, box, bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); ok.focus({ preventScroll: true }); // the notes' answer asks the feed again first, and names a release out // since the one downloaded (#910), which the restart then waits for const w = await api(updatePath("update/notes")).catch(() => null); if (confirmAsk !== ed) return; if (w?.latest && w.latest !== u.latest) title.textContent = t("Update to {v}", { v: "v" + w.latest }); if (w?.releases?.length) draw(w.releases); } // ---------- picker ---------- function score(q, o) { if (!q) return 1; const lv = o.value.toLowerCase(), ll = (o.label || "").toLowerCase(); if (lv === q || ll === q) return 100; if (lv.startsWith(q) || ll.startsWith(q)) return 60; if (lv.includes(q) || ll.includes(q)) return 40; let i = 0; for (const ch of lv) if (ch === q[i]) i++; if (i === q.length) return 20; if ((o.note || "").toLowerCase().includes(q) || (o.group || "").toLowerCase().includes(q)) return 10; return 0; } // popTop is the highest a popover's top edge may go, pad under the window's // own chrome: on a Mac window the traffic lights are drawn over the page's // header.top, so a list that opens upward in a short window stops under it // rather than over them (#1573, lyston11). Elsewhere the header is the // page's own row and the edge is pad, as it always was. The header's // measured bottom already counts the text size (--zoom). function popTop(pad) { const b = document.body.classList; if (!b.contains("window") || !b.contains("mac")) return pad; const head = document.querySelector("header.top"); return Math.max(0, head ? head.getBoundingClientRect().bottom : 0) + pad; } function placePop(anchor, w, h) { const pop = $("#pop"); const r = anchor.getBoundingClientRect(), pad = 8, top = popTop(pad); w = Math.min(w, innerWidth - pad * 2); // a window too short for it holds it to the room between the chrome and // the foot, and its list scrolls, rather than running off the bottom const most = innerHeight - pad - top; pop.style.maxHeight = ""; if (!(parseFloat(getComputedStyle(pop).maxHeight) <= most)) pop.style.maxHeight = most + "px"; h = Math.min(h, most); pop.style.width = w + "px"; let x = Math.max(pad, Math.min(r.left, innerWidth - w - pad)); let y = r.bottom + 5; pop.classList.remove("up"); pop.style.left = x + "px"; // it grows out of the button's middle, or near the edge it's held to pop.style.setProperty("--ox", Math.max(16, Math.min(w - 16, r.left + r.width / 2 - x)) + "px"); // h is the most it can be: opened upward, its bottom edge is held to the // button, so a short list sits on the button rather than h above it if (y + h > innerHeight - pad && r.top - 5 - h >= top) { pop.classList.add("up"); pop.style.top = "auto"; pop.style.bottom = innerHeight - r.top + 5 + "px"; return; } if (y + h > innerHeight - pad) y = Math.max(top, innerHeight - pad - h); pop.style.bottom = "auto"; pop.style.top = y + "px"; } // ultracodeToggle: Claude Code's ultracode as a square that a click turns // on or off, lit while on; nothing to pick between. What it does, and that // an open session keeps what it started with, is said as it changes. function ultracodeToggle(a, f) { const on = f.value === "on"; const b = el("button", "field extra" + (on ? " set" : "")); b.append(svg(EXTRA_GLYPH.ultracode, 13, 1.5)); b.title = t("{label}: {value}", { label: "ultracode", value: t(on ? "on" : "off") }) + "\n" + t("Claude plans a workflow for each substantive task"); b.setAttribute("aria-label", b.title); b.setAttribute("aria-pressed", String(on)); b.dataset.key = f.key; b.onclick = async (ev) => { ev.stopPropagation(); try { state = await api("set", { agent: a.id, field: f.key, value: on ? "" : "on" }); renderAgents(); const msg = t("{agent} ultracode → {value}", { agent: a.name, value: t(on ? "off" : "on") }); if (state.notice) status(withNotice(msg, state.notice), "warn", 9000); else status(msg, "ok"); } catch (e) { status(e.message, "err"); } }; return b; } // oneRowPerModel: an alias and its dated id (claude-opus-4-5 and // claude-opus-4-5-20251101, models.dev's two names of one model) are one // row, the alias's; the dated one's while it is the value set, or starred // where the alias isn't, so a pick or a star made before still shows (#496). function oneRowPerModel(options, cur) { const byValue = new Map(options.map((o) => [o.value, o])); const gone = new Set(); for (const o of options) { const alias = o.alias && byValue.get(o.alias); if (alias) gone.add(o.value === cur || (alias.value !== cur && isFavorite(o) && !isFavorite(alias)) ? alias : o); } return options.filter((o) => !gone.has(o)); } // foldSame: magpie's rows for the very account the agent is signed in to // itself (Claude Code's Claude subscription, added in magpie too) are the // agent's own models a second time; they fold into one row that a click // opens, for the few who want them (failover to more accounts, a fix that // only magpie's way has). The value set stays a row of its own (#496). The // row comes after the agent's own rows of its group: the account is listed // after the providers the user added, and in its place the group was // headed twice. A query shows every row it finds, for Enter to pick. function foldSame(items) { if (!pick.modelPicker || pick.groupFilter === "favorites" || $("#q").value.trim()) return items; const same = items.filter((o) => o.same && o.value !== pick.field.value); if (!same.length) return items; const first = same[0]; const row = { fold: true, open: !!pick.unfold, n: same.length, group: first.group, icon: first.icon, account: (first.note || "").replace(/ · via magpie$/, "") }; const out = items.filter((o) => !same.includes(o)); const own = out.findLastIndex((o) => o.group === first.group); out.splice(own >= 0 ? own + 1 : items.indexOf(first), 0, row, ...(pick.unfold ? same : [])); return out; } // toggleFold opens or closes the folded rows, the fold's row staying under // the pointer (or the keys' cursor) where it was function toggleFold() { pick.unfold = !pick.unfold; filter((o) => o.fold); } // openPicker drops the option list under a field button. `only` narrows the // options (the providers page offers one vendor's models at a time). function openPicker(agent, field, anchor, ev, only) { ev.stopPropagation(); const again = pick?.anchor === anchor; closePicker(); if (again) return; const cur = field.value; let options = field.options.filter((o) => !only || only(o)); // routing groups come first, before the agent's own models and each // provider's; only the picker's own choices (Automatic, Off) above them options = [...options.filter((o) => o.reset), ...options.filter((o) => !o.reset && o.group === ROUTING_GROUPS), ...options.filter((o) => !o.reset && o.group !== ROUTING_GROUPS)]; const effortPicker = !only && (field.key === "effort" || field.label === "effort" || field.label === "thinking" || field.label === SUB_EFFORT || roleLevel(field.label)); options = oneRowPerModel(options, cur); // Current model first, then the rest in catalog order. Effort levels keep // their natural low → high order because their position is meaningful. // The row keeps its group as `home`: a provider picked in the rail still // shows its current model (#1229: gpt-6.1-sol missing under OpenAI), and // the rail lists the providers in catalog order, the current one's among // them where it was, even when its only listed model is the current one. const groups = [...new Set(options.map((o) => o.group).filter(Boolean))]; const i = options.findIndex((o) => o.value === cur); if (!effortPicker && !field.menu && i > 0) { const [c] = options.splice(i, 1); options.unshift({ ...c, group: "", home: c.group }); } else if (i < 0 && cur && !only) options.unshift({ value: cur, note: t("current value") }); // the agent's own default: magpie's wiring comes out and the key is removed if (FOLLOWS_MODEL.includes(field.label)) { const main = agent.fields.find((f) => f.key === "model"); const mainName = main && (optionFor(main, main.value)?.label || main.value); options.unshift(main && leadPicks(agent, field) ? { value: "", label: t("Lead's pick"), note: t("{model} unless the lead names another", { model: mainName }), icon: optionFor(main, main.value)?.icon, reset: true } : main ? { value: "", label: t("Same as model"), note: mainName, icon: optionFor(main, main.value)?.icon, reset: true } : { value: "", label: t("Not set"), note: t("a Claude model of the tier, else the chat's model"), icon: agent.icon, reset: true }); } else if (!only && !field.menu && !field.onPick && !options.some((o) => o.value === "")) { // Pi has no default model of its own: with none set it takes the first // provider signed in, in its own order, so Default is no fixed model // and a model picked in Pi's /model lasts the session only unless // saved there with Ctrl+S (#709) const note = agent.id === "reasonix" && ["model", "planner"].includes(field.key) ? "restore the previous {field} selection" : PICKS_ITSELF.includes(agent.id) && field.key === "model" ? "clears the default model; {agent} picks one on its own" : field.label === MEMORIES ? MEMORIES_DEFAULT : field.label === SUB_MODEL ? "each subagent on the model {agent}'s lead asks for" : ompAgent(agent) && OMP_OWN_PICK.includes(field.label) ? OMP_UNSET[field.label] : asideAccount(agent, field) ? "the account active in {agent}" : "what {agent} ships with"; options.unshift({ value: "", label: t("Default"), note: t(note, { agent: agent.name, field: t(field.label) }), icon: agent.icon, reset: true }); } // Default is the agent as installed; this is the agent as it was before // magpie, beside it so the two aren't taken for each other if (agent.wired && field.key === "model" && !only && !field.menu && !field.onPick) { const at = options.findIndex((o) => !o.reset); options.splice(at < 0 ? options.length : at, 0, { value: "\0disconnect", label: t("Disconnect from magpie"), note: t("put back what {agent} had before magpie", { agent: agent.name }), svg: UNPLUG, reset: true, run: () => askDisconnect(agent) }); } const modelPicker = ["model", "small", "large", MEMORIES, SUB_MODEL, "executor", "planner", ...ROLE_MODELS].includes(field.label) && !only; pick = { agent, field, options, groups, anchor, cursor: 0, free: !only && !field.menu, modelPicker, effortPicker, groupFilter: "all" }; anchor.classList.add("open"); const pop = $("#pop"); pop.classList.toggle("model-picker", modelPicker); pop.classList.toggle("effort-picker", effortPicker); // a choice explained in a sentence (Codex's sign-in) shows all of it pop.classList.toggle("explained", field.label === "sign-in"); pop.hidden = false; $("#effortControl").hidden = !effortPicker; pop.querySelector(".search").hidden = effortPicker; pop.querySelector(".picker-body").hidden = effortPicker; placePop(anchor, effortPicker ? 232 : modelPicker ? Math.min(490, innerWidth - 16) : (options.some((o) => o.note && o.note !== o.value) ? 372 : 300), effortPicker ? 96 : modelPicker ? Math.min(420, innerHeight - 16) : 340); if (effortPicker) { renderEffortPicker(); $("#effortRange").focus(); return; } const q = $("#q"); q.value = ""; q.placeholder = modelPicker && extra(field) ? t("{field} — filter, or type any model id…", { field: t(field.label) }) : modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) }); filter(); // On touch screens leave the keyboard closed until the filter is tapped, // so opening a model list leaves room to browse its choices. if (!web || !matchMedia("(pointer: coarse)").matches) q.focus(); } function effortName(option) { // the agent's default, with the level it takes then when the agent says // (Codex: the model's default_reasoning_level), so Default doesn't read // as a level of its own that turned into medium (lgtm) if (!option?.value) return option?.takes ? t("default ({level})", { level: t(option.takes) }) : t("default"); return t(option.label || option.value); } // The thinking levels agents name, lowest first; off and none are no // thinking at all. const EFFORT_ORDER = ["off", "none", "minimal", "low", "medium", "high", "xhigh", "max"]; // effortStops are an effort field's options with its value among them when // it isn't one, as the panel's slider has its stops: a level in its place // (max above high), anything else — unset, auto, one magpie doesn't know — // first. function effortStops(f) { const options = f?.options || []; if (!f || options.some((o) => o.value === f.value)) return options; const r = EFFORT_ORDER.indexOf(f.value); const i = r < 0 ? 0 : options.findIndex((o) => EFFORT_ORDER.indexOf(o.value) > r); const cut = i < 0 ? options.length : i; return [...options.slice(0, cut), { value: f.value }, ...options.slice(cut)]; } // effortLit: how many of n bars an effort lights, as far as its stop goes // among the levels: none for the default, off, none, auto or a value that // isn't a level, all n for the highest. function effortLit(f, n) { const levels = effortStops(f).filter((o) => o.value && !["off", "none", "auto"].includes(o.value) && (EFFORT_ORDER.includes(o.value) || f.options?.includes(o))); const at = levels.findIndex((o) => o.value === f.value); return at < 0 ? 0 : Math.max(1, Math.round(((at + 1) / levels.length) * n)); } // An effort level as four bars filled up to it. function effortIcon(f) { const lit = effortLit(f, 4); const e = el("span", "ic effort-ic"); const s = document.createElementNS("http://www.w3.org/2000/svg", "svg"); s.setAttribute("viewBox", "0 0 16 16"); s.innerHTML = [4, 7, 10, 13].map((h, i) => ``).join(""); e.append(s); return e; } // effortBars: the panel's effort at a glance, three bars lit up to it. function effortBars(f) { const e = el("span", "eff"); e.dataset.l = effortLit(f, 3); e.append(el("i"), el("i"), el("i")); if (f) e.title = t("{label}: {value}", { label: t(f.label), value: effortName(optionFor(f, f.value) || { value: f.value }) }); return e; } // effortSeg: an opened panel row's effort, as the effort picker's slider, // drawn rather than native so the thumb glides from stop to stop. A level // shows at once, bars and all; the write follows, in order, so a slow agent // config never holds the thumb (巨卡). function effortSeg(a, f) { // a value that isn't one of the levels offered is a stop of its own, as // the picker's current value is (shown as the lowest level, a touch wrote // that level over it) const options = effortStops(f); const last = Math.max(1, options.length - 1); const box = el("div", "effort-control"); const head = el("div", "effort-head"); const value = el("b"); head.append(el("span", "", t(f.label)), value); const track = el("div", "eslide"); track.tabIndex = 0; track.setAttribute("role", "slider"); track.setAttribute("aria-label", t(f.label)); track.setAttribute("aria-valuemin", "0"); track.setAttribute("aria-valuemax", String(options.length - 1)); const rail = el("span", "rail"); rail.append(el("span", "fill")); const ticks = el("span", "effort-ticks"); ticks.setAttribute("aria-hidden", "true"); ticks.append(...options.map((_, i) => { const dot = el("i"); dot.style.setProperty("--at", i / last); return dot; })); track.append(rail, ticks, el("span", "knob")); const ends = el("div", "effort-ends"); ends.setAttribute("aria-hidden", "true"); ends.append(el("span", "", effortName(options[0])), el("span", "", effortName(options[options.length - 1]))); box.append(head, track, ends); let at = options.findIndex((o) => o.value === f.value); const show = (i) => { at = i; track.style.setProperty("--p", i / last); [...ticks.children].forEach((dot, j) => { dot.classList.toggle("on", j < i); dot.classList.toggle("cur", j === i); }); value.textContent = effortName(options[i]); track.setAttribute("aria-valuenow", String(i)); track.setAttribute("aria-valuetext", effortName(options[i])); }; let saving = Promise.resolve(); const commit = () => { const o = options[at]; if (!o || o.value === f.value) return; f.value = o.value; box.closest(".row")?.querySelector(".ag-sum .eff")?.replaceWith(effortBars(f)); saving = saving.then(async () => { state = await api("set", { agent: a.id, field: f.key, value: o.value }); effortSaid(a, f, o); }).catch((e) => { status(e.message, "err"); renderAgents(); }); }; const stopAt = (x) => { const r = rail.getBoundingClientRect(); return Math.round(Math.max(0, Math.min(1, (x - r.left) / r.width)) * last); }; track.onpointerdown = (ev) => { track.setPointerCapture(ev.pointerId); track.classList.add("drag"); show(stopAt(ev.clientX)); }; track.onpointermove = (ev) => { if (track.classList.contains("drag")) show(stopAt(ev.clientX)); }; track.onpointerup = track.onpointercancel = () => { if (!track.classList.contains("drag")) return; track.classList.remove("drag"); commit(); }; track.onkeydown = (ev) => { const to = { ArrowLeft: at - 1, ArrowDown: at - 1, ArrowRight: at + 1, ArrowUp: at + 1, Home: 0, End: options.length - 1 }[ev.key]; if (to === undefined) return; ev.preventDefault(); show(Math.max(0, Math.min(options.length - 1, to))); commit(); }; show(at); return box; } // effortSaid: an effort set, and what the agent says of it, such as that an // open Claude Code session keeps the level it started with. function effortSaid(a, f, o) { const msg = `${a.name} ${t(f.label)} → ${effortName(o)}`; if (state.notice) status(withNotice(msg, state.notice), "warn", 9000); else status(msg, "ok"); } function renderEffortPicker() { const range = $("#effortRange"); const options = pick.options; const selected = Math.max(0, options.findIndex((o) => o.value === pick.field.value)); range.max = String(Math.max(0, options.length - 1)); range.value = String(selected); $("#effortTitle").textContent = t(pick.field.label); $("#effortMin").textContent = effortName(options[0]); $("#effortMax").textContent = effortName(options[options.length - 1]); // a dot at every level, so the stops show before the thumb gets there const ticks = $("#effortTicks"); ticks.replaceChildren(...options.map((_, i) => { const dot = el("i"); dot.style.setProperty("--at", options.length > 1 ? i / (options.length - 1) : 0); return dot; })); const update = () => { const i = Number(range.value); [...ticks.children].forEach((dot, j) => { dot.classList.toggle("on", j < i); dot.classList.toggle("cur", j === i); }); $("#effortValue").textContent = effortName(options[i]); const fill = `${options.length > 1 ? 100 * i / (options.length - 1) : 0}%`; range.style.setProperty("--fill", fill); range.closest(".effort-track").style.setProperty("--fill", fill); range.setAttribute("aria-valuetext", effortName(options[i])); }; range.oninput = update; range.onchange = () => { const opened = pick; const option = options[Number(range.value)]; if (!opened || !option || option.value === opened.field.value) return; opened.field.value = option.value; const value = opened.anchor.querySelector(".v"); if (value) { value.textContent = effortName(option); value.classList.toggle("empty", !option.value); } opened.anchor.querySelector(".effort-ic")?.replaceWith(effortIcon(opened.field)); // a square (the subagents' effort) says it in its title, lit while set if (opened.field.label === SUB_EFFORT) { opened.anchor.classList.toggle("set", !!option.value); opened.anchor.title = subEffortTitle(opened.agent, opened.field, option); opened.anchor.setAttribute("aria-label", opened.anchor.title); } // a tier's effort, opened from the tiers' square: that square's title // and light follow the level if (roleLevel(opened.field.label) && opened.anchor.classList.contains("ag-eff")) { opened.anchor.title = t("{label}: {value}", { label: t(opened.field.label), value: option.value ? effortName(option) : levelUnset(opened.agent) }); opened.anchor.setAttribute("aria-label", opened.anchor.title); } else if (roleLevel(opened.field.label)) { const menu = tierMenu(opened.agent); if (menu) { opened.anchor.classList.toggle("set", menu.custom); opened.anchor.title = menuTitle(menu); opened.anchor.setAttribute("aria-label", opened.anchor.title); } } // Persist every settled slider value, but keep the compact control open so // the user can compare adjacent levels. Queue writes to preserve ordering // when keyboard input changes several stops quickly. opened.effortSave = (opened.effortSave || Promise.resolve()).then(async () => { const next = await api("set", { agent: opened.agent.id, field: opened.field.key, value: option.value }); state = next; effortSaid(opened.agent, opened.field, option); }).catch((e) => status(e.message, "err")); }; range.onkeydown = (ev) => { if (ev.key === "Escape") { ev.preventDefault(); ev.stopPropagation(); closePicker(); } }; update(); } // filter lists the options the query finds; keep: the row for the cursor, // the first by default function filter(keep) { if (!pick) return; const q = $("#q").value.trim().toLowerCase(); let source = pick.options; if (pick.modelPicker && pick.groupFilter === "favorites") source = source.filter((o) => isFavorite(o)); else if (pick.modelPicker && pick.groupFilter !== "all") source = source.filter((o) => (o.group || o.home) === pick.groupFilter || o.reset); const scored = source.map((o) => ({ o, i: pick.options.indexOf(o), s: score(q, o) })).filter((x) => x.s > 0); // with a query, best matches first; without, catalog order keeps the groups together if (q) scored.sort((a, b) => b.s - a.s || a.i - b.i); pick.items = scored.map((x) => x.o); const typed = $("#q").value.trim(); if (typed && pick.free && ["model", "small", "large", "executor", "planner", ...ROLE_MODELS].includes(pick.field.label) && !pick.items.some((o) => o.value === typed)) { pick.items.push({ value: typed, note: t("use as typed"), custom: true }); } pick.items = foldSame(pick.items); // a model the filter finds among those kept for routing groups, which // aren't offered: said why, rather than missing without a word pick.kept = pick.modelPicker && q ? (state?.unlisted || []).filter((m) => [m.id, m.name].some((s) => s?.toLowerCase().includes(q))).slice(0, 3) : []; pick.cursor = typeof keep === "function" ? Math.max(0, pick.items.findIndex(keep)) : 0; renderPickerRail(); renderList(); } function updatePickerRailSelection() { const rail = $("#pickerRail"); const active = rail.querySelector(`.rail-item[data-group="${CSS.escape(pick?.groupFilter || "all")}"]`); for (const b of rail.querySelectorAll(".rail-item")) b.classList.toggle("on", b === active); const thumb = rail.querySelector(".rail-thumb"); if (active && thumb) { thumb.style.opacity = "1"; thumb.style.transform = `translate3d(0, ${active.offsetTop}px, 0)`; } } function switchPickerGroup(id) { if (!pick?.modelPicker || id === pick.groupFilter) return; const railItems = [...$("#pickerRail").querySelectorAll(".rail-item")]; const from = railItems.findIndex((b) => b.dataset.group === pick.groupFilter); const to = railItems.findIndex((b) => b.dataset.group === id); pick.groupFilter = id; updatePickerRailSelection(); $("#q").focus(); const list = $("#list"); pick.groupAnimation?.cancel(); const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches; if (reduced) { filter(); return; } const direction = to >= from ? 1 : -1; const token = (pick.groupTransition || 0) + 1; pick.groupTransition = token; const out = list.animate([ { opacity: 1, transform: "translate3d(0, 0, 0)" }, { opacity: 0, transform: `translate3d(${-direction * 5}px, 0, 0)` }, ], { duration: 75, easing: "cubic-bezier(.4, 0, 1, 1)", fill: "forwards" }); pick.groupAnimation = out; out.finished.then(() => { if (!pick || pick.groupTransition !== token) return; out.cancel(); filter(); const incoming = list.animate([ { opacity: 0, transform: `translate3d(${direction * 7}px, 0, 0)` }, { opacity: 1, transform: "translate3d(0, 0, 0)" }, ], { duration: 190, easing: "cubic-bezier(.22, 1, .36, 1)" }); pick.groupAnimation = incoming; }).catch(() => {}); } // a rail icon's name, beside it on the right: the browser's own tooltip // came up under the pointer, over the icon below — Devin's name on ZCode's // Z, as if that were ZCode's (Elan on X). Hovering from one icon to the // next moves it at once; the first waits a moment, as a tooltip does. let railTip = null, railTipTimer = 0, railTipShownAt = 0; function showRailTip(b, now) { clearTimeout(railTipTimer); const warm = railTip?.classList.contains("on") || performance.now() - railTipShownAt < 400; const show = () => { if (!b.isConnected || !pick?.modelPicker) return; if (!railTip) { railTip = el("div", "rail-tip"); railTip.setAttribute("role", "tooltip"); document.body.append(railTip); } railTip.textContent = b.getAttribute("aria-label"); const r = b.getBoundingClientRect(), w = railTip.offsetWidth; const right = r.right + 8 + w <= innerWidth - 4; railTip.style.left = (right ? r.right + 8 : Math.max(4, r.left - 8 - w)) + "px"; railTip.style.top = r.top + r.height / 2 + "px"; railTip.classList.toggle("left", !right); railTip.classList.add("on"); railTipShownAt = performance.now(); }; if (now || warm) show(); else railTipTimer = setTimeout(show, 450); } function hideRailTip() { clearTimeout(railTipTimer); if (railTip?.classList.contains("on")) { railTip.classList.remove("on"); railTipShownAt = performance.now(); } } $("#pickerRail").addEventListener("scroll", hideRailTip, { passive: true }); function renderPickerRail() { const rail = $("#pickerRail"); rail.hidden = !pick?.modelPicker; if (!pick?.modelPicker) { rail.replaceChildren(); rail.dataset.signature = ""; return; } const groups = pick.groups; const signature = groups.join("\u001f"); if (rail.dataset.signature !== signature) { rail.replaceChildren(); rail.dataset.signature = signature; rail.append(el("span", "rail-thumb")); const add = (id, title, child) => { const b = el("button", "rail-item"); b.dataset.group = id; b.setAttribute("aria-label", title); b.append(child); b.onclick = () => { hideRailTip(); switchPickerGroup(id); }; b.onpointerenter = () => showRailTip(b, false); b.onpointerleave = hideRailTip; b.onfocus = () => { if (b.matches(":focus-visible")) showRailTip(b, true); }; b.onblur = hideRailTip; rail.append(b); }; add("all", t("All models"), svg("M3 3h4v4H3zM9 3h4v4H9zM3 9h4v4H3zM9 9h4v4H9z", 15, 1.4)); add("favorites", t("Favorites"), svg("m8 2 1.8 3.7 4.1.6-3 2.9.7 4.1L8 11.4l-3.6 1.9.7-4.1-3-2.9 4.1-.6z", 16, 1.4)); if (groups.length) rail.append(el("span", "rail-sep")); for (const group of groups) { const sample = pick.options.find((o) => (o.group || o.home) === group); if (group === ROUTING_GROUPS) add(group, t(group), svg(FAN, 16, 1.5)); else add(group, group, icon(sample?.groupIcon || sample?.icon || "generic")); } } queueMicrotask(updatePickerRailSelection); } // namedFree: a model its vendor names free (OpenRouter's foo/bar:free, a // free-model), "free" as a word of its id or name, not freedom-7b (#185) function namedFree(...names) { return names.some((n) => /(^|[^a-z])free($|[^a-z])/i.test(n || "")); } // freeBadge: the green FREE by a model, and why it is free function freeBadge(plan) { const f = el("span", "badge free", t("free")); f.title = t(plan ? "free: it doesn't use the plan's credits" : "free: so its name says"); return f; } // rateTag: the plan's credits a request to a model costs, as its vendor // lists them (Qoder's 0.5×, WorkBuddy's x0.03), small and grey by it, so a // cheap one is picked without opening the vendor's app (01huadalang on // Discord); a discount's price before it struck through, as Qoder's // client shows it (a free one's beside its FREE) function rateTag(rate = 0, was = 0) { if (!(rate > 0) && !(was > rate)) return null; const times = (n) => (n < 0.01 ? "<0.01" : String(+n.toFixed(2))) + "×"; const tag = el("span", "badge rate"); if (was > rate) tag.append(el("s", "", times(was))); if (rate > 0) tag.append(el("span", "", times(rate))); tag.title = rate > 0 ? (was > rate ? t("costs {rate} credits a request, {was} before the discount", { rate: times(rate), was: times(was) }) : t("costs {rate} credits a request", { rate: times(rate) })) : t("free now, {was} before the discount", { was: times(was) }); return tag; } // contextTag: the small grey 1M by a model that holds a million tokens or // more (Cursor's names said it, and no longer do); the usual 128K–400K // aren't marked, as nearly every model has one of those; nor is a name // that says it itself ("GPT-5.5 Mini (1M)", kept to tell it from another) function contextTag(n, name) { if (!(n >= 1e6) || /\b\d+M\b/.test(name || "")) return null; const m = n / 1e6; const tag = el("span", "badge ctx", (Number.isInteger(m) ? m : m.toFixed(1)) + "M"); tag.title = t("holds {n} tokens", { n: n.toLocaleString(intlLang()) }); return tag; } // pathTag: an agent's model picker says by each model whether the agent // asks it through magpie or of its own vendor directly (Claude Code on its // own sign-in), and its Default, while it is connected, that it takes the // agent off magpie. Every agent's picker says it so, in one tag the note's // ellipsis can't cut off: the others' "· via magpie" ended their notes, // where Claude Code's was a tag (EZN7L2C3, #834). Codex's own models, // through magpie while it is routed, say so too (via); Codex's, Grok // Build's and Antigravity CLI's own said nothing at all function pathTag(o) { if (!pick?.agent || o.custom || o.run) return null; let tag = null; if (o.ref || o.via) { tag = el("span", "badge path via", t("via magpie")); tag.title = t("{agent} asks magpie for it", { agent: pick.agent.name }); } else if (o.direct) { tag = el("span", "badge path direct", t("direct, not via magpie")); tag.title = t("straight to {vendor}, not through magpie", { vendor: o.direct }); } else if (o.reset && o.value === "" && leavesMagpie(pick.agent, pick.field, "", o)) { tag = el("span", "badge path direct", t("off magpie")); tag.title = t("{agent} as installed: magpie's endpoint and models come out", { agent: pick.agent.name }); } return tag; } function renderList() { const list = $("#list"); list.replaceChildren(); if (!pick.items.length) { list.append(el("div", "none", t("No matches."))); for (const m of pick.kept || []) list.append(keptNote(m)); return; } const hasIcons = pick.items.some((o) => o.icon || o.effortOf); const q = $("#q").value.trim(); let group = null; pick.items.forEach((o, idx) => { if (!q && o.group && o.group !== group) list.append(el("li", "group", o.group === ROUTING_GROUPS ? t(o.group) : o.group)); if (!q) group = o.group ?? group; if (o.fold) { list.append(foldRow(o, idx, hasIcons)); return; } const li = el("li", (idx === pick.cursor ? "sel" : "") + (o.value === pick.field.value || pick.field.picked?.(o.value) ? " cur" : "") + (o.custom ? " custom" : "") + (o.reset ? " reset" : "")); li.dataset.i = idx; if (hasIcons) li.append(optionIcon(o)); const words = el("span", "option-words"); // a choice of magpie's own (Codex's sign-in) reads in the page's language const own = pick.field.label === "sign-in"; words.append(el("span", "v", own ? t(o.label || o.value) : o.label || o.value)); if (o.free || (pick.modelPicker && o.value && namedFree(o.value, o.label))) words.append(freeBadge(o.free)); const rate = rateTag(o.rate, o.rateWas); if (rate) words.append(rate); const ctx = contextTag(o.context, o.label); if (ctx) words.append(ctx); // an Aside account's note is its e-mail, or Aside's "Local Account", // then whether Aside has it active: the words are magpie's, the e-mail not let note = o.note && o.note !== (o.label || o.value) ? (own ? t(o.note) : asideAccount(pick.agent, pick.field) ? o.note.split(" · ").map((w) => t(w)).join(" · ") : o.note) : ""; // which way the model goes, as a tag the note's ellipsis can't cut // off: "· via magpie" ended a long note (an account's e-mail), and // Claude Code's own models said nothing, so an Opus asked of Anthropic // directly and a Sonnet through magpie looked alike (#726) const path = pathTag(o); if (path) { words.append(path); note = note.replace(/(^| · )via magpie$/, ""); } if (q && o.group && !note) note = o.group; // a note cut off by its ellipsis (the other groups a model is in, // #907) reads whole on hover if (note) { const n = el("span", "n", note); n.title = note; words.append(n); } li.append(words); if (o.run) li.title = t(DISCONNECT_TIP, { agent: pick.agent.name }); if (pick.modelPicker && o.value && !o.custom && !o.run) { const star = el("button", "favorite" + (isFavorite(o) ? " on" : "")); star.title = isFavorite(o) ? t("Remove from favorites") : t("Add to favorites"); star.setAttribute("aria-pressed", String(isFavorite(o))); star.append(svg("m8 2 1.8 3.7 4.1.6-3 2.9.7 4.1L8 11.4l-3.6 1.9.7-4.1-3-2.9 4.1-.6z", 14, 1.4)); star.onclick = (ev) => { ev.stopPropagation(); const key = favoriteKey(o); if (isFavorite(o)) { modelFavorites.delete(key); modelFavorites.delete(o.value); } else modelFavorites.add(key); localStorage.setItem("magpie.modelFavorites", JSON.stringify([...modelFavorites])); filter(); }; li.append(star); } if (o.fastFor && o.ref && !o.run) li.append(fastToggle(o)); const ck = el("span", "check"); ck.append(svg(CHECK, 12, 1.8)); li.append(ck); li.onmousemove = () => { if (pick.cursor !== idx) { pick.cursor = idx; renderList(); } }; li.onclick = () => commit(o.value); list.append(li); }); for (const m of pick.kept || []) list.append(keptNote(m)); list.querySelector(`li[data-i="${pick.cursor}"]`)?.scrollIntoView({ block: "nearest" }); } // fastToggle: a model with a fast mode (a ChatGPT account's GPT, Cursor's // -fast, …) is sent in it, or not, for the agent the picker is of (#954), // switched by the model as a routing group's member is; the pick itself // stays as it is const BOLT = "M9.25 1.75 3.75 9h4l-1 5.25L12.25 7h-4z"; function fastToggle(o) { const b = el("button", "fast" + (o.fast ? " on" : "")); const name = o.label || o.value; const agent = pick.agent.name || o.fastFor; // on a provider the user added (ownFast, #1615) fast is only asked for: // magpie can't know the provider serves it b.title = o.ownFast ? (o.fast ? t("{model} is asked for OpenAI's fast mode for {agent}, where your provider serves it. Click to send it as {agent} asks", { model: name, agent }) : t("Ask your provider for OpenAI's fast mode (service_tier \"priority\") on {model} for {agent}: quicker, at a higher price, where it serves it", { model: name, agent })) : o.fast ? t("{model} is sent fast for {agent}: quicker, at a higher price. Click to send it at the usual speed", { model: name, agent }) : t("Send {model} fast for {agent}: quicker, at a higher price", { model: name, agent }); b.setAttribute("aria-pressed", String(!!o.fast)); b.setAttribute("aria-label", t("Fast")); b.append(svg(BOLT, 14, 1.4)); b.onclick = async (ev) => { ev.stopPropagation(); const fast = !o.fast; setFast(o, fast); try { await api("agent-fast", { for: o.fastFor, ref: o.ref, fast }); status(t(fast ? "{model} is sent fast for {agent}" : "{model} is sent at the usual speed for {agent}", { model: name, agent }), "ok"); } catch (e) { setFast(o, !fast); status(e.message, "err"); } }; return b; } // setFast marks the model fast or not in every list it is in for the agent: // the open picker's, and the agent's fields (its tiers pick the same model) function setFast(o, fast) { const same = (x) => x.ref === o.ref && x.fastFor === o.fastFor; for (const a of state.agents) for (const f of a.fields) for (const x of f.options || []) if (same(x)) x.fast = fast; for (const x of [...(pick?.options || []), ...(pick?.items || [])]) if (same(x)) x.fast = fast; o.fast = fast; // the field's button says it of the model it has const anchor = pick?.anchor; if (anchor?.classList.contains("field") && optionFor(pick.field, pick.field.value)?.ref === o.ref) { anchor.querySelector(".fast-tag")?.remove(); if (fast) anchor.querySelector(".v")?.after(fastTag()); } if (pick) renderList(); } // fastTag: the bolt after a field's model that is sent fast function fastTag() { const s = el("span", "fast-tag"); s.title = t("Fast"); s.append(svg(BOLT, 11, 1.4)); return s; } // foldRow: the one row the models on the agent's own account through // magpie fold into (foldSame), opened or closed at a click function foldRow(o, idx, hasIcons) { const li = el("li", "fold" + (o.open ? " open" : "") + (idx === pick.cursor ? " sel" : "")); li.dataset.i = idx; li.setAttribute("role", "button"); li.setAttribute("aria-expanded", String(o.open)); if (hasIcons) li.append(optionIcon(o)); const words = el("span", "option-words"); words.append(el("span", "v", t(o.n === 1 ? "{n} model via magpie" : "{n} models via magpie", { n: o.n }))); words.append(el("span", "n", o.account ? t("{account} · the account {agent} is signed in to", { account: o.account, agent: pick.agent.name }) : t("the account {agent} is signed in to", { agent: pick.agent.name }))); li.append(words); const chev = el("span", "chev"); chev.append(svg("m6 4 4 4-4 4", 12, 1.6)); li.append(chev); li.title = t(o.open ? "Fold them away again" : "The same models as {agent}'s own, through magpie: click to show them", { agent: pick.agent.name }); li.onmousemove = () => { if (pick.cursor !== idx) { pick.cursor = idx; renderList(); } }; // the filter keeps the keys: the picker stays open, and the arrows, // Enter and Esc go on working li.onmousedown = (ev) => ev.preventDefault(); li.onclick = (ev) => { ev.stopPropagation(); toggleFold(); }; return li; } // keptNote: a model of a provider set to "Only through routing groups", // found by the picker's filter. It isn't offered: in a group, that group // is, picked here at a click; in none, nothing uses it, and a click makes // a group of it. function keptNote(m) { const li = el("li", "kept"); li.append(icon(m.icon || "generic")); const words = el("span", "kept-words"); const model = m.name || m.id; words.append(el("b", "", model)); const via = m.groups.map((g) => pick.options.find((o) => o.ref === g && o.group === ROUTING_GROUPS)).filter(Boolean); const act = el("button", "text action"); if (via.length) { words.append(el("span", "", t("{provider} is used only through routing groups: agents reach {model} by picking {group}.", { provider: m.provider, model, group: via.map((o) => o.label || o.value).join(", ") }))); act.textContent = t("Pick {group}", { group: via[0].label || via[0].value }); act.onclick = (ev) => { ev.stopPropagation(); commit(via[0].value); }; } else { words.append(el("span", "", t("{provider} is used only through routing groups, and {model} is in none, so no agent can use it. Make a group of it, or untick “Only through routing groups” in {provider}'s models.", { provider: m.provider, model }))); act.textContent = t("Make a routing group of it"); act.onclick = (ev) => { ev.stopPropagation(); closePicker(); if (mode !== "window") api("window/main?view=routing&newgroup=" + encodeURIComponent(m.id), {}).catch((e) => status(e.message, "err")); else window.newGroupWith?.(m.id, m.name, ev); }; } li.append(words, act); return li; } function move(d) { if (!pick || !pick.items.length) return; pick.cursor = (pick.cursor + d + pick.items.length) % pick.items.length; renderList(); } async function commit(value) { if (!pick || value == null) return; const { agent, field, anchor } = pick; const opt = pick.options.find((o) => o.value === value); if (field.multi && !opt?.run) { // a picker that takes several (a group's models, PAMI on Discord) // stays open: each pick adds one, or takes it out again, and is ticked field.onPick(value, opt); if (opt) renderList(); else { $("#q").value = ""; filter(); } // a model typed in is in now // the filter keeps the keys, for the next one and Escape if (!web || !matchMedia("(pointer: coarse)").matches) $("#q").focus({ preventScroll: true }); return; } closePicker(); if (opt?.run) return opt.run(); // an act rather than a value (Disconnect from magpie) if (field.onPick) return field.onPick(value, opt); // a picker opened for something other than an agent's setting if (field.menu) { // a tier chosen from the tiers menu: now its model const tier = agent.fields.find((f) => f.key === value); if (tier) openPicker(agent, tier, anchor, { stopPropagation() {} }); return; } if (value === field.value) return; if (agent.native) return setPick(agent, field, value, opt); // a pick that takes a connected agent off magpie (its Default, or a // model of its own asked of its vendor directly) is asked first, as the // switch's off is: it moved Claude Code under Not set up at a click // (#726) if (leavesMagpie(agent, field, value, opt)) { askLeave(agent, field, value, opt); return; } return setPick(agent, field, value, opt); } // asideAccount: Aside's account field, which of its accounts (~/.aside/u/N) // magpie configures; empty follows the one Aside has active (#1499) function asideAccount(a, f) { return a?.id === "aside" && f?.key === "account"; } // leavesMagpie: picking value in field takes the connected agent off // magpie: its Default in the field it is connected through (Set("") takes // out what magpie wired in), or a model of its own it asks its vendor for // directly (Claude Code's own, which unroutes it). From one of its own // models already, the pick doesn't move it off magpie. function leavesMagpie(a, field, value, opt) { if (a?.native || !a?.wired || !connectable(a)) return false; // Reasonix restores each role separately; either role can keep its provider. if (a.id === "reasonix" && value === "") { return !!optionFor(field, field.value)?.ref && !a.fields.some((f) => f !== field && optionFor(f, f.value)?.ref); } if (field !== (startField(a) || connectField(a))) return false; if (optionFor(field, field.value)?.direct) return false; return value === "" || !!opt?.direct; } // askLeave: what such a pick does, and the way back, before it is made. // Default isn't Disconnect: it leaves the agent as installed, where // Disconnect puts back what it had before magpie, so both are offered. function askLeave(a, field, value, opt) { const model = opt?.label || value; const ed = el("div", "editor disconnect-ask leave-ask"); const head = el("div", "ehead"); head.append(icon(a.icon), el("b", "", t("Take {agent} off magpie?", { agent: a.name }))); ed.append(head); ed.append(el("p", "lib-confirm", value === "" && a.id === "reasonix" ? t("Restores {agent}'s previous {field} selection. Magpie's provider and private credential are removed when neither executor nor planner uses them.", { agent: a.name, field: t(field.label) }) : value === "" ? t("Default is {agent} as installed: magpie's endpoint and models come out, and {agent} starts on its own default model. What it had before magpie isn't put back; Disconnect and restore does that.", { agent: a.name }) : t("{model} is {agent}'s own model: {agent} asks {vendor} for it itself, with its own sign-in, not through magpie. Picking it takes {agent} off magpie, and it starts on {model}.", { agent: a.name, model, vendor: opt.direct }))); const others = state.agents.some((x) => x.id !== a.id && onMagpie(x) && !isHidden(x)); ed.append(el("p", "lib-confirm", others ? t("「接入」 goes off, and {agent} is listed under Not set up with the agents not connected. Switch it on again to go back through magpie.", { agent: a.name }) : t("「接入」 goes off. Switch it on again to go back through magpie."))); const bar = el("div", "bar"); const go = el("button", "text primary", value === "" ? t("Use default") : t("Use {model}", { model })); go.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); setPick(a, field, value, opt); }; const cancel = el("button", "text", t("Cancel")); cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; bar.append(STARTS_WITH.has(a.id) ? el("span", "ag-bar-note", t("Running {agent} copies take it once reopened", { agent: a.name })) : el("span"), el("span", "grow"), cancel); if (value === "") { const restore = el("button", "text", t("Disconnect and restore")); restore.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); askDisconnect(a); }; bar.append(restore); } bar.append(go); ed.append(bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); cancel.focus({ preventScroll: true }); } // setPick writes a value picked for an agent's field async function setPick(agent, field, value, opt) { // The pick shows at once: the row is drawn with it before magpie has // written the config and answered with the whole state, which can take // seconds (every agent's lists are read again for it). The answer then // draws what the config really says; a refused pick puts the old one back. const was = field.value; if (agent.native) { try { state = await api("set", { agent: agent.id, field: field.key, value }); renderAgents(); } catch (err) { if (err.code === "runtime_unavailable" && err.offline === "stage") { const ed = el("div", "editor disconnect-ask"); ed.append(el("p", "lib-confirm", t("Aside is unavailable. Save this model for its next start?"))); const bar = el("div", "bar"), cancel = el("button", "text", t("Cancel")), save = el("button", "text primary", t("Save for next start")); cancel.onclick = () => closeConfirmAsk(); save.onclick = async () => { save.disabled = true; try { state = await api("agents/stage/" + agent.id, { field: field.key, value }); closeConfirmAsk(); renderAgents(); } catch (err) { save.disabled = false; status(t(err.message), "err"); } }; bar.append(cancel, save); ed.append(bar); confirmAsk = ed; openModal(ed); cancel.focus({ preventScroll: true }); } else status(t(err.message), "err"); } return; } const leaving = leavesMagpie(agent, field, value, opt); const seq = commit.seq = (commit.seq || 0) + 1; field.value = value; const picked = performance.now(); // the green flash runs on through the row drawn again with the answer const flash = () => { const b = document.querySelector(`.agent[data-id="${CSS.escape(agent.id)}"] .field[data-key="${grouped(agent, field) ? "tiers" : field.key}"]`); const gone = performance.now() - picked; if (!b || gone > 1200) return; b.style.animationDelay = `${-gone}ms`; b.classList.add("flash"); }; renderAgents(); flash(); try { const next = await api("set", { agent: agent.id, field: field.key, value }); // a later pick is already on its way: its answer is the one to draw if (seq !== commit.seq) return; state = next; renderAgents(); flash(); const shown = opt?.label || value; if (state.notice) status(withNotice(`${agent.name} → ${shown}`, state.notice), "warn", 9000); else if (leaving && value === "") status(t(agent.id === "reasonix" ? "{agent} no longer goes through magpie; its own settings are back" : "{agent} no longer goes through magpie · on its own default", { agent: agent.name }), "ok", 6000); else if (opt?.direct) status(`${agent.name} ${t(field.label)} → ${shown} · ${t("straight to {vendor}, not through magpie", { vendor: opt.direct })}`, "ok", 6000); else status(`${agent.name} ${t(field.label)} → ${shown}`, "ok"); if (providers) loadProviders(); } catch (e) { if (seq === commit.seq && field.value === value) { field.value = was; renderAgents(); } status(e.message, "err"); } } // popGhost leaves a likeness of the picker where it was, to fade and sink // away while the real one is already put back for its next opening. function popGhost(pop) { if (pop.hidden || matchMedia("(prefers-reduced-motion: reduce)").matches) return; const g = pop.cloneNode(true); g.removeAttribute("id"); g.querySelectorAll("[id]").forEach((e) => e.removeAttribute("id")); g.classList.add("leaving"); g.setAttribute("aria-hidden", "true"); g.inert = true; pop.after(g); // what a clone doesn't carry: where its lists were scrolled, what was typed const from = pop.querySelectorAll("*"), to = g.querySelectorAll("*"); from.forEach((e, i) => { if (e.scrollTop) to[i].scrollTop = e.scrollTop; if (e.tagName === "INPUT") to[i].value = e.value; }); const done = () => g.remove(); g.addEventListener("animationend", done, { once: true }); setTimeout(done, 400); } function closePicker() { if (!pick) return; hideRailTip(); pick.groupAnimation?.cancel(); popGhost($("#pop")); pick.anchor.classList.remove("open"); $("#pop").hidden = true; $("#pop").classList.remove("model-picker", "effort-picker", "explained"); $("#pop .search").hidden = false; $("#pop .picker-body").hidden = false; $("#effortControl").hidden = true; pick = null; } $("#q").addEventListener("input", filter); $("#q").addEventListener("keydown", (e) => { if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n")) { e.preventDefault(); move(1); } else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p")) { e.preventDefault(); move(-1); } else if (e.key === "Enter") { e.preventDefault(); if (pick?.items[pick.cursor]?.fold) toggleFold(); else commit(pick?.items[pick.cursor]?.value); } else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closePicker(); } }); document.addEventListener("mousedown", (e) => { if (pick && !$("#pop").contains(e.target) && !pick.anchor.contains(e.target)) closePicker(); }); document.addEventListener("keydown", (e) => { if (e.key !== "Escape" || pick) return; if (editing !== null || importingApps) cancelEdit(); else if (adding && !$("#view-providers").hidden && providers.providers.length) closeAddSheet(); else if (profileEscape()) e.preventDefault(); else if (mode === "panel") api("window/hide", {}); }); // ---------- profiles ---------- // profileLibrary is what a profile gives out from the Library, in a few // words; "" for one saved without it. function profileLibrary(l) { if (!l) return ""; const parts = []; if (l.servers) parts.push(t(l.servers === 1 ? "{n} server" : "{n} servers", { n: l.servers })); if (l.skills) parts.push(t(l.skills === 1 ? "{n} skill" : "{n} skills", { n: l.skills })); if (l.instructions) parts.push(t("instructions")); return parts.length ? t("+ Library: {what}", { what: parts.join(t(", ")) }) : t("+ Library: nothing on"); } // profilePending are the profiles a save, update, delete or use is on its // way for. What the click does shows at once — the chip saved is there, the // one deleted gone, the name field closed — rather than when magpie has read // every agent again for the answer: that took seconds, and a Save or × that // changed nothing for that long looked broken. An error puts the list back. const profilePending = new Set(); async function profileAction(action, name, update) { const before = state.profiles; if (action === "delete") state.profiles = before.filter((p) => p.name !== name); else if (action === "save" && !before.some((p) => p.name === name)) { // where magpie will list it: by name, as Go's sort.Strings has them state.profiles = [...before, { name, summary: "" }].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); } if (action !== "delete") profilePending.add(name); renderProfiles(); fit(); try { const data = await api("profile/" + action, { name }); profilePending.delete(name); state = data; renderAgents(); if (action === "use") { // the details close, renderAgents having drawn them again (#489: // profileOpen dropped first, closeProfileDetail found nothing open and // left them there, their × doing nothing) closeProfileDetail(); closeProfiles(); // the agents, as they are now, in sight let msg = t(data.changed === 1 ? "{name} applied · {n} setting changed" : "{name} applied · {n} settings changed", { name, n: data.changed }); const lib = data.library; if (lib?.missing?.length) msg += " · " + t("skipped, no longer in the Library: {names}", { names: lib.missing.map((m) => m.replace(/^\w+:/, "")).join(", ") }); if (lib?.problems?.length) status(msg + " · " + t("some of the Library couldn't be given; see Library"), "err", 6000); else status(msg, "ok", lib?.missing?.length ? 6000 : 3500); } else if (action === "save") status(t(update ? "Updated {name} to the current setup" : "Saved {name}", { name }), "ok"); else status(t("Deleted {name}", { name })); } catch (e) { profilePending.delete(name); state.profiles = before; renderProfiles(); fit(); status(e.message, "err"); } } // + Save current opens a name field beside it, and the button is Save; a // click on it saves as Enter does (it did nothing: the field lost focus to // it and went). The field goes where the button is, not at the head of the // list: in the panel it drew the list up under the tabs, the field's top // cut off, or put the button out of sight below it. const saveCurrent = $("#save"); const saveField = () => $(".profiles > .chip-input"); const closeSave = (input) => { input.remove(); if (!saveField()) { saveCurrent.textContent = t("+ Save current"); $(".profiles").classList.remove("naming"); } }; saveCurrent.onmousedown = (e) => { if (saveField()) e.preventDefault(); }; // the field keeps focus saveCurrent.onclick = () => { const open = saveField(); if (open) { if (open.value.trim()) profileAction("save", open.value.trim()); else open.focus({ preventScroll: true }); return; } const input = el("input", "chip-input"); input.placeholder = t("Profile name"); input.onkeydown = (e) => { if (e.key === "Enter" && input.value.trim()) profileAction("save", input.value.trim()); else if (e.key === "Escape") closeSave(input); e.stopPropagation(); }; input.onblur = () => setTimeout(() => closeSave(input), 100); saveCurrent.before(input); $(".profiles").classList.add("naming"); // for the panel's hint: :has() came in Safari 15.4 (#220) saveCurrent.textContent = t("Save"); input.focus({ preventScroll: true }); }; // ---------- providers view ---------- // // A provider is a vendor plus the key the user pasted. Presets need only the // key; a custom one needs a name and a base URL too. Every exposed model of // every provider becomes "provider/model" in the agents' pickers, served by // the local gateway in whichever API the agent speaks. async function loadProviders() { // the skeletons only while there is nothing yet: a reload keeps what is // drawn, and where the reader is in it, until the new one is in if (!providers) { if (view === "gateway") renderGatewayLoading(); else renderProvidersLoading(); } // the gateway page opened from another that had the list: drawn from it // at once, not left as empty cards until the new one is in (#123) else if (view === "gateway" && !$("#gateway").childElementCount) renderGatewayView(); const was = providers; providers = await api("providers"); renderSideGw(providers.gateway); // a reload's provider may be gone since if (typeof editing === "string" && !providers.providers.some((p) => p.id === editing)) editing = null; // a providers.json that can't be read is not a first use: no Add sheet if (!providers.providers.length && editing === null && !providers.fileError) adding = true; if (view === "gateway") { // the gateway page is looked at and left open: coming back to the window // redraws it only when something on it changed, and when only the calls // did, only them (an account's last sign-in check isn't on it) const json = (a) => JSON.stringify(a, (k, v) => (k === "seen" ? undefined : v)); const same = (a, b) => json(a) === json(b); if (was && !$("#view-gateway").classList.contains("loading") && same({ ...was, gateway: { ...was.gateway, calls: 0 } }, { ...providers, gateway: { ...providers.gateway, calls: 0 } })) { if (!same(was.gateway.calls, providers.gateway.calls)) renderActivity(); } else renderGatewayView(); backToReader($("#view-gateway")); } else renderProviders(); renderArchive(); providersWhileFetching(); if (view === "providers") loadUpstream(); discoverLocalProviders(); } // Accounts' lists still on their way from their vendors (#541: the page no // longer waits for them): asked again every few seconds until they are in, // and drawn again only when something changed — never under an open editor. // A read that failed, or a reload that did, is asked again rather than ending // the asking: this timer is what brings the lists in. function providersWhileFetching() { clearTimeout(providersWhileFetching.timer); if (!providers?.fetching) return; providersWhileFetching.timer = setTimeout(async () => { if (!["providers", "gateway", "routing"].includes(view) || editing !== null || adding || document.hidden) return; let next; try { next = await api("providers"); } catch { providersWhileFetching(); return; } const json = (p) => JSON.stringify({ ...p, fetching: false, gateway: { ...p.gateway, calls: 0 } }); if (json(next) !== json(providers)) { // a reload that failed says nothing about the lists being in: it is // asked again too, as loadProviders would have try { await loadProviders(); } catch { providersWhileFetching(); } } else { providers.fetching = next.fetching; providersWhileFetching(); } }, 2500); } // What the vendors' own status pages say of the APIs the providers call // (#971, emo172): a vendor's API degraded or down is marked on its // providers' rows and usage cards, so its outage isn't taken for a sign-in // or quota problem. The gateway reads each page at most once in five // minutes; it is asked when the Providers or Usage page loads, and again // every five minutes while one stays open. A page that couldn't be read // marks nothing: unknown is not "all well", and not an outage either. let upstream = null, upstreamAsking = null; function loadUpstream() { if (upstreamAsking) return upstreamAsking; clearTimeout(loadUpstream.timer); upstreamAsking = api("upstream").then((u) => { if (Array.isArray(u?.vendors)) { upstream = u; markUpstream(); } }, () => {}).finally(() => { upstreamAsking = null; loadUpstream.timer = setTimeout(() => { if (!document.hidden && (view === "providers" || view === "usage")) loadUpstream(); }, 5 * 60e3); }); return upstreamAsking; } const UPSTREAM_LEVEL = { degraded: "API degraded", partial: "API outage", major: "API outage", maintenance: "API maintenance" }; const UPSTREAM_PART = { degraded_performance: "degraded performance", partial_outage: "partial outage", major_outage: "major outage", under_maintenance: "under maintenance" }; // the vendor's reading for a provider, when its page says the API is affected function upstreamOf(id) { const v = upstream?.providers?.[id]; const s = v && upstream.vendors.find((x) => x.vendor === v); return s && UPSTREAM_LEVEL[s.level] ? s : null; } function upstreamBadge(s) { const b = el("button", "badge upstream " + s.level, t(UPSTREAM_LEVEL[s.level])); b.type = "button"; const lines = [t("{vendor}'s status page says its API is affected", { vendor: s.name })]; for (const p of s.parts || []) lines.push("· " + p.name + ": " + t(UPSTREAM_PART[p.status] || p.status)); for (const i of s.incidents || []) lines.push("· " + i.name); lines.push(t("Click to open the status page")); b.title = lines.join("\n"); // the incident's own page when it has one, else the vendor's b.onclick = (e) => { e.stopPropagation(); api("open", { url: s.incidents?.find((i) => i.url)?.url || s.page }).catch(() => {}); }; return b; } // marks (or unmarks) what is drawn; the lists call it after each redraw function markUpstream() { const put = (box, s, after) => { if (!box) return; box.querySelector(":scope > .badge.upstream")?.remove(); box.classList.remove("with-upstream"); if (!s) return; // a row's name as a box of its own, to be the part cut short if (!after && box.firstChild?.nodeType === Node.TEXT_NODE) { const nm = el("span", "nm"); nm.append(box.firstChild); box.prepend(nm); } const b = upstreamBadge(s); if (after) after.after(b); else box.append(b); // a class, not :has(), which Safari 15.0 doesn't parse (#220) box.classList.add("with-upstream"); }; for (const row of document.querySelectorAll("#providers .row.provider[data-id], #offProviders .row.provider[data-id]")) { put(row.querySelector(".name"), upstreamOf(row.dataset.id)); } for (const card of document.querySelectorAll("#subscriptionUsage > .subscription-card[data-provider]")) { const head = card.querySelector(":scope > .subscription-head"); put(head, upstreamOf(card.dataset.provider), head?.querySelector(":scope > b")); } } // Rows in the shape of the list while it is first asked for; a reload keeps // the list it has until the new one is in. function renderProvidersLoading() { const page = $("#view-providers"); page.classList.add("loading"); page.setAttribute("aria-busy", "true"); const list = $("#providers"); list.hidden = false; list.replaceChildren(); for (let i = 0; i < 5; i++) { const row = el("div", "row provider pv-sk-row"); const who = el("div", "who pv-sk-who"); who.append(el("span", "skeleton pv-sk-name"), el("span", "skeleton pv-sk-sub")); row.append(el("span", "skeleton pv-sk-icon"), who, el("span", "skeleton pv-sk-key")); list.append(row); } $("#offHead").hidden = $("#offProviders").hidden = true; $("#excluded").replaceChildren(); } // Providers switched off are kept apart, below the ones on, under a // "Turned off (N)" fold that starts folded: among the rest they took the // room of the ones in use (01huadalang on Discord). The fold is // remembered, per viewer. let offFolded = true; try { offFolded = localStorage.getItem("magpie.offProvidersOpen") !== "1"; } catch {} $("#foldOff").prepend(svg(CHEV_R, 11, 1.6)); $("#foldOff").onclick = () => { offFolded = !offFolded; try { localStorage.setItem("magpie.offProvidersOpen", offFolded ? "0" : "1"); } catch {} renderProviders(); }; // One row per provider: logo, name, the agents pointed at it, key status. // Everything else lives in the editor, a dialog over the page. function renderProviders() { if (accountArranging || providerArranging) { accountRenderPending = true; return; } // Rebuilding the list empties the page for a moment, which clamps its // scroll to the top; put it back so closing the editor leaves the reader // where they were. const view = $("#view-providers"), top = view.scrollTop; markNewPartners(); keepIcons($("#providers"), $("#offProviders"), $("#addSheet"), $("#excluded")); view.classList.remove("loading"); view.removeAttribute("aria-busy"); closeProtoMenu(); syncURL(); const onList = $("#providers"), offList = $("#offProviders"); onList.replaceChildren(); offList.replaceChildren(); const offs = providers.providers.filter((p) => p.off).length; onList.hidden = offs === providers.providers.length; $("#offHead").hidden = !offs; offList.hidden = !offs || offFolded; const fold = $("#foldOff"); fold.setAttribute("aria-expanded", String(!offFolded)); fold.title = t(offFolded ? "Show the providers turned off" : "Fold the providers turned off away"); $("#offCount").textContent = offs ? String(offs) : ""; let dialog = null; // the editor, if one is open for (const p of providers.providers) { const list = p.off ? offList : onList; const open = editing === p.id; const row = el("div", "row provider" + (open ? " selected" : "") + (p.off ? " off" : "")); row.dataset.id = p.id; const who = el("div", "who"); const name = el("div", "name", p.name); if (p.sponsored) name.append(el("span", "badge", t("sponsored"))); if (p.off) name.append(el("span", "badge off", t("Switched off"))); if (p.move && p.move.state !== "plugin") name.append(deprecatedBadge()); const n = p.models.filter((m) => m.on).length; // a provider that only draws images (Settings → Image generation) says so const models = n ? t(n === 1 ? "{n} model" : "{n} models", { n }) : p.draws ? t(p.draws === 1 ? "{n} image model" : "{n} image models", { n: p.draws }) : t("no models exposed"); // every account in use refused by its vendor: signed out, as the // accounts list says of each, not a green "signed in" const inUse = (p.account?.logins || []).filter((l) => l.on || l.active); const lapsed = inUse.length > 0 && inUse.every((l) => l.lapsed); who.append(name, el("div", "sub", (p.account ? t(lapsed ? "{user} is signed out" : "signed in as {user}", { user: p.account.user }) : p.host) + " · " + models)); const using = p.agents.filter((a) => a.current); const uses = el("div", "uses"); for (const a of using) { const b = el("button", "use"); b.title = a.group ? t("{name} · {model}, through the routing group {group} — click to change", { name: a.name, model: a.model, group: a.group }) : t("{name} · {model} — click to change", { name: a.name, model: a.model }); b.append(icon(a.icon)); b.onclick = (ev) => pickForAgent(a, p, b, ev); uses.append(b); } let key; if (p.account && lapsed) { key = el("span", "key acct none", t("Signed out")); key.title = t("Signed out — add this account again to use it"); } else if (p.account) { // the row names the vendor: a plan too long for the pill goes without it const plan = accountPlan(p.account), bare = plan.startsWith(p.name + " ") ? plan.slice(p.name.length + 1) : ""; key = el("span", "key acct", bare && plan.length > 15 ? bare : plan); key.title = t("{agent} is signed in; its models are here for every other agent", { agent: p.account.agentName }); } else if (p.vertex) { // Vertex AI signs with the user's Google credentials, never a key; // the pill says which: the service account it acts as, else the // credentials file, else Application Default Credentials (ADC) const v = p.vertex; key = el("span", "key " + (p.ready ? "acct" : "none"), !p.ready ? t("needs a project") : v.impersonate || (v.credentials ? baseName(v.credentials) : t("Google ADC"))); key.title = !p.ready ? t("Open the row and give your Google Cloud project's id") : (v.impersonate ? t("Signed as the service account {account}, with your Google credentials", { account: v.impersonate }) : t("Signed with your Google credentials")) + " · " + (v.credentials || t("Application Default Credentials")); } else { key = el("span", "key " + (p.key.set ? (keyPill(p) === p.key.masked ? "on" : "on acct") : p.ready ? "free" : "none"), p.key.set ? keyPill(p) : p.ready ? t("no key") : t("needs a key")); key.title = p.key.set ? t("API key {masked}", { masked: p.key.masked }) : p.ready ? t("Local servers need no key") : t("Open the row and paste an API key"); } // every pill is one width so the dots line up down the list; a label too long for it ends in "…" and is said whole on hover const label = key.textContent; key.textContent = ""; key.append(el("span", "", label)); if (!key.title.includes(label)) key.title = (p.account && !lapsed ? accountPlan(p.account) : label) + " · " + key.title; const chev = el("span", "chev"); chev.append(svg(CHEV_R, 11, 1.7)); // a provider on is listed, and tried, in the order the user puts it in // (#499): its logo is the handle, as an agent row's is row.append(p.off ? icon(p.icon || "generic") : providerHandle(p, row), who, uses, key, providerSwitch(p), chev); // right-click: Move to Top, Move Up, Move Down, Move to Bottom (#1614) if (!p.off) row.oncontextmenu = (ev) => { ev.preventDefault(); openProviderMenu(row.querySelector(".pv-handle"), p); }; row.onclick = async () => { if (providerDirty() && !(await confirmDiscard())) return; editing = open ? null : p.id; draft = null; renderProviders(); }; // the preset sheet stays as it is under the dialog list.append(row); if (open) dialog = renderEditor(p); } findProviders(); renderExcluded(); renderFileError(); renderMovable(); renderProviderDiscovery(); dialog = renderAdd() || dialog; if (importing) dialog = renderImport(importing); if (importingApps) dialog = renderImportApps(importingApps); keptIcons = null; markUpstream(); view.scrollTop = top; // first: a closing dialog folds into its row where it is if (dialog) openModal(dialog); else closeModal(); } // providerHandle is an on row's logo, which is also its handle (#499): // drag it to move the row among the ones on, Alt+↑/↓ moves it from the // keyboard, and a click opens the row as a click anywhere on it does. The // grip that says so is drawn in the row's margin on hover (app.css). The // order is the one providers are tried in too: a model several serve goes // to the higher one first. let providerArranging = false; function providerHandle(p, row) { const b = el("button", "ag-handle pv-handle"); b.type = "button"; b.setAttribute("aria-label", t("Arrange {agent}", { agent: p.name })); b.title = t("Drag to reorder — a model several providers serve goes to the higher one first · Alt+↑/↓ to move") + " · " + t("right-click to move it to the top or the bottom"); b.append(icon(p.icon || "generic")); b.onkeydown = (e) => { if (!e.altKey || (e.key !== "ArrowUp" && e.key !== "ArrowDown")) return; e.preventDefault(); e.stopPropagation(); const up = e.key === "ArrowUp"; // Alt+Shift+↑/↓: all the way to the top or the bottom if (e.shiftKey) arrangeProvider(p.id, up ? 0 : onProviderIds().length - 1, true); else stepProvider(p.id, up ? -1 : 1, true); }; // the click that ends a drag doesn't open the row b.addEventListener("click", (e) => { if (b.dataset.dragged) { e.stopPropagation(); e.preventDefault(); } }); b.onpointerdown = (e) => { if (providerArranging) return; const list = $("#providers"); // while a search hides some, the row moves among the ones shown: it // takes the place of the one it is dropped on (shownToOn) const rows = [...list.children].filter((r) => r.classList.contains("provider") && !r.hidden); providerArranging = dragRows(e, b, row, list, rows, (to) => arrangeProvider(p.id, shownToOn(rows[to]?.dataset.id)), () => { closeProtoMenu(); closeAgentMenu(); }, () => { providerArranging = false; if (accountRenderPending && !accountArranging) { accountRenderPending = false; renderProviders(); } }); }; return b; } // The ids of the providers that are on, in their order, and of those a // search shows. While searching, a provider moves among the ones shown: // Alt+↑ puts it just above the one shown above it, a drop puts it where the // row dropped on was; the ones hidden keep their order among themselves. // Move to Top and Move to Bottom go to the top or the bottom of them all. const onProviderIds = () => providers.providers.filter((x) => !x.off).map((x) => x.id); const shownProviderIds = () => [...$("#providers").children].filter((r) => r.classList.contains("provider") && !r.hidden).map((r) => r.dataset.id); const shownToOn = (id) => (id ? onProviderIds().indexOf(id) : -1); function stepProvider(id, by, keyboard) { const shown = shownProviderIds(), i = shown.indexOf(id); if (i < 0 || i + by < 0 || i + by >= shown.length) return; arrangeProvider(id, shownToOn(shown[i + by]), keyboard); } // openProviderMenu: a provider row's right-click, the quick way through a // long list (#1614): Move to Top and Move to Bottom beside one step up or // down, each with its keys. function openProviderMenu(anchor, p) { if (!anchor) return; const again = agentMenu?.anchor === anchor; closeAgentMenu(); if (again) return; const on = onProviderIds(), shown = shownProviderIds(); const i = on.indexOf(p.id), k = shown.indexOf(p.id); if (i < 0) return; openRowMenu(anchor, [ { name: "Move to top", icon: MOVE_TOP, key: ALT + SHIFT + "↑", off: i === 0, run: () => arrangeProvider(p.id, 0) }, { name: "Move up", icon: MOVE_UP, key: ALT + "↑", off: k <= 0, run: () => stepProvider(p.id, -1) }, { name: "Move down", icon: MOVE_DOWN, key: ALT + "↓", off: k < 0 || k >= shown.length - 1, run: () => stepProvider(p.id, 1) }, { name: "Move to bottom", icon: MOVE_BOTTOM, key: ALT + SHIFT + "↓", off: i === on.length - 1, run: () => arrangeProvider(p.id, on.length - 1) }, ]); } // Providers' search (#1614, ququdu: "供应商很多,然后经常需要翻找"): the // words typed keep the rows that say them all, on and off alike, matched on // the row's own text and on what it doesn't show: its id, preset, addresses, // every model's id and name, each account's user and plan, and the keys' // names. The ones turned off show unfolded while searching. Escape or // clearing the box brings back every row, the fold as it was. let pvQuery = ""; function providerText(p, row) { const a = p.account; return [row.textContent, p.id, p.name, p.preset, p.host, p.chat, p.responses, p.anthropic, p.gemini, ...(p.models || []).flatMap((m) => [m.id, m.name]), a?.user, a?.agentName, a?.plan, ...(a?.logins || []).flatMap((l) => [l.user, l.plan]), ...Object.values(p.accountNames || {}), ...(p.keyList || []).map((k) => k.name), ].filter(Boolean).join(" ").toLowerCase(); } function findProviders() { const view = $("#view-providers"), q = $("#pvQ"), none = $("#pvNone"); q.setAttribute("aria-label", t("Find a provider")); $("#pvHead").hidden = !providers.providers.length; view.classList.toggle("pv-searching", !!pvQuery); const words = pvQuery.split(/\s+/).filter(Boolean), byId = new Map(providers.providers.map((p) => [p.id, p])); let on = 0, off = 0; for (const row of view.querySelectorAll("#providers > .row.provider, #offProviders > .row.provider")) { const p = byId.get(row.dataset.id); const hit = !p || words.every((w) => providerText(p, row).includes(w)); row.hidden = !hit; if (hit) p?.off ? off++ : on++; } const offs = providers.providers.filter((p) => p.off).length; // while searching, the ones off that match show, whatever the fold says const fold = $("#foldOff"); fold.disabled = !!pvQuery; fold.setAttribute("aria-expanded", String(!!pvQuery || !offFolded)); if (pvQuery) { $("#providers").hidden = !on; $("#offHead").hidden = !off; $("#offProviders").hidden = !off; $("#offCount").textContent = off ? String(off) : ""; } else { $("#providers").hidden = offs === providers.providers.length; $("#offHead").hidden = !offs; $("#offProviders").hidden = !offs || offFolded; $("#offCount").textContent = offs ? String(offs) : ""; } none.hidden = !pvQuery || on + off > 0; none.textContent = none.hidden ? "" : t("No provider matches “{q}”", { q: q.value.trim() }); } { const q = $("#pvQ"); if (q) { q.oninput = () => { pvQuery = q.value.trim().toLowerCase(); findProviders(); }; q.onkeydown = (e) => { if (e.key !== "Escape" || !q.value) return; e.preventDefault(); e.stopPropagation(); q.value = ""; pvQuery = ""; findProviders(); }; } } // arrangeProvider puts the provider at index `to` among the ones on; the // ones switched off keep their places among the rest. The list is drawn in // its new order at once and put back if the save fails. async function arrangeProvider(id, to, keyboard) { const prev = providers; const on = prev.providers.filter((p) => !p.off).map((p) => p.id); const from = on.indexOf(id); if (from < 0 || to < 0 || to >= on.length || to === from) return; on.splice(to, 0, ...on.splice(from, 1)); let k = 0; const order = prev.providers.map((p) => (p.off ? p.id : on[k++])); const byId = new Map(prev.providers.map((p) => [p.id, p])); const handle = () => $(`#providers .row.provider[data-id="${CSS.escape(id)}"] .pv-handle`); providers = { ...prev, providers: order.map((x) => byId.get(x)) }; renderProviders(); if (keyboard) handle()?.focus({ preventScroll: true }); const seq = ++providerArrangeSeq; let next; try { next = await api("providers/arrange", { order }); status(t("Provider order saved"), "ok"); } catch (e) { next = prev; status(e.message, "err"); } // a later move, made while this one was saved, has the last word if (seq !== providerArrangeSeq) return; // the handle the keyboard is on keeps it as the list is drawn again: this // one's, or another's taken up while this one was saved const a = document.activeElement, held = a?.matches?.("#providers .pv-handle") ? a.closest(".row.provider").dataset.id : null; providers = next; renderProviders(); if (held) $(`#providers .row.provider[data-id="${CSS.escape(held)}"] .pv-handle`)?.focus({ preventScroll: true }); } let providerArrangeSeq = 0; // providerSwitch turns a provider off and on (#163): off, it stays with its // keys and settings, but agents are given none of its models and no request // goes to it (a key out of quota, say), without removing it. function providerSwitch(p) { const on = !p.off; const s = el("button", "lib-switch pswitch" + (on ? " on" : "")); s.setAttribute("role", "switch"); s.setAttribute("aria-checked", on ? "true" : "false"); s.setAttribute("aria-label", t("Use {name}", { name: p.name })); s.title = on ? t("On · switch it off and agents no longer get its models; its keys and settings are kept") : t("Off · switch it on and agents get its models again"); s.append(el("i")); s.onclick = (e) => { e.stopPropagation(); switchProvider(p, !on, s); }; return s; } // switchProvider saves it on or off at once, leaving an editor open as it // was; the agents' own model lists follow. async function switchProvider(p, on, s) { s?.classList.toggle("on", on); try { providers = await api("provider/" + (on ? "on" : "off"), { id: p.id }); renderProviders(); state = await api("state"); renderAgents(); saidMoved(t(on ? "{name} is on" : "{name} is off: agents no longer get its models", { name: p.name })); } catch (e) { s?.classList.toggle("on", !on); status(e.message, "err"); } } // renderFileError: over the list, that providers.json is there but can't // be read, so the list is the signed-in accounts alone: magpie left the // file as it is, and nothing is saved over it until it is fixed or moved. function renderFileError() { const box = $("#fileError"); if (!box) return; box.replaceChildren(); box.hidden = !providers.fileError; if (box.hidden) return; const r = el("div", "signing file-error"); r.setAttribute("role", "alert"); r.append(el("span", "mark", "!")); const tt = el("span", "tt"); tt.append(el("span", "n", t("Your providers file can't be read")), el("span", "s", t("magpie left it unchanged and lists no providers from it. Fix the file or move it aside, then reopen this page; until then, changes to providers are refused.")), el("span", "s", providers.fileError)); r.append(tt); box.append(r); } // DEPRECATED_WHY: why a built-in subscription a community plugin can run // is deprecated, said wherever it is marked so. const DEPRECATED_WHY = "Some subscriptions are reached in ways their vendors' terms may not allow. So that magpie itself isn't banned over them, subscription providers are being decoupled from magpie and run by community plugins instead."; // deprecatedSub: a built-in subscription with a plugin, not moved onto it const deprecatedSub = (agent) => (providers?.movable || []).includes(agent) && !movedSub(agent); // unusedSub: a deprecated built-in with no account in magpie, which the // add sheet leaves to the Plugins page const unusedSub = (agent) => deprecatedSub(agent) && !(providers?.providers || []).some((p) => p.account?.agent === agent); // replacedSub: a deprecated built-in whose plugin is installed and serves // it, under the plugin's own id (the built-in's with "-plugin") until moved; // its accounts, if any, still work, and its plugin's Move brings them over const replacedSub = (agent) => deprecatedSub(agent) && (providers?.plugins || []).some((x) => x.pid === agent); function deprecatedBadge() { const b = el("span", "badge deprecated", t("Deprecated")); b.title = t(DEPRECATED_WHY); return b; } // renderMovable: over the list, the signed-in built-in subscriptions that // are deprecated, why, and the way to their plugins: for one, its editor // at its Runs on; for several, the Plugins tab, where each has its own Move // (opening the first one's editor read as if the notice were about it // alone). Hidden, it stays hidden until another one is signed in. function renderMovable() { const box = $("#movable"); if (!box) return; box.replaceChildren(); const ps = providers.providers.filter((p) => p.move && p.move.state !== "plugin" && p.account); let hid = ""; try { hid = localStorage.getItem("magpie.deprecatedHidden") || ""; } catch {} const ids = ps.map((p) => p.id).join(","); box.hidden = !ps.length || hid === ids; if (box.hidden) return; const names = ps.map((p) => p.name).join(t(", ")); // one quiet line over the list, as calm as its rows: an amber dot, what // happened and why, and the two answers on the right (the owner: 这个太丑了 — // it was a tinted box with a tile, a badge, three lines and a purple button) const card = el("div", "deprecation"); card.setAttribute("role", "note"); const body = el("div", "dep-body"); body.append(el("div", "dep-head", ps.length > 1 ? t("These built-in subscriptions are deprecated: {names}", { names }) : t("{name}'s built-in subscription is deprecated", { name: names })), el("p", "dep-why", [t(DEPRECATED_WHY), t("Moving keeps your accounts, models and agents as they are.")].join(locale === "zh" || locale === "zh-TW" || locale === "ja" ? "" : " "))); const acts = el("div", "dep-acts"); const hide = el("button", "text", t("Not now")); hide.title = t("Hide this until another deprecated subscription is signed in"); hide.onclick = () => { try { localStorage.setItem("magpie.deprecatedHidden", ids); } catch {} renderMovable(); }; const review = el("button", "text action", ps.length > 1 ? t("Review in Plugins") : t("Review the move")); // the editor opens over the list: the page itself doesn't move review.onclick = () => { if (ps.length > 1) { openPlugins(); return; } editing = ps[0].id; draft = null; renderProviders(); }; acts.append(hide, review); card.append(el("span", "dep-dot"), body, acts); box.append(card); } // Sign-ins magpie found but leaves alone, so nobody wonders why an agent that // is clearly logged in is not in the list: the ones the user removed. function renderExcluded() { const box = $("#excluded"); box.replaceChildren(); for (const x of providers.excluded) { if (x.quiet) continue; // dismissed: the Add sheet offers it back (#116) const r = el("div", "excluded"); r.append(icon(x.agentIcon), el("span", "", "")); r.lastChild.append(el("b", "", t(x.signedOut ? "{agent}'s saved accounts aren't offered. " : "{agent} is signed in, but stays out of this list. ", { agent: x.agentName })), x.signedOut ? x.why : t(x.why)); if (x.provider) { const back = el("button", "link", t("Add it back")); back.onclick = () => providerAction("show", { id: x.provider }, t("{name} added back", { name: x.agentName })); const quiet = el("button", "link", t("Don't remind me")); quiet.title = t("Hide this line; Add a provider still offers it back"); quiet.onclick = () => providerAction("quiet", { id: x.provider }); const out = el("button", "link", t("Sign out")); out.title = t("magpie signs out the accounts it keeps for {name}; adding it again signs in afresh", { name: x.agentName }); out.onclick = () => askForgetAccount(x); r.lastChild.append(" ", back, " · ", quiet, " · ", out); } // an agent signed out here (a banned account logged out, say) lists // its saved accounts nowhere else, so this is where they are removed if (x.signedOut && x.users?.length) { const rm = el("button", "link", t("Remove")); rm.title = t("magpie forgets the accounts it saved; {agent}'s own files are left as they are", { agent: x.agentName }); rm.onclick = () => askForgetSaved(x); r.lastChild.append(" ", rm); } box.append(r); } } // askForgetSaved asks before magpie drops the accounts it saved of an agent // signed out here, as a reset asks; it forgets only magpie's copies, never // the agent's own files or keychain. It is the reset's dialog, so the // backdrop and Escape close it the same way. function askForgetSaved(x) { const ed = el("div", "editor forget-ask"); const head = el("div", "ehead"); head.append(icon(x.agentIcon), el("b", "", t(x.users.length === 1 ? "Remove {agent}'s saved account?" : "Remove {agent}'s {n} saved accounts?", { agent: x.agentName, n: x.users.length }))); ed.append(head); ed.append(el("p", "lib-confirm", t("magpie forgets its copy of {users}. {agent}'s own files and sign-in, and the account itself, are left as they are.", { users: x.users.join(", "), agent: x.agentName }))); const bar = el("div", "bar"); const go = el("button", "text primary danger-fill", t("Remove")); go.onclick = async (e) => { e.stopPropagation(); go.disabled = true; go.classList.add("busy"); for (const [i, user] of x.users.entries()) { const last = i === x.users.length - 1; if (!await accountAction("login/forget", { agent: x.agent, user }, last ? t("{user} removed", { user: x.users.join(", ") }) : "", true)) { go.disabled = false; go.classList.remove("busy"); return; } } closeConfirmAsk(); }; const cancel = el("button", "text", t("Cancel")); cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; bar.append(el("span", "grow"), cancel, go); ed.append(bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); cancel.focus(); } // askForgetAccount asks before magpie signs a removed account out for // good: what magpie keeps of its sign-ins goes, so adding it again signs in // afresh rather than bringing the old account back (#694). The vendor's // account itself is left as it is. function askForgetAccount(x) { const ed = el("div", "editor forget-ask"); const head = el("div", "ehead"); head.append(icon(x.agentIcon), el("b", "", t("Sign {name} out of magpie?", { name: x.agentName }))); ed.append(head); ed.append(el("p", "lib-confirm", t("magpie signs out the accounts it keeps for {name} and forgets them; adding {name} again signs in afresh. The account itself is left as it is.", { name: x.agentName }))); // the one Codex is signed in to goes last, and Codex with it (ForgetLogin) if (x.agent === "codex") ed.append(el("p", "lib-confirm", t("Codex itself is signed out too, as codex logout does."))); const bar = el("div", "bar"); const go = el("button", "text primary danger-fill", t("Sign out")); go.onclick = async (e) => { e.stopPropagation(); go.disabled = true; go.classList.add("busy"); // failed, the ask stays with the error in it rather than close over it // (#874: the error showed for a blink as the ask closed) if (await providerAction("forget", { id: x.provider }, t("{name} signed out", { name: x.agentName }))) closeConfirmAsk(); else go.disabled = false; }; const cancel = el("button", "text", t("Cancel")); cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; bar.append(el("span", "grow"), cancel, go); ed.append(bar); confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); cancel.focus({ preventScroll: true }); } // askSignOutLogin asks before Codex is signed out of its only account, as // codex logout does: its sign-in file goes and magpie forgets the account. // It is the reset's dialog, so the backdrop and Escape close it the same way, // back to the provider's editor it was asked from. function askSignOutLogin(a, l) { const ed = el("div", "editor forget-ask"); const head = el("div", "ehead"); head.append(icon(a.agentIcon), el("b", "", t("Sign {agent} out of {user}?", { agent: a.agentName, user: l.user }))); ed.append(head); ed.append(el("p", "lib-confirm", t("{agent} is signed out, as codex logout does, and magpie forgets the account. Sign in again to use it; an open {agent} may need quitting and opening again. The account itself is left as it is.", { agent: a.agentName }))); const bar = el("div", "bar"); const go = el("button", "text primary danger-fill", t("Sign out")); go.onclick = async (e) => { e.stopPropagation(); go.disabled = true; go.classList.add("busy"); if (await accountAction("login/forget", { agent: a.agent, user: l.user }, t("{agent} signed out of {user}", { agent: a.agentName, user: l.user }), true)) closeConfirmAsk(); else go.disabled = false; }; const cancel = el("button", "text", t("Cancel")); cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; bar.append(el("span", "grow"), cancel, go); ed.append(bar); ed.back = renderProviders; // the provider's editor it was asked from confirmAsk = ed; openModal(ed); $("#modal").classList.add("lib"); cancel.focus({ preventScroll: true }); } // accountPlan is the account's chip: its vendor and plan, the plan alone // when it already names the vendor (a plugin's own "Zed Pro"). function accountPlan(a) { // a plugin beside a built-in (cursor-plugin) by the built-in's const agent = a.builtin || a.agent; const cap = (s) => s[0].toUpperCase() + s.slice(1); // "Xiaomi MiMo" and "MiMo 高阶" overlap in "MiMo": said once const named = (name, plan) => { if (!plan) return name; const w = name.split(" "); for (let i = 0; i < w.length; i++) { if ((plan.toLowerCase() + " ").startsWith(w.slice(i).join(" ").toLowerCase() + " ")) return [...w.slice(0, i), plan].join(" "); } return name + " " + plan; }; if (agent === "codex" || agent === "chatgpt-api") return named("ChatGPT", a.plan && cap(a.plan)); if (agent === "copilot") return named("GitHub", a.plan && cap(a.plan)); if (agent === "claude") return named("Claude", a.plan && cap(a.plan)); if (agent === "cursor") return named("Cursor", a.plan && cap(a.plan)); if (agent === "grok") return a.plan || "SuperGrok"; if (agent === "gemini" || agent === "antigravity") return a.plan || "Google"; if (agent === "zcode") return a.plan || "GLM Coding Plan"; if (agent === "workbuddy") return a.plan || "WorkBuddy"; if (agent === "workbuddy-ai") return a.plan || "WorkBuddy AI"; if (agent === "commandcode-plan") return named("Command Code", a.plan && t(a.plan)); if (agent === "qoder") return named("Qoder", a.plan && t(a.plan)); if (agent === "qoder-cn") return named("Qoder CN", a.plan && t(a.plan)); if (agent === "zed") return named("Zed", a.plan && t(a.plan)); if (agent === "mimo-app") return named("Xiaomi MiMo", a.plan && t(a.plan)); return a.plan || t("signed in"); } // ---------- gateway view ---------- // // The gateway is one local endpoint speaking five APIs; this tab is the // page that gets anything else connected to it: base URL, key, model ids, // and a snippet in whichever language the reader is holding. // copy asks magpie to put text on the clipboard, as the page's own // clipboard API is refused inside the app's window; a browser tab on the // dev UI falls back to it. A tab on `magpie web` reached over plain http // from another computer (a NAS's) has no clipboard API at all, so the // older copy command is the last try there. magpie refuses a copy it // couldn't read back (#1881: GTK 3 on KDE Plasma without middle-click // paste served it empty), and the page's ways are tried then too. When // none copies, the page says so and shows the text to copy by hand. async function copy(text, what, btn, message) { const done = () => { status(message || t("{what} copied", { what }), "ok"); flashCopied(btn); }; const res = await fetch("/api/copy", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }) }).catch(() => null); if (res && res.ok) return done(); try { await navigator.clipboard.writeText(text); return done(); } catch {} if (copyByCommand(text)) return done(); status(t("Couldn't copy. Select it here and copy it yourself: {text}", { text }), "err"); } // copyByCommand copies text with the page's copy command, through a // textarea out of sight that is never scrolled to, the focus going back // where it was. function copyByCommand(text) { const was = document.activeElement; const box = document.createElement("textarea"); box.value = text; box.setAttribute("readonly", ""); box.style.cssText = "position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none"; document.body.append(box); let ok = false; try { box.focus({ preventScroll: true }); box.select(); ok = document.execCommand("copy"); } catch { ok = false; } box.remove(); if (was && was.focus) was.focus({ preventScroll: true }); return ok; } // flashCopied answers on the button itself: the icon becomes a tick and // the button takes a green breath, then it reverts on its own. The footer // toast says what was copied; this says it landed. Clicking again restarts // the pop and re-arms the timer. function flashCopied(b) { if (!b) return; b.classList.remove("done"); void b.offsetWidth; // restart the animation when clicked again b.classList.add("done"); b.title = t("Copied"); b.replaceChildren(svg(CHECK, 12, 1.7)); clearTimeout(b.copiedT); b.copiedT = setTimeout(() => { b.classList.remove("done"); b.title = t("Copy"); b.replaceChildren(svg(COPY_ICON, 12, 1.5)); }, 1200); } function copyBtn(text, what, message) { const b = el("button", "copy"); b.title = t("Copy"); b.append(svg(COPY_ICON, 12, 1.5)); b.onclick = (ev) => { ev.stopPropagation(); copy(text, what, b, message); }; return b; } function renderGatewayLoading() { const page = $("#view-gateway"); page.classList.add("loading"); page.setAttribute("aria-busy", "true"); $("#connectNote").textContent = ""; $("#callsNote").textContent = ""; $("#copyModels").hidden = true; const gateway = $("#gateway"); gateway.replaceChildren(); const mark = el("span", "skeleton gw-sk-dot"); const who = el("div", "who gw-sk-who"); who.append(el("span", "skeleton gw-sk-title"), el("span", "skeleton gw-sk-sub")); gateway.append(mark, who, el("span", "skeleton gw-sk-url")); const connect = $("#connect"); connect.replaceChildren(); connect.hidden = connectFolded; for (let i = 0; i < 4; i++) { connect.append(el("span", "skeleton gw-sk-label")); const value = el("div", "gw-sk-field"); value.append(el("span", "skeleton"), el("span", "skeleton short")); connect.append(value); } const models = $("#gwModels"); models.replaceChildren(); for (let i = 0; i < 4; i++) { const row = el("div", "row model gw-sk-row"); row.append(el("span", "skeleton gw-sk-model"), el("span", "grow"), el("span", "skeleton gw-sk-provider")); models.append(row); } const activity = $("#activity"); activity.replaceChildren(); for (let i = 0; i < 4; i++) { const row = el("div", "call gw-sk-call"); row.append(el("span", "skeleton time"), el("span", "skeleton agent"), el("span", "skeleton model"), el("span", "grow"), el("span", "skeleton result")); activity.append(row); } } function renderGatewayView() { const page = $("#view-gateway"); page.classList.remove("loading"); page.removeAttribute("aria-busy"); renderGateway(); $("#gatewayKeysBlock").hidden = !providers.gateway.lan; if (!providers.gateway.lan) gatewayKeyDraft = null; if (gatewayKeyDraft === null && gatewayLimit === null && !$("#gatewayKeys .rename-in")) renderGatewayKeys(); renderConnect(); renderGatewayModels(); renderActivity(); } // The status card's button (leslie_luo on Discord: told to quit the older // magpie serving the gateway, with no way to tell which one it was): with // an older magpie on the port it quits that one, checked to be magpie by // its process, and this one serves the gateway at once; otherwise it // restarts the gateway this one serves, or starts it. A magpie of this // version or newer serving it gets none: that one is not to be quit here. // What stood in the way stays under it until the gateway's state changes. let gatewayFix = { busy: false, err: "", when: "" }; const gatewayFixWhen = (g) => [g.running, g.mine, g.version || ""].join("|"); function gatewayFixButton(g, older) { if (g.running && !g.mine && !older) return null; // bordered: a plain text button read as words on the card in dark mode const b = el("button", "text action gw-fix"); b.textContent = gatewayFix.busy ? (older ? t("Quitting magpie {v}…", { v: g.version }) : t(g.running ? "Restarting the gateway…" : "Starting the gateway…")) : (older ? t("Quit magpie {v} and take over", { v: g.version }) : t(g.running ? "Restart gateway" : "Start gateway")); b.disabled = gatewayFix.busy; b.onclick = async () => { const when = gatewayFixWhen(g); gatewayFix = { busy: true, err: "", when }; renderGateway(); let out; try { out = await api(older ? "gateway/take-over" : "gateway/restart", {}); } catch (e) { out = { reason: "error", error: e.message }; } gatewayFix = { busy: false, err: out?.ok ? "" : gatewayFixSays(out || {}), when }; try { await loadProviders(); } catch {} renderGateway(); }; return b; } // gatewayFixSays is why a take-over or a restart didn't go, in the page's // language, naming the process it was function gatewayFixSays(o) { const p = { port: o.port || "", pid: o.pid || "", path: o.path || "", v: o.version || "", error: o.error || "" }; switch (o.reason) { case "not-magpie": return t("Port {port} is held by {path} (pid {pid}), which isn't magpie, so magpie leaves it alone. Quit it yourself, or move the gateway to another port in Settings.", p); // leslie_luo on Discord: an old magpie in OrbStack, its helper named // as the program to quit case "container": return t("Port {port} is forwarded by {path} (pid {pid}) to a container or a VM: the magpie {v} answering there runs inside it, out of this magpie's reach. Stop that container (docker ps lists it, docker stop stops it, or stop it in OrbStack or Docker Desktop), or move this magpie's gateway to another port in Settings.", p); case "unseen": return t("magpie can't see which process holds port {port}: it runs as another user or as administrator. Quit it there.", p); case "denied": return t("magpie {v} (pid {pid}, {path}) runs as another user or as administrator, so this magpie can't quit it. Quit it there.", p); case "stuck": return t("magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).", p); case "respawned": return t("Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.", p); case "taken": return p.pid ? t("Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.", p) : t("Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.", p); case "other": return t("magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.", p); } return t("The gateway couldn't be served here: {error}", p); } // The status card: dot, state, the URL. function renderGateway() { const g = providers.gateway; const box = $("#gateway"); box.replaceChildren(); // an older magpie keeping the port sends every agent's request its own // way, without this version's fixes (#506): said in place of the counts const older = g.running && !g.mine && g.older; const dot = el("span", "dot " + (older ? "old" : g.running ? "on" : "")); const who = el("div", "who"); const name = el("div", "name", t("Gateway")); name.append(el("span", "state", older ? t("running · served by magpie {v}, older than this one", { v: g.version }) : t(g.running ? (g.mine ? "running" : "running · served by another magpie") : "not running"))); const routed = new Set(); for (const p of providers.providers) for (const a of p.agents) if (a.current) routed.add(a.id); const n = routed.size; if (older) { who.append(name, el("div", "sub old", t("Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.", { v: g.version }))); } else who.append(name, el("div", "sub", g.running ? [t(g.models === 1 ? "{n} model" : "{n} models", { n: g.models }), n ? t(n === 1 ? "{n} agent routed through it" : "{n} agents routed through it", { n }) : t("no agent routed through it yet"), t("five APIs, one URL")].join(" · ") : t("start it with magpie serve, or open magpie at login"))); const fix = gatewayFixButton(g, older); if (fix) who.append(fix); if (gatewayFix.err && gatewayFix.when === gatewayFixWhen(g)) who.append(el("div", "sub old err", gatewayFix.err)); // served to other machines' browsers (magpie web), the address shown is // the one they reach, MAGPIE_PUBLIC_URL's, not this computer's loopback // (#1551) const shown = web && g.publicURL || g.url; const url = el("button", "url"); url.append(el("code", "", shown)); url.title = t("Copy the gateway URL"); url.onclick = () => copy(shown, t("Gateway URL")); box.append(dot, who, url); } // One entry per API the gateway serves: where each SDK's base URL points, // the env vars the usual tools read, and a request in four dialects. const FLAVORS = { openai: { name: "OpenAI", base: (u) => u + "/v1", baseEnv: "OPENAI_BASE_URL", keyEnv: "OPENAI_API_KEY", note: "Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.", curl: (b, m, k = "magpie") => ({ url: `${b}/chat/completions`, headers: [`Authorization: Bearer ${k}`], body: `{"model": "${m}",\n "messages": [{"role": "user", "content": "hi"}]}` }), python: (b, m, k = "magpie") => `from openai import OpenAI client = OpenAI(base_url="${b}", api_key="${k}") r = client.chat.completions.create( model="${m}", messages=[{"role": "user", "content": "hi"}], ) print(r.choices[0].message.content)`, node: (b, m, k = "magpie") => `import OpenAI from "openai"; const client = new OpenAI({ baseURL: "${b}", apiKey: "${k}" }); const r = await client.chat.completions.create({ model: "${m}", messages: [{ role: "user", content: "hi" }], }); console.log(r.choices[0].message.content);`, }, responses: { name: "Responses", base: (u) => u + "/v1", baseEnv: "OPENAI_BASE_URL", keyEnv: "OPENAI_API_KEY", note: "OpenAI's newer API: reasoning, built-in tool items, encrypted reasoning. Codex speaks this.", curl: (b, m, k = "magpie") => ({ url: `${b}/responses`, headers: [`Authorization: Bearer ${k}`], body: `{"model": "${m}", "input": "hi"}` }), python: (b, m, k = "magpie") => `from openai import OpenAI client = OpenAI(base_url="${b}", api_key="${k}") r = client.responses.create(model="${m}", input="hi") print(r.output_text)`, node: (b, m, k = "magpie") => `import OpenAI from "openai"; const client = new OpenAI({ baseURL: "${b}", apiKey: "${k}" }); const r = await client.responses.create({ model: "${m}", input: "hi" }); console.log(r.output_text);`, }, anthropic: { name: "Anthropic", base: (u) => u, baseEnv: "ANTHROPIC_BASE_URL", keyEnv: "ANTHROPIC_API_KEY", note: "Messages API. Claude Code reads ANTHROPIC_AUTH_TOKEN instead of the key; the Agents tab sets that for you.", curl: (b, m, k = "magpie") => ({ url: `${b}/v1/messages`, headers: [`x-api-key: ${k}`, "anthropic-version: 2023-06-01"], body: `{"model": "${m}", "max_tokens": 1024,\n "messages": [{"role": "user", "content": "hi"}]}` }), python: (b, m, k = "magpie") => `import anthropic client = anthropic.Anthropic( base_url="${b}", api_key="${k}", ) m = client.messages.create( model="${m}", max_tokens=1024, messages=[{"role": "user", "content": "hi"}], ) print(m.content[0].text)`, node: (b, m, k = "magpie") => `import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic({ baseURL: "${b}", apiKey: "${k}" }); const m = await client.messages.create({ model: "${m}", max_tokens: 1024, messages: [{ role: "user", content: "hi" }], }); console.log(m.content[0].text);`, }, gemini: { name: "Gemini", base: (u) => u, baseEnv: "GOOGLE_GEMINI_BASE_URL", keyEnv: "GEMINI_API_KEY", note: "Google's generateContent API, v1beta. Gemini CLI and the google-genai SDKs speak this.", curl: (b, m, k = "magpie") => ({ url: `${b}/v1beta/models/${m}:generateContent`, headers: [`x-goog-api-key: ${k}`], body: `{"contents": [{"parts": [{"text": "hi"}]}]}` }), python: (b, m, k = "magpie") => `from google import genai client = genai.Client(api_key="${k}", http_options={"base_url": "${b}"}) r = client.models.generate_content(model="${m}", contents="hi") print(r.text)`, node: (b, m, k = "magpie") => `import { GoogleGenAI } from "@google/genai"; const ai = new GoogleGenAI({ apiKey: "${k}", httpOptions: { baseUrl: "${b}" }, }); const r = await ai.models.generateContent({ model: "${m}", contents: "hi" }); console.log(r.text);`, }, // magpie's own System One API (ARNO on Discord: gateway添加system one // api 有想法吗): a decision model — Jev, Clef, Bailian's — answers typed // questions about a state; no SDK speaks it, so no shell variables systemone: { name: "System One", base: (u) => u + "/v1", decide: true, note: "TypeSafe's decision API: a Jev or Clef model answers typed questions (choice, noul, score) about a state, with how sure it is. Clef also reads images: add \"images\": [\"data:image/png;base64,…\"].", curl: (b, m, k = "magpie") => ({ url: `${b}/systemone`, headers: [`Authorization: Bearer ${k}`], body: `{"model": "${m}",\n "state": {"message": "My order never arrived, refund it"},\n "questions": {"team": {"type": "choice",\n "instructions": "Which team should answer the message?",\n "criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"}}}}` }), python: (b, m, k = "magpie") => `import requests r = requests.post("${b}/systemone", headers={"Authorization": "Bearer ${k}"}, json={ "model": "${m}", "state": {"message": "My order never arrived, refund it"}, "questions": {"team": { "type": "choice", "instructions": "Which team should answer the message?", "criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"}, }}, }) a = r.json()["answers"]["team"] print(a["choice"], a["confidence"])`, node: (b, m, k = "magpie") => `const r = await fetch("${b}/systemone", { method: "POST", headers: { Authorization: "Bearer ${k}", "Content-Type": "application/json" }, body: JSON.stringify({ model: "${m}", state: { message: "My order never arrived, refund it" }, questions: { team: { type: "choice", instructions: "Which team should answer the message?", criteria: { billing: "Payments and refunds", shipping: "Deliveries", other: "Anything else" }, } }, }), }); const a = (await r.json()).answers.team; console.log(a.choice, a.confidence);`, }, }; // The Shell and curl snippets are written for one shell: PowerShell on // Windows ($env: in place of export, and the curl.exe that ships with it, // as plain curl there is Invoke-WebRequest; the body goes in on stdin, // since Windows PowerShell drops the quotes inside an argument), or a POSIX // shell (bash, zsh) on macOS and Linux. They start as the shell of the // machine magpie runs on, and can be switched to the other: a Windows // desktop's user often runs them on a Linux server over ssh (FourLeafTec, // #1514). The choice is kept with the snippet language. const WIN = /^Win/.test(navigator.platform); const SNIP_OSES = [["windows", "Windows"], ["unix", "macOS · Linux"]]; const snipWin = () => (SNIP_OSES.some(([id]) => id === snipOS) ? snipOS : WIN ? "windows" : "unix") === "windows"; const langs4 = () => [["shell", snipWin() ? "PowerShell" : "Shell"], ["curl", "curl"], ["python", "Python"], ["node", "Node"]]; // A word each shell takes as it is, quoted only where it has to be: a key // of the user's own can hold any ASCII symbol (", $, `, ', !), and a model // id brackets ([1m]) that zsh would glob; a comma would make PowerShell // pass a list. const plainWord = /^[\w%+=:./-]+$/; const shQuote = (s) => (plainWord.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`); // in "…" for a header's spaces, unless it holds what bash expands there const shHeader = (s) => (/[$`"\\!]/.test(s) ? `'${s.replaceAll("'", `'\\''`)}'` : `"${s}"`); const psQuote = (s) => (plainWord.test(s) ? s : `'${s.replace(/['‘’‚‛]/g, "$&$&")}'`); // "…" as the C runtime splits a command line: \" for a quote, and the // backslashes before one doubled const winArg = (s) => (plainWord.test(s) ? s : `"${s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`); const psHeader = (s) => (/[$`"“”„]/.test(s) ? `'${s.replace(/['‘’‚‛]/g, "$&$&")}'` : `"${s}"`); function curlSnippet({ url, headers, body }) { headers = [...headers, "Content-Type: application/json"]; // curl reads [ ] { } in a URL as a range unless told not to const g = /[[\]{}]/.test(url) ? " -g" : ""; // A " inside an argument reaches curl.exe differently from Windows // PowerShell 5.1 and from PowerShell 7, and whole from neither as // written; after --% the line goes to curl.exe as it stands, on one line, // quoted as the C runtime reads a command line. (A %NAME% of a variable // the shell has is still put in there; a key would have to hold both.) if (snipWin() && headers.some((h) => h.includes('"'))) return `@'\n${body}\n'@ | curl.exe --%${g} ${winArg(url)} ${headers.map((h) => `-H ${winArg(h)}`).join(" ")} --data-binary "@-"`; if (snipWin()) return `@'\n${body}\n'@ | curl.exe${g} ${psQuote(url)} \`\n${headers.map((h) => ` -H ${psHeader(h)} \``).join("\n")}\n --data-binary "@-"`; return `curl${g} ${shQuote(url)} \\\n${headers.map((h) => ` -H ${shHeader(h)} \\`).join("\n")}\n -d '${body.replaceAll("'", `'\\''`).replaceAll("\n", "\n ")}'`; } function envSnippet(vars) { return vars.map(([k, v]) => (snipWin() ? `$env:${k}=${psHeader(v)}` : `export ${k}=${shQuote(v)}`)).join("\n"); } // a decision model on the list: one only System One asks, never an agent const decideEntry = (m) => !m.group && !!m.provider?.id && decidesModel(m.provider, m.id.slice(m.provider.id.length + 1)); // every exposed model, as the ids agents use function gatewayModels() { // the routing groups first, as the agents' pickers list them // a group's lists may come as null (#1585): one such group mustn't take // every model off the list const out = (providers.gateway.groups || []).filter((g) => g && typeof g.id === "string").map((g) => ({ id: g.id, name: g.name || g.id, icons: g.icons || [], group: true, provider: { name: [t("routing group"), (g.providers || []).join(", ")].filter(Boolean).join(" · ") }, efforts: g.efforts || [], images: !!g.images, context: g.context, output: g.output, members: g.members || [] })); // a provider switched off is skipped: the gateway refuses its models, so // they are not ids an agent can use, and listing them here would show a // model the picker's own list, the Gateway count and the Connect example // all say works but a request to it turns away (the same off gate the // backend's providerEntries and the fallback picker already honour). // the levels agents are offered: those kept, else all it has; one whose // levels aren't known (given) offers only those it was given const offered = (m) => m.kept?.length || m.given ? m.kept || [] : m.efforts || []; for (const p of providers.providers) { if (p.off) continue; for (const m of p.models) if (m.on) out.push({ id: `${p.id}/${m.id}`, name: m.name, provider: p, context: m.context, output: m.output, efforts: offered(m), images: !!m.images }); } return out; } let segsMade = 0; function segs(items, current, onPick) { const box = el("div", "segs"); const kind = items.map(([id]) => id).join("|"); box.dataset.kind = kind; // where its thumb was is remembered per control, not per set of options: // every Off/On on the settings page has the same, and each would slide in // from where the one clicked was as the page redraws. A control is known // by its place: the nearest element with an id, and which of the same // options it is there; one not in the page yet by itself only. let key = kind + "#" + ++segsMade; for (const [id, name] of items) { const b = el("button", "opt" + (id === current ? " on" : ""), name); b.type = "button"; b.setAttribute("aria-pressed", String(id === current)); b.onclick = () => { for (const x of box.querySelectorAll(".opt")) { x.classList.toggle("on", x === b); x.setAttribute("aria-pressed", String(x === b)); } slide(box, key); onPick(id); }; box.append(b); } queueMicrotask(() => { // once it is in the page key = segsPlace(box) || key; slide(box, key); }); return box; } // where a control is in the page: the nearest element with an id, and which // of the same options it is there; "" for one not in the page function segsPlace(box) { const home = box.isConnected && box.parentElement.closest("[id]"); return home ? box.dataset.kind + "@" + home.id + ":" + [...home.querySelectorAll(".segs")].filter((x) => x.dataset.kind === box.dataset.kind).indexOf(box) : ""; } // A press on an option still picks it when the control is drawn again // before the button is let go: a save's answer redraws Settings, and a // second option pressed while the first one's save came back was let go // on a new button. Down and up were on two buttons, so the browser sent the // click to neither and nothing was picked. Let go on the same option of the // same control, the new one is clicked; let go anywhere else (dragged off // to another option), nothing is, as for any button. A tap is left to the // browser, which clicks what is under the finger as it lifts. let segsPress = null; const optAt = (b) => [...b.parentElement.querySelectorAll(":scope > .opt")].indexOf(b); // the same control is at the same place, among as many of its kind, in rows // that are the same by their data-* (an agent's, a provider's): a list drawn // again with a row gone, come in or moved above it is another control there function segsWho(box) { const place = segsPlace(box); if (!place) return ""; const home = box.parentElement.closest("[id]"), rows = []; for (let n = box.parentElement; n !== home; n = n.parentElement) rows.push(Object.entries(n.dataset).join()); return [place, [...home.querySelectorAll(".segs")].filter((x) => x.dataset.kind === box.dataset.kind).length, ...rows].join(" "); } addEventListener("pointerdown", (e) => { const b = e.isPrimary && e.button === 0 && e.pointerType !== "touch" && e.target.closest?.(".segs > .opt"); segsPress = b ? { b, who: segsWho(b.parentElement), i: optAt(b) } : null; }, true); addEventListener("pointercancel", () => { segsPress = null; }, true); addEventListener("pointerup", (e) => { const p = segsPress; segsPress = null; if (!p?.who || p.b.isConnected || !e.isPrimary) return; const b = document.elementFromPoint(e.clientX, e.clientY)?.closest(".segs > .opt"); if (!b || segsWho(b.parentElement) !== p.who || optAt(b) !== p.i) return; // after the browser's own click, should one come to it after all let clicked = false; const seen = (c) => { if (b.contains(c.target)) clicked = true; }; addEventListener("click", seen, true); setTimeout(() => { removeEventListener("click", seen, true); if (!clicked && b.isConnected) b.click(); }); }, true); // An installed list's order, the reader's pick, remembered for each list // (#481): its names A→Z or Z→A, and for a list that has one, a view of its // own first (the skills by where they came from). sortOf(list) is the pick, // sortBy(list, …) the control; a list missing or unreadable in storage // takes the first. const NAME_SORTS = [["az", "A→Z"], ["za", "Z→A"]]; function sortOf(list, items = NAME_SORTS) { let v = ""; try { v = localStorage.getItem("magpie.sort." + list) || ""; } catch {} return items.some(([id]) => id === v) ? v : items[0][0]; } function sortBy(list, items, onPick) { const box = segs(items, sortOf(list, items), (id) => { try { localStorage.setItem("magpie.sort." + list, id); } catch {} onPick(id); }); box.classList.add("sortby"); box.dataset.sort = list; const tips = { az: t("Names from A to Z"), za: t("Names from Z to A") }; for (const [i, b] of [...box.querySelectorAll(".opt")].entries()) if (tips[items[i][0]]) b.title = tips[items[i][0]]; return box; } // a comparer of names for a pick: A→Z, or Z→A const byName = (pick, nameOf = (x) => x.name) => (a, b) => (pick === "za" ? -1 : 1) * nameOf(a).localeCompare(nameOf(b)); // Connect is set up once and seldom looked at again, so it folds away under // its heading, the base URL left beside it; the fold is remembered // (connectFolded, with the tab's other choices at the top). $("#foldConnect").prepend(svg(CHEV_R, 11, 1.6)); $("#foldConnect").onclick = () => { connectFolded = !connectFolded; try { localStorage.setItem("magpie.gwConnectFolded", connectFolded ? "1" : "0"); } catch {} renderConnect(); backToReader($("#view-gateway")); }; function renderConnect() { const g = providers.gateway; const box = $("#connect"); box.replaceChildren(); const f = FLAVORS[flavor] || FLAVORS.openai; // System One's snippets take a decision model, the others any other const models = gatewayModels().filter((m) => decideEntry(m) === !!f.decide); let model; if (f.decide) { if (!models.some((m) => m.id === decideModel)) decideModel = models[0]?.id || ""; model = decideModel || "provider/jev-latest"; } else { if (!models.some((m) => m.id === exampleModel)) exampleModel = models[0]?.id || ""; model = exampleModel || "provider/model"; } // no SDK speaks System One, so it has no shell variables to set const langs = f.baseEnv ? langs4() : langs4().filter(([id]) => id !== "shell"); const snipLang = langs.some(([id]) => id === lang) ? lang : "curl"; const urls = [g.url, ...(g.lanURLs || [])]; // the address picked is kept (coeo91): an address not offered right now // (the network not up yet after a start) shows this computer's, and the // pick comes back with it. With none picked, MAGPIE_PUBLIC_URL is where // it starts: it says the address other machines use (#1551) const first = g.publicURL && urls.includes(g.publicURL) ? g.publicURL : g.url; connectURL = urls.includes(connectWant) ? connectWant : first; // a gateway MAGPIE_ADDR puts on the network (a Docker image's, whose // host is another machine to it) is shown with a gateway key everywhere const remote = connectURL !== g.url || !!g.onNetwork; const keys = g.lan ? (gatewayKeys || []).filter((k) => !k.off) : []; if (!keys.some((k) => k.id === connectKeyID)) { connectKeyID = ""; connectSecret = null; } if (!connectKeyID && connectKeyWant && keys.some((k) => k.id === connectKeyWant)) { queueMicrotask(() => selectConnectKey(connectKeyWant)); } else if (remote && !connectKeyID && keys.length) { queueMicrotask(() => selectConnectKey(keys[0].id)); } const key = keys.find((k) => k.id === connectKeyID); const secret = key ? (connectSecret?.id === key.id ? connectSecret.secret : "") : remote ? "" : "magpie"; const base = f.base(connectURL); const fold = $("#foldConnect"); fold.setAttribute("aria-expanded", String(!connectFolded)); fold.title = t(connectFolded ? "Show how to connect" : "Fold Connect away"); box.hidden = connectFolded; // folded, the head keeps the one thing reached for: the address, to copy const note = $("#connectNote"); note.replaceChildren(); note.classList.toggle("brief", connectFolded); if (connectFolded) note.append(el("code", "", base), copyBtn(base, "Base URL")); else note.textContent = t(remote ? "Local network · an enabled gateway key is required" : g.lan && gatewayKeys?.length ? "Use a gateway key to track usage" : "Loopback only · the key can be anything"); box.append(...field("API", segs(Object.entries(FLAVORS).map(([k, v]) => [k, v.name]), flavor, (id) => { flavor = id; localStorage.setItem("magpie.flavor", id); renderConnect(); }), t(f.note))); const b = el("div", "val"); if (urls.length > 1) b.append(connectPick("connectAddress", "Address", base, urls.map((u) => ({ v: u, name: f.base(u), note: t(u === g.url ? "This computer" : u === g.publicURL ? "Public address" : "Local network") })), connectURL, (u) => { connectWant = u; keepPick("magpie.connectAddress", u); renderConnect(); })); else b.append(el("code", "", base)); b.append(copyBtn(base, "Base URL")); box.append(...field("Base URL", b, f.baseEnv ? t("What {env} takes.", { env: f.baseEnv }) : t("Requests go to POST {url}.", { url: base + "/systemone" }))); const k = el("div", "val"); const options = keys.map((k) => ({ v: k.id, name: k.name, literalName: true, note: k.masked })); if (!remote) options.unshift({ v: "", name: "This computer", note: t("Any key · no key attribution") }); const keyLabel = remote || key ? "Gateway key" : "API key"; if (!g.lan) k.append(el("code", "", "magpie")); else if (options.length) k.append(connectPick("connectKey", keyLabel, key ? key.name : remote ? t("Choose a gateway key") : t("This computer"), options, connectKeyID, (id) => { connectKeyWant = id; keepPick("magpie.connectKey", id); selectConnectKey(id); })); else k.append(el("code", "", t("Create a gateway key above to connect"))); if (key) k.append(copyCallerKeyBtn(key)); else if (!remote) k.append(copyBtn("magpie", t("Key"))); box.append(...field(t(keyLabel), k, !f.keyEnv ? t(g.lan && (remote || gatewayKeys?.length) ? "Choose a gateway key to send as Authorization: Bearer; usage is tracked by key." : "Sent as Authorization: Bearer. The gateway trusts everything on loopback, so any value works.") : t(g.lan && (remote || gatewayKeys?.length) ? "Choose a gateway key to use as {env}; usage is tracked by key." : "{env}=magpie. The gateway trusts everything on loopback, so any value works.", { env: f.keyEnv }))); const m = el("div", "val"); m.append(el("code", "", model), copyBtn(model, t("Model id"))); box.append(...field(t("Model"), m, f.decide ? t(models.length ? "A decision model (Jev, Clef), as listed below. Click one there to put it in the snippets." : "No decision models yet. Add a System One, Jev or Workers AI provider.") : t(models.length ? "provider/model, as listed below. Click a model there to put it in the snippets." : "No models yet. Add a provider, or sign in to Codex or Copilot."))); const ex = el("div", "stack"); const tabs = el("div", "snip-tabs"); tabs.append(segs(langs, snipLang, (id) => { lang = id; localStorage.setItem("magpie.lang", id); renderConnect(); })); // the shell the Shell and curl snippets are for; Python and Node read the same everywhere if (snipLang === "shell" || snipLang === "curl") { const os = segs(SNIP_OSES.map(([id, name]) => [id, t(name)]), snipWin() ? "windows" : "unix", (id) => { snipOS = id; try { localStorage.setItem("magpie.snipOS", id); } catch {} renderConnect(); }); os.classList.add("snip-os"); os.setAttribute("role", "group"); os.setAttribute("aria-label", t("Where the snippet runs")); os.title = t("Where the snippet runs"); tabs.append(os); } ex.append(tabs); const code = !secret ? t(key ? "Loading gateway key…" : "Create a gateway key above to connect") : snipLang === "shell" ? envSnippet([[f.baseEnv, base], [f.keyEnv, secret]]) : snipLang === "curl" ? curlSnippet(f.curl(base, model, secret)) : f[snipLang](base, model, secret); const pre = el("pre", "snip"); const c = el("code"); c.append(highlight(code, snipLang)); pre.append(c); // the button sits outside the scrolling box, so a long line doesn't carry it off const wrap = el("div", "snip-wrap"); wrap.append(pre); if (secret) wrap.append(copyBtn(code, t("Snippet"))); ex.append(wrap); box.append(...field(t("Example"), ex, snipLang === "shell" ? t("Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.") : "")); } // A small highlighter for the four snippet dialects: strings, comments, // keywords, numbers, calls, and the env vars and flags shells care about. const KEYWORDS = { python: /^(from|import|def|return|await|async|for|in|if|else|None|True|False)$/, node: /^(import|from|const|let|await|async|new|return|function|export|default)$/, shell: /^(export|curl)$/, curl: /^(curl|curl\.exe)$/, }; function highlight(code, lang) { const re = lang === "node" ? /("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)|(\/\/.*)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)|(\s+|.)/g : /("(?:[^"\\]|\\.)*"|'[^']*')|(#.*)|(\b\d+(?:\.\d+)?\b(?=[,\s\]}]))|(-{1,2}[A-Za-z][\w-]*)|([A-Z][A-Z0-9_]+)(?==)|([A-Za-z_][\w.]*)(?=\s*\()|([A-Za-z_][\w.]*)|(\\\n|`\n)|(\s+|.)/g; const out = document.createDocumentFragment(); const kw = KEYWORDS[lang] || KEYWORDS.shell; let m; while ((m = re.exec(code))) { // an unquoted value after "=" is a string too; found here, as a // lookbehind in the pattern is a syntax error before Safari 16.4 (#220) if (lang !== "node" && !m[1] && code[m.index - 1] === "=") { const v = /\S+/y; v.lastIndex = m.index; const s = v.exec(code); if (s) { out.append(el("span", "tk-s", s[0])); re.lastIndex = m.index + s[0].length; continue; } } let cls = ""; if (lang === "node") { if (m[1]) cls = "s"; else if (m[2]) cls = "c"; else if (m[3]) cls = "n"; else if (m[4]) cls = kw.test(m[4]) ? "k" : "f"; else if (m[5] && kw.test(m[5])) cls = "k"; } else { if (m[1]) cls = "s"; else if (m[2]) cls = "c"; else if (m[3]) cls = "n"; else if (m[4]) cls = "o"; else if (m[5]) cls = "v"; else if (m[6]) cls = kw.test(m[6]) ? "k" : "f"; else if (m[7] && kw.test(m[7])) cls = "k"; else if (m[9]) cls = "o"; } if (cls) out.append(el("span", "tk-" + cls, m[0])); else out.append(m[0]); } return out; } let modelQuery = ""; // The model list can be folded away, so Recent calls sits under Connect; // the fold is remembered. let modelsFolded = false; try { modelsFolded = localStorage.getItem("magpie.gwModelsFolded") === "1"; } catch {} $("#foldModels").prepend(svg(CHEV_R, 11, 1.6)); $("#foldModels").onclick = () => { modelsFolded = !modelsFolded; try { localStorage.setItem("magpie.gwModelsFolded", modelsFolded ? "1" : "0"); } catch {} renderGatewayModels(); backToReader($("#view-gateway")); }; function renderGatewayModels() { const list = $("#gwModels"); list.replaceChildren(); const all = gatewayModels(); const fold = $("#foldModels"); fold.setAttribute("aria-expanded", String(!modelsFolded)); fold.title = t(modelsFolded ? "Show the models" : "Fold the models away"); $("#modelsCount").textContent = all.length ? String(all.length) : ""; list.hidden = modelsFolded && all.length > 0; // the search sits in the section head, beside Copy all ids; typing // redraws only the list, so it keeps its focus let q = $("#findModel"); if (!q) { q = input(modelQuery, t("Find a model…")); q.id = "findModel"; q.className = "find"; q.oninput = () => { modelQuery = q.value; renderGatewayModels(); }; q.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape" && q.value) { q.value = modelQuery = ""; renderGatewayModels(); } }; $("#copyModels").before(q); } q.hidden = all.length < 5 || list.hidden; q.title = t("Words match a model's id, name, provider or a group's models"); const words = modelQuery.trim().toLowerCase().split(/\s+/).filter(Boolean); const models = q.hidden ? all : all.filter((m) => { const hay = `${m.id} ${m.name || ""} ${m.provider.name} ${(m.members || []).join(" ")}`.toLowerCase(); return words.every((w) => hay.includes(w)); }); $("#copyModels").hidden = !models.length || list.hidden; $("#copyModels").onclick = () => copy(models.map((m) => m.id).join("\n"), t("Model ids")); if (!all.length) { const empty = el("div", "empty-state", ""); empty.append(el("b", "", t("No models exposed yet")), t("Add a provider, or sign in to Codex or Copilot; their models show up here for every agent.")); list.append(empty); return; } if (!models.length) { list.append(el("div", "none", t("No models match “{q}”", { q: modelQuery.trim() }))); return; } for (const m of models) { const row = el("div", "row model" + (m.id === (FLAVORS[flavor]?.decide ? decideModel : exampleModel) ? " selected" : "")); const who = el("div", "who"); const name = el("div", "name", m.id); if (namedFree(m.id, m.name)) name.append(freeBadge(false)); who.append(name, el("div", "sub", m.name && m.name !== m.id.split("/")[1] ? `${m.name} · ${m.provider.name}` : m.provider.name)); row.append(m.group ? stackIcon(m.icons) : icon(m.provider.icon || "generic"), who, modelInfo(m), copyBtn(m.id, t("Model id"))); row.title = t("Use this model in the snippets"); // a decision model is put in System One's snippets, any other in the // other APIs'; the API follows the model clicked row.onclick = () => { const selection = window.getSelection(); if (selection && !selection.isCollapsed && row.contains(selection.anchorNode)) return; const so = decideEntry(m); if (so) { decideModel = m.id; localStorage.setItem("magpie.decideModel", m.id); } else { exampleModel = m.id; localStorage.setItem("magpie.model", m.id); } if (so !== !!FLAVORS[flavor]?.decide) { flavor = so ? "systemone" : "openai"; localStorage.setItem("magpie.flavor", flavor); } renderConnect(); renderGatewayModels(); }; list.append(row); } } // What agents are told of a model on the Gateway list (ARNO on Discord: // 支持显示模型或者模型组更多的信息): its reasoning levels, whether it takes // images and the context it holds, as small chips at the row's end, and in // full in their tooltip; a group's are what its members all have, and the // tooltip names its models. const IMAGE_GLYPH = "M2.5 3.5h11v9h-11zM2.5 10.5l3.25-3.25 3 3 2-2 2.75 2.75M10.25 6.75a.75.75 0 1 0 0-.01"; function effortSpan(levels) { const say = levels.map((l) => t(l)); return say.length > 2 ? `${say[0]}–${say[say.length - 1]}` : say.join(" / "); } function modelInfo(m) { const box = el("span", "minfo"); const lines = []; const levels = m.efforts || []; // a decision model answers a routing group's questions, it doesn't reason if (decideEntry(m)) lines.push(t("Decision model: routing groups ask it, agents never see it")); else if (levels.length) { box.append(el("span", "badge mi-effort", effortSpan(levels))); // a group's levels are not its own: they are the ones every model in it // has, as its images are whichever member's and its window the largest's lines.push(m.group ? t("Reasoning: {levels} (the levels every model in it has)", { levels: levels.map((l) => t(l)).join(", ") }) : t("Reasoning: {levels}", { levels: levels.map((l) => t(l)).join(", ") })); } else lines.push(t("Reasoning levels: none known")); // nothing read of its images either way: magpie counts it text-only for a // describer (gateway.blindTo), which is not the same as its list saying so, // so it is not called text-only here either. Only a model that carries the // flag is unknown; one magpie has an answer for carries no such key at all. const imgUnknown = m.imagesUnknown === true; if (m.images) { const c = el("span", "badge mi-img"); c.append(svg(IMAGE_GLYPH, 11, 1.4)); box.append(c); } lines.push(t(imgUnknown ? "Images: not known" : m.images ? (m.group ? "Accepts images (one of its models does)" : "Accepts images") : "Text only")); if (m.context) { box.append(el("span", "badge mi-ctx", ctxShort(m.context))); lines.push(t(m.group ? "Context: {n} tokens (the largest of its models')" : "Context: {n} tokens", { n: m.context.toLocaleString(intlLang()) })); } if (m.output) lines.push(t("Output: up to {n} tokens", { n: m.output.toLocaleString(intlLang()) })); if (m.group && m.members?.length) lines.push(t("Models: {models}", { models: m.members.join(", ") })); box.title = lines.join("\n"); return box; } function formatWireBody(raw) { if (!raw) return ""; try { return JSON.stringify(JSON.parse(raw), null, 2); } catch { return raw; } } // A JSON body as a tree: each object and array folds at its bracket, its // parts in the snippets' colours; the copy button a line shows on hover // copies its value, and a click on a key copies the key. The text is the // JSON pretty-printed, as before, so what is selected and copied by hand // still reads as JSON. What is folded is kept by the body's key and the // node's path, across the redraws a new call brings. const jsonFolds = new Set(); function jsonTree(v, key) { const code = el("code", "jt"); code.append(jtNode(v, undefined, "", key + "|", "")); return code; } function jtNode(v, k, indent, path, comma) { const f = document.createDocumentFragment(); const head = el("span", "jt-head"); f.append(indent, head); if (k !== undefined) { const ks = el("span", "jt-key", JSON.stringify(k)); ks.title = t("Click to copy the key"); // a click copies; a drag selects, as in any text ks.onclick = (ev) => { ev.stopPropagation(); if (!String(getSelection())) copy(String(k), String(k), null); }; head.append(ks, ": "); } const copyV = el("button", "jt-copy"); copyV.type = "button"; copyV.title = t("Copy value"); copyV.append(svg(COPY_ICON, 11, 1.5)); // a string's value is its text, not the JSON that quotes it copyV.onclick = (ev) => { ev.stopPropagation(); copy(typeof v === "string" ? v : JSON.stringify(v, null, 2), k !== undefined ? String(k) : t("Value"), copyV); }; if (v === null || typeof v !== "object") { head.append(el("span", typeof v === "string" ? "tk-s" : typeof v === "number" ? "tk-n" : "tk-k", JSON.stringify(v)), copyV); f.append(comma); return f; } const arr = Array.isArray(v); const keys = arr ? v.map((_, i) => i) : Object.keys(v); const [o, c] = arr ? ["[", "]"] : ["{", "}"]; if (!keys.length) { head.append(o + c, copyV); f.append(comma); return f; } const tog = el("button", "jt-fold"); tog.type = "button"; tog.append(svg(CHEV_R, 10, 1.6)); const kids = el("span", "jt-kids"); const sum = el("button", "jt-sum", "…"); sum.type = "button"; sum.title = t("Unfold"); sum.dataset.n = t(keys.length === 1 ? "1 item" : "{n} items", { n: keys.length }); // the summary is on the head's line: what a click on it holds in place is // then its neighbours there, not the line after, which the unfolding pushes down head.prepend(tog); head.append(o, sum, copyV); f.append(kids, c, comma); let built = false; const set = (folded) => { if (!folded && !built) { // its insides are drawn the first time it opens built = true; keys.forEach((kk, i) => kids.append("\n", jtNode(v[kk], arr ? undefined : kk, indent + " ", path + "/" + kk, i < keys.length - 1 ? "," : ""))); kids.append("\n" + indent); } kids.hidden = folded; sum.hidden = !folded; tog.classList.toggle("open", !folded); tog.setAttribute("aria-expanded", String(!folded)); tog.title = t(folded ? "Unfold" : "Fold"); if (folded) jsonFolds.add(path); else jsonFolds.delete(path); }; // the box keeps its height across a fold, so what is below it, and the // page, stay where they are const keep = () => { const pre = tog.closest("pre"); if (pre) pre.style.minHeight = pre.offsetHeight + "px"; }; tog.onclick = (ev) => { ev.stopPropagation(); keep(); set(!kids.hidden); }; sum.onclick = (ev) => { ev.stopPropagation(); keep(); set(false); }; set(jsonFolds.has(path)); return f; } // A streamed body (server-sent events) as its events: each one's name and // its data, the data lines joined. Anything else is not one: null. function parseSSE(raw) { if (!raw || !/^\s*(?::[^\n]*\n\s*)*(event|data|id|retry):/.test(raw)) return null; const events = []; let ev = null; const done = () => { if (ev && ev.data.length) events.push({ event: ev.event, data: ev.data.join("\n") }); ev = null; }; for (const line of raw.split(/\r?\n/)) { if (line === "") { done(); continue; } if (line[0] === ":") continue; // a comment, a keep-alive const i = line.indexOf(":"); const field = i < 0 ? line : line.slice(0, i); let value = i < 0 ? "" : line.slice(i + 1); if (value[0] === " ") value = value.slice(1); ev = ev || { event: "", data: [] }; if (field === "event") ev.event = value; else if (field === "data") ev.data.push(value); } done(); return events.length ? events : null; } const jsonOr = (s) => { try { return JSON.parse(s); } catch { return undefined; } }; // What a stream adds up to — its text, reasoning and tool calls, how it // stopped and what it used — for the Anthropic Messages, OpenAI Responses, // Chat Completions and Gemini streams; null for one it can't read. function sseReply(events) { const out = {}; const blocks = []; // Anthropic content blocks, Chat tool calls, Responses items, in order const byKey = new Map(); const block = (key, init) => { let b = byKey.get(key); if (!b) { b = { ...init }; byKey.set(key, b); blocks.push(b); } return b; }; let kind = ""; for (const e of events) { const d = jsonOr(e.data); if (!d || typeof d !== "object") continue; const type = d.type || e.event || ""; if (d.error) { out.error = d.error; continue; } if (type === "message_start" && d.message) { kind = "anthropic"; out.id = d.message.id; out.model = d.message.model; if (d.message.usage) out.usage = { ...d.message.usage }; } else if (type === "content_block_start" && d.content_block) { kind = "anthropic"; const cb = d.content_block; const b = block("a" + d.index, { type: cb.type }); if (cb.type === "tool_use" || cb.type === "server_tool_use") { b.id = cb.id; b.name = cb.name; b.input = ""; } else if (cb.type === "text") b.text = cb.text || ""; else if (cb.type === "thinking") b.thinking = cb.thinking || ""; else Object.assign(b, cb); } else if (type === "content_block_delta" && d.delta) { const b = block("a" + d.index, { type: "text" }); const x = d.delta; if (x.type === "text_delta") b.text = (b.text || "") + x.text; else if (x.type === "thinking_delta") b.thinking = (b.thinking || "") + x.thinking; else if (x.type === "input_json_delta") b.input = (b.input || "") + x.partial_json; } else if (type === "message_delta") { if (d.delta?.stop_reason) out.stop_reason = d.delta.stop_reason; if (d.usage) out.usage = { ...out.usage, ...d.usage }; } else if (type.startsWith("response.")) { kind = "responses"; if (d.response) { out.id = d.response.id; out.model = d.response.model; out.status = d.response.status; if (d.response.usage) out.usage = d.response.usage; if (d.response.error) out.error = d.response.error; if (d.response.incomplete_details) out.incomplete = d.response.incomplete_details; if (type === "response.completed" && d.response.output?.length) out.output = d.response.output; } const key = "r" + (d.item_id || d.item?.id || d.output_index); if (type === "response.output_item.added" || type === "response.output_item.done") { const it = d.item || {}; const b = block(key, { type: it.type }); if (it.type === "function_call" || it.type === "custom_tool_call") { b.call_id = it.call_id; b.name = it.name; } if (type === "response.output_item.done") { if (it.arguments !== undefined) b.arguments = it.arguments; if (it.input !== undefined) b.input = it.input; const text = (it.content || []).map((c) => c.text || c.refusal || "").join(""); if (text) b.text = text; const sum = (it.summary || []).map((c) => c.text || "").join("\n\n"); if (sum) b.summary = sum; } } else if (type === "response.output_text.delta" || type === "response.refusal.delta") { const b = block(key, { type: "message" }); b.text = (b.text || "") + d.delta; } else if (type === "response.reasoning_summary_text.delta") { const b = block(key, { type: "reasoning" }); b.summary = (b.summary || "") + d.delta; } else if (type === "response.reasoning_text.delta") { const b = block(key, { type: "reasoning" }); b.text = (b.text || "") + d.delta; } else if (type === "response.function_call_arguments.delta") { const b = block(key, { type: "function_call" }); b.arguments = (b.arguments || "") + d.delta; } else if (type === "response.custom_tool_call_input.delta") { const b = block(key, { type: "custom_tool_call" }); b.input = (b.input || "") + d.delta; } } else if (Array.isArray(d.choices)) { kind = "chat"; if (d.id) out.id = d.id; if (d.model) out.model = d.model; if (d.usage) out.usage = d.usage; for (const c of d.choices) { const x = c.delta || c.message || {}; const msg = block("c" + (c.index || 0), { type: "message" }); if (typeof x.content === "string") msg.content = (msg.content || "") + x.content; const r = x.reasoning_content ?? x.reasoning; if (typeof r === "string") msg.reasoning = (msg.reasoning || "") + r; for (const tc of x.tool_calls || []) { const b = block("c" + (c.index || 0) + ":" + (tc.index ?? tc.id), { type: "tool_call" }); if (tc.id) b.id = tc.id; if (tc.function?.name) b.name = (b.name || "") + tc.function.name; if (tc.function?.arguments) b.arguments = (b.arguments || "") + tc.function.arguments; } if (c.finish_reason) out.finish_reason = c.finish_reason; } } else if (Array.isArray(d.candidates)) { kind = "gemini"; if (d.modelVersion) out.model = d.modelVersion; if (d.usageMetadata) out.usage = d.usageMetadata; for (const c of d.candidates) { for (const p of c.content?.parts || []) { if (typeof p.text === "string") { const b = block("g" + (c.index || 0) + (p.thought ? "t" : ""), { type: p.thought ? "thought" : "text" }); b.text = (b.text || "") + p.text; } else if (p.functionCall) blocks.push({ type: "functionCall", ...p.functionCall }); } if (c.finishReason) out.finishReason = c.finishReason; } } } if (!kind && !out.error) return null; // the Responses API's own finished output is the reply, when it came const content = (out.output || blocks).filter((b) => !(kind === "chat" && b.type === "message" && !b.content && !b.reasoning)); // a tool's arguments read as the object they spell, when they are whole for (const b of content) { for (const k of ["input", "arguments"]) { if (typeof b[k] !== "string") continue; const v = b[k] === "" && k === "input" ? {} : jsonOr(b[k]); if (v !== undefined) b[k] = v; } } const reply = {}; for (const k of ["id", "model", "status"]) if (out[k] !== undefined) reply[k] = out[k]; if (content.length) reply[{ anthropic: "content", responses: "output", gemini: "parts" }[kind] || "choices"] = content; for (const k of ["stop_reason", "finish_reason", "finishReason", "incomplete", "usage", "error"]) if (out[k] !== undefined) reply[k] = out[k]; return reply; } // The data of each event, as JSON where it is JSON, under its name. function sseEventNode(e, key) { const box = el("span", "sse-ev"); if (e.event) box.append(el("span", "sse-name", "event: " + e.event + "\n")); const d = jsonOr(e.data); box.append(d !== null && typeof d === "object" ? jtNode(d, undefined, "", key + "|", "") : e.data); // [DONE] as it is return box; } function sseData(data) { const d = jsonOr(data); return d !== null && typeof d === "object" ? JSON.stringify(d, null, 2) : data; // [DONE] as it is } const SSE_PAGE = 200; // events drawn at a time: a long stream stays quick to open function sseBodyPanel(label, raw, truncated, id) { const events = parseSSE(raw); if (!events) return null; const reply = sseReply(events); const panel = el("section", "call-body sse"); const head = el("div", "call-body-head"); head.append(el("span", "call-body-label", t(label))); if (truncated) head.append(el("span", "call-body-truncated", typeof truncated === "string" ? truncated : t("first 256 KB"))); const views = [["reply", t("Reply")], ["events", t("Events")], ["raw", t("Raw")]].filter(([v]) => v !== "reply" || reply); let view = views.some(([v]) => v === sseView) ? sseView : "events"; const count = el("span", "call-body-count", t(events.length === 1 ? "1 event" : "{n} events", { n: events.length })); const pick = segs(views, view, (v) => { view = sseView = v; try { localStorage.setItem("magpie.sseView", v); } catch {} draw(); }); pick.classList.add("sse-views"); const copyB = copyBtn("", t(label)); // what it copies is set below head.append(count, el("span", "grow"), pick, copyB); panel.append(head); const pre = el("pre"); // a long stream's events come a page at a time; what draws more sits // under the box, where it stays as they come in rather than at the end // of what is drawn const foot = el("div", "call-body-foot"); const shownNote = el("span"); const moreB = el("button", "link", ""); foot.append(shownNote, el("span", "grow"), moreB); panel.append(pre, foot); let code = null, shown = 0; const more = () => { const upto = Math.min(events.length, Math.max(sseShown.get(id) || 0, shown + SSE_PAGE)); for (; shown < upto; shown++) code.append(sseEventNode(events[shown], id + "|ev" + shown)); if (shown > SSE_PAGE) sseShown.set(id, shown); foot.hidden = view !== "events" || shown >= events.length; shownNote.textContent = t("{n} of {total} events shown", { n: shown, total: events.length }); moreB.textContent = t("Show {n} more events", { n: Math.min(SSE_PAGE, events.length - shown) }); }; moreB.onclick = (ev) => { ev.stopPropagation(); more(); }; const draw = () => { // the box keeps its height across a switch, so what is below it, and // the page, stay where they are if (pre.isConnected) pre.style.minHeight = pre.offsetHeight + "px"; code = view === "reply" ? jsonTree(reply, id + "|reply") : el("code", view === "events" ? "jt" : ""); pre.replaceChildren(code); pre.scrollTop = 0; shown = 0; if (view === "raw") code.textContent = raw; if (view === "events") more(); else foot.hidden = true; }; // what is copied is what is shown: the reply, every event, or the body copyB.onclick = (ev) => { ev.stopPropagation(); const text = view === "reply" ? JSON.stringify(reply, null, 2) : view === "raw" ? raw : events.map((e) => (e.event ? "event: " + e.event + "\n" : "") + sseData(e.data)).join("\n\n"); copy(text, t(label), copyB); }; draw(); return panel; } // id, given, is a response's, whose stream reads as its events; key names // the body for what is folded in it function callBodyPanel(label, raw, truncated, id, key = id) { if (id) { const sse = sseBodyPanel(label, raw, truncated, id); if (sse) return sse; } const panel = el("section", "call-body"); const head = el("div", "call-body-head"); head.append(el("span", "call-body-label", t(label))); if (truncated) head.append(el("span", "call-body-truncated", typeof truncated === "string" ? truncated : t("first 256 KB"))); const formatted = formatWireBody(raw); if (formatted) head.append(el("span", "grow"), copyBtn(raw, t(label))); panel.append(head); const pre = el("pre"); const v = formatted ? jsonOr(raw) : undefined; if (v !== null && typeof v === "object") pre.append(jsonTree(v, key)); else { const code = el("code", "", formatted || t("No body captured")); if (!formatted) code.classList.add("empty"); pre.append(code); } panel.append(pre); return panel; } // The request archive: with it on, each call's headers and bodies, secrets // taken out, go to the S3 bucket sync keeps its backup in, and a request's // row on the Usage page reads its own back from there (gateway/archive.go). // Its switch sits over that list, at its right (Jorben on Discord); what it // keeps, and where, or what it needs first, is its tooltip, and a failed // upload says so beside it. The switch is the same element across redraws, // changed in place, so one being pressed or focused is never swapped out. let archiveSaving = false; function renderArchive() { const box = $("#ledArchive"); if (!box) return; // not said Off before the gateway's state is in box.hidden = !providers?.gateway; if (box.hidden) return; const a = providers.gateway.archive || {}; let b = box.querySelector(".led-arch-sw"); if (!b) { b = el("button", "led-arch-sw"); b.type = "button"; b.setAttribute("role", "switch"); const sw = el("span", "lib-switch"); sw.append(el("i")); b.append(el("span", "led-arch-name"), sw); b.onclick = () => { if (archiveSaving) return; archiveSaving = true; renderArchive(); api("settings/archive", { on: !providers.gateway.archive?.on }) .then((na) => { providers.gateway.archive = na; }) .catch((e) => status(t(e.message), "err")) .finally(() => { archiveSaving = false; renderArchive(); }); }; box.append(b); } b.classList.toggle("on", !!a.on); b.querySelector(".lib-switch").classList.toggle("on", !!a.on); b.setAttribute("aria-checked", a.on ? "true" : "false"); b.disabled = archiveSaving; b.querySelector(".led-arch-name").textContent = t("Request archive"); b.title = a.bucket ? t("Keeps each call’s headers and bodies, secrets taken out, in {where}", { where: a.bucket }) : t("Keeps each call’s headers and bodies, secrets taken out, in your S3 bucket. Set up Sync and backup in Settings with an s3:// address first"); let err = box.querySelector(".led-arch-err"); if (a.on && a.error) { if (!err) { err = el("span", "led-arch-err"); box.prepend(err); } err.textContent = t("Upload failed"); err.title = t("Last upload failed: {e}", { e: a.error }); } else err?.remove(); } // What was read back from the archive, by "/": the archive's // copy, or {busy} while it is read, or {error}. const archivedCalls = new Map(); function headersPanel(label, first, headers) { const panel = el("section", "call-body"); const head = el("div", "call-body-head"); const lines = [first, ...Object.keys(headers || {}).sort().flatMap((k) => headers[k].map((v) => `${k}: ${v}`))].filter(Boolean); head.append(el("span", "call-body-label", label), el("span", "grow"), copyBtn(lines.join("\n"), label)); const pre = el("pre"); pre.append(el("code", "", lines.join("\n"))); panel.append(head, pre); return panel; } // The archived file, whole, however large: to the browser in magpie web, // to Downloads in the app (#447). async function downloadArchive(name, b) { const [date, aid] = name.split("/"); const q = `date=${encodeURIComponent(date)}&id=${encodeURIComponent(aid)}`; if (web) { const a = el("a"); a.href = "/api/archive/file?" + q; a.download = ""; a.click(); return; } b.classList.add("busy"); b.disabled = true; try { const r = await api("archive/export?" + q, {}); status(t("Saved to {path}", { path: r.path }), "ok"); } catch (e) { status(t(e.message), "err"); } finally { b.classList.remove("busy"); b.disabled = false; } } // one body read back from the archive: shown, or, past 256 KB, only its // size — the server leaves it out — for the file to be downloaded whole function archiveBodyPanel(label, part, id, key = id) { if (part.omitted) { const panel = el("section", "call-body"); const head = el("div", "call-body-head"); head.append(el("span", "call-body-label", t(label)), el("span", "call-body-count", fmtBytes(part.size))); panel.append(head, el("p", "call-archive-big", t("Too long to show here. Download the archive to read it whole."))); return panel; } // cut where the archive stops: its limit, or 256 KB in one from before #447 const cut = part.truncated && (part.size ? t("first {n} of {size}", { n: fmtBytes(new Blob([part.body]).size), size: fmtBytes(part.size) }) : true); return callBodyPanel(label, part.body, cut, id, key); } // A call the archive kept, by "/": read back when asked, and its // file downloaded, drawn again by redraw as it is read — under a request's // row on the Usage page (the Gateway page's recent calls show their own // bodies, and no longer the archive's copy as well). function archivePanel(name, id, redraw) { const box = el("section", "call-archive"); const [date, aid] = name.split("/"); const got = archivedCalls.get(name); const head = el("div", "call-body-head"); head.append(el("span", "call-body-label", t("Request archive")), el("code", "call-archive-id", name), el("span", "grow")); box.append(head); const dl = el("button", "text call-archive-dl", t("Download")); dl.onclick = (ev) => { ev.stopPropagation(); downloadArchive(name, dl); }; if (!got || got.busy || got.error) { const b = el("button", "text", t(got?.busy ? "Fetching…" : "Fetch from archive")); b.disabled = !!got?.busy; b.onclick = (ev) => { ev.stopPropagation(); archivedCalls.set(name, { busy: true }); redraw(); api(`archive?date=${encodeURIComponent(date)}&id=${encodeURIComponent(aid)}`) .then((a) => archivedCalls.set(name, a)) .catch((e) => archivedCalls.set(name, { error: t(e.message) })) .finally(redraw); }; head.append(b); if (got?.error) box.append(el("div", "call-archive-err", got.error)); else head.append(dl); // one not in the bucket has nothing to download return box; } head.append(el("span", "call-body-truncated call-archive-note", t("Secrets taken out")), dl); if (got.large) { box.append(el("p", "call-archive-big", t("This archive is {size}, too large to show here. Download it to read it.", { size: got.bytes > 0 ? fmtBytes(got.bytes) : t("very large") }))); return box; } const grid = el("div", "call-details"); grid.append( headersPanel(t("Request Headers"), `${got.request.method || ""} ${got.request.path || ""}`.trim(), got.request.headers), headersPanel(t("Response Headers"), got.response.status ? `HTTP ${got.response.status}` : "", got.response.headers), archiveBodyPanel("Request Body", got.request, undefined, id + "|archive|req"), archiveBodyPanel("Response Body", got.response, id + "|archive"), ); box.append(grid); return box; } // A recent call's bodies, which /api/providers leaves out: forty calls' // bodies made every refresh of it 20 MB (#1521). function loadCallBodies(c, id) { const pending = { busy: true }; callBodies.set(id, pending); api(`gateway/call?id=${encodeURIComponent(c.id)}`) .then((body) => { if (callBodies.get(id) === pending) callBodies.set(id, body); }) .catch((e) => { if (callBodies.get(id) === pending) callBodies.set(id, { error: t(e.message) }); }) .finally(() => { if (view === "gateway" && providers) renderActivity(); }); } // a recent call's row: by the gateway's number for it, as two calls of // one agent to one model can come in the same instant const callRow = (c) => (c.id ? `#${c.id}` : `${c.time}|${c.agent}|${c.model}`); function renderActivity() { const g = providers.gateway; // what calls left the ring keep, they let go of const ids = new Set(g.calls.map(callRow)); for (const id of callBodies.keys()) if (!ids.has(id)) callBodies.delete(id); for (const id of expandedCalls) if (!ids.has(id)) expandedCalls.delete(id); const box = $("#activity"); // a body being read keeps its place as new calls come in const kept = new Map(); for (const item of box.querySelectorAll(".call-item[data-id]")) kept.set(item.dataset.id, [...item.querySelectorAll("pre")].map((p) => p.scrollTop)); box.replaceChildren(); $("#callsNote").textContent = g.running && !g.mine ? t("shown by the magpie that serves the gateway") : ""; const calls = g.calls.slice(0, callsShown); if (!calls.length) { box.append(el("div", "none", t("No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens."))); return; } for (const c of calls) { const id = callRow(c); const open = expandedCalls.has(id); const item = el("div", "call-item" + (open ? " open" : "") + (c.status >= 400 ? " bad" : "")); const r = el("div", "call"); r.setAttribute("role", "button"); r.setAttribute("tabindex", "0"); r.setAttribute("aria-expanded", String(open)); const chev = el("span", "call-chev"); chev.append(svg(CHEV_R, 11, 1.6)); r.append(chev); r.append(el("span", "when", new Date(c.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit" }))); r.append(el("span", "a", c.agent || "—")); r.append(el("span", "m", c.model)); r.append(el("span", "p", c.from === c.to ? c.from : `${c.from} → ${c.to}`)); r.append(el("span", "grow")); r.append(el("span", "st", c.error ? `${c.status} ${c.error}` : `${c.status} · ${ledTook(c.ms)}` + (c.ttft ? " · " + t("TTFT {ms}", { ms: ledTook(c.ttft) }) : ""))); r.title = open ? t("Hide request and response bodies") : t("Show request and response bodies"); const toggle = () => { if (expandedCalls.has(id)) expandedCalls.delete(id); else expandedCalls.add(id); renderActivity(); }; r.onclick = toggle; r.onkeydown = (ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); toggle(); } }; item.append(r); if (open) { if (!callBodies.has(id)) loadCallBodies(c, id); const body = callBodies.get(id); const details = el("div", body.busy || body.error ? "" : "call-details"); if (body.busy) details.append(el("div", "none", t("Fetching…"))); else if (body.error) { details.append(el("div", "call-archive-err", body.error)); const retry = el("button", "text", t("Try again")); retry.onclick = () => { loadCallBodies(c, id); renderActivity(); }; details.append(retry); } else details.append( callBodyPanel("Request Body", body.requestBody, body.requestTruncated, undefined, id + "|req"), callBodyPanel("Response Body", body.responseBody, body.responseTruncated, id), ); item.dataset.id = id; item.append(details); } box.append(item); } if (g.calls.length > calls.length) { const more = el("button", "text activity-more"); more.textContent = t("Show {n} more", { n: Math.min(CALLS_PAGE, g.calls.length - calls.length) }); more.onclick = () => { callsShown = Math.min(g.calls.length, callsShown + CALLS_PAGE); renderActivity(); }; box.append(more); } for (const item of box.querySelectorAll(".call-item[data-id]")) { const tops = kept.get(item.dataset.id) || []; item.querySelectorAll("pre").forEach((p, i) => { if (tops[i]) p.scrollTop = tops[i]; }); } } // An agent's model field, and whether any of its options come from provider p. function modelField(a) { const agent = state.agents.find((x) => x.id === a.id); return agent?.fields.find((f) => f.key === "model") || null; } function ofProvider(p) { return new RegExp(`^(magpie/)?${p.id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`); } // Pick one of this provider's models for an agent, straight from the row. function pickForAgent(a, p, btn, ev) { const agent = state.agents.find((x) => x.id === a.id); const field = modelField(a); if (!field) return; // on a routing group: the whole picker, the group first, not only this // provider's models — picking one would take the agent off the group if (a.group) return openPicker(agent, field, btn, ev); const pre = ofProvider(p); if (!field.options.some((o) => pre.test(o.value))) { ev.stopPropagation(); status(t("{p} exposes no models yet — pick some below", { p: p.name }), "warn"); editing = p.id; draft = null; renderProviders(); return; } openPicker(agent, field, btn, ev, (o) => pre.test(o.value)); } // The add sheet: presets first (a key is all they need), custom last. let presetQuery = "", addReturnPick = null; function renderAdd() { const sheet = $("#addSheet"); // a redraw (providers reloaded) gives the focus back where it was in it const active = document.activeElement, hadFocus = sheet.contains(active); const focusPick = hadFocus && active.closest("[data-pick]")?.dataset.pick; const selection = hadFocus && active.matches(".find") ? [active.selectionStart, active.selectionEnd] : null; sheet.replaceChildren(); // A sheet put away by a redraw rather than rolled up (a sign-in done // opens its account's editor, an import or an action closes it) takes // what it held with it, as closeAddSheet does: a click in it still held // the page where the sheet had been, and the room made for that was left // under a list now ending far above it — the page blank (#509). if (!adding && !sheet.hidden) { const view = $("#view-providers"); if (held?.v === view) held = null; setRoom(view, 0); } sheet.hidden = !adding; if (!adding) partnersCounted = null; // Duplicate and Add another open a new provider's editor with no sheet if (!adding) return editing && typeof editing === "object" ? renderEditor(null, editing.preset) : null; const head = el("div", "row-head"); head.append(el("span", "label", t(providers.providers.length ? "Add a provider" : "Add your first provider")), el("span", "grow")); const q = input(presetQuery, t("Find a vendor…")); q.className = "find"; // Escape empties the search, then closes the sheet; it never hides the tray q.onkeydown = (e) => { if (e.key !== "Escape") return; e.preventDefault(); e.stopPropagation(); if (q.value) { q.value = presetQuery = ""; drawTiles(); } else if (providers.providers.length) closeAddSheet(); }; q.oninput = () => { presetQuery = q.value; drawTiles(); }; head.append(q); const imp = el("button", "text", t("Import…")); imp.title = t("Bring over providers set up in other apps"); imp.onclick = openImportApps; head.append(imp); if (providers.providers.length) { const x = el("button", "text", t("Close")); x.onclick = closeAddSheet; head.append(x); } sheet.append(head); const tiles = el("div", "tiles"); sheet.append(tiles); const drawTiles = () => { tiles.replaceChildren(); const f = presetQuery.trim().toLowerCase(); // the note is found in the words it is shown in, too (远程 for Remote magpie) const hit = (pr) => !f || pr.name.toLowerCase().includes(f) || pr.id.includes(f) || hostOf(pr.chat || pr.responses || pr.anthropic).includes(f) || (pr.note || "").toLowerCase().includes(f) || (pr.note ? t(pr.note).toLowerCase().includes(f) : false); // a section: its name, what it is in a word, and its rows, three to a line const section = (title, hint) => { const k = el("div", "kind"); k.append(el("b", "", t(title))); if (hint) k.append(el("span", "", t(hint))); const grid = el("div", "grid"); tiles.append(k, grid); return grid; }; let any = false; // one moved onto its plugin stays where it was, signing in through it; // a deprecated one whose plugin is installed is that plugin's row alone // (ARNO on Discord: Qoder CN twice), and one with no account isn't // offered at all: it is the Plugins page's, installed from there // (yetone: 对于新用户来说,这里应该只显示内置的 provider), unless it is // signing in now. A search naming one finds it there. const named = (x) => !f || x.name.toLowerCase().includes(f) || x.agent.includes(f) || "subscription".includes(f); const subs = SUBS.filter((x) => !(replacedSub(x.agent) || unusedSub(x.agent)) || signing?.agent === x.agent).map((x) => subOf(x.agent)).filter(named); const inPlugins = f && SUBS.some((x) => unusedSub(x.agent) && signing?.agent !== x.agent && named(subOf(x.agent))); // partners pay to be listed first, under a heading that says so; who // they are comes from usemagpie.ai (internal/provider/partners.go), and // each may name the languages it is shown in const partners = providers.presets.filter((p) => p.kind === "partner" && partnerShown(p) && (hit(p) || partnerNote(p).toLowerCase().includes(f))); if (partners.length) { any = true; const grid = section("Partners", "magpie's sponsors"); for (const pr of partners) grid.append(partnerTile(pr)); partnersCounted ??= new Set(); const fresh = partners.filter((p) => !partnersCounted.has(p.id)); for (const p of fresh) partnersCounted.add(p.id); countPartner("shown", fresh.map((p) => p.id)); // shown, they are new no more (provider.NoticePartners) for (const p of partners) p.new = false; markNewPartners(); } if (subs.length || inPlugins) { any = true; const grid = section("Subscriptions", "sign in, no key"); for (const x of subs) grid.append(subTile(x)); if (!f || inPlugins) grid.append(morePluginsTile(f)); const w = subs.find((x) => signing?.agent === x.agent); if (w) tiles.append(renderSigning(w)); } const plugged = pluginSubs().filter((x) => !(movedSub(x.agent) && SUBS.some((y) => y.agent === x.agent))).filter((x) => !f || x.name.toLowerCase().includes(f) || x.agent.includes(f) || "plugin".includes(f)); if (plugged.length) { any = true; const grid = section("From plugins", "signed in by an OpenCode plugin or a pi package"); for (const x of plugged) grid.append(subTile(x)); const w = plugged.find((x) => signing?.agent === x.agent); if (w) tiles.append(renderSigning(w)); } // the removed ones the user asked not to be reminded of, each with its // two ways out side by side: added back as it was, or signed out for // good (#694, mintonight: no menu to open first, and no "Don't show // here": hiding one left its sign-in where it was). One hidden before // (#116) is listed with the rest. const gone = (providers.excluded || []).filter((x) => x.quiet && x.provider && (!f || x.agentName.toLowerCase().includes(f) || x.agent.includes(f))); if (gone.length) { any = true; const grid = section("Removed from magpie", "still signed in"); for (const x of gone) { const r = el("div", "tile removed"); r.dataset.pick = "removed:" + x.provider; // not the subscription's own row, named alike const nm = el("span", "nm"); nm.append(el("span", "n", x.agentName)); const back = el("button", "text action", t("Add it back")); back.title = t("its accounts and model picks as they were"); back.onclick = (e) => { e.stopPropagation(); providerAction("show", { id: x.provider }, t("{name} added back", { name: x.agentName })); }; const out = el("button", "text action danger", t("Sign out…")); out.title = t("magpie forgets its accounts; adding it again signs in afresh"); out.onclick = (e) => { e.stopPropagation(); askForgetAccount(x); }; const acts = el("span", "acts"); acts.append(back, out); r.append(icon(x.agentIcon), nm, acts); grid.append(r); } } // another computer's magpie is no relay: a heading of its own, after // this machine's (Avalon on Discord didn't find it among the relays) for (const [kind, title, hint] of [["vendor", "Vendors", "the makers' own APIs"], ["relay", "Relays", "one key, many vendors"], ["local", "On this machine", ""], ["remote", "Another computer's magpie", "shared on its network"]]) { // a vendor's China endpoint is a preset of its own: one row with the global one const rows = providers.presets.filter((p) => p.kind === kind && !globalOf(p)) .map((p) => [p, chinaOf(p)]).filter(([p, cn]) => hit(p) || (cn && hit(cn))); if (!rows.length) continue; any = true; const grid = section(title, hint); for (const [pr, cn] of rows) grid.append(cn ? pairTile(pr, cn) : tile(pr)); } if (!any) { const none = el("div", "none"); none.append(t("Nothing called “{q}”. ", { q: presetQuery.trim() })); const b = el("button", "link", t("Add it as a custom provider")); b.onclick = () => { editing = { custom: true }; draft = null; renderProviders(); }; const pl = el("button", "link", t("look for a plugin")); pl.onclick = () => openPlugins(presetQuery.trim()); none.append(b, t(", or "), pl); tiles.append(none); } else if (!f) { // a vendor not listed: one line under them all const foot = el("div", "custom-foot"); const c = el("button", "custom" + (editing?.custom ? " on" : "")); c.append(svg(PLUS, 13, 1.8), el("span", "", t("Custom provider"))); c.dataset.pick = "custom"; c.onclick = () => { editing = { custom: true }; draft = null; renderProviders(); }; foot.append(c, el("span", "hint", t("any OpenAI or Anthropic compatible URL"))); tiles.append(foot); } }; drawTiles(); if (hadFocus && $("#modal").hidden) { (focusPick && sheet.querySelector(`[data-pick="${CSS.escape(focusPick)}"]`) || q).focus({ preventScroll: true }); if (selection) q.setSelectionRange(...selection); } return editing && typeof editing === "object" ? renderEditor(null, editing.preset) : null; } // pickRow is one row of the add sheet: an icon and a name, nothing framing // them; what more there is to say goes in its title. function pickRow(ic, name, cls = "") { const b = el("button", "tile" + cls); b.dataset.pick = name; // the dialog it opens folds back into it, re-rendered const nm = el("span", "nm"); nm.append(el("span", "n", name)); b.append(icon(ic), nm); return b; } // morePluginsTile: the add sheet's way to the Plugins tab, where more // subscriptions are, each signed in to by a plugin function morePluginsTile(q) { const b = el("button", "tile more-plugins"); b.dataset.pick = "plugins"; const nm = el("span", "nm"); nm.append(el("span", "n", t("More in Plugins"))); const ic = el("span", "puzzle"); ic.append(svg(PUZZLE, 15, 1.4)); b.append(ic, nm, svg(CHEV_R, 11, 1.6)); b.title = t("Subscriptions magpie doesn't sign in to itself: install a plugin for one in the Plugins tab"); b.onclick = () => openPlugins(q); return b; } // openPlugins: the Plugins tab, looking for q when there is one async function openPlugins(q) { if (mode !== "window") { api("window/main?view=plugins", {}).catch(() => {}); return; } if (!await show("plugins")) return; window.pluginQuery?.(q || ""); } // pluginSignIn: a plugin's provider signed in to as every subscription is, // in the Providers add sheet async function pluginSignIn(id) { if (!await show("providers")) return; closeModal(); adding = true; editing = null; draft = null; presetQuery = ""; renderProviders(); startSignIn(id); } // openProvider: a provider opened in the Providers tab async function openProvider(id) { if (view === "providers" && providerDirty() && !(await confirmDiscard())) return; if (!await show("providers")) return; closeModal(); adding = false; editing = id; draft = null; presetQuery = ""; // the list not in yet (the tab not opened before), show's load draws it // with this one open if (providers) renderProviders(); syncURL(); } // a row already added: a green dot after its name, and how many accounts // when a subscription has more than one function markAdded(b, n = 1) { b.classList.add("added"); const nm = b.querySelector(".nm"); nm.append(el("span", "have")); if (n > 1) nm.append(el("span", "cnt", String(n))); } // the add sheet names a row without what its title tells: a subscription's // plan in brackets, a preset's long name const shortName = (name) => name.replace(/\s*[((][^()()]*[))]\s*$/, "") || name; // a vendor's China endpoint is a preset of its own, id-cn beside the global id const chinaOf = (pr) => providers.presets.find((x) => x.id === pr.id + "-cn"); const globalOf = (pr) => pr.id.endsWith("-cn") ? providers.presets.find((x) => x.id === pr.id.slice(0, -3)) : null; // pairTile is a vendor's global and China presets as one row; the editor // switches between them. A click adds the one not added yet, or opens the // provider when both are. function pairTile(pr, cn) { const both = [pr, cn]; const b = pickRow(pr.icon || "generic", shortName(pr.short || pr.name), both.some((x) => editing?.preset === x.id) ? " on" : ""); const added = both.filter((x) => x.added); b.title = both.map((x) => t(x === pr ? "Global" : "China") + " " + hostOf(x.chat || x.responses || x.anthropic) + (x.added ? " · " + t("Added") : "")).join("\n"); if (added.length) markAdded(b); const next = both.find((x) => !x.added); b.onclick = () => { if (next) { editing = { preset: next.id }; draft = null; } else { editing = presetProvider(pr)?.id ?? pr.id; draft = null; } renderProviders(); }; return b; } // regionAt is the region of a preset a draft's endpoints are at, by its // chat URL (a new one's are the preset's own: its first region) const regionAt = (pr, d) => pr?.regions?.find((r) => r.chat && r.chat === (d?.chat || pr.chat)); // the first provider made from a preset, which may not have the preset's id const presetProvider = (pr) => providers.providers.find((p) => p.preset === pr.id) || providers.providers.find((p) => p.id === pr.id); // subTile adds a subscription: one more account when the agent has some. function subTile(x) { const have = providers.providers.find((p) => p.account?.agent === x.agent); const n = have ? (have.account.logins?.length || 1) : 0; const b = pickRow(x.icon, shortName(x.name), signing?.agent === x.agent ? " on" : ""); b.title = t("{name} subscription", { name: x.name }) + " · " + x.plans; if (x.hint) b.title += "\n" + t(x.hint); // deprecated: badged (one with no account isn't offered here) if (!x.plugin && deprecatedSub(x.agent) && n) { b.querySelector(".nm").append(deprecatedBadge()); b.title += "\n" + t("Deprecated") + " · " + t(DEPRECATED_WHY); } if (n) { markAdded(b, x.single ? 1 : n); b.title += "\n" + (x.single ? t("Signed in") : t(n === 1 ? "1 account" : "{n} accounts", { n })) + " · " + t(x.single ? "signed in · click to switch account" : "click to add another account"); } b.onclick = () => startSignIn(x.agent); return b; } function tile(pr) { const b = pickRow(pr.icon || "generic", pr.short || pr.name, editing?.preset === pr.id ? " on" : ""); if (pr.sponsored) b.querySelector(".nm").append(el("span", "badge", t("sponsored"))); b.title = (pr.short ? pr.name + " · " : "") + (pr.note ? t(pr.note) : hostOf(pr.chat || pr.responses || pr.anthropic)); if (pr.added) { markAdded(b); b.title = t("{name} is already added — open it", { name: pr.name }); const have = presetProvider(pr); b.onclick = () => { editing = have?.id ?? pr.id; draft = null; renderProviders(); }; } else { b.onclick = () => { editing = { preset: pr.id }; draft = null; renderProviders(); }; } return b; } // the page's language and its base ("zh-TW", "zh") function pageLangs() { const l = document.documentElement.lang || "en"; return [l, l.split("-")[0]]; } // a partner listed in no language of its own is listed in every one function partnerShown(pr) { return !pr.langs?.length || pageLangs().some((l) => pr.langs.includes(l)); } // the partner's tagline in the page's language, else its English one; the // partner writes it, so it isn't translated here function partnerNote(pr) { const n = pr.notes || {}; for (const l of pageLangs()) if (n[l]) return n[l]; return n.en || ""; } // countPartner counts what for partners (provider.CountPartner): magpie // counts them only when the stats are on, and nothing waits on it function countPartner(what, ids) { if (ids.length) api("partner", { what, ids }).catch(() => {}); } // a partner listed since the add sheet last showed the partners puts a // small dot on the add button, its name in the button's title, until the // sheet shows it (yetone: 有了新的合作伙伴的时候…提醒吸引用户点击查看) function markNewPartners() { const b = $("#addProvider"); if (!b) return; const fresh = adding ? [] : (providers?.presets || []).filter((p) => p.kind === "partner" && p.new && !p.added && partnerShown(p)); b.classList.toggle("has-new", fresh.length > 0); if (fresh.length) b.title = t("New in Partners: {names}", { names: fresh.map((p) => p.name).join(", ") }); else b.removeAttribute("title"); } // a partner's row: its own section says it is sponsored, so no badge function partnerTile(pr) { const b = tile({ ...pr, sponsored: false, note: "" }); if (!pr.added) { const open = b.onclick; b.onclick = (e) => { countPartner("opened", [pr.id]); open(e); }; } if (!pr.added) b.title = pr.name + (partnerNote(pr) ? " · " + partnerNote(pr) : "") + "\n" + hostOf(pr.chat || pr.responses || pr.anthropic); return b; } let fieldIDs = 0; function field(label, control, hint) { const l = el("label", "", label); const wrap = el("div"); wrap.append(control); const inputSelector = "input, select, textarea"; const inputs = control.matches(inputSelector) ? [control] : [...control.querySelectorAll(inputSelector)]; if (label && inputs.length) { for (const input of inputs) { if (!input.id) input.id = "field-" + ++fieldIDs; if (!input.closest("label") && !input.hasAttribute("aria-label") && !input.hasAttribute("aria-labelledby")) input.setAttribute("aria-label", label); } l.htmlFor = inputs[0].id; } if (hint) { const help = el("div", "hint", hint); help.id = "field-help-" + ++fieldIDs; wrap.append(help); for (const input of inputs) input.setAttribute("aria-describedby", [input.getAttribute("aria-describedby"), help.id].filter(Boolean).join(" ")); } return [l, wrap]; } // decimalOf is a number as typed in a price box, a comma taken for the // decimal point as some keyboards give it (0,25); NaN for anything else. // The boxes are text ones: a number box drops what its locale doesn't // take, and "0,25" became 25. function decimalOf(s) { s = String(s ?? "").trim(); if (/^\d*,\d+$/.test(s)) s = s.replace(",", "."); return /^(\d+\.?\d*|\.\d+)$/.test(s) ? Number(s) : NaN; } // tokensTyped is a number of tokens as typed, 272K, 1M or 200000; NaN for // anything else function tokensTyped(s) { const x = /^(\d+(?:[.,]\d+)?)\s*([km]?)$/i.exec(String(s ?? "").trim()); if (!x) return NaN; const n = Math.round(Number(x[1].replace(",", ".")) * ({ k: 1e3, m: 1e6 }[x[2].toLowerCase()] || 1)); return n > 0 ? n : NaN; } function tokenSize(n) { return n >= 1e6 && n % 1e6 === 0 ? n / 1e6 + "M" : n >= 1e3 && n % 1e3 === 0 ? n / 1e3 + "K" : String(n); } // samePrice: two prices alike in every part, their 1-hour cache writes and // long-context prices included function samePrice(a, b) { const norm = (p) => JSON.stringify([p.input, p.output, p.cache_read || 0, p.cache_write || 0, p.cache_write_1h || 0, (p.tiers || []).map((x) => [x.above, x.input, x.output, x.cache_read || 0, x.cache_write || 0, x.cache_write_1h || 0])]); return norm(a) === norm(b); } function input(value, placeholder, type = "text") { const i = el("input"); i.type = type; i.value = value || ""; i.placeholder = placeholder || ""; i.spellcheck = false; i.autocomplete = "off"; i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") { if (editing !== null || importing || importingApps) cancelEdit(); } }; return i; } // keep: leaving the page, a sign-in under way in the editor goes on; the // editor put away (Cancel, Escape, a click outside) takes it with it (#526) let providerDraftRef = null, providerDraftBase = ""; function providerDraftValue() { return JSON.stringify({ ...draft, headers: headersOf(draft?.headers), modelPrefs: modelPrefsOfDraft() }); } function providerDirty() { // Price boxes parse on change; a page closed while typing hasn't blurred one yet. const active = document.activeElement; return !!draft && draft === providerDraftRef && (providerDraftValue() !== providerDraftBase || (active?.matches(".editor .mprice input") && active.value !== active.defaultValue)); } // backdropClick(el, on) says whether a click on el is one on its backdrop: // pressed and let go both where on(e) says the backdrop is. A press inside // the dialog let go out over the backdrop, a selection dragged out of a // field (#1373), clicks the two's nearest shared ancestor, the backdrop, so // the click's own target can't tell it apart. Every dialog that closes from // its backdrop asks this. function backdropClick(el, on = (e) => e.target === el) { let down = false, up = false; el.addEventListener("pointerdown", (e) => { down = on(e); up = false; }, true); el.addEventListener("pointerup", (e) => { up = down && on(e); }, true); return (e) => up && on(e); } let confirmationPending = null; function confirmAction(title, message, action) { if (confirmationPending) return Promise.resolve(false); const dialog = el("dialog", "action-confirm"); dialog.setAttribute("role", "alertdialog"); dialog.setAttribute("aria-labelledby", "actionConfirmTitle"); dialog.setAttribute("aria-describedby", "actionConfirmMessage"); const heading = el("h2", "", title); heading.id = "actionConfirmTitle"; const description = el("p", "", message); description.id = "actionConfirmMessage"; const bar = el("div", "bar"); const cancel = el("button", "text", t("Cancel")); const accept = el("button", "text primary danger-fill", action); cancel.type = accept.type = "button"; bar.append(el("span", "grow"), cancel, accept); dialog.append(heading, description, bar); const previousFocus = document.activeElement; document.body.append(dialog); return new Promise((resolve) => { confirmationPending = dialog; const finish = (accepted) => { dialog.close(); dialog.remove(); confirmationPending = null; if (previousFocus?.isConnected) previousFocus.focus({ preventScroll: true }); resolve(accepted); }; cancel.onclick = () => finish(false); accept.onclick = () => finish(true); dialog.addEventListener("cancel", (event) => { event.preventDefault(); finish(false); }); // the dialog's ::backdrop is the dialog itself, outside its box const onBackdrop = backdropClick(dialog, (event) => { const rect = dialog.getBoundingClientRect(); return event.target === dialog && (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom); }); dialog.addEventListener("click", (event) => { if (onBackdrop(event)) finish(false); }); // Keep the underlying editor's Escape handlers from seeing this dialog. dialog.addEventListener("keydown", (event) => { event.stopPropagation(); if (event.key !== "Tab") return; const boundary = event.shiftKey ? cancel : accept; if (document.activeElement !== boundary) return; event.preventDefault(); (event.shiftKey ? accept : cancel).focus(); }); // Open after the triggering Escape has finished, so it cannot cancel this dialog. requestAnimationFrame(() => { dialog.showModal(); cancel.focus({ preventScroll: true }); }); }); } function confirmRemoval(name, consequence = "This removes the selected item. Continue?") { return confirmAction(t("Remove {name}?", { name }), t(consequence), t("Remove")); } function confirmDiscard() { return confirmAction(t("Discard"), t("Discard unsaved changes? Your changes will be lost."), t("Discard")); } async function cancelEdit(keep) { if ((providerDirty() || ((importing || importingApps) && modalFormDirty())) && !(await confirmDiscard())) return false; if (keep !== true) dropSigningIn(editing); editing = null; draft = null; importing = null; importingApps = null; renderProviders(); return true; } window.addEventListener("beforeunload", (e) => { if (providerDirty() || window.routingDirty?.() || ((view === "library" || importing || importingApps) && modalFormDirty())) { e.preventDefault(); e.returnValue = ""; } }); // priceTypedError: a model with no list price given only part of its // price in Names & levels (its input and output both needed) holds the // Save, its empty box focused, rather than the part typed being dropped. function priceTypedError(ed) { const id = Object.keys(draft?.priceTyped || {}).find((x) => !draft.chosen?.length || draft.chosen.includes(x)); if (id === undefined) return false; const row = [...ed.querySelectorAll(".mname")].find((r) => r.querySelector("code")?.textContent === id); [...(row?.querySelectorAll(".mprice input") || [])].find((i) => i.value.trim() === "" && !i.placeholder)?.focus({ preventScroll: true }); editorError(t("{id} has no list price: give its input and output prices", { id }), "warn"); return true; } // modelPrefsOfDraft: the names, levels and images staged in the editor's // Names & levels, for its Save, or nothing when none changed. function modelPrefsOfDraft() { const x = draft?.modelPrefs; return x && Object.keys(x).length ? x : undefined; } // proxyPicker: the proxy one provider's requests go through (#237) — the // one in Settings, none, or its own — so Codex can go through a proxy // while a vendor at home goes direct. The draft keeps the choice as // proxyMode ("" global, "direct", "custom") and the address as proxyURL; // proxyOfDraft is what is saved. const PROXY_HINT = { "": "Follows the proxy in Settings", direct: "Requests to it go direct, whatever the proxy in Settings", custom: "Requests to it go through this proxy: http://, https:// or socks5://", }; function proxyPicker() { const box = el("div", "stack proxy-pick"); const hint = el("div", "hint", t(PROXY_HINT[draft.proxyMode || ""])); const addr = input(draft.proxyURL || "", "http://127.0.0.1:7890"); addr.className = "proxy-url"; addr.classList.toggle("off", draft.proxyMode !== "custom"); addr.oninput = () => { draft.proxyURL = addr.value; }; const seg = segs([["", t("Global proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], draft.proxyMode || "", (v) => { draft.proxyMode = v; addr.classList.toggle("off", v !== "custom"); hint.textContent = t(PROXY_HINT[v]); }); seg.classList.add("proxy-mode"); // the address sits beside the options, its room kept while it is not // asked for, so picking one never changes the dialog's height (a // centred dialog would move under the pointer) const row = el("div", "proxy-row"); row.append(seg, addr); box.append(row, hint); return box; } // concurrencyField: how many requests each of the provider's keys or // accounts may have out at the vendor at once (Discord, Lemon: a Codex // account is risk-controlled past five or six); more wait their turn and // go in order. The draft keeps what is typed as concurrency, "" for none // set — a plugin's provider then takes what its plugin says, shown as the // placeholder — and concurrencyOfDraft is what is saved. function concurrencyField(p) { const plugin = p?.pluginConcurrency || 0; const box = input(draft.concurrency ?? "", plugin ? t("{n}, as its plugin says", { n: plugin }) : t("No limit"), "number"); box.classList.add("concurrency"); box.min = "0"; box.max = "1000"; box.step = "1"; box.inputMode = "numeric"; box.oninput = () => { draft.concurrency = box.value; }; // the queue each key or account has past it (#892): how many may wait, // and how long; past either, a request is turned away with a 429 const queue = input(draft.queueLimit ?? "", t("No bound"), "number"); queue.classList.add("queue-limit"); const wait = input(draft.queueWait ?? "", t("As long as it takes"), "number"); wait.classList.add("queue-wait"); // how many requests each key or account sends the vendor in any minute // (coeo91 on Discord: OpenRouter's free models take 20); one more waits // for room in the minute const rpm = input(draft.maxRPM ?? "", t("No limit"), "number"); rpm.classList.add("rpm"); for (const [b, max, k] of [[queue, 10000, "queueLimit"], [wait, 3600, "queueWait"], [rpm, 10000, "maxRPM"]]) { b.min = "0"; b.max = String(max); b.step = "1"; b.inputMode = "numeric"; b.oninput = () => { draft[k] = b.value; }; } return [ ...field(t("Concurrency"), box, (plugin ? t("Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit", { n: plugin }) : t("Over it, requests queue and go out in order; 0 or empty is no limit"))), ...field(t("Requests per minute"), rpm, t("How many requests each key or account sends in any minute, retries included; one more waits for room, up to 2 minutes. 0 or empty is no limit")), ...field(t("Queue size"), queue, t("How many requests may wait for each key or account; one more is turned away at once. 0 or empty is no bound")), ...field(t("Queue wait"), wait, t("Seconds a request waits for a free slot before it is turned away. 0 or empty waits as long as it takes")), ]; } // priceRateField: what the provider charges against the official price // (ITea312, #819), as a relay bills 0.8× or 1.5× of it: the Usage page's // costs are its list price, else its maker's, times this. Empty is the // price as listed; steps of 0.001. function priceRateField() { const box = input(draft.priceRate ?? "", t("1, the official price")); box.classList.add("price-rate"); box.inputMode = "decimal"; box.oninput = () => { draft.priceRate = box.value; }; return field(t("Price rate"), box, t("Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set")); } // priceRateOfDraft is the draft's rate as it is saved — null for none, // else the number — or undefined when what is typed isn't one. function priceRateOfDraft() { const v = String(draft.priceRate ?? "").trim(); if (!v) return null; const n = decimalOf(v); if (!(n >= 0 && n <= 1000) || Math.abs(n * 1000 - Math.round(n * 1000)) > 1e-6) return undefined; return n; } function priceRateError(ed) { ed.querySelector("input.price-rate")?.focus({ preventScroll: true }); return editorError(t("Price rate: a number from 0 to 1000, at most three decimals"), "warn"); } function concurrencyDraft(p) { return { concurrency: p?.maxConcurrency == null ? "" : String(p.maxConcurrency), priceRate: p?.priceRate ? String(p.priceRate) : "", queueLimit: p?.queueLimit ? String(p.queueLimit) : "", queueWait: p?.queueWait ? String(p.queueWait) : "", maxRPM: p?.maxRPM ? String(p.maxRPM) : "" }; } // queueOfDraft is the draft's queue and limit a minute as they are saved, // { queueLimit, queueWait, maxRPM } with 0 for none, or { bad } naming the // field typed wrong. function queueOfDraft() { const out = {}; for (const [k, max] of [["queueLimit", 10000], ["queueWait", 3600], ["maxRPM", 10000]]) { const v = String(draft[k] ?? "").trim(); if (!v) { out[k] = 0; continue; } if (!/^\d+$/.test(v) || +v > max) return { bad: k }; out[k] = +v; } return out; } function queueError(ed, bad) { if (bad === "maxRPM") { ed.querySelector("input.rpm")?.focus({ preventScroll: true }); return editorError(t("Requests per minute: a whole number from 0 to 10000"), "warn"); } ed.querySelector(bad === "queueLimit" ? "input.queue-limit" : "input.queue-wait")?.focus({ preventScroll: true }); return editorError(bad === "queueLimit" ? t("Queue size: a whole number from 0 to 10000") : t("Queue wait: a whole number of seconds from 0 to 3600"), "warn"); } // concurrencyOfDraft is the draft's limit as it is saved — null for none // set, else the number — or undefined when what is typed isn't one. function concurrencyOfDraft() { const v = String(draft.concurrency ?? "").trim(); if (!v) return null; if (!/^\d+$/.test(v) || +v > 1000) return undefined; return +v; } function concurrencyError(ed) { ed.querySelector("input.concurrency")?.focus({ preventScroll: true }); return editorError(t("Concurrency: a whole number from 0 to 1000"), "warn"); } function proxyDraft(p) { const v = (p?.proxy || "").trim(); // each account's own (accountProxies), by its name in lower case const accountProxies = {}; for (const [u, x] of Object.entries(p?.accountProxies || {})) accountProxies[u] = { mode: x === "direct" ? "direct" : "custom", url: x === "direct" ? "" : x }; return { proxyMode: !v ? "" : v === "direct" ? "direct" : "custom", proxyURL: v && v !== "direct" ? v : "", accountProxies }; } // asTyped: the editor's form as it stands, for Refresh and the Tests to // ask with before a Save — a key just pasted over the saved one is the one // tried, and nothing is saved by it. Outside the editor, nothing. function asTyped() { if (!draft) return {}; // many keys pasted (361 on Discord) are asked about by the first const keys = splitKeys(draft.key || ""); const body = { typed: true, key: keys.length > 1 ? keys[0] : (draft.key || "").trim(), chat: (draft.chat || "").trim(), responses: (draft.responses || "").trim(), anthropic: (draft.anthropic || "").trim(), gemini: (draft.gemini || "").trim(), modelsURL: (draft.modelsURL || "").trim() }; Object.assign(body, movedURLs(draft)); // a System One base is asked at POST …/systemone, not on the three APIs if (draft.api === "decide") body.decide = (draft.decide || "").trim(); // a Vertex AI provider is asked at the project typed, with the // credentials typed, as a pasted key is if (draft.vertex) body.vertex = vertexOfDraft(); if (draft.headers) body.headers = headersOf(draft.headers); // the extra body typed, when it reads; one that doesn't is the saved one's const xb = extraBodyOf(draft.extraBody); if (xb.value) body.extraBody = xb.value; const proxy = draft.proxyMode === undefined ? null : proxyOfDraft(); if (proxy !== null) body.proxy = proxy; return body; } // proxyOfDraft is the draft's proxy as it is saved, or null when Custom // has no address yet. function proxyOfDraft() { if (draft.proxyMode === "direct") return "direct"; if (draft.proxyMode !== "custom") return ""; return (draft.proxyURL || "").trim() || null; } // accountProxyPicker: one proxy per account of a subscription holding // several (gakki: one Codex account through one proxy, another through // another) — the provider's own (the row above), none, or its own address. // Each account is a line of its name over the same row as the provider's, // the address's room kept while it isn't asked for, so a pick moves // nothing. null for a subscription with one account: the row above is its. const ACCOUNT_PROXY_HINT = "Each account can go through a proxy of its own; Provider's proxy is the one above"; function accountProxyPicker(a) { const ls = [...(a?.logins || [])]; ls.sort((x, y) => (y.active ? 1 : 0) - (x.active ? 1 : 0)); return proxyLines(ls.map((l) => ({ k: l.user.toLowerCase(), name: l.user, user: l.user })), ACCOUNT_PROXY_HINT); } // keyProxyPicker is accountProxyPicker for a provider's keys (Beyfish_Wang // on X: 不同 key 走不同的代理), each by its fingerprint, named as the // Accounts list names it. null for a provider with one key. const KEY_PROXY_HINT = "Each key can go through a proxy of its own; Provider's proxy is the one above"; function keyProxyPicker(p) { return proxyLines((p?.keyList || []).map((k) => ({ k: k.id, name: k.name || k.masked, key: k.id })), KEY_PROXY_HINT); } function proxyLines(items, hint) { if (items.length < 2) return null; draft.accountProxies = draft.accountProxies || {}; const box = el("div", "acct-proxies"); for (const it of items) { const k = it.k; const cur = draft.accountProxies[k] || { mode: "", url: "" }; const line = el("div", "acct-proxy"); if (it.user) line.dataset.user = it.user; if (it.key) line.dataset.key = it.key; const who = el("span", "who", it.name); who.title = it.name; const addr = input(cur.url || "", "http://127.0.0.1:7890"); addr.className = "proxy-url"; addr.classList.toggle("off", cur.mode !== "custom"); addr.oninput = () => { draft.accountProxies[k] = { ...(draft.accountProxies[k] || { mode: "custom" }), url: addr.value }; }; const seg = segs([["", t("Provider's proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], cur.mode || "", (v) => { draft.accountProxies[k] = { ...(draft.accountProxies[k] || {}), mode: v }; addr.classList.toggle("off", v !== "custom"); }); seg.classList.add("proxy-mode"); const row = el("div", "proxy-row"); row.append(seg, addr); line.append(who, row); box.append(line); } box.append(el("div", "hint", t(hint))); return box; } // accountProxiesOfDraft is each account's own proxy as it is saved — the // accounts that follow the provider's left out — or { missing: user } when // one's Custom has no address yet. function accountProxiesOfDraft() { const out = {}; for (const [u, x] of Object.entries(draft.accountProxies || {})) { if (x.mode === "direct") out[u] = "direct"; else if (x.mode === "custom") { const v = (x.url || "").trim(); if (!v) return { missing: u }; out[u] = v; } } return { map: out }; } // Custom request headers: the draft keeps them as an ordered [name, value, // json?] list so a half-typed row (and its open JSON editor) survives a // re-render; headersOf folds that back into the object the backend stores, // dropping rows with an empty name or value (a suggested header left unfilled // is not sent), keeping the last of two rows that name one header in any // case, and minifying any value that parses as JSON — a header value is one // line, so pretty-printing is display-only. function headerRows(obj) { return Object.entries(obj || {}).map(([k, v]) => [k, v, false]); } function headersOf(rows) { const out = {}; for (const [k, v] of rows || []) { const name = (k || "").trim(); const val = (v || "").trim(); if (!name || !val) continue; for (const had of Object.keys(out)) if (had.toLowerCase() === name.toLowerCase()) delete out[had]; // minify only a JSON blob; a plain value like "2.0" must stay verbatim out[name] = looksJSON(val) ? minifyJSON(val) : val; } return out; } // minifyJSON collapses a value to one line when it is valid JSON, so a // pretty-printed blob in the editor never reaches the wire with newlines. function minifyJSON(s) { try { return JSON.stringify(JSON.parse(s)); } catch { return s; } } function prettyJSON(s) { try { return JSON.stringify(JSON.parse(s), null, 2); } catch { return s; } } function looksJSON(s) { s = (s || "").trim(); return s.startsWith("{") || s.startsWith("["); } // hints are the optional headers a preset's vendor documents: each one not // in the list yet is offered as a button that adds its row, value left empty. function headerEditor(hints = []) { const box = el("div", "headers"); const render = () => { box.replaceChildren(); draft.headers.forEach((row, i) => { const line = el("div", "pair"); const name = input(row[0], t("Header-Name")); name.oninput = () => { row[0] = name.value; }; // the value: a one-line box, or (when the row is expanded) a full-width // textarea that pretty-prints JSON for editing. The toggle is always // offered — a value only becomes JSON after you paste it in. let valCtl; if (row[2]) { valCtl = el("textarea", "json"); valCtl.value = prettyJSON(row[1]); valCtl.spellcheck = false; valCtl.wrap = "off"; // each JSON line stays on one line; scroll instead valCtl.rows = Math.min(16, Math.max(4, valCtl.value.split("\n").length)); valCtl.placeholder = t("value"); valCtl.oninput = () => { row[1] = valCtl.value; valCtl.classList.toggle("bad", looksJSON(valCtl.value) && !parses(valCtl.value)); }; valCtl.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); }; } else { valCtl = input(row[1], t("value")); valCtl.oninput = () => { row[1] = valCtl.value; }; } const side = el("div", "side"); const j = el("button", "text" + (row[2] ? " on" : ""), "{ }"); j.title = row[2] ? t("Collapse to one line") : t("Edit as JSON"); j.onclick = () => { row[2] = !row[2]; if (!row[2]) row[1] = minifyJSON(row[1]); render(); }; side.append(j); const del = el("button", "text danger", "×"); del.title = t("Remove header"); del.onclick = () => { draft.headers.splice(i, 1); render(); }; side.append(del); if (row[2]) { line.classList.add("col"); const top = el("div", "hhead"); top.append(name, side); line.append(top, valCtl); } else { line.append(name, valCtl, side); } box.append(line); }); const adds = el("div", "hadds"); const add = el("button", "text", t("+ Add header")); add.onclick = () => { draft.headers.push(["", "", false]); render(); }; adds.append(add); for (const h of hints) { if (draft.headers.some((r) => (r[0] || "").trim().toLowerCase() === h.toLowerCase())) continue; const b = el("button", "text", "+ " + h); b.title = t("Add the {h} header; its value is yours to fill in", { h }); b.onclick = () => { draft.headers.push([h, "", false]); render(); [...box.querySelectorAll(".pair")].pop()?.querySelectorAll("input, textarea")[1]?.focus(); }; adds.append(b); } box.append(adds); }; render(); return box; } function parses(s) { try { JSON.parse(s); return true; } catch { return false; } } // A provider's extra body fields (#1604): a JSON object the gateway merges // into the top of every request's body to the vendor, filling in what the // body lacks, or replacing it for a name written "!name"; ${sessionId} is // the conversation's id. The fields magpie sets itself — the model, stream, // the conversation — are refused, as provider.ExtraBodyReserved refuses // them on a save. The draft keeps the text as typed; extraBodyOf reads it. const EXTRA_BODY_RESERVED = ["model", "stream", "messages", "input", "contents", "system", "systemInstruction", "system_instruction", "instructions", "tools"]; function extraBodyText(obj) { return obj && Object.keys(obj).length ? JSON.stringify(obj, null, 2) : ""; } // extraBodyOf is the object a save sends ({} for none), or why it can't be function extraBodyOf(text) { const s = (text || "").trim(); if (!s) return { value: {} }; let v; try { v = JSON.parse(s); } catch { return { error: t("not valid JSON") }; } if (!v || typeof v !== "object" || Array.isArray(v)) return { error: t("write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}") }; const seen = new Set(); for (const k of Object.keys(v)) { const name = k.trim().replace(/^!/, "").trim(); if (!name) return { error: t("a field needs a name") }; if (EXTRA_BODY_RESERVED.includes(name)) return { error: t("magpie sets {k} itself, so it can't be added", { k: name }) }; if (seen.has(name)) return { error: t("{k} is named twice", { k: name }) }; seen.add(name); } return { value: v }; } function extraBodyEditor() { const box = el("div", "extra-body"); const ta = el("textarea", "json"); ta.value = draft.extraBody || ""; ta.spellcheck = false; ta.wrap = "off"; ta.rows = Math.min(12, Math.max(3, ta.value.split("\n").length)); ta.placeholder = "{\n \"prompt_cache_key\": \"${sessionId}\"\n}"; const why = el("div", "why"); why.setAttribute("aria-live", "polite"); const check = () => { const err = (draft.extraBody || "").trim() ? extraBodyOf(draft.extraBody).error || "" : ""; ta.classList.toggle("bad", !!err); ta.setAttribute("aria-invalid", err ? "true" : "false"); why.textContent = err; }; ta.oninput = () => { draft.extraBody = ta.value; check(); }; ta.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); }; check(); box.append(ta, why); return box; } // iconPicker: a custom provider's icon — one of the built-in ones, or a // picture of the user's own, which magpie keeps in ~/.config/magpie/icons. // A routing group's icon: its providers' icons stacked, the first on top, // so which providers a group routes over shows at a glance. function stackIcon(icons) { if (!icons || icons.length < 2) return icon(icons?.[0] || "generic"); const e = el("span", "ic-stack"); for (const n of icons.slice(0, 3)) { const d = el("span", "disc"); d.append(icon(n || "generic")); e.append(d); } if (icons.length > 3) e.append(el("span", "disc more", "+" + (icons.length - 3))); return e; } function optionIcon(o) { if (o.effortOf) return effortIcon(o.effortOf); if (o.svg) { const e = el("span", "ic"); e.append(svg(o.svg, 16, 1.4)); return e; } return o.icons?.length ? stackIcon(o.icons) : icon(o.icon); } // The picker's own section for routing groups (agent.RoutingGroups), and // its mark on the rail: one model fanning out to several providers. const ROUTING_GROUPS = "Routing groups"; const dot = (x, y) => `M${x - 1.4} ${y}a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0 -2.8 0`; const FAN = [dot(2.9, 8), dot(13.1, 3.4), dot(13.1, 8), dot(13.1, 12.6), "M4.3 8h7.4", "M4.3 8c2.6 0 3.2-4.6 5.8-4.6h1.6", "M4.3 8c2.6 0 3.2 4.6 5.8 4.6h1.6"].join(" "); // Icons no preset uses, there to be picked for a provider of one's own // (Tom on X: Built-in icons 太少了): vendors' and platforms' marks from // lobehub/icons, as the presets' are. const MORE_ICONS = [ "ai21", "ai360-color", "alibaba-color", "alibabacloud-color", "anyscale-color", "aws", "azureai-color", "baichuan-color", "baidu-color", "bailian-color", "baseten", "burncloud-color", "bytedance-color", "cerebras", "chatglm-color", "chutes", "codebuddy-color", "cohere-color", "cometapi-color", "copilot-color", "coze", "deepinfra-color", "deepmind-color", "doubao-color", "featherless-color", "friendli", "gemma-color", "giteeai", "github", "glama", "gmicloud", "google-color", "grok", "huawei-color", "huggingface-color", "hunyuan-color", "hyperbolic-color", "iflytekcloud-color", "inference", "infinigence-color", "internlm-color", "jina", "kilocode", "kling-color", "lambda", "leptonai-color", "liquid", "llmapi", "longcat", "metaai-color", "microsoft-color", "monica-color", "morph-color", "nebius", "newapi-color", "nousresearch", "nova-color", "novita-color", "openwebui", "parasail", "perplexity-color", "phala-color", "poe", "ppio-color", "qiniu-color", "reka", "replicate", "roocode", "sambanova-color", "sensenova-color", "snowflake-color", "sophnet-color", "spark-color", "straico-color", "submodel-color", "targon-color", "tencent-color", "tiangong-color", "upstage-color", "venice-color", "vertexai-color", "vllm-color", "voyage-color", "wenxin-color", "windsurf", "workersai-color", "xiaomimimo", "xinference-color", "yi", "yuanbao-color", "zenmux", "zeroone" ]; function iconPicker(ed) { const box = el("div", "icon-pick"); const draw = () => { box.replaceChildren(); const now = el("span", "icon-now"); now.append(icon(draft.icon || "generic")); box.append(now); const file = el("input"); file.type = "file"; file.accept = "image/png,image/jpeg,image/gif,image/webp,image/x-icon,image/svg+xml,.ico,.svg"; file.hidden = true; file.onchange = async () => { const f = file.files[0]; if (!f) return; try { // as base64 in JSON: the app's web view drops a File sent as the body const bytes = new Uint8Array(await f.arrayBuffer()); let bin = ""; for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); const data = await api("icons", { data: btoa(bin) }); draft.icon = data.icon; editorError(""); draw(); syncHead(); } catch (e) { editorError(e.message); } }; const choose = el("button", "text", t("Choose a picture…")); choose.onclick = () => file.click(); // the site's own icon, looked for from the base URL typed above const site = el("button", "text", t("From the website")); site.title = t("Look for the icon of the site the base URL is on"); site.onclick = async () => { const base = draft[apiField[draft.api]] || draft.chat || draft.responses || draft.anthropic || ""; site.disabled = true; site.textContent = t("Looking…"); try { const data = await api("icons/favicon", { url: base, name: draft.name || "" }); draft.icon = data.icon; editorError(""); draw(); syncHead(); } catch (e) { editorError(e.message); site.disabled = false; site.textContent = t("From the website"); } }; const builtin = el("button", "text", t("Built-in icons")); builtin.onclick = () => { open = !open; draw(); }; box.append(file, choose, site, builtin); if (draft.icon && draft.icon !== "generic") { const reset = el("button", "text", t("Default")); reset.onclick = () => { draft.icon = ""; draw(); syncHead(); }; box.append(reset); } if (open) { const grid = el("div", "icon-grid"); const names = [...new Set([...(providers.presets || []).map((p) => p.icon), ...MORE_ICONS].filter((n) => n && n !== "generic"))] .sort((a, b) => a.replace(/-color$/, "").localeCompare(b.replace(/-color$/, ""))); // well over a hundred of them: a vendor is found by its name const find = input(seek, t("Find an icon…")); find.onkeydown = (e) => e.stopPropagation(); find.oninput = () => { seek = find.value; const f = seek.trim().toLowerCase(); for (const b of grid.querySelectorAll("button")) b.hidden = !!f && !b.title.includes(f); }; for (const n of names) { const b = el("button", n === draft.icon ? "on" : ""); b.title = n.replace(/-color$/, ""); b.append(icon(n)); b.onclick = () => { draft.icon = n; open = false; draw(); syncHead(); }; grid.append(b); } box.append(find, grid); find.oninput(); } }; let open = false, seek = ""; // the dialog's title shows the icon too const syncHead = () => { const old = ed.querySelector(".ehead .ic"); if (old) old.replaceWith(icon(draft.icon || "generic")); }; draw(); return box; } // ---------- modal ---------- // The provider editor opens as a dialog over the page; Escape, the backdrop // or Cancel close it. As on iOS it grows out of what was pressed, on a // spring, and closing folds it back into that (still there, re-rendered or // not); with nothing pressed it rises from a little below. const SPRING = CSS.supports?.("animation-timing-function", "linear(0, 1)") // a damped spring (response .42 s, damping .8): 1.5% over, settled at 570 ms ? "linear(0, 0.0203, 0.0723, 0.1448, 0.2292, 0.3188, 0.4086, 0.4951, 0.576, 0.6498, 0.7157, 0.7735, 0.8232, 0.8654, 0.9005, 0.9293, 0.9525, 0.9708, 0.9849, 0.9956, 1.0033, 1.0087, 1.0122, 1.0142, 1.015, 1.0151, 1.0146, 1.0136, 1.0124, 1.0111, 1.0097, 1.0084, 1.0071, 1.0059, 1.0049, 1.0039, 1.0031, 1.0024, 1.0018, 1.0013, 1)" : "cubic-bezier(.2, .9, .25, 1.02)"; const IOS_EASE = "cubic-bezier(.32, .72, 0, 1)"; const calm = () => matchMedia("(prefers-reduced-motion: reduce)").matches; // what was last pressed, and a way to find it again once re-rendered let pressed = null; document.addEventListener("pointerdown", (e) => { const at = e.target.closest?.("[data-pick], .row.provider[data-id], button"); if (!at || at.closest("#modal")) return; const find = at.dataset.pick ? `[data-pick="${CSS.escape(at.dataset.pick)}"]` : at.matches(".row.provider") ? `.row.provider[data-id="${CSS.escape(at.dataset.id)}"]` : null; pressed = { el: at, find, time: performance.now() }; }, true); // Text cut short with an ellipsis says its whole self on hover (#721): an // agent's status line, a long model name. Which lines are cut depends on the // window's width, so it is measured when the pointer comes over one, and the // title follows: set while the text is cut, gone again once it fits. A title // the app wrote itself is never touched: data-full-tip keeps the text put here, // and a title that no longer reads the same was written by the app since. document.addEventListener("mouseover", (e) => { let el = e.target instanceof Element ? e.target : null; for (let i = 0; el && i < 4 && getComputedStyle(el).textOverflow !== "ellipsis"; i++) el = el.parentElement; if (!el || getComputedStyle(el).textOverflow !== "ellipsis") return; const ours = el.hasAttribute("title") && el.getAttribute("title") === el.dataset.fullTip; if (el.hasAttribute("title") && !ours) return; const full = el.textContent.replace(/\s+/g, " ").trim(); if (el.scrollWidth > el.clientWidth && full) { el.title = full; el.dataset.fullTip = full; } else if (ours) { el.removeAttribute("title"); el.removeAttribute("data-full-tip"); } }, { passive: true }); let modalOrigin = null, modalDone = null; // originRect: where the dialog came from, as it is now, or null when it's gone function originRect(o) { const at = o && (o.el.isConnected ? o.el : o.find ? document.querySelector(o.find) : null); if (!at || at.closest("[hidden]")) return null; const r = at.getBoundingClientRect(); return r.width && r.height && r.bottom > 0 && r.top < innerHeight ? r : null; } // fromRect: the transform putting the dialog (at `to`) over the rect `from` function fromRect(from, to) { const s = Math.max(.3, Math.min(1, from.width / to.width)); const dx = from.left + from.width / 2 - (to.left + to.width / 2), dy = from.top + from.height / 2 - (to.top + to.height / 2); return `translate(${dx}px, ${dy}px) scale(${s})`; } let modalReturnFocus = null, modalFormBase = ""; function formValues(box) { return JSON.stringify([ [...box.querySelectorAll("input:not([type=search]), textarea, select")].map((input) => [input.type, input.type === "checkbox" || input.type === "radio" ? input.checked : input.value]), [...box.querySelectorAll(".segs button")].map((button) => button.getAttribute("aria-pressed")), ]); } function modalFormValues() { return formValues($("#modal")); } function modalFormDirty() { return !$("#modal").hidden && !!modalFormBase && modalFormValues() !== modalFormBase; } function markModalSaved() { modalFormBase = modalFormValues(); } let modalBackgroundElements = []; function modalBackground(inert) { if (inert) { // A fresh editor may interrupt its closing animation; keep the original background. if (modalBackgroundElements.length) return; const modal = $("#modal"); modalBackgroundElements = [...document.body.children].filter((element) => element !== modal && element.tagName !== "SCRIPT" && !element.inert); for (const element of modalBackgroundElements) element.inert = true; } else { for (const element of modalBackgroundElements) element.inert = false; modalBackgroundElements = []; } } $("#modal").addEventListener("keydown", (e) => { if (e.key !== "Tab") return; const modal = e.currentTarget; const controls = [...modal.querySelectorAll('button, input, select, textarea, a[href], [tabindex="0"]')] .filter((element) => !element.disabled && element.getClientRects().length && !element.closest("[inert]")); if (!controls.length) { e.preventDefault(); modal.querySelector(".dialog").focus(); return; } const first = controls[0], last = controls.at(-1); const boundary = e.shiftKey ? first : last; if (document.activeElement !== boundary && modal.contains(document.activeElement)) return; e.preventDefault(); (e.shiftKey ? last : first).focus(); }); function openModal(content) { const m = $("#modal"), d = m.firstElementChild; const fresh = m.hidden || m.classList.contains("out"); const top = m.hidden ? 0 : d.querySelector(".ebody")?.scrollTop || 0; // Names & levels scrolls inside the editor body, so keep its own position. const names = !fresh && d.querySelector(".mnames:not([hidden])"); const namesAt = names && { provider: names.dataset.provider, top: names.scrollTop }; m.classList.remove("out"); d.classList.remove("swap"); if (!fresh) { void d.offsetWidth; d.classList.add("swap"); } // content changed: a soft refresh, not a re-entrance frame(content); // an editor that reads long text (a prompt's) takes a wider dialog d.classList.toggle("wide", content.classList.contains("wide")); // Keep focus through a redraw of an open editor. const active = d.contains(document.activeElement) ? document.activeElement : null; const focusID = active?.id; const focusLabel = active?.getAttribute("aria-label"); const focusIndex = active ? [...d.querySelectorAll("input, textarea, select, button")].indexOf(active) : -1; if (fresh) modalReturnFocus = document.activeElement; d.replaceChildren(content); d.setAttribute("role", "dialog"); d.setAttribute("aria-modal", "true"); d.tabIndex = -1; const title = content.querySelector(".ehead b, .mk-name, h2, h3"); if (title) { title.id = "modalTitle"; d.setAttribute("aria-labelledby", title.id); d.removeAttribute("aria-label"); } else { d.removeAttribute("aria-labelledby"); d.setAttribute("aria-label", t("Settings")); } m.hidden = false; if (fresh) modalBackground(true); if (fresh) markModalSaved(); const focus = focusID && content.querySelector("#" + CSS.escape(focusID)) || focusLabel && [...content.querySelectorAll("[aria-label]")].find((element) => element.getAttribute("aria-label") === focusLabel) || focusIndex >= 0 && content.querySelectorAll("input, textarea, select, button")[focusIndex]; (focus || content.querySelector("input:not([disabled]), textarea, select, button:not([disabled])") || d).focus({ preventScroll: true }); const body = content.querySelector(":scope > .ebody"); if (body) body.scrollTop = top; // a re-render keeps the place const nextNames = content.querySelector(".mnames:not([hidden])"); if (namesAt && nextNames?.dataset.provider === namesAt.provider) nextNames.scrollTop = namesAt.top; if (!fresh) return; for (const a of [...m.getAnimations(), ...d.getAnimations()]) a.cancel(); d.style.opacity = d.style.transform = m.style.opacity = ""; modalDone = null; modalOrigin = pressed && performance.now() - pressed.time < 1000 ? pressed : null; pressed = null; m.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 280, easing: "ease-out" }); if (calm()) { d.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 160 }); return; } const to = d.getBoundingClientRect(), from = originRect(modalOrigin); d.animate([{ transform: from ? fromRect(from, to) : "translateY(24px) scale(.94)" }, { transform: "none" }], { duration: 570, easing: SPRING }); d.animate([{ opacity: 0 }, { opacity: 1 }], { duration: from ? 200 : 240, easing: "ease-out" }); } // frame holds an editor's head and its buttons still while the fields // between them scroll. function frame(ed) { if (!ed.matches(".editor") || ed.querySelector(":scope > .ebody")) return; const body = el("div", "ebody"); body.append(...[...ed.children].filter((c) => !c.matches(".ehead, .bar"))); ed.querySelector(":scope > .bar") ? ed.querySelector(":scope > .bar").before(body) : ed.append(body); ed.classList.add("framed"); } function closeModal() { const m = $("#modal"), d = m.firstElementChild; if (m.hidden) return Promise.resolve(); if (m.classList.contains("out")) return modalDone || Promise.resolve(); m.classList.add("out"); modalBackground(false); modalFormBase = ""; for (const a of [...m.getAnimations(), ...d.getAnimations()]) a.commitStyles?.(), a.cancel(); // where it would sit at rest, whatever an opening cut short left it at const was = d.style.transform; d.style.transform = "none"; const to = d.getBoundingClientRect(), from = calm() ? null : originRect(modalOrigin); d.style.transform = was; const shape = { duration: from ? 380 : 260, easing: IOS_EASE, fill: "forwards" }; const moves = [ m.animate([{ opacity: 0 }], { ...shape, easing: "ease-out" }), calm() ? d.animate([{ opacity: 0 }], { duration: 140, fill: "forwards" }) : d.animate([{ transform: from ? fromRect(from, to) : "translateY(14px) scale(.95)" }], shape), ]; // it fades as it lands, the last part of the way if (!calm()) moves.push(d.animate([{ offset: from ? .45 : .2, opacity: getComputedStyle(d).opacity }, { opacity: 0 }], shape)); const done = modalDone = Promise.all(moves.map((a) => a.finished)).then(() => { if (modalDone !== done) return; modalDone = null; m.hidden = true; m.classList.remove("out"); d.replaceChildren(); modalFormBase = ""; if (modalReturnFocus?.isConnected && !modalReturnFocus.closest("[hidden]")) modalReturnFocus.focus({ preventScroll: true }); else if (!$("#view-" + view).hidden) $("#view-" + view).focus({ preventScroll: true }); modalReturnFocus = null; for (const a of [...m.getAnimations(), ...d.getAnimations()]) a.cancel(); d.style.opacity = d.style.transform = m.style.opacity = ""; // an editor opened from the add sheet gives the focus back to its option const sheet = $("#addSheet"); if (adding && !sheet.hidden && !$("#view-providers").hidden) { const option = addReturnPick && sheet.querySelector(`[data-pick="${CSS.escape(addReturnPick)}"]`); (option || sheet.querySelector(".find"))?.focus({ preventScroll: true }); } }, () => {}); return done; } // the providers page's dialog; the library and a confirmation that borrow it // ask the same of its backdrop const modalBackdrop = backdropClick($("#modal")); $("#modal").onclick = (e) => { if (modalBackdrop(e)) cancelEdit(); }; // ---------- sliding thumb ---------- // Pills (the nav, every segmented control) have one thumb that glides to the // selected option instead of each option lighting up on its own. // // A thumb glides only when the option picked changes, and only from where // it is on the screen. Most controls are drawn again on every save (all of // Settings is), and a redrawn control takes the thumb of the one it // replaces, the glide under way with it: the same element, so nothing about // its motion is worked out again. It glides on to the option picked if that // is another (a save refused puts one back), and otherwise is left as it // is. A thumb is placed only where the control is laid out: one drawn // hidden (Settings at start, a tab not shown) is put under its option, // still, when it is shown or sized again (thumbFit). Before, a redrawn // control made a new thumb and replayed what was remembered of the old // one's glide from its start (a click's thumb jumped back and slid again), // and positions taken while Settings was hidden, 0 wide, made every thumb // on the page grow in from the left on the first save. const thumbs = new Map(); // control position → { th, pick, to }: its thumb, the option it is under or going to, and where that is const THUMB_MS = 280, THUMB_EASE = "cubic-bezier(.2, .8, .2, 1)"; // --ease const thumbKeys = new WeakMap(); // box → its key, for thumbFit function thumbKey(box, choices) { const path = []; for (let node = box; node?.parentElement; node = node.parentElement) { if (node.id) return node.id + "/" + path.reverse().join("/") + ":" + choices; path.push(Array.prototype.indexOf.call(node.parentElement.children, node)); } return null; } // where the thumb goes under the option picked; null while it isn't laid out function thumbTo(box, on) { if (!on.offsetParent || !on.offsetWidth) return null; const to = { x: on.offsetLeft, w: on.offsetWidth }; // a strip that wraps (the editor's Base URL APIs, narrow): the row of // the one picked (top: 2px is the first's), and that row's height, not // the strip's if (box.clientHeight > on.offsetHeight + 8) Object.assign(to, { y: on.offsetTop - 2, h: on.offsetHeight }); return to; } const thumbAt = (p) => ({ transform: p.y ? `translate(${p.x}px, ${p.y}px)` : `translateX(${p.x}px)`, width: p.w + "px" }); const thumbGlide = (th) => th.getAnimations().find((a) => a.id === "thumb" && a.playState === "running"); // a thumb put at p at once, any glide of it stopped function thumbPut(th, p) { for (const a of th.getAnimations()) if (a.id === "thumb") a.cancel(); th.classList.add("still"); Object.assign(th.style, thumbAt(p), { height: p.h ? p.h + "px" : "" }); void th.offsetWidth; th.classList.remove("still"); } // where a thumb in the page is drawn now, partway through a glide included function thumbNow(th) { if (!th.style.width || !th.isConnected) return null; const cs = getComputedStyle(th), m = new DOMMatrixReadOnly(cs.transform === "none" ? undefined : cs.transform); return { x: m.m41, y: m.m42, w: parseFloat(cs.width), h: th.style.height ? parseFloat(cs.height) : 0 }; } // which option is picked: its place among the options const thumbPick = (box, on) => [...box.children].filter((c) => !c.classList.contains("thumb")).indexOf(on); const thumbSame = (a, b) => Math.abs(a.x - b.x) < 0.5 && Math.abs((a.y || 0) - (b.y || 0)) < 0.5 && Math.abs(a.w - b.w) < 0.5; // a control shown, or sized again (the fonts come in, the language changes, // the window narrows): its thumb is put under its option, still const thumbFit = new ResizeObserver((es) => { for (const { target: box } of es) { if (!box.isConnected) { thumbFit.unobserve(box); continue; } const th = box.querySelector(":scope > .thumb"), on = box.querySelector(":scope > .on"); const to = th && on && thumbTo(box, on); if (!to) continue; const control = thumbKey(box, thumbKeys.get(box)); const last = control && thumbs.get(control); const pick = thumbPick(box, on); if (last?.th === th && last.pick === pick && thumbSame(last.to, to) && th.style.width) continue; thumbPut(th, to); if (control) thumbs.set(control, { th, pick, to }); } }); function slide(box, key) { const control = thumbKey(box, key); const last = control && thumbs.get(control); let th = box.querySelector(":scope > .thumb"); if (!th) { // drawn again: the thumb of the control it replaces, glide and all th = last?.th && !last.th.isConnected ? last.th : el("span", "thumb"); box.prepend(th); } thumbKeys.set(box, key); thumbFit.observe(box); const on = box.querySelector(":scope > .on"); if (!on) { th.style.opacity = "0"; return; } th.style.opacity = ""; const to = thumbTo(box, on); if (!to) return; // hidden: thumbFit puts it once it is shown const pick = thumbPick(box, on); if (control) thumbs.set(control, { th, pick, to }); // already there, or on its way there if (last?.th === th && thumbSame(last.to, to) && (thumbGlide(th) || (th.style.width && thumbSame(thumbNow(th), to)))) return; const from = thumbNow(th); thumbPut(th, to); if (!from || thumbSame(from, to)) return; // the height is the strip's unless it wraps: only a wrapped one's glides const f = thumbAt(from), t = thumbAt(to); if (from.h && to.h) { f.height = from.h + "px"; t.height = to.h + "px"; } th.animate([f, t], { duration: THUMB_MS, easing: THUMB_EASE, id: "thumb" }); } const PROTOS = [["chat", "OpenAI", "Chat Completions — most agents"], ["responses", "Responses", "OpenAI Responses — what Codex speaks"], ["anthropic", "Anthropic", "Anthropic Messages — what Claude Code speaks"], ["gemini", "Gemini", "Gemini generateContent — what the Gemini CLI speaks"], ["decide", "System One", "A decision API on System One (TypeSafe's Jev, a gateway's, or Bailian's decision model) — what a routing group asks as a turn begins"]]; // Gemini generateContent at a Vertex AI provider's project, as its // endpoint is shown and tested const VERTEX_EP_HINT = "Gemini generateContent — what Vertex AI serves at your Google Cloud project"; // apiLabel: the name an API (a protocol) goes by in the editor const apiLabel = (proto) => (PROTOS.find(([k]) => k === proto) || [])[1] || proto; // vertexBase is where a Vertex AI provider's requests go, the address its // project and location make (provider.vertexBase): "" until the project // typed is one an address can be made of function vertexBase(v) { const project = (v?.project || "").trim().toLowerCase(), loc = (v?.location || "").trim().toLowerCase() || "global"; if (!/^[a-z0-9][a-z0-9.:-]*[a-z0-9]$/.test(project) || !/^[a-z]+(-[a-z0-9]+)*$/.test(loc)) return ""; const host = loc === "global" ? "aiplatform.googleapis.com" : loc === "us" || loc === "eu" ? `aiplatform.${loc}.rep.googleapis.com` : `${loc}-aiplatform.googleapis.com`; return `https://${host}/v1/projects/${project}/locations/${loc}`; } // vertexOfDraft is the editor's Vertex AI fields as a Save sends them function vertexOfDraft() { const v = draft.vertex || {}; return { project: (v.project || "").trim(), location: (v.location || "").trim(), credentials: (v.credentials || "").trim(), impersonate: (v.impersonate || "").trim() }; } const decideOnly = (p) => !!p?.decide && !(p.chat || p.responses || p.anthropic || p.gemini); // a provider that lists its decision models apart (OpenRouter) says which // they are: its Jev Router (typesafe/jev-router) is a chat model const decidesModel = (p, id) => !!p.decide && (decideOnly(p) || (p.deciders ? p.deciders.includes(id) : id.split("/").some((s) => /^jev(?:-|$)/i.test(s)))); // modelAPIs: the APIs one of p's models can be asked on alone, those it has // a URL for when it has more than one — a custom provider's, a preset's or // a subscription's alike (01huadalang on Discord: 一个 api 里有很多模型但是不同协议; // OpenCode Go's DeepSeek answers on Responses too), its Gemini URL's // among them (Kayphoon on Discord: 自定义供应商兼容 gemini 格式了,模型的 // 配置里还是只能选 chat 和 anthropic) const modelAPIs = (p) => { const urls = ["chat", "responses", "anthropic", "gemini"].filter((k) => ((draft?.id === p.id ? draft[k] : undefined) ?? p[k] ?? "").trim()); return urls.length < 2 ? [] : PROTOS.filter(([k]) => urls.includes(k)); }; // pickedOf: the models the user picked for p, as its editor starts them. // Only the picks: with none, agents are served the vendor's list (its // first 24), which the models list marks on too; taking those as picks // drew them ticked on opening and the next Save wrote them as picks, so // Select none and Save came back as 24 ticked (#614). function pickedOf(p) { const on = p.models.filter((m) => m.on); if (!Array.isArray(p.chosen)) return on.map((m) => m.id); // no picks said: those served, as before const picks = new Set(p.chosen); return on.filter((m) => picks.has(m.id)).map((m) => m.id); } // baseAPIOf is the API a saved provider's Base URL is shown as: the one the // user picked and saved (baseAPI), while it has a URL, else the first that // has one. Without the pick, a provider with a chat URL beside its Responses // one came back as OpenAI compatible after Responses was picked and saved // (01huadalang). function baseAPIOf(p) { const picked = p.baseAPI === "chat" ? "openai" : p.baseAPI; if (picked && p[apiField[picked]]) return picked; return p.chat ? "openai" : p.anthropic ? "anthropic" : p.responses ? "responses" : p.gemini ? "gemini" : p.decide ? "decide" : "openai"; } // draftOf is a saved provider as its editor's form holds it. function draftOf(p) { return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) }; } // duplicateProvider opens the Add form on a copy of p (#268): its URLs, // headers, models, balance and proxy, under a name of its own. The key is // p's unless another is pasted: the Add takes it from p, with its other // keys (copyOf). A signed-in account has no copy. function duplicateProvider(p) { const name = t("{name} copy", { name: p.name }); editing = p.preset && providers.presets.some((x) => x.id === p.preset) ? { preset: p.preset } : { custom: true }; const d = draftOf(p); draft = { ...d, id: slug(name), name, chosen: [], extra: d.chosen, copyOf: p.id }; if (p.zhipuTeam) draft.zhipuTeam = { org: p.zhipuTeam.org || "", project: p.zhipuTeam.project || "" }; if (p.vertex) draft.vertex = { project: p.vertex.project || "", location: p.vertex.location || "", credentials: p.vertex.credentials || "", impersonate: p.vertex.impersonate || "" }; renderProviders(); } // renderEditor: an existing provider (p), a new preset (presetID), or custom. function renderEditor(p, presetID) { // its own icons, not the page's kept ones, which the rows after it take back const kept = keptIcons; keptIcons = null; try { const editor = drawEditor(p, presetID); if (draft && draft !== providerDraftRef) { providerDraftRef = draft; providerDraftBase = providerDraftValue(); } return editor; } finally { keptIcons = kept; } } function drawEditor(p, presetID) { const pr = presetID ? providers.presets.find((x) => x.id === presetID) : p?.preset ? providers.presets.find((x) => x.id === p.preset) : null; const isNew = !p, custom = !pr && !p?.account, decides = !!(p?.decide || pr?.decide); // a preset already added is added again only through "Add another": one // more provider of it, under a name and id of its own const another = isNew && !!pr?.added; // an editor opened afresh has Names & levels folded: it stayed open in // every editor after, until magpie was restarted (Hu9956, #868) if (!draft) naming = null; draft = draft || (p ? draftOf(p) : pr ? { id: pr.id, name: pr.name, preset: pr.id, key: "", chosen: [], extra: [], headers: [] } : { id: "", name: "", preset: "", chat: "", responses: "", anthropic: "", decide: "", catalog: "", key: "", api: "openai", chosen: [], extra: [], headers: [], icon: "" }); const ed = el("div", "editor" + (isNew ? " new" : "")); ed.onclick = (e) => e.stopPropagation(); { const h = el("div", "ehead"); const copyOf = draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf); h.append(icon(p?.icon || (copyOf && draft.icon) || pr?.icon || "generic"), el("b", "", p ? p.name : copyOf ? t("Copy of {name}", { name: copyOf.name }) : pr ? pr.name : t("Custom provider"))); if (pr?.kind === "partner") { if (partnerNote(pr)) h.append(el("span", "note", partnerNote(pr))); } else if (pr?.note) h.append(el("span", "note", t(pr.note))); h.append(el("span", "grow")); // a plugin's provider has plugin:// for its base, and its id is no // address to open: only a host with a dot or a port makes a link // a region with docs of its own (Tencent Cloud's plan and TokenHub) has // its page here, following the region picked below const site = regionAt(pr, draft)?.website || pr?.website || p?.website || (/[.:]/.test(p?.host || "") ? "https://" + p.host : ""); if (site) { const b = el("button", "link site", hostOf(site) + " ↗"); b.dataset.url = site; b.onclick = () => api("open", { url: b.dataset.url }); h.append(b); } if (p) h.append(providerSwitch(p)); ed.append(h); if (p?.off) ed.append(el("div", "hint off-note", t("Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again."))); } // a vendor's global and China endpoints are presets of their own, one row // in the add sheet: here the new provider picks between them, the key kept const pair = isNew && pr ? (globalOf(pr) ? [globalOf(pr), pr] : chinaOf(pr) ? [pr, chinaOf(pr)] : null) : null; if (pair) { const seg = el("div", "segs area"); pair.forEach((x, i) => { const b = el("button", "opt" + (x.id === pr.id ? " on" : ""), t(i ? "China" : "Global")); b.title = hostOf(x.chat || x.responses || x.anthropic) + (x.added ? " · " + t("Added") : ""); b.onclick = () => { if (x.id === pr.id) return; editing = { preset: x.id }; draft = { id: x.id, name: x.name, preset: x.id, key: draft.key, chosen: [], extra: [], headers: [] }; renderProviders(); }; seg.append(b); }); queueMicrotask(() => slide(seg, "area")); ed.append(...field(t("Region"), seg, "")); } // who uses it: just the agents already pointed here, so a click changes // one's model. Pointing a new agent at the provider happens in the Agent // tab's picker, not here. if (p) { const on = p.agents.filter((a) => a.current); if (on.length) { const chips = el("div", "achips"); for (const a of on) { const c = el("button", "achip on"); c.append(icon(a.icon), el("span", "n", a.name), el("span", "m", a.group || a.model)); c.title = a.group ? t("{agent} is on the routing group {group}, {model} here among its members — click to change", { agent: a.name, group: a.group, model: a.model }) : t("{agent} is on {model} — click to change", { agent: a.name, model: a.model }); c.onclick = (ev) => pickForAgent(a, p, c, ev); chips.append(c); } ed.append(...field(t("Agents"), chips, "")); } } let name, url; if (another) { name = input(draft.name === pr.name ? "" : draft.name, t("e.g. {name} · Work", { name: pr.name })); const hint = el("div", "hint"); const idHint = () => { hint.textContent = t("id {id} — a number is added if it is taken", { id: draft.id }); }; name.oninput = () => { draft.name = name.value.trim() || pr.name; draft.id = slug(name.value) || pr.id; idHint(); }; idHint(); const wrap = el("div"); wrap.append(name, hint); ed.append(el("label", "", t("Name")), wrap); } // an added provider's id can change: its models are picked by it, and // the agents and routing groups on them move to the new one const idField = () => { const idIn = input(draft.id, p.id); const hint = el("div", "hint"); const idOf = () => slug(draft.id) || p.id; const show = () => { hint.textContent = t(decideOnly(p) ? "Routing groups name its models as {id} for their classifier" : "Agents pick its models as {id}", { id: idOf() + "/…" }) + (idOf() !== p.id ? " · " + t("agents and routing groups on {id} move to it", { id: p.id + "/…" }) : ""); }; idIn.oninput = () => { draft.id = idIn.value; show(); }; idIn.onblur = () => { draft.id = idIn.value = idOf(); show(); }; show(); const w = el("div"); w.append(idIn, hint); ed.append(el("label", "", t("ID")), w); }; if (p && !p.account && !custom) idField(); let fillEndpoints = () => {}; // a URL typed and not saved that a protocol switch carried to another // protocol: the protocol it was typed for, and the URL as typed let carried = null; // the Web search row, shown while there is an API it can search on const searchable = () => !!((draft.anthropic || "").trim() || (draft.responses || "").trim()); let showSearch = () => {}; // the Redaction row, shown while every address is on this computer or // the local network let showLocal = () => {}; // the Key header row, shown while the provider has a third-party // Anthropic API, which is sent its key in both headers by default let showAuth = () => {}; if (custom) { name = input(draft.name, t("e.g. My Relay")); name.oninput = () => { draft.name = name.value; if (isNew) draft.id = slug(name.value); }; ed.append(...field(t("Name"), name)); if (p) idField(); // the base URL is the one the chosen protocol is asked at; a vendor // that serves only the Responses API is added (and tested) with that // alone, since /chat/completions would only fail (#73) const seg = el("div", "segs base-apis"); for (const [v, hint] of [["openai", "…/v1 — chat completions, and responses when the vendor has it"], ["responses", "…/v1 — for a vendor that serves only the Responses API, not chat completions"], ["anthropic", "the root URL, what ANTHROPIC_BASE_URL would take"], ["gemini", "…/v1beta — Google's Gemini API (generateContent), or one that answers as it does; the key goes in x-goog-api-key"], ["decide", "a decision API's root, POST …/systemone under it: its models are a routing group's classifier, never an agent's"]]) { const b = el("button", "opt" + (draft.api === v ? " on" : ""), t(API_NAMES[v])); b.title = t(hint); b.onclick = () => { if (draft.api === v) return; // each protocol keeps its own URL (#105). One typed here and not // saved moves to a protocol without one, spelled as that protocol // wants it: the kind was picked after the URL (#73). A saved URL // stays where it is, and one not given yet stays empty. // A URL then typed for the protocol it was carried to is that // protocol's own, and the carried one goes back where it was typed, // so a URL can be typed for each protocol in turn (#1231). const from = apiField[draft.api], to = apiField[v]; carried = null; if (!draft[to] && draft[from] && draft[from] !== (p?.[from] || "")) { carried = { from, value: draft[from] }; draft[to] = respellURL(draft[from], v); draft[from] = p?.[from] || ""; } showApi(v); }; b.dataset.api = v; seg.append(b); } // the protocol the base URL is for, shown as picked: by its button, // or by a detection taken (useDetected) const showApi = (v) => { draft.api = v; url.value = draft[apiField[v]] || ""; for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x.dataset.api === v); slide(seg, "api"); url.placeholder = urlHint(v); fillEndpoints(); showSearch(); showLocal(); showAuth(); }; queueMicrotask(() => slide(seg, "api")); url = input(draft[apiField[draft.api]], urlHint(draft.api), "url"); url.classList.add("base-url"); url.oninput = () => { draft[apiField[draft.api]] = url.value; if (carried) { draft[carried.from] = carried.value; carried = null; fillEndpoints(); } showSearch(); showLocal(); showAuth(); }; const urlWrap = el("div", "stack"); urlWrap.append(seg, url); // the APIs that answered a detection, taken for the provider: their // URLs set, one that wasn't found there (404, 405) cleared, and the // base URL's protocol one of those that answered const useDetected = (rs) => { carried = null; for (const x of rs) { if (x.ok) draft[x.protocol] = x.base; else if ((x.status === 404 || x.status === 405) && (draft[x.protocol] || "").trim().replace(/\/+$/, "") === x.base) draft[x.protocol] = ""; } const v = draft[apiField[draft.api]] ? draft.api : ["openai", "responses", "anthropic", "gemini", "decide"].find((a) => draft[apiField[a]]); showApi(v || draft.api); draft.onModelPrefs?.(); // the APIs a model can be given follow the URLs }; // Detect asks OpenAI's, Anthropic's and Gemini's APIs (#1346) urlWrap.append(detectAPIs(p, () => url.value, useDetected)); ed.append(...field("Base URL", urlWrap)); } // the Cline API serves a model from whichever host its AI gateway picks; // pinned, its DeepSeek models are served by DeepSeek's own API alone, // which keeps their prompt cache (White Immortal on Discord). ClinePass, // or the Cline plugin's provider (ARNO on Discord) const upstreamField = () => { const [ptk, pcb] = tick(t("DeepSeek models only from DeepSeek's own API"), !!draft.pinUpstream); ptk.classList.add("pin-upstream"); pcb.onchange = () => { draft.pinUpstream = pcb.checked; }; return field(t("Upstream"), ptk, t("Cline serves a model from any host its gateway picks; pinned, a request for a DeepSeek model goes only to DeepSeek, which keeps its prompt cache, and fails when DeepSeek can't take it")); }; if (p?.account) { // the sign-in belongs to the agent; magpie only borrows it const a = p.account; if (subOf(a.agent)) { // no Claude Code on Windows: the gateway runs the one in WSL const via = a.wsl ? t("Runs through WSL · {distro}: Claude Code there signs in and answers; Windows has none of its own.", { distro: a.wsl }) + " " : ""; ed.append(...field(t("Accounts"), renderAccounts(a, p), via + (p.routing ? t("Tick every account to use; Routing says how requests spread over them.") : subOf(a.agent).single ? t("{agent} keeps one account; the gateway runs it for every request. Signing in to another replaces it.", { agent: a.agentName }) : subOf(a.agent).own && (a.logins || []).some((l) => l.own) ? t("The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota. {agent} itself stays signed in as it is.", { agent: a.agentName && a.agentName !== a.agent ? a.agentName : p.name }) : subOf(a.agent).own || subOf(a.agent).plugin ? t("The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota.") : t("{agent} signs in to the first. Tick more and the gateway moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.", { agent: a.agentName })))); if ((a.logins || []).filter((l) => l.active || l.on).length > 1) ed.append(...renderRouting(p)); if (p.move) ed.append(...renderMove(p)); } else { const acct = el("div", "acct"); acct.append(icon(a.agentIcon), el("span", "n", a.user), el("span", "plan", accountPlan(a))); ed.append(...field(t("Account"), acct, t("{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.", { agent: a.agentName }))); } ed.append(...field(t("Models"), renderModels(p), "")); if (p.drawIds?.length) ed.append(...renderDrawers(p)); // a subscription's window too: Codex's backend says 272K for models // that take 872K (#120) const cx = input(draft.contexts || "", t("e.g. 128k · or gpt-6=1m, comma separated")); ed.append(...field(t("Context window"), contextPicks(p, cx), t("How long a request the models take, told to the agents; empty leaves it to the vendor and models.dev"))); ed.append(...outputField()); ed.append(...compactField()); ed.append(...field(t("Fallback"), renderFallback(p), fallbackHint(p))); const proxies = el("div", "stack"); proxies.append(proxyPicker()); const perAccount = subOf(a.agent) ? accountProxyPicker(a) : null; if (perAccount) proxies.append(perAccount); ed.append(...field(t("Proxy"), proxies)); ed.append(...concurrencyField(p)); ed.append(...priceRateField()); if (p.cline) ed.append(...upstreamField()); // a plugin's provider is reached inside magpie: its plugin:// URLs go // nowhere to show or test const urls = [p.chat, p.responses, p.anthropic].filter(Boolean); if (urls.length && !urls.some((u) => u.startsWith("plugin://"))) ed.append(...field(t("Endpoints"), renderEndpoints(p, p))); const bar = el("div", "bar"); // removing only hides it from magpie; the agent stays signed in const del = el("button", "text danger", t("Remove")); del.title = t("{agent} stays signed in; magpie just stops offering it", { agent: a.agentName }); del.onclick = () => providerAction("delete", { id: p.id }, t("{name} removed", { name: p.name })); bar.append(del, el("span", "grow")); const cancel = el("button", "text", t("Cancel")); cancel.onclick = cancelEdit; const saveBtn = el("button", "text primary", t("Save")); saveBtn.onclick = () => { const cx = parseContexts(draft.contexts || ""); if (cx.error) return editorError(t("Context window: {v} is not a length like 128k or 1m", { v: cx.error }), "warn"); const ox = parseContexts(draft.outputs || ""); if (ox.error) return outputError(ed, ox.error); const cpx = parseContexts(draft.compacts || ""); if (cpx.error) return compactError(ed, cpx.error); const proxy = proxyOfDraft(); if (proxy === null) { ed.querySelector(".proxy-url")?.focus(); return editorError(t("Proxy: type its address, like http://127.0.0.1:7890"), "warn"); } const own = accountProxiesOfDraft(); if (own.missing) { const line = [...ed.querySelectorAll(".acct-proxy")].find((x) => x.dataset.user.toLowerCase() === own.missing); line?.querySelector(".proxy-url")?.focus({ preventScroll: true }); return editorError(t("Proxy of {user}: type its address, like http://127.0.0.1:7890", { user: line?.dataset.user || own.missing }), "warn"); } const maxConcurrency = concurrencyOfDraft(); if (maxConcurrency === undefined) return concurrencyError(ed); const queue = queueOfDraft(); if (queue.bad) return queueError(ed, queue.bad); const priceRate = priceRateOfDraft(); if (priceRate === undefined) return priceRateError(ed); if (priceTypedError(ed)) return; saving(saveBtn, t("Saving…")); providerAction("save", { id: p.id, models: chosenIds(), noModels: noneChosen(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...routingOfDraft(p) }, t("{name} saved", { name: p.name })); }; bar.append(cancel, saveBtn); ed.append(bar); return ed; } // a vendor reached at the user's own resource (Azure OpenAI): no URL of // the preset's, the one the resource is at is typed or pasted here, and // magpie puts it on the API the preset speaks when it is saved let endpoint = null; if (pr?.endpoint) { if (draft.chat === undefined) { draft.chat = p?.chat || ""; draft.responses = p?.responses || ""; } endpoint = input(draft.chat || draft.responses || "", pr.endpoint, "url"); endpoint.classList.add("endpoint"); endpoint.oninput = () => { draft.chat = draft.responses = endpoint.value.trim(); refreshEndpoints(); }; ed.append(...field(t("Endpoint"), endpoint, pr.endpointHint ? t(pr.endpointHint) : "")); } // a server on this machine (Ollama, LM Studio, oMLX, MLX-Serve) can // listen on another port, or be another computer's: its address moves each URL, each API // keeping its path, as provider.AtAddress does let address = null, addressMore = null; if (pr?.kind === "local") { // a saved provider's URLs (or a duplicate's) start it; a new one's are // the preset's, sent as none unless moved, so the gateway takes them const own = draft.chat !== undefined; // oMLX's decision API (#1641) is the same server's, and moves with it draft.addressFrom ??= { chat: draft.chat ?? pr.chat ?? "", responses: draft.responses ?? pr.responses ?? "", anthropic: draft.anthropic ?? pr.anthropic ?? "", decide: draft.decide ?? (p?.decide || pr.decide || "") }; draft.addressWas ??= own ? originOf(draft.addressFrom) : ""; const from = draft.addressFrom, addressWas = draft.addressWas; draft.address ??= addressWas; address = input(draft.address, originOf(pr)); address.inputMode = "url"; address.classList.add("address"); // the Jev endpoint field shows where the decision API moved to, until // one is typed there address.oninput = () => { draft.address = address.value; refreshEndpoints(); const du = ed.querySelector("input.decide-url"); if (du && draft.decide === draft.addressFrom.decide) du.value = movedURLs(draft)?.decide || draft.decide; }; const keys = address.onkeydown; address.onkeydown = (e) => { keys(e); if (e.key === "Enter" && isNew) save(); }; // folded: most run where the preset says; open for one that doesn't, // or an address typed before the editor was drawn again addressMore = el("details", "more"); addressMore.open = (own && originOf(from) !== originOf(pr)) || draft.address.trim() !== addressWas; addressMore.append(el("summary", "", t("Server address"))); const inner = el("div", "inner"); inner.append(...field(t("Address"), address, t("Where the server listens; change the port, or give another computer's address"))); addressMore.append(inner); } // null, not false, when there is none: false?.key is undefined, and a // provider with no key read .set of it (willz: a local Ollama without a // key opened no editor, its row just toggling) const copied = (!p && draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf)) || null; const key = input(draft.key || "", p?.key.set ? t("{masked} · paste a new key to replace it", { masked: p.key.masked }) : copied?.key.set ? t("{masked} · {name}'s key, or paste another", { masked: copied.key.masked, name: copied.name }) : t(pr?.keyHint || (pr?.noKey || p?.key.optional ? "optional for local servers" : "paste an API key")), "password"); // many keys pasted at once (361 on Discord): one a line, or separated by // commas or spaces, are kept as one list; saved, the first is the key // and the others are added to its accounts, as Paste several does const keyCount = el("span", "hint key-count"); const countKeys = () => { const n = splitKeys(key.value).length; keyCount.textContent = n > 1 ? t("{n} keys", { n }) : ""; keyCount.title = n > 1 ? t("The first is tried first; the other {n} are added to its accounts", { n: n - 1 }) : ""; }; key.oninput = () => { draft.key = key.value; countKeys(); }; key.onpaste = (e) => { const keys = splitKeys(e.clipboardData?.getData("text") || ""); if (keys.length < 2) return; e.preventDefault(); // an input keeps no line breaks: the keys are kept comma separated key.value = draft.key = keys.join(", "); countKeys(); }; countKeys(); key.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter" && isNew) save(); else if (e.key === "Escape") cancelEdit(); }; const side = el("div", "side"); side.append(keyCount); const eye = el("button", "text", t("Show")); let revealed = false; // the saved key is in the box, not a draft eye.onclick = async () => { if (key.type === "password") { if (!key.value && p?.key.set) { try { key.value = (await api("provider/key", { id: p.id })).key; revealed = true; } catch (e) { status(e.message, "err"); return; } } key.type = "text"; eye.textContent = t("Hide"); } else { if (revealed && !draft.key) key.value = ""; revealed = false; key.type = "password"; eye.textContent = t("Show"); } }; side.append(eye); const keysUrl = p?.keysUrl || pr?.keysUrl; // the link follows the plan picked: a region's keysUrl goes with its // endpoints, and one without falls back to the preset's own page if (keysUrl) { const b = el("button", "link", t("Get a key ↗")); b.onclick = () => { if (pr?.kind === "partner") countPartner("keys", [pr.id]); api("open", { url: draft?.keysUrl || pr?.keysUrl || p?.keysUrl }); }; side.append(b); } const keyWrap = el("div", "pair"); keyWrap.append(key, side); // Google Vertex AI takes no key: it is asked at the user's own Google // Cloud project with a token their Google credentials mint, so its // project, location, credentials file and a service account to go as // are asked in its place, the project first const vertex = p ? !!p.vertex : !!pr?.vertex; let vertexProject = null; if (vertex) draft.vertex = draft.vertex || { project: p?.vertex?.project || "", location: p?.vertex?.location || "", credentials: p?.vertex?.credentials || "", impersonate: p?.vertex?.impersonate || "" }; const vertexFields = () => { const box = (k, placeholder, cls) => { const i = input(draft.vertex[k], placeholder); i.classList.add(cls); i.oninput = () => { draft.vertex[k] = i.value; refreshEndpoints(); }; i.onkeydown = key.onkeydown; // Enter adds it, as from the key's box return i; }; vertexProject = box("project", "my-project-123", "vertex-project"); return [ ...field(t("Project ID"), vertexProject, t("Your Google Cloud project, with the Agent Platform API (aiplatform.googleapis.com) enabled: requests are made, and billed, there")), ...field(t("Location"), box("location", "global", "vertex-location"), t("global, us, eu or a region such as us-central1. Each location serves its own models; global serves them all.")), ...field(t("Credentials file"), box("credentials", "~/.config/gcloud/application_default_credentials.json", "vertex-credentials"), t("Optional. Left empty, gcloud's Application Default Credentials are used (gcloud auth application-default login), or the file GOOGLE_APPLICATION_CREDENTIALS names. A service account's key file works too.")), ...field(t("Service account"), box("impersonate", t("optional · a service account's email"), "vertex-impersonate"), t("Requests are then made as this service account, impersonated with the credentials above: their account needs roles/iam.serviceAccountTokenCreator on it.")), ]; }; if (p?.keyList?.length) ed.append(...field(t("Accounts"), renderKeyAccounts(p), p.routing ? t("Tick every key to use; Routing says how requests spread over them.") : t("Tick every key to use. Requests go to the first; when it runs out of quota or hits a rate limit, the next ticked key takes over."))); if (p?.keyList?.filter((k) => k.on).length > 1) ed.append(...renderRouting(p)); else if (vertex) ed.append(...vertexFields()); else ed.append(...field(t("API key"), keyWrap, isNew ? t("Kept in ~/.config/magpie/providers.json, readable by you alone. Nothing is read from your shell.") : "")); if (addressMore) ed.append(addressMore); // A user-defined provider can have its own picture; presets keep theirs. if (custom) ed.append(...field(t("Icon"), iconPicker(ed), "")); // Request headers of the user's own, for a preset's provider as much as a // custom one — which workspace a key is for, who the app is; signed-in // accounts returned above use the agent's own authentication headers. if (custom) { if (!draft.headers.length) draft.headers.push(["", ""]); ed.append(...field(t("Headers"), headerEditor(), t("Extra HTTP headers sent to the vendor, applied after auth. For gateways that need a private scheme."))); } else { ed.append(...field(t("Headers"), headerEditor(pr?.headerHints || []), t("Optional headers sent with every request to {p}, applied after auth.", { p: pr?.name || p?.name }))); } // and JSON fields of the user's own for each request's body (#1604) ed.append(...field(t("Extra body"), extraBodyEditor(), t("JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id."))); const proxies = el("div", "stack"); proxies.append(proxyPicker()); const perKey = keyProxyPicker(p); if (perKey) proxies.append(perKey); ed.append(...field(t("Proxy"), proxies)); ed.append(...concurrencyField(p)); ed.append(...priceRateField()); if (p?.cline || (isNew && pr?.id === "clinepass")) ed.append(...upstreamField()); // a relay in front of Anthropic's or OpenAI's API searches the web as // they do, which magpie can't tell from its host (#359): a client's web // search goes to it as sent, rather than through magpie's own. Only its // Anthropic or Responses API can be asked to: a Chat one has no such tool if (custom) { const [stk, scb] = tick(t("Searches the web by itself"), !!draft.searches); scb.onchange = () => { draft.searches = scb.checked; }; const row = field(t("Web search"), stk, t("For a relay in front of Anthropic's or OpenAI's own API: Claude Code's WebSearch and Codex's web_search go to it as they were sent, not through magpie's search. magpie doesn't automatically search with it for other models, but you can name it as the searcher.")); showSearch = () => { for (const e of row) e.style.display = searchable() ? "" : "none"; }; showSearch(); ed.append(...row); } // which header the key goes in on a third-party Anthropic API: both by // default, one alone for a service that refuses the two together (Aloha // on Discord: "x-api-key 和 Authorization 不可以同时存在"), which magpie // also learns from that refusal. Anthropic's, Bedrock's and Azure's own // APIs take x-api-key alone already const twoKeyHeaders = () => { if (p?.account || vertex) return false; if (p && !custom) return !!p.bothAuth; const a = ((draft.anthropic ?? (isNew && pr ? pr.anthropic : "")) || "").trim(); if (!a) return false; let host = ""; try { host = new URL(/^[a-z]+:\/\//i.test(a) ? a : "https://" + a).hostname.toLowerCase(); } catch { return true; } return !host.endsWith("anthropic.com") && !/^bedrock-runtime\..*\.amazonaws\.com$/.test(host) && !host.endsWith(".azure.com"); }; if (!p?.account && !vertex) { const seg = segs([["", t("Both")], ["x-api-key", "x-api-key"], ["bearer", "Authorization: Bearer"]], draft.authHeader || "", (v) => { draft.authHeader = v; }); seg.classList.add("auth-header"); const row = field(t("Key header"), seg, t("Which header the API key goes in on the Anthropic API. Most services take both; pick one for a service that refuses the two together. magpie also switches to one by itself when a service says so.")); showAuth = () => { for (const e of row) e.style.display = twoKeyHeaders() ? "" : "none"; }; showAuth(); ed.append(...row); } // a coding plan that serves only agents it names knows them by their // User-Agent (#1851): a provider with a key may be sent the one the agent // gave in place of magpie's. A signed-in account, and a vendor whose own // client magpie goes as (OpenCode, Cline, Kilo, another magpie), keep // the identity they sign with const uaPassable = () => !p?.account && !(p ? p.ownClient : pr?.ownClient); if (uaPassable()) { const [utk, ucb] = tick(t("Send the agent's own User-Agent"), !!draft.passUserAgent); ucb.onchange = () => { draft.passUserAgent = ucb.checked; }; ed.append(...field(t("User-Agent"), utk, t("For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins."))); } // a model on this computer or the local network (Ollama, LM Studio, a // vLLM box) may be sent requests unmasked by Settings' redaction (lc on // Discord). Only the user can say it is local all the way: a relay run // locally, or Ollama's cloud models, pass a request on to a vendor const addressOf = (k) => (draft[k] ?? (isNew && pr ? pr[k] : "")) || ""; const onLAN = () => !p?.account && (p?.preset || pr?.id) !== "remote-magpie" && localAddresses(["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf)); if (!p?.account) { const [ltk, lcb] = tick(t("Send requests unmasked"), !!draft.unredacted); lcb.onchange = () => { draft.unredacted = lcb.checked; }; const row = field(t("Redaction"), ltk, t("For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.")); showLocal = () => { for (const e of row) e.style.display = onLAN() ? "" : "none"; }; showLocal(); ed.append(...row); } // a vendor that tells the whole account's balance only to a token of its // own (AiHubMix's system access token), where a key knows just its own // — or a custom provider's, whose Balance URL may not be named yet: a // token pasted there says at once which URL it wants (balanceFix) let balFix = null; if (p?.balanceToken?.takes || custom) { const saved = !!p?.balanceToken?.set; const tok = input(draft.balanceToken || "", saved && !draft.clearBalanceToken ? t("saved · paste a new one to replace it") : t("optional · the account's system access token"), "password"); tok.oninput = () => { draft.balanceToken = tok.value.trim(); }; tok.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); }; const pair = el("div", "pair"); pair.append(tok); if (saved && !draft.clearBalanceToken) { const side = el("div", "side"); const drop = el("button", "text", t("Remove")); drop.onclick = () => { draft.clearBalanceToken = true; draft.balanceToken = ""; tok.value = ""; tok.placeholder = t("optional · the account's system access token"); drop.remove(); balFix?.refresh(); }; side.append(drop); pair.append(side); } const tokHelp = custom || p.balanceURL ? t("What the Balance URL is asked with in place of the key, when it wants the account's own token: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.") : t("A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.", { p: pr?.name || p.name }); const [label, wrap] = field(t("Account balance"), pair, tokHelp); if (custom) { balFix = balanceFix(p); wrap.append(balFix); // whatever is typed — the token, the Balance URL, a header — may // make it or unmake it ed.addEventListener("input", () => balFix.refresh()); } ed.append(label, wrap); } // StepFun tells a Step Plan's 5-hour, weekly and credit windows only to // its platform's sign-in, never to a key: signed in once in a window of // magpie's, the Usage page shows them if (p?.stepPlan) ed.append(...field(t("Step Plan allowances"), renderStepPlan(p.stepPlan), t("A key tells only the balance. The Step Plan's 5-hour, weekly and credit windows are told only to a StepFun sign-in: bring yours here once and magpie keeps it (for 30 days), used for nothing else."))); // a key on a team's GLM Coding Plan is told the team's windows only with // the team's organization and project, which the console shows (#236) const team = p ? !!p.zhipuTeam : !!pr?.zhipuTeam; if (team) { draft.zhipuTeam = draft.zhipuTeam || { org: p?.zhipuTeam?.org || "", project: p?.zhipuTeam?.project || "" }; const org = input(draft.zhipuTeam.org, t("optional · only for a team plan")); org.classList.add("team-org"); org.oninput = () => { draft.zhipuTeam.org = org.value; }; const proj = input(draft.zhipuTeam.project, t("optional · only for a team plan")); proj.classList.add("team-project"); proj.oninput = () => { draft.zhipuTeam.project = proj.value; }; ed.append(...field(t("Team org ID"), org, "")); ed.append(...field(t("Team project ID"), proj, t("Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.", { p: pr?.name || p.name }))); } // Volcengine Ark tells a Coding or Agent Plan's windows only to the // account's access key, never to the plan's key (#1427), and Tencent // Cloud a Token Plan 企业版's only to its SecretId and SecretKey (#1574), // asked only at the regions that are that plan; the saved Secret is // never sent back here, only that one is saved const access = p ? p.accessKey : pr?.accessKey ? { vendor: pr.accessKeyVendor || "volcengine", id: "", secretSet: false } : null; let accessAt = () => {}, accessShown = () => !!access; if (access) { const tc = access.vendor === "tencent"; const idName = tc ? t("SecretId") : t("AccessKey ID"), secretName = tc ? t("SecretKey") : t("Secret Access Key"); if (draft.accessKeyID === undefined) draft.accessKeyID = access.id || ""; const ak = input(draft.accessKeyID, idName); ak.classList.add("volc-ak"); ak.oninput = () => { draft.accessKeyID = ak.value.trim(); }; const saved = access.secretSet && !draft.clearAccessKey; const sk = input(draft.secretAccessKey || "", saved ? t("saved · paste a new one to replace it") : secretName, "password"); sk.classList.add("volc-sk"); sk.oninput = () => { draft.secretAccessKey = sk.value.trim(); }; sk.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); }; const pair = el("div", "pair"); pair.append(sk); if (saved) { const side = el("div", "side"); const drop = el("button", "text", t("Remove")); drop.onclick = () => { draft.clearAccessKey = true; draft.accessKeyID = ""; draft.secretAccessKey = ""; ak.value = ""; sk.value = ""; sk.placeholder = secretName; drop.remove(); }; side.append(drop); pair.append(side); } const rows = [ ...field(idName, ak, ""), ...field(secretName, pair, tc ? t("Token Plan Enterprise's usage is told only to the Tencent Cloud account's API key (console → Access management → API keys), not to the plan's API key. Give its SecretId and SecretKey here for the Usage page to show it; a sub-user's key that may read TokenHub is enough. It is used for nothing else.") : t("The plan's 5-hour, weekly and monthly windows are told only to the account's access key (Volcengine console → API Access Keys), not to the plan's API key. Give it here for the Usage page to show them; it is used for nothing else.")), ]; ed.append(...rows); // a preset with the plan at some of its regions only (Tencent Cloud's // 企业版 beside its personal plan) asks for it at those, and at an // endpoint none of its regions has, which may be one of them const at = pr?.accessKeyRegions; if (at?.length) { accessAt = (r) => { const on = !r || at.includes(r.id) || !regionAt(pr, draft); for (const x of rows) x.hidden = !on; }; accessShown = () => !rows[0].hidden; } } // a relay that offers several regional endpoints, or a vendor whose plans // are served at their own: one selector, and the provider's base URLs follow it let refreshEndpoints = () => {}, onRegion = () => {}; if (pr?.regions?.length) { // Bedrock's ten regions don't fit the editor's width: they scroll const seg = el("div", "segs regions"); const cur = regionAt(pr, draft) || pr.regions.find((r) => r.decide && (r.id === draft.region || (!draft.region && workspaceOf(r.decide, draft.decide ?? p?.decide ?? pr.decide) !== null))) || pr.regions[0]; for (const r of pr.regions) { const b = el("button", "opt" + (r.id === cur.id ? " on" : ""), t(r.name)); b.onclick = () => { draft.chat = r.chat || ""; draft.responses = r.responses || ""; draft.anthropic = r.anthropic || ""; draft.keysUrl = r.keysUrl || ""; const site = ed.querySelector(".ehead .link.site"); if (site && pr.regions.some((x) => x.website)) { site.dataset.url = r.website || pr.website; site.textContent = hostOf(site.dataset.url) + " ↗"; } onRegion(r); accessAt(r); for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); slide(seg, "regions"); refreshEndpoints(); }; seg.append(b); } accessAt(cur); queueMicrotask(() => { slide(seg, "regions"); // the region in use in view, where they scroll const on = seg.querySelector(":scope > .on"); if (on && seg.scrollWidth > seg.clientWidth) seg.scrollLeft = on.offsetLeft - (seg.clientWidth - on.offsetWidth) / 2; }); ed.append(...field(t(pr.regionLabel || "Region"), seg, t("which endpoint {p} is reached through", { p: pr.name }))); } if (p) ed.append(...field(t("Models"), renderModels(p), "")); if (p?.drawIds?.length) ed.append(...renderDrawers(p)); { // the window agents are told a model has, over what the vendor or // models.dev says: one for all of them, and model=size for one const cx = input(draft.contexts || "", t("e.g. 128k · or gpt-6=1m, comma separated")); if (!decideOnly(p || pr)) ed.append(...field(t("Context window"), contextPicks(p, cx), t("How long a request the models take, told to the agents; empty leaves it to the vendor and models.dev"))); if (!decideOnly(p || pr)) ed.append(...outputField()); if (!decideOnly(p || pr)) ed.append(...compactField()); } if (p && !decideOnly(p)) ed.append(...field(t("Fallback"), renderFallback(p), fallbackHint(p))); else if (custom) { const ex = input(draft.extra.join(", "), t("model ids, comma separated · e.g. gpt-5.5, claude-sonnet-5")); const pick = addFormModels(ex); ex.oninput = () => { draft.extra = ex.value.split(/[,\s]+/).filter(Boolean); pick.draw(); }; ed.append(...field(t("Models"), pick.box, t("Optional: Fetch models to pick from the vendor's list, or type ids; none picked, magpie asks for the list after saving."))); } // Jev's endpoint can be the one its gateway's docs give — Cloudflare's // names the account, …/accounts//ai/run — in place of the preset's if (decides && !custom && (p?.preset || pr?.id) !== "remote-magpie") { if (draft.decide === undefined) draft.decide = p?.decide || pr?.decide || ""; const du = input((address && movedURLs(draft)?.decide) || draft.decide, pr?.decide || "https://…", "url"); du.classList.add("decide-url"); // Bailian's is at the host of the key's workspace (#647): its id is // typed on its own, the plan's address filled in with it if (!draft.region && pr?.regions?.some((r) => r.decide)) draft.region = (pr.regions.find((r) => r.decide && workspaceOf(r.decide, draft.decide) !== null) || pr.regions[0]).id; const tmpl = () => (pr?.regions || []).find((r) => r.id === draft.region)?.decide || (draft.region ? "" : pr?.decide) || ""; const wsIn = input((draft.workspace ?? workspaceOf(tmpl(), draft.decide)) || "", t("e.g. ws-…, from the Bailian console")); wsIn.classList.add("workspace-id"); const wsRow = field(t("Workspace ID"), wsIn, t("The workspace your API key belongs to, in the Bailian console; its decision model is asked at that workspace's host")); const fill = () => { const tp = tmpl(); const ws = tp.includes(WORKSPACE); for (const x of wsRow) x.hidden = !ws; if (!ws) return; draft.decide = du.value = tp.split(WORKSPACE).join((draft.workspace ?? wsIn.value).trim() || WORKSPACE); }; wsIn.oninput = () => { draft.workspace = wsIn.value; fill(); }; du.oninput = () => { draft.decide = du.value; }; onRegion = (r) => { draft.region = r.id; if (r.decide) { draft.decide = du.value = r.decide; fill(); } }; ed.append(...wsRow); fill(); ed.append(...field(t(decideOnly(p || pr) && !/jev/i.test(pr?.name || p?.name || "") ? "System One endpoint" : "Jev endpoint"), du, tmpl().includes(WORKSPACE) ? t("The address the decision model is asked at, POST …/systemone under it; the workspace ID above fills it in") : t("The address Jev is asked at; paste the one from your gateway's docs, e.g. Cloudflare's …/accounts//ai/run"))); } if (!custom && !(decides && !p)) { const ebox = el("div"); const row = field(t("Endpoints"), ebox, ""); refreshEndpoints = () => { const base = p || pr || {}; const src = { chat: draft.chat || base.chat || "", responses: draft.responses || base.responses || "", anthropic: draft.anthropic || base.anthropic || "", decide: base.decide || "" }; // Vertex AI's is the address its project and location make, shown // with its Test once a project is typed, saved one or not: with none // there is nowhere to ask if (vertex) { src.gemini = vertexBase(draft.vertex); for (const x of row) x.hidden = !src.gemini; } Object.assign(src, address && movedURLs(draft)); ebox.replaceChildren(renderEndpoints(p, src)); }; refreshEndpoints(); ed.append(...row); } if (custom) { const more = el("details", "more"); more.append(el("summary", "", t("More endpoints"))); const inner = el("div", "inner"); // the other protocols' URLs, drawn again when the base URL's changes const eps = el("div"); eps.style.display = "contents"; fillEndpoints = () => { eps.replaceChildren(); const add = (label, key, ph, hint) => { if (apiField[draft.api] === key) return; const i = input(draft[key], ph, "url"); i.oninput = () => { draft[key] = i.value; if (carried?.from === key) carried = null; showSearch(); showLocal(); showAuth(); }; eps.append(...field(t(label), i, t(hint))); }; add("OpenAI URL", "chat", "https://…/v1", "if the vendor also serves chat completions"); add("Anthropic URL", "anthropic", "https://…", "if the vendor also serves Anthropic messages"); add("Responses URL", "responses", "https://…/v1", "if the vendor serves the OpenAI Responses API (Codex uses it natively)"); add("Gemini URL", "gemini", "https://…/v1beta", "if the vendor serves Google's Gemini API (generateContent)"); }; fillEndpoints(); inner.append(eps); const mu = input(draft.modelsURL, "https://…/v1/models", "url"); mu.oninput = () => { draft.modelsURL = mu.value; }; inner.append(...field(t("Models URL"), mu, t("Where the vendor lists its models, when that isn't under the base URL; asked with the key"))); const cat = input(draft.catalog, t("models.dev ids, e.g. openai, deepseek")); cat.oninput = () => { draft.catalog = cat.value; }; inner.append(...field(t("Catalog"), cat, t("Display names and reasoning levels for the models; for a gateway that serves several vendors, list them all, first match wins"))); const bal = input(draft.balanceURL, "https://…/api/usage/token", "url"); bal.classList.add("bal-url"); bal.oninput = () => { draft.balanceURL = bal.value; balPath.placeholder = balanceFieldOf(bal.value); }; inner.append(...field(t("Balance URL"), bal, t("Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page"))); const balPath = input(draft.balancePath, balanceFieldOf(draft.balanceURL)); balPath.classList.add("bal-path"); balPath.oninput = () => { draft.balancePath = balPath.value; }; // asked as the form has it, before a Save: what the Usage page would show const balPair = el("div", "pair"); balPair.append(balPath); if (p) { const side = el("div", "side"); const check = el("button", "text action", t("Check balance")); check.title = t("Ask the Balance URL now, as the form has it"); side.append(check); balPair.append(side); const res = el("div", "bal-res"); check.onclick = async () => { check.classList.add("busy"); res.className = "bal-res wait"; res.textContent = "…"; res.title = ""; const body = { id: p.id, balanceURL: (draft.balanceURL || "").trim(), balancePath: (draft.balancePath || "").trim(), headers: headersOf(draft.headers) }; if (draft.balanceToken) body.balanceToken = draft.balanceToken; else if (draft.clearBalanceToken) body.clearBalanceToken = true; try { const r = await api("provider/balance", body); res.className = "bal-res " + (r.error ? "bad" : r.ok ? "ok" : ""); res.textContent = r.error ? balanceError(r.error) || r.error : r.ok ? t("Balance") + " " + r.amount : t("No Balance URL to ask"); res.title = r.error || ""; } catch (e) { res.className = "bal-res bad"; res.textContent = e.message; } check.classList.remove("busy"); }; balPair.append(res); balPair.classList.add("wrap"); } inner.append(...field(t("Balance field"), balPair, t("Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent, with a bar; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left"))); more.append(inner); ed.append(more); } const bar = el("div", "bar"); if (p) { const del = el("button", "text danger", t("Remove")); del.onclick = () => providerAction("delete", { id: p.id }, t("{name} removed", { name: p.name })); bar.append(del); } if (p && pr) { // another key of the vendor, or the same key for another workspace const more = el("button", "text", t("Add another {name}", { name: pr.name })); more.title = vertex ? t("One more {name} provider, with its own project, credentials, headers and models", { name: pr.name }) : t("One more {name} provider, with its own key, headers and models", { name: pr.name }); more.onclick = () => { editing = { preset: pr.id }; draft = null; renderProviders(); }; bar.append(more); } if (p) { const dup = el("button", "text", t("Duplicate")); dup.title = vertex ? t("A new provider with {name}'s project, credentials, headers and models, to change before adding", { name: p.name }) : t("A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding", { name: p.name }); dup.onclick = () => duplicateProvider(p); bar.append(dup); } bar.append(el("span", "grow")); const cancel = el("button", "text", t("Cancel")); cancel.onclick = cancelEdit; const saveBtn = el("button", "text primary", t(isNew ? "Add" : "Save")); const save = () => { // new: an Add never replaces a provider that has the id already const body = { id: p ? slug(draft.id) || p.id : draft.id, from: p?.id, name: draft.name, preset: draft.preset, key: draft.key || "", chat: draft.chat, responses: draft.responses, anthropic: draft.anthropic, gemini: (draft.gemini || "").trim(), catalog: draft.catalog, models: p ? chosenIds() : draft.extra, headers: headersOf(draft.headers), new: isNew }; if (isNew && draft.copyOf) body.copyOf = draft.copyOf; const xb = extraBodyOf(draft.extraBody); if (xb.error) { ed.querySelector(".extra-body textarea")?.focus({ preventScroll: true }); return editorError(t("Extra body: {why}", { why: xb.error }), "warn"); } body.extraBody = xb.value; if (decides || custom) body.decide = (custom && draft.api !== "decide" && !p?.decide ? "" : draft.decide || "").trim(); if ((body.decide || "").includes(WORKSPACE)) { ed.querySelector(".workspace-id")?.focus({ preventScroll: true }); return editorError(t("Give the workspace ID your API key belongs to, or pick the Token Plan"), "warn"); } if (custom) { // the API picked for the Base URL is saved with it, and one left with // no URL is said rather than lost: the editor would open on another if (!(draft[apiField[draft.api]] || "").trim() && ["chat", "responses", "anthropic", "gemini", "decide"].some((k) => (draft[k] || "").trim())) { ed.querySelector(".base-url")?.focus({ preventScroll: true }); return editorError(t("Base URL: type the {api} URL, or pick the API the URL you have is for", { api: t(API_NAMES[draft.api]) }), "warn"); } body.baseAPI = draft.api === "openai" ? "chat" : draft.api; } if (custom) { body.icon = draft.icon || "generic"; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.modelsURL = (draft.modelsURL || "").trim(); } if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; body.noModels = noneChosen(); body.modelPrefs = modelPrefsOfDraft(); Object.assign(body, routingOfDraft(p)); } body.searches = !!draft.searches && searchable(); body.pinUpstream = !!draft.pinUpstream; if (twoKeyHeaders()) body.authHeader = draft.authHeader || ""; body.unredacted = !!draft.unredacted && onLAN(); body.passUserAgent = !!draft.passUserAgent && uaPassable(); const cx = parseContexts(draft.contexts || ""); if (cx.error) return editorError(t("Context window: {v} is not a length like 128k or 1m", { v: cx.error }), "warn"); body.contexts = cx.map; if (!decideOnly(p || pr)) { const ox = parseContexts(draft.outputs || ""); if (ox.error) return outputError(ed, ox.error); body.outputs = ox.map; const cpx = parseContexts(draft.compacts || ""); if (cpx.error) return compactError(ed, cpx.error); body.compacts = cpx.map; } body.proxy = proxyOfDraft(); if (body.proxy === null) { ed.querySelector(".proxy-url")?.focus(); return editorError(t("Proxy: type its address, like http://127.0.0.1:7890"), "warn"); } if (perKey) { const own = accountProxiesOfDraft(); if (own.missing) { const line = ed.querySelector(`.acct-proxy[data-key="${own.missing}"]`); line?.querySelector(".proxy-url")?.focus({ preventScroll: true }); return editorError(t("Proxy of {user}: type its address, like http://127.0.0.1:7890", { user: line?.querySelector(".who")?.textContent || own.missing }), "warn"); } body.accountProxies = own.map; } body.maxConcurrency = concurrencyOfDraft(); if (body.maxConcurrency === undefined) return concurrencyError(ed); const queue = queueOfDraft(); if (queue.bad) return queueError(ed, queue.bad); Object.assign(body, queue); body.priceRate = priceRateOfDraft(); if (body.priceRate === undefined) return priceRateError(ed); if (p && priceTypedError(ed)) return; if (draft.balanceToken) body.balanceToken = draft.balanceToken; else if (draft.clearBalanceToken) body.clearBalanceToken = true; if (team) { // both or neither: {} clears them const org = (draft.zhipuTeam.org || "").trim(), project = (draft.zhipuTeam.project || "").trim(); if (!org !== !project) { ed.querySelector(org ? ".team-project" : ".team-org")?.focus({ preventScroll: true }); return editorError(t("Team plan: give both the organization ID and the project ID"), "warn"); } body.zhipuTeam = org ? { org, project } : {}; } if (access) { // the Secret is sent only when a new one is typed: blank keeps the // saved one, unless it was removed body.accessKeyID = draft.accessKeyID || ""; if (draft.secretAccessKey) body.secretAccessKey = draft.secretAccessKey; else if (draft.clearAccessKey) body.clearAccessKey = true; if (accessShown() && body.accessKeyID && !body.secretAccessKey && !(access.secretSet && !draft.clearAccessKey)) { ed.querySelector(".volc-sk")?.focus({ preventScroll: true }); return editorError(t("Give the access key's Secret too"), "warn"); } } if (vertex) body.vertex = vertexOfDraft(); if (isNew && custom && !body.name) { name.focus(); return editorError(t("Give it a name"), "warn"); } if (isNew && custom && !body.chat && !body.anthropic && !body.responses && !body.decide) { url.focus(); return editorError(t("A base URL is needed"), "warn"); } if (endpoint && !body.chat && !body.responses) { endpoint.focus(); return editorError(t(pr.endpointNeeded || "Your resource's endpoint is needed"), "warn"); } if (vertex && !body.vertex.project) { vertexProject?.focus({ preventScroll: true }); return editorError(t("Google Vertex AI needs the id of your Google Cloud project"), "warn"); } if (address) { const a = (draft.address || "").trim(); if (localAddress(a) === null) { addressMore.open = true; address.focus({ preventScroll: true }); return editorError(t("Address: {v} isn't an address like http://localhost:11434", { v: a }), "warn"); } Object.assign(body, movedURLs(draft)); } editorError(""); saving(saveBtn, t(isNew ? "Adding…" : "Saving…")); providerAction("save", body, t(isNew ? "{name} added" : "{name} saved", { name: draft.name || draft.id })); }; saveBtn.onclick = save; bar.append(cancel, saveBtn); ed.append(bar); setTimeout(() => (isNew ? (custom || another ? name : endpoint || vertexProject || key) : null)?.focus(), 0); return ed; } // contextsText is a provider's contexts as the editor shows them: the one // for all its models first, then model=size. function contextsText(cx) { if (!cx) return ""; const size = (n) => n % 1e6 === 0 ? n / 1e6 + "m" : n % 1e3 === 0 ? n / 1e3 + "k" : String(n); const out = cx["*"] ? [size(cx["*"])] : []; for (const [id, n] of Object.entries(cx).sort()) if (id !== "*") out.push(id + "=" + size(n)); return out.join(", "); } // contextPicks puts the usual windows under the context field, one click // each, and, when some models take more than they are said to (Codex's // GPT-6: 272K said, 872K taken), their own most: sizes nobody remembers // (#120). The pick matching what is typed is lit. function contextPicks(p, cx) { const size = (n) => contextsText({ "*": n }); const picks = [128e3, 200e3, 256e3, 1e6].map((n) => ({ label: size(n).toUpperCase(), value: size(n) })); // above the window its vendor says, not the one set here: a model set to // its most still offers it const big = (p?.models || []).filter((m) => m.max > ("listed" in m ? m.listed || 0 : m.context || 0)); if (big.length) { const tops = [...new Set(big.map((m) => m.max))]; const value = () => { const on = big.filter((m) => draft.chosen?.includes(m.id)); return contextsText(Object.fromEntries((on.length ? on : big).map((m) => [m.id, m.max]))); }; picks.push({ label: tops.length === 1 ? t("Each model's most · {n}", { n: size(tops[0]).toUpperCase() }) : t("Each model's most"), title: big.map((m) => `${m.id}: ${size(m.max).toUpperCase()}`).join("\n"), value, most: true, }); } const row = el("div", "cxpicks"); const same = (a, b) => JSON.stringify(parseContexts(a).map || {}) === JSON.stringify(parseContexts(b).map || {}); const light = () => { for (const [i, b] of [...row.children].entries()) { const v = picks[i].value; b.classList.toggle("on", !!cx.value.trim() && same(cx.value, typeof v === "function" ? v() : v)); } }; for (const pk of picks) { const b = el("button", "cxpick" + (pk.most ? " most" : ""), pk.label); b.type = "button"; if (pk.title) b.title = pk.title; b.onclick = () => { cx.value = typeof pk.value === "function" ? pk.value() : pk.value; draft.contexts = cx.value; light(); }; row.append(b); } cx.oninput = () => { draft.contexts = cx.value; light(); }; light(); const wrap = el("div", "cxfield"); wrap.append(cx, row); return wrap; } // outputField is the editor's Max output: the most a reply of its models // may hold, over what the vendor or models.dev says, one for all of them // and model=size for one, as the context window is set (ARNO on Discord: a // model's maxTokens was wrong, and only its window could be set here). // The usual sizes sit under it, one click each, as under the window (#875). function outputField() { const ox = input(draft.outputs || "", t("e.g. 32k · or gpt-6=128k, comma separated")); ox.classList.add("outputs"); const sizes = [8e3, 16e3, 32e3, 64e3, 128e3].map((n) => contextsText({ "*": n })); const row = el("div", "cxpicks"); const same = (a, b) => JSON.stringify(parseContexts(a).map || {}) === JSON.stringify(parseContexts(b).map || {}); const light = () => { for (const [i, b] of [...row.children].entries()) b.classList.toggle("on", !!ox.value.trim() && same(ox.value, sizes[i])); }; for (const v of sizes) { const b = el("button", "cxpick", v.toUpperCase()); b.type = "button"; b.onclick = () => { ox.value = v; draft.outputs = v; light(); }; row.append(b); } ox.oninput = () => { draft.outputs = ox.value; light(); }; light(); const wrap = el("div", "cxfield"); wrap.append(ox, row); return field(t("Max output"), wrap, t("The most a reply may hold, told to the agents as their max tokens and sent as max_tokens on Anthropic's API when the agent names none; empty leaves it to the vendor and models.dev")); } // compactField is the editor's Compact at (#876): where Codex and Claude // Code compact a conversation on its models when their window is longer, // one for all of them and model=size for one, as the window is set. Empty // follows Settings → Long conversations; one at or above a model's window // runs it to the whole window. function compactField() { const cp = input(draft.compacts || "", t("e.g. 500k · or deepseek-v4-flash=272k, comma separated")); cp.classList.add("compacts"); const sizes = [128e3, 200e3, 272e3, 500e3, 1e6].map((n) => contextsText({ "*": n })); const row = el("div", "cxpicks"); const same = (a, b) => JSON.stringify(parseContexts(a).map || {}) === JSON.stringify(parseContexts(b).map || {}); const light = () => { for (const [i, b] of [...row.children].entries()) b.classList.toggle("on", !!cp.value.trim() && same(cp.value, sizes[i])); }; for (const v of sizes) { const b = el("button", "cxpick", v.toUpperCase()); b.type = "button"; b.onclick = () => { cp.value = v; draft.compacts = v; light(); }; row.append(b); } cp.oninput = () => { draft.compacts = cp.value; light(); }; light(); const wrap = el("div", "cxfield"); wrap.append(cp, row); return field(t("Compact at"), wrap, t("Where Codex and Claude Code compact a long conversation on these models; empty follows Settings → Long conversations, and a size at or above a model's window runs it to its whole window")); } function compactError(ed, v) { ed.querySelector("input.compacts")?.focus({ preventScroll: true }); return editorError(t("Compact at: {v} is not a number of tokens like 272k", { v }), "warn"); } function outputError(ed, v) { ed.querySelector("input.outputs")?.focus({ preventScroll: true }); return editorError(t("Max output: {v} is not a number of tokens like 32k", { v }), "warn"); } // parseContexts reads "128k, gpt-6=1m" back: sizes by model id, "*" for // all; error is the first part that isn't a size. function parseContexts(text) { const map = {}; for (const part of text.split(/[,,\n]/).map((x) => x.trim()).filter(Boolean)) { const i = part.lastIndexOf("="); const id = i < 0 ? "*" : part.slice(0, i).trim(), v = (i < 0 ? part : part.slice(i + 1)).trim().toLowerCase().replace(/_/g, ""); const m = /^(\d+(?:\.\d+)?)([km]?)$/.exec(v); if (!m || !id) return { error: part }; const n = Math.round(parseFloat(m[1]) * (m[2] === "m" ? 1e6 : m[2] === "k" ? 1e3 : 1)); if (n > 0) map[id] = n; } return { map }; } // fetchImportIcon asks the server to download the vendor's own logo, named // by the link. It swaps the header mark when it lands; a failure is silent // (the generic outline stays), since the icon is decoration, not the deal. function fetchImportIcon(p, head, ed) { const host = hostOf(p.iconUrl); const note = el("div", "hint", t("Fetching {host}’s icon…", { host: host || t("the vendor") })); ed.append(note); api("import/icon", { url: p.iconUrl }).then((r) => { p.icon = r.icon; delete p.iconUrl; const old = head.firstChild; const now = icon(p.icon); old ? old.replaceWith(now) : head.prepend(now); note.remove(); }).catch(() => note.remove()); } // Scan off the page's loading path, at most once a minute as it is opened // or refreshed. A completed import forces a fresh scan; an older response // cannot put the pre-import hint back. Ignored configurations stay quiet // across launches; new or changed ones can still be offered. async function discoverLocalProviders(force = false) { if (mode !== "window" || view !== "providers" || providers?.fileError) return; if (!force && (discoveryPending || Date.now() - discoveryAt < 60000)) return; const run = ++discoveryRun; discoveryPending = true; try { const result = await api("importapps/discovery"); if (run !== discoveryRun) return; providerDiscovery = Array.isArray(result) ? result : []; } catch { if (run !== discoveryRun) return; providerDiscovery = []; // optional discovery must not block adding by hand } finally { if (run === discoveryRun) { discoveryPending = false; discoveryAt = Date.now(); renderProviderDiscovery(); } } } function renderProviderDiscovery() { const hint = $("#providerDiscovery"); const fresh = providerDiscovery.filter((c) => !discoveryIgnored.has(c.fingerprint)); const count = fresh.length, compact = !!providers?.providers.length; hint.hidden = !count || !!providers?.fileError; if (hint.hidden) return; hint.classList.toggle("compact", compact); const parent = compact ? $("#addProvider").parentElement : $("#view-providers"); if (hint.parentElement !== parent) parent.insertBefore(hint, compact ? null : $("#providers")); $("#providerDiscoveryCount").textContent = t(count === 1 ? "Found 1 local provider configuration" : "Found {n} local provider configurations", { n: count }); const sources = [...new Set(fresh.map((c) => c.source))].join(" · "); $("#providerDiscoverySources").textContent = sources; const review = $("#reviewProviderDiscovery"); review.textContent = compact ? t("Import local configurations ({n})…", { n: count }) : t("Review and import…"); review.classList.toggle("primary", !compact); review.title = sources; } $("#reviewProviderDiscovery").onclick = () => openImportApps(new Set(providerDiscovery.filter((c) => !discoveryIgnored.has(c.fingerprint)).map((c) => c.fingerprint))); $("#dismissProviderDiscovery").onclick = () => { // Merge other windows' choices before saving, without forgetting candidates // that happen to be unavailable or already imported during this scan. try { for (const id of JSON.parse(localStorage.getItem("magpie.discoveryIgnored") || "[]")) discoveryIgnored.add(id); } catch {} for (const c of providerDiscovery) discoveryIgnored.add(c.fingerprint); try { localStorage.setItem("magpie.discoveryIgnored", JSON.stringify([...discoveryIgnored])); } catch {} renderProviderDiscovery(); }; window.addEventListener("storage", (e) => { if (e.key !== "magpie.discoveryIgnored" && e.key !== null) return; try { discoveryIgnored = new Set(JSON.parse(e.newValue || "[]")); } catch { return; } renderProviderDiscovery(); }); // Providers other apps have set up, for the user to pick from. magpie only // reads those apps; the keys stay on the server side and the dialog sees them masked. async function openImportApps(discovered) { importingApps = { loading: true, sources: [], picks: {} }; renderProviders(); try { const sources = await api("importapps"); const picks = {}; for (const s of sources) for (const it of s.items) { if (it.skip || it.status === "same") continue; const offered = !(discovered instanceof Set) || discovered.has(it.fingerprint); // one named as a subscription (claude, workbuddy) comes in beside // it, so it is picked like a new one (#1487) picks[s.id + "\n" + it.ref] = { on: offered && !it.off && (it.status !== "taken" || !!it.keyOf || !!it.reserved), mode: it.keyOf ? "key" : "add" }; } if (!importingApps) return; const tab = sources.find((s) => s.items.some((it) => picks[s.id + "\n" + it.ref]?.on))?.id; importingApps = { sources, picks, tab }; } catch (e) { if (!importingApps) return; importingApps = { error: e.message, sources: [], picks: {} }; } renderProviders(); } // appIcon is an import source's logo; Claude Code has its mark among the // vendor icons rather than an app tile of its own. const appIcon = (id) => id === "claude-code" ? "icons/claudecode-color.svg" : id === "codex" ? "icons/codex-color.svg" : `icons/app-${id}.png`; function renderImportApps(ia) { const ed = el("div", "editor new importapps"); ed.onclick = (e) => e.stopPropagation(); const h = el("div", "ehead"); h.append(el("b", "", t("Import from other apps"))); ed.append(h); const bar = el("div", "bar"); const count = el("span", "note grow"); const cancel = el("button", "text", t("Cancel")); cancel.onclick = cancelEdit; const go = el("button", "text primary", t("Import")); const recount = () => { const n = Object.values(ia.picks).filter((x) => x.on).length; count.textContent = n ? t("{n} selected", { n }) : ""; go.disabled = !n; }; bar.append(count, cancel, go); if (ia.loading) { ed.append(el("div", "appnote", t("Reading other apps…")), bar); go.disabled = true; return ed; } if (ia.error) { ed.append(el("div", "warnbox", ia.error), bar); go.disabled = true; return ed; } ed.append(el("div", "appnote", t("magpie reads these apps' settings and changes nothing in them. Pick the providers to bring over."))); // one tab per app magpie can import from, so which ones it can is plain // at a glance; each shows how many providers it has to bring over const tabs = el("div", "apptabs"); tabs.setAttribute("role", "tablist"); const list = el("div", "applist"); const secs = {}; const pickable = (s) => s.items.some((it) => ia.picks[s.id + "\n" + it.ref]); if (!ia.sources.some((s) => s.id === ia.tab)) { ia.tab = (ia.sources.find(pickable) || ia.sources.find((s) => s.found) || ia.sources[0])?.id; } const showTab = (id) => { ia.tab = id; for (const [sid, [tab, sec]] of Object.entries(secs)) { tab.classList.toggle("on", sid === id); tab.setAttribute("aria-selected", String(sid === id)); sec.hidden = sid !== id; } list.scrollTop = 0; }; for (const s of ia.sources) { const sec = el("div", "appsrc"); const tab = el("button", "apptab" + (s.found && !s.error ? "" : " missing")); tab.setAttribute("role", "tab"); const tlogo = el("img", "applogo"); tlogo.src = appIcon(s.id); tlogo.alt = ""; tlogo.draggable = false; const n = s.items.filter((it) => ia.picks[s.id + "\n" + it.ref]).length; tab.append(tlogo, el("span", "", s.name), el("span", "count", s.found && !s.error ? String(n) : "–")); tab.title = s.found ? (s.error || t(n === 1 ? "1 provider to bring over" : "{n} providers to bring over", { n })) : t("Not found on this computer"); tab.onclick = () => showTab(s.id); tabs.append(tab); secs[s.id] = [tab, sec]; const sh = el("div", "apphead"); const logo = el("img", "applogo"); logo.src = appIcon(s.id); logo.alt = ""; logo.draggable = false; sh.append(logo, el("b", "", s.name), el("code", "", s.path.replace(/^\/Users\/[^/]+|^\/home\/[^/]+/, "~"))); sec.append(sh); if (!s.found) sec.append(el("div", "appempty", t("Not found on this computer"))); else if (s.error) sec.append(el("div", "appempty", s.error)); else if (!s.items.length) sec.append(el("div", "appempty", t("No providers in it"))); // everything this app has that can come over, on or off at once const mine = s.items.map((it) => ia.picks[s.id + "\n" + it.ref]).filter(Boolean); const boxes = []; const all = el("input"); all.type = "checkbox"; const allState = () => { const n = mine.filter((x) => x.on).length; all.checked = n > 0 && n === mine.length; all.indeterminate = n > 0 && n < mine.length; }; const tick = () => { allState(); recount(); }; for (const it of s.items) sec.append(importAppRow(ia, s, it, tick, boxes)); if (mine.length) { const lab = el("label", "appall"); all.onchange = () => { for (const x of mine) x.on = all.checked; for (const b of boxes) b.checked = all.checked; tick(); }; lab.append(all, el("span", "", t("Select all"))); sh.append(lab); allState(); } list.append(sec); } ed.append(tabs, list); showTab(ia.tab); go.onclick = async () => { const picks = []; for (const [k, v] of Object.entries(ia.picks)) { if (!v.on) continue; const [source, ref] = k.split("\n"); picks.push({ source, ref, mode: v.mode, ...(v.name?.trim() ? { name: v.name.trim() } : {}) }); } go.classList.add("busy"); try { const r = await api("importapps", { picks }); providers = r.state; importingApps = null; adding = false; editing = null; draft = null; providerDiscovery = []; discoveryAt = 0; discoveryRun++; discoveryPending = false; renderProviders(); discoverLocalProviders(true); state = await api("state"); renderAgents(); status(t("Imported {n}: {names}", { n: r.added.length, names: r.added.join(", ") }), "ok"); } catch (e) { go.classList.remove("busy"); if (!editorError(e.message, "err")) status(e.message, "err"); } }; ed.append(bar); recount(); return ed; } function importAppRow(ia, s, it, recount, boxes) { const p = it.provider; const pick = ia.picks[s.id + "\n" + it.ref]; const row = el("label", "approw" + (pick ? "" : " dim")); const box = el("input"); box.type = "checkbox"; box.checked = !!pick?.on; box.disabled = !pick; box.onchange = () => { pick.on = box.checked; recount(); }; if (pick) boxes.push(box); const who = el("div", "appwho"); const name = el("div", "name"); name.append(el("span", "", p.name || it.ref)); if (it.from) name.append(el("span", "from", it.from)); who.append(name); const bits = []; const host = hostOf(p.anthropic || p.chat || p.responses || ""); if (it.skip) bits.push(t(it.skip)); else { if (host) bits.push(host); if (p.key) bits.push(p.key); if (p.models?.length) bits.push(t(p.models.length === 1 ? "1 model" : "{n} models", { n: p.models.length })); } who.append(el("div", "sub", bits.join(" · "))); if (pick && it.off) who.append(el("div", "sub", t(it.off))); if (pick && (it.keyOf || it.status === "taken")) { const renamed = () => !!pick.name?.trim() && pick.name.trim() !== p.name; const choices = () => { const opts = []; if (it.keyOf) opts.push(["key", t("Add as another key")]); opts.push(["add", t(it.status === "taken" && !it.reserved && !renamed() ? "Keep both" : "Add as a new provider")]); // a subscription is never replaced by a provider of keys, nor is // anything by one the user gave a name of its own (#1487) if (it.status === "taken" && !it.reserved && !renamed()) opts.push(["replace", t("Replace it")]); // one way in alone needs no choice if (opts.length === 1) { pick.mode = opts[0][0]; const none = el("span"); none.hidden = true; return none; } const sg = segs(opts, pick.mode, (m) => { pick.mode = m; if (!pick.on) { pick.on = box.checked = true; recount(); } }); sg.onclick = (e) => e.preventDefault(); // a click on a choice is not a click on the checkbox return sg; }; who.append(el("div", "sub", t(it.reserved ? "{name} is a subscription in magpie; this one comes in beside it as a provider of its own" : "magpie has {name} already", { name: it.existing }))); let sg = choices(); if (it.status === "taken") { // a name that collides can be changed right here (#1487) const nm = input(pick.name ?? p.name, t("e.g. My Relay")); nm.className = "appname"; nm.setAttribute("aria-label", t("Name")); nm.onclick = (e) => e.preventDefault(); // typing in it never ticks the row nm.oninput = () => { pick.name = nm.value; if (renamed() && pick.mode === "replace") pick.mode = "add"; const next = choices(); sg.replaceWith(next); sg = next; if (renamed() && !pick.on) { pick.on = box.checked = true; recount(); } }; who.append(nm); } who.append(sg); } let tag = null; // which provider holds it, so the user can find it (#1486) if (it.status === "same" && it.existing) who.append(el("div", "sub", t("magpie has {name} already", { name: it.existing }))); if (it.status === "same") tag = el("span", "apptag", t("Already added")); else if (it.skip) tag = el("span", "apptag", t("Can't import")); else if (it.status === "taken") tag = el("span", "apptag", t("Name in use")); else if (it.keyOf) tag = el("span", "apptag", t("Same vendor")); row.append(box, icon(p.icon || "generic"), who); if (tag) row.append(tag); return row; } // renderImport: what a magpie://import link would add, for the user to // check. Nothing is saved until they press Add; the key stays hidden unless // they ask to see it. function renderImport(im) { const ed = el("div", "editor new import"); ed.onclick = (e) => e.stopPropagation(); const p = im.provider || {}; const h = el("div", "ehead"); h.append(icon(p.icon || "generic"), el("b", "", im.error ? t("Import link") : p.name)); if (!im.error) h.append(el("span", "note", t("from a link"))); ed.append(h); const bar = el("div", "bar"); bar.append(el("span", "grow")); const cancel = el("button", "text", t(im.error ? "Close" : "Cancel")); cancel.onclick = cancelEdit; bar.append(cancel); if (im.error) { ed.append(el("div", "warnbox", t("This link can't be imported: {e}", { e: im.error })), bar); return ed; } const hosts = [...new Set([p.chat, p.responses, p.anthropic].filter(Boolean).map(hostOf))]; ed.append(el("div", "warnbox", t("Added from a link. Your prompts and this key will go to {hosts}; add it only if you trust the site that sent you here.", { hosts: hosts.join(", ") }))); const name = input(im.name ?? p.name, t("e.g. My Relay")); name.oninput = () => { im.name = name.value; }; ed.append(...field(t("Name"), name)); const key = input(im.key ?? p.key ?? "", t(p.key ? "" : "paste an API key"), "password"); key.oninput = () => { im.key = key.value; }; key.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") add(); else if (e.key === "Escape") cancelEdit(); }; const side = el("div", "side"); const eye = el("button", "text", t("Show")); eye.onclick = () => { const on = key.type === "password"; key.type = on ? "text" : "password"; eye.textContent = t(on ? "Hide" : "Show"); }; side.append(eye); if (p.keysUrl && !p.key) { const b = el("button", "link", t("Get a key ↗")); b.onclick = () => api("open", { url: p.keysUrl }); side.append(b); } const keyWrap = el("div", "pair"); keyWrap.append(key, side); ed.append(...field(t("API key"), keyWrap, p.key ? t("From the link. Kept in ~/.config/magpie/providers.json, readable by you alone.") : "")); ed.append(...field(t("Endpoints"), renderEndpoints(null, p), "")); if (p.models?.length) { const chips = el("div", "mchips"); for (const m of p.models) { const c = el("span", "mchip on", m); if (namedFree(m)) c.append(freeBadge(false)); chips.append(c); } ed.append(...field(t("Models"), chips, "")); } if (im.replaces) ed.append(el("div", "warnbox soft", t("Replaces your {name}, key and all.", { name: im.replaces }))); // The link may name the vendor's own logo — an explicit icon= wins over // whatever the catalog or preset gave. magpie fetches it here (the dialog // being open is the confirmation), once, quietly, and only ever into its // icons folder; the fallback mark stays when it fails. if (p.iconUrl) fetchImportIcon(p, h, ed); const addBtn = el("button", "text primary", t(im.replaces ? "Replace" : "Add")); const add = () => { const n = (im.name ?? p.name).trim(); if (!n) { name.focus(); return status(t("Give it a name"), "warn"); } saving(addBtn, t(im.replaces ? "Replacing…" : "Adding…")); providerAction("save", { ...p, name: n, key: (im.key ?? p.key ?? "").trim() }, t("{name} added", { name: n })); }; addBtn.onclick = add; bar.append(addBtn); ed.append(bar); setTimeout(() => (p.key ? addBtn : key).focus(), 0); return ed; } // Which of the vendor's models the agents get to see: click to toggle, type // to add one the vendor's list lacks, Fetch models to ask the vendor again. // The endpoints a provider serves, with a Test that reports against each one. function renderEndpoints(p, src) { const eps = el("div", "eps"); const slots = {}; const urls = src || {}; for (const [proto, label, hint] of PROTOS) { if (!urls[proto]) continue; const e = el("div", "ep"); const pl = el("span", "pl", label); pl.title = t(proto === "gemini" && draft?.vertex ? VERTEX_EP_HINT : hint); e.append(pl, el("code", "", urls[proto]), slots[proto] = el("span", "res")); eps.append(e); } if (p) { const test = el("button", "text action", t("Test")); test.title = t("Send a tiny request through each endpoint"); test.onclick = async () => { test.classList.add("busy"); for (const s of Object.values(slots)) { s.className = "res wait"; s.textContent = "…"; } try { const r = await api("provider/test", { ...asTyped(), id: p.id }); for (const x of r.results) { const s = slots[x.protocol]; if (!s) continue; s.className = "res " + (x.ok ? "ok" : "bad"); s.replaceChildren(); s.append(svg(x.ok ? CHECK : "M4.5 4.5l7 7M11.5 4.5l-7 7", 10, 2)); const result = x.ok ? ledTook(x.ms) : x.status ? `${x.status} · ${x.error}` : x.error; s.append(el("span", "", x.account ? t("Tested {user}: {result}", { user: x.account, result }) : result)); s.title = x.ok ? t("model {model}", { model: x.model }) : x.error; } } catch (e) { for (const s of Object.values(slots)) { s.className = "res"; s.textContent = ""; } status(e.message, "err"); } test.classList.remove("busy"); }; eps.append(test); } return eps; } // showRest: the button at the foot of a long model list that draws the // models left out of it (#685: "… 4 more, filter to find them" named none of // them, so there was nothing to filter by). It goes down with what it opens. function showRest(n, open) { const b = el("button", "text action mchips-rest", t("Show the other {n}", { n })); b.dataset.unrolls = ""; b.onclick = (e) => { e.preventDefault(); open(); }; return b; } // detectAPIs: which of the APIs magpie speaks to a vendor answer at the base // URL typed (01huadalang on Discord: 一键检测支持什么协议) — Detect sends // each the smallest request there, with the key typed (or the saved one) // and a model typed or picked from the vendor's list, and shows what each // answered; "Use these" takes those that answered for the provider. With // a model typed for a saved provider and only some APIs answering, that // model alone can be asked on one of them (staged with Names & levels). // "Each picked model" asks every model picked on each API (01huadalang: // 应该能看出来选择的模型支持情况…有的仅支持 response 有的双协议), a few at // a time, and shows model by API; its "Use these" also gives each model // that answered on one API only that API, staged as Names & levels does. // DETECT_MAX: the most models one detection asks (provider.DetectMax) const DETECT_MAX = 30; // addFormModels: the add form's models, typed in (ex) or picked from the // vendor's list, asked with the form as it stands before anything is saved // (#578: 添加供应商的时候,希望添加可以获取全模型的按钮或者下拉框). A chip // ticked or unticked is in draft.extra, which the Save sends as the models. function addFormModels(ex) { const box = el("div", "stack add-models"); const row = el("div", "detect-row"); const go = el("button", "text action fetch-models", t("Fetch models")); go.title = t("Ask the vendor for its model list with the URL and key typed, to pick from; nothing is saved"); row.append(ex, go); const out = el("div", "models add-models-list"); out.hidden = true; box.append(row, out); let listed = [], showAll = false; const q = input("", ""); q.classList.add("add-models-filter"); q.oninput = () => draw(); q.onkeydown = (e) => e.stopPropagation(); const chips = el("div", "mchips"); const acts = el("div", "detect-acts"); const sync = () => { ex.value = draft.extra.join(", "); }; const draw = () => { if (!listed.length) return; chips.replaceChildren(); const f = q.value.trim().toLowerCase(); let shown = 0, hidden = 0; const match = listed.filter((m) => !f || m.id.toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f)); for (const m of match) { const on = draft.extra.includes(m.id); // past the first 120 only the picked are drawn, till the rest are asked for if (shown >= 120 && !f && !showAll && !on) { hidden++; continue; } const c = el("button", "mchip" + (on ? " on" : "")); c.append(el("span", "", m.name || m.id)); if (m.name) c.title = m.id; c.dataset.model = m.id; c.onclick = (e) => { e.preventDefault(); draft.extra = on ? draft.extra.filter((x) => x !== m.id) : [...draft.extra, m.id]; sync(); draw(); }; chips.append(c); shown++; } if (hidden) chips.append(showRest(hidden, () => { showAll = true; draw(); })); if (f && !match.length) chips.append(el("span", "hint", t("No model here matches “{q}”.", { q: q.value.trim() }))); acts.replaceChildren(); const picked = draft.extra.filter((id) => listed.some((m) => m.id === id)).length; acts.append(el("span", "hint", t("{n} of {all} picked", { n: picked, all: listed.length }))); const all = el("button", "text action", t(f ? "Pick those shown" : "Pick all")); all.onclick = (e) => { e.preventDefault(); draft.extra = [...draft.extra, ...match.map((m) => m.id).filter((id) => !draft.extra.includes(id))]; sync(); draw(); }; const none = el("button", "text action", t("Pick none")); none.onclick = (e) => { e.preventDefault(); const ids = new Set(listed.map((m) => m.id)); draft.extra = draft.extra.filter((id) => !ids.has(id)); sync(); draw(); }; acts.append(all, none); }; go.onclick = async (e) => { e.preventDefault(); const body = { ...asTyped(), preset: draft.preset || "", name: draft.name || "" }; if (!body.chat && !body.responses && !body.anthropic && !body.modelsURL) { status(t("Type the base URL first"), "warn"); return; } go.classList.add("busy"); out.hidden = false; out.replaceChildren(el("span", "hint", t("Asking the vendor…"))); try { const r = await api("provider/list", body); listed = r?.models || []; out.replaceChildren(); if (!listed.length) { out.append(el("span", "hint", t("The vendor's list is empty. Type the model ids instead."))); return; } q.placeholder = t("filter {n} models…", { n: listed.length }); // the picks' count and Pick all / none above the chips, which a pick // can make a line longer or shorter, so they stay where they are if (listed.length > 24) out.append(q); out.append(acts, chips); draw(); } catch (err) { out.replaceChildren(el("span", "hint err", err.message)); } finally { go.classList.remove("busy"); } }; return { box, draw }; } function detectAPIs(p, base, use) { const box = el("div", "detect"); const row = el("div", "detect-row"); const go = el("button", "text action", t("Detect APIs")); go.title = t("Send the smallest request to each API (OpenAI chat completions, Responses, Anthropic messages, Gemini generateContent) at this URL, to see which answer"); const each = el("button", "text action detect-each", t("Each picked model")); each.title = t("Ask every model picked below on each API, to see which API serves which model (up to {n}, a few at a time)", { n: DETECT_MAX }); const model = input(draft.detectModel || "", t("model to try · empty picks one from the vendor's list")); model.classList.add("detect-model"); model.oninput = () => { draft.detectModel = model.value; }; model.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") go.click(); else if (e.key === "Escape") cancelEdit(); }; row.append(go, model, each); const out = el("div", "eps detect-out"); out.hidden = true; box.append(row, out); // the APIs by row: each one's URL and how it answered const byAPI = (results) => { for (const x of results) { const e = el("div", "ep"); e.dataset.api = x.protocol; const [, label, hint] = PROTOS.find(([k]) => k === x.protocol) || [x.protocol, x.protocol, ""]; const pl = el("span", "pl", label); pl.title = t(hint); const res = el("span", "res " + (x.ok ? "ok" : "bad")); res.append(svg(x.ok ? CHECK : CROSS, 10, 2)); const why = x.status ? `${x.status} · ${x.error}` : t(x.error || ""); res.append(el("span", "", x.ok ? ledTook(x.ms) : why)); res.title = (x.model ? t("model {model}", { model: x.model }) : "") + (x.ok ? "" : "\n" + why); e.append(pl, el("code", "", x.base || "—"), res); out.append(e); } }; // what is missing, or what went wrong, said here under the buttons // rather than in the toast at the top (#1545) const say = (msg, kind) => { out.hidden = false; out.replaceChildren(el("span", "hint detect-say " + kind, msg)); }; // the models the form has picked, saved or not: a new provider's typed // or ticked in its Models field (draft.extra), a saved one's chips with // the ids still in its add box const picked = () => p ? chosenIds() : (draft.extra || []).filter((id, i, all) => id && all.indexOf(id) === i); // no key typed, none saved and none copied: a refusal is likely the key const keyless = () => { if ((draft.key || "").trim() || p?.key?.set || draft.vertex) return false; const of = !p && draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf); return !of?.key?.set; }; const noneAnswered = () => el("span", "hint", keyless() ? t("None answered, and no API key is typed: paste the key under API key and detect again") : t("None answered: check the URL and the key, or type a model the vendor serves")); const ask = async (btn, extra) => { const typedBase = (base() || "").trim(); if (!typedBase && !(draft.chat || draft.responses || draft.anthropic || draft.gemini || "").trim()) { say(t("Type the base URL first"), "warn"); return null; } btn.classList.add("busy"); out.hidden = false; out.replaceChildren(el("span", "hint", t("Asking each API…"))); try { // the URL typed is asked as each API takes it, not as the field // holding it would send it; URLs given under More endpoints as they are. // The form as it stands is asked and nothing is saved: a saved // provider's key (or the copied one's) stands for a key not typed. const body = { ...asTyped(), id: p?.id, base: typedBase, ...extra }; if (!p && draft.copyOf) Object.assign(body, { new: true, copyOf: draft.copyOf }); for (const k of ["chat", "responses", "anthropic", "gemini"]) if (body[k] === typedBase) body[k] = ""; const r = await api("provider/detect", body); out.replaceChildren(); return r; } catch (e) { say(e.message, "err"); return null; } finally { btn.classList.remove("busy"); } }; go.onclick = async () => { const m = model.value.trim(); // no model typed: one of those the form has picked, else the vendor's const r = await ask(go, m ? { model: m } : { model: "", picked: picked().slice(0, DETECT_MAX) }); if (!r) return; byAPI(r.results); const ok = r.results.filter((x) => x.ok); const acts = el("div", "detect-acts"); if (!ok.length) acts.append(noneAnswered()); else { const take = el("button", "text action", t("Use these")); take.title = t("Set the URLs of the APIs that answered; one not found there is cleared"); take.onclick = () => { use(r.results); take.disabled = true; take.textContent = t("Taken · save to keep"); }; acts.append(take); // one model the provider serves, answering on some APIs only: // it can be asked on one of them alone const pm = p && m && p.models.find((x) => x.id === m); if (pm && ok.length < r.results.filter((x) => x.base).length) { for (const x of ok) { const label = apiLabel(x.protocol); const b = el("button", "text action", t("Ask {model} on {api} only", { model: m, api: label })); b.title = t("Staged in Names & levels and made with the Save; Auto there gives it back"); b.onclick = () => { stageAPI(pm, x.protocol); if (!draft[x.protocol]) use(r.results); for (const o of acts.querySelectorAll(".pick-api")) o.classList.toggle("on", o === b); draft.onModelPrefs?.(); status(t("{model} is asked on {api} once saved", { model: m, api: label }), "ok"); }; b.classList.add("pick-api"); acts.append(b); } } } out.append(acts); }; // a model's API staged in Names & levels: the one it has saved stages nothing const stageAPI = (pm, proto) => { const prefs = draft.modelPrefs = draft.modelPrefs || {}; const id = pm.id; prefs[id] = prefs[id] || {}; if ((pm.api || "") === proto) delete prefs[id].api; else prefs[id].api = proto; if (!Object.keys(prefs[id]).length) delete prefs[id]; }; each.onclick = async () => { if (draft.api === "decide") { say(t("A decision API is asked with one model: type it and press Detect APIs"), "warn"); return; } const ids = picked(); if (!ids.length) { say(t("Pick models first, or type one and press Detect APIs"), "warn"); return; } const r = await ask(each, { detectModels: ids }); if (!r) return; byAPI(r.results); // the APIs asked: those with a URL const asked = r.results.filter((x) => x.base).map((x) => x.protocol); const grid = el("div", "detect-grid"); grid.style.gridTemplateColumns = `minmax(0, 1.3fr) repeat(${asked.length}, minmax(0, 1fr))`; grid.append(el("span", "dg-head", t("Model")), ...asked.map((a) => el("span", "dg-head", apiLabel(a)))); // a model that answered on one API alone, of two or more asked, is // given that one by the Use these const only = {}; for (const md of r.models) { const name = el("code", "dg-model", md.model); name.title = md.model; grid.append(name); const okOn = []; for (const a of asked) { const x = md.results.find((y) => y.protocol === a) || {}; const cell = el("span", "dg-cell " + (x.ok ? "ok" : "bad")); cell.dataset.model = md.model; cell.dataset.api = a; cell.append(svg(x.ok ? CHECK : CROSS, 10, 2)); const why = x.status ? `${x.status} · ${x.error || ""}` : t(x.error || ""); cell.append(el("span", "", x.ok ? ledTook(x.ms) : why)); cell.title = `${md.model} · ${apiLabel(a)}\n` + (x.ok ? t("Answered in {took}", { took: ledTook(x.ms) }) : why); if (x.ok) okOn.push(a); grid.append(cell); } if (okOn.length === 1 && asked.length > 1) only[md.model] = okOn[0]; } out.append(grid); if (ids.length > r.models.length) out.append(el("span", "hint", t("Only the first {n} of {all} models were asked", { n: r.models.length, all: ids.length }))); const acts = el("div", "detect-acts"); if (!r.results.some((x) => x.ok)) acts.append(noneAnswered()); else { const take = el("button", "text action", t("Use these")); // only a saved provider's models are given an API; a new one's, in // Names & levels once it is saved const give = p ? Object.entries(only).map(([id, a]) => [p.models.find((x) => x.id === id), a]).filter(([pm]) => pm) : []; take.title = give.length ? t("Set the URLs of the APIs that answered, and give each model that answered on one API only that API (staged in Names & levels, made with the Save)") : t("Set the URLs of the APIs that answered; one not found there is cleared"); take.onclick = () => { for (const [pm, a] of give) stageAPI(pm, a); use(r.results); take.disabled = true; take.textContent = t("Taken · save to keep"); if (give.length) status(t("{n} models are asked on the one API that answered them once saved", { n: give.length }), "ok"); }; acts.append(take); if (give.length) acts.append(el("span", "hint", give.map(([pm, a]) => t("{model}: {api} only", { model: pm.id, api: apiLabel(a) })).join(" · "))); } out.append(acts); }; return box; } // modelTestWhy: why a provider's models can't each be sent a test request // (the server's providerJSON.modelTest), in words, or "" when they can function modelTestWhy(p) { if (p.modelTest === "decide") return t("A classifier's models aren't sent test requests: Test under Endpoints asks Jev's endpoint for them."); if (p.modelTest === "own-api") return t("{name} is reached through its own API, which magpie translates each agent request for, so a test request can't be sent to it on its own. Ask the model from an agent to try it.", { name: p.name }); return ""; } // modelTests: what each provider's models answered Test models, by id; a // model still being asked is null const modelTests = {}; // chosenIds: the models picked, with the ids still in the add box, which // a Save takes as if Enter had been pressed on them function chosenIds() { const typed = (draft.typed || "").split(/[,\s]+/).filter(Boolean); return [...draft.chosen, ...typed.filter((id) => !draft.chosen.includes(id))].filter((id, i, all) => all.indexOf(id) === i); } // noneChosen: Select none kept, with nothing picked (#1818): none of the // provider's models served, not to agents, not to routing groups, while its // balance and usage still show. Without it no picks is the vendor's list. const noneChosen = () => !!draft.none && !chosenIds().length; // servedIds: the models the provider serves as the editor has it: the // picks; none after Select none; else those the vendor's list serves const servedIds = (p) => draft.chosen.length ? draft.chosen : draft.none ? [] : p.models.filter((m) => m.on).map((m) => m.id); // modelsOpen: a provider editor's models let out to their full height // (#833), kept for the next editor opened. MCHIPS_MAX: the most the box is // tall held, as app.css's .mchips max-height: min(132px, 28vh) says let modelsOpen = false; const MCHIPS_MAX = 132; function renderModels(p) { // a chip's dot: how its model answered, when it has been asked const tested = (c, id) => { const got = modelTests[p.id]; if (!got || !(id in got)) return; const x = got[id]; c.append(el("span", "tdot " + (!x ? "wait" : x.ok ? "ok" : "bad"))); // the API it was asked on said, where the answer says (01huadalang: // 右键选择测试只能测试出是不是通的,不能说什么协议是通的) const via = x?.protocol ? apiLabel(x.protocol) : ""; c.title = !x ? t("Testing…") : x.ok ? (via ? t("Answered via {api} in {took}", { api: via, took: ledTook(x.ms) }) : t("Answered in {took}", { took: ledTook(x.ms) })) : (via ? via + " · " : "") + (x.status ? x.status + " · " : "") + x.error; }; // a chip's right-click (or the menu key) tests that model alone: Test models // asks every one, and a list of many takes a while (yonghe, Discord). A // signed-in account is tested as a key is; where no test request can be // sent the menu still opens, its item off and saying why (ARNO, Discord: // 有些provider里的模型可以右击检测,有些却不可以) const noTest = modelTestWhy(p); // the API a model is asked on, set beside its test (01huadalang: a // preset's or a subscription's model, not only a custom provider's): // staged as Names & levels stages it, and made with the Save const apis = modelAPIs(p); const apiNow = (id) => draft.modelPrefs?.[id]?.api ?? p.models.find((m) => m.id === id)?.api ?? ""; const pickAPI = (c, id) => { const m = p.models.find((x) => x.id === id) || { id }; const auto = (m.auto || []).map(apiLabel).join(" · "); const opts = [{ v: "", name: "Auto", note: auto ? t("As its vendor's list says: {apis}", { apis: auto }) : "Each API the provider has, as it answers" }, ...apis.map(([k, l, hint]) => ({ v: k, name: l, note: hint }))]; openProtoMenu(c, opts, apiNow(id), (v) => { if (v === apiNow(id)) return; const prefs = draft.modelPrefs = draft.modelPrefs || {}; prefs[id] = prefs[id] || {}; if (v === (m.api || "")) delete prefs[id].api; else prefs[id].api = v; if (!Object.keys(prefs[id]).length) delete prefs[id]; draw(); status(v ? t("{model} is asked on {api} once saved", { model: id, api: apiLabel(v) }) : t("{model} is asked as its vendor's list says once saved", { model: id }), "ok"); }, "API this model is asked on", "model-api-menu"); }; const menu = (c, id) => { // a decision model is asked a System One question where the server // says its API takes one (decideTest) const noTest = decidesModel(p, id) ? (p.decideTest ? "" : modelTestWhy({ modelTest: "decide" })) : modelTestWhy(p); if (!noTest) c.title = (c.title ? c.title + "\n" : "") + t("Right-click to test just this model"); c.oncontextmenu = (e) => { e.preventDefault(); const again = agentMenu?.anchor === c || protoMenu?.anchor === c; closeAgentMenu(); closeProtoMenu(); if (again) return; const acts = [noTest ? { name: "Test this model", icon: "M5.5 3.75v8.5L12.25 8z", off: true, why: noTest, run() {} } : { name: "Test this model", icon: "M5.5 3.75v8.5L12.25 8z", run: () => testOne(id) }]; // asked as Codex or Claude Code asks, for a relay that serves only // them (耍赖天都爱 on Discord); Claude Code's once it has come // through magpie, its headers being the ones it came with if (!noTest && !decidesModel(p, id)) { for (const [as, agent, name] of [["codex", "Codex", "Test as Codex"], ["claude-code", "Claude Code", "Test as Claude Code"]]) { if (!(as in (p.testsAs || {}))) continue; const why = p.testsAs[as] ? t(p.testsAs[as]) : ""; acts.push({ name, icon: "M5.5 3.75v8.5L12.25 8z", off: !!why, why, tip: t("Asked as {agent} asks, for a relay that serves only {agent}", { agent }), run: () => testOne(id, as) }); } } // its id as agents and the gateway name it, to paste where a model is // typed (ARNO, Discord: 右击菜单除了测试模型外,还能添加拷贝模型id的功能) acts.push({ name: "Copy model ID", icon: COPY_ICON, tip: id, run: () => copy(id, id, null, t("Model ID {model} copied", { model: id })) }); if (apis.length && !decidesModel(p, id)) { const now = apiNow(id); acts.push({ name: now ? t("Asked on {api}…", { api: apiLabel(now) }) : t("Asked on: Auto…"), icon: "M2.5 5h11M2.5 11h11M10.5 2.5 13.5 5l-3 2.5M5.5 8.5 2.5 11l3 2.5", tip: t("Pick the API this model is asked on"), run: () => pickAPI(c, id) }); } openRowMenu(c, acts); }; // the API it is asked on, when one is picked (or staged) const now = apis.length && !decidesModel(p, id) ? apiNow(id) : ""; if (now) { const tag = el("span", "badge mapi-tag", apiLabel(now)); tag.title = t("Asked on {api} alone; right-click to change", { api: apiLabel(now) }); c.append(tag); } }; const box = el("div", "models"); const chips = el("div", "mchips"); const names = el("div", "mnames"); names.dataset.provider = p.id; const q = p.models.length > 24 ? input("", t("filter {n} models…", { n: p.models.length })) : null; let showAll = false; // the chips are held to a few lines, scrolled within; a long list can be // let out to its full height and folded back (#833: 模型区域像 Agent 页面 // 一样支持展开 / 收起), as the Agents page's Show more is. Offered only // while the list is taller than those lines; kept open from one editor to // the next till folded const fold = el("button", "agent-more mchips-fold"); fold.dataset.unrolls = ""; // it goes down with the models it lets out const foldLabel = el("span", "", ""); const foldChev = el("span", "chev"); foldChev.append(svg(CHEV, 10, 1.8)); fold.append(foldLabel, foldChev); fold.onclick = (e) => { e.preventDefault(); modelsOpen = !modelsOpen; drawFold(); }; const drawFold = () => { chips.classList.toggle("open", modelsOpen); fold.setAttribute("aria-expanded", modelsOpen); foldLabel.textContent = t(modelsOpen ? "Collapse the list" : "Expand the list"); fold.title = t(modelsOpen ? "Hold the models to a few lines again" : "Show every model at once, not in a small box to scroll"); // laid out first: the editor is put on the page after it is drawn. // Held, the box is MCHIPS_LINES tall (app.css .mchips); open, it is as // tall as its chips, which must be more than that to fold requestAnimationFrame(() => { const most = Math.min(MCHIPS_MAX, innerHeight * 0.28); fold.hidden = !(chips.scrollHeight > (modelsOpen ? most : chips.clientHeight) + 1); }); }; const draw = () => { if (agentMenu && chips.contains(agentMenu.anchor)) closeAgentMenu(); chips.replaceChildren(); const f = (q?.value || "").trim().toLowerCase(); let shown = 0, hidden = 0; // with none picked agents are served the vendor's list, up to 24 of // it: those are drawn as served, not as left out (#614: the one model // unticked and saved was still "1 model" on the card). Kept for routing // groups alone, those are what the groups use (#1818: drawn as none // while the card and the auto groups had all 17); after Select none, // none is served const served = draft.chosen.length || decideOnly(p) || draft.none ? new Set() : new Set(p.models.slice(0, 24).map((m) => m.id)); // a filter is a search: what it doesn't match is left out, picked or not for (const m of p.models) { const on = draft.chosen.includes(m.id); if (f && !m.id.toLowerCase().includes(f) && !(m.name || "").toLowerCase().includes(f) && !(m.default || "").toLowerCase().includes(f)) continue; // past the first 80 only the picked are drawn, till the rest are // asked for: a picked model is never out of sight (#685: 10 picked, // 7 shown, and "4 more, filter to find them" with no names to filter by) if (shown >= 80 && !f && !showAll && !on) { hidden++; continue; } const c = el("button", "mchip" + (on ? " on" : served.has(m.id) ? " auto" : "")); c.append(el("span", "", m.name && m.name !== m.id ? m.name : m.id)); // one the plan serves at no cost to it (WorkBuddy's x0.00 credits) // or one its vendor names free (#185) const free = m.free || namedFree(m.id, m.name); if (free) c.append(el("span", "badge free", t("free"))); const rate = rateTag(m.rate, m.rateWas); if (rate) c.append(rate); const ctx = contextTag(m.context, m.name); if (ctx) c.append(ctx); if (m.default) c.title = `${m.id} · ${m.default}`; else if (m.name && m.name !== m.id) c.title = m.id; if (free) c.title = (c.title || m.id) + " · " + t(m.free ? "free: it doesn't use the plan's credits" : "free: so its name says"); if (served.has(m.id)) c.title = (c.title || m.id) + "\n" + t(draft.unlisted ? "Routing groups use it: none are picked, so the vendor's list is used" : "Agents see it: none are picked, so the vendor's list is used") + "\n" + t("Click to pick just this model"); tested(c, m.id); menu(c, m.id); // a click picks the model, a served one too: with none picked it // becomes the only pick. A served one clicked used to be left out, // the rest of what was served picked in its place, so a click on // the one model wanted ticked every other (#681) c.onclick = () => { draft.chosen = on ? draft.chosen.filter((x) => x !== m.id) : [...draft.chosen, m.id]; draw(); }; chips.append(c); shown++; } if (hidden) chips.append(showRest(hidden, () => { showAll = true; draw(); })); for (const id of draft.chosen) { if (p.models.some((m) => m.id === id) || (f && !id.toLowerCase().includes(f))) continue; const c = el("button", "mchip on own"); c.append(el("span", "", id)); c.title = t("Added by hand"); tested(c, id); menu(c, id); c.onclick = () => { draft.chosen = draft.chosen.filter((x) => x !== id); draw(); }; chips.append(c); } if (!p.models.length && !draft.chosen.length) chips.append(el("span", "hint", t("The vendor's list is empty. Fetch models again, or type a model id."))); // the list is of models agents chat with: image, embedding and speech // models are left out of it, and an image model is set in Settings else if (f && !chips.children.length) chips.append(el("span", "hint", t("No model here matches “{q}”. Image, embedding and speech models aren't listed, as agents can't chat with them: pick an image model in Settings → Images.", { q: q.value.trim() }))); drawNames(); drawFold(); drawWorkOn(); why.textContent = decideOnly(p) ? t("Agents never see them: a routing group picks one as its classifier.") : !draft.chosen.length && draft.none ? t("None selected: no agent or routing group uses its models. Its balance and usage still show. Click a model to pick it.") : draft.unlisted ? t(draft.chosen.length ? "Agents don't see them: only the routing groups they are in use them." : "Agents don't see them: the routing groups they are in use the vendor's list, up to {n} (dashed). Select none to use none of them.", { n: 24 }) : t(draft.chosen.length ? "Agents see the models picked." : "None picked: agents see the vendor's list, up to {n} (dashed). Click a model to pick just it, or Select none to use none of them while its balance and usage still show.", { n: 24 }); drawLost(); }; // those of its models in no routing group, while it is kept for groups: // nothing can use them, which is said here rather than left for the // reader to find them gone from every picker; each, once that is saved, // makes a group of itself at a click const drawLost = () => { lost.replaceChildren(); const ids = servedIds(p); const none = decideOnly(p) || !draft.unlisted ? [] : ids.filter((id) => !p.groups?.[id]?.length && !decidesModel(p, id)); lost.hidden = !none.length; if (!none.length) return; lost.append(t("In no routing group, so no agent can use them now: {models}.", { models: none.slice(0, 8).join(", ") + (none.length > 8 ? " …" : "") })); if (!p.unlisted) { lost.append(" " + t("Once saved, make a group of them in Routing.")); return; } for (const id of none.slice(0, 4)) { const b = el("button", "text action", t("Make a routing group of {model}", { model: id })); b.onclick = (ev) => { if (mode !== "window") api("window/main?view=routing&newgroup=" + encodeURIComponent(p.id + "/" + id), {}); else window.newGroupWith?.(p.id + "/" + id, "", ev); }; lost.append(b); } }; // the names and reasoning levels of the models agents see, and whether // they see images: staged in draft.modelPrefs and made with the editor's // Save, as the rest of it is, Cancel dropping them. Each tick used to be // saved on its own, every one rewriting the agents' files, so picking a // model's levels lagged a click behind (ARNO on Discord). const drawNames = () => { // drawn again, the list stays where it was scrolled to const top = names.scrollTop; names.replaceChildren(); names.hidden = naming !== p.id; if (names.hidden) return; // its own quiet title and a Fold where it opened (Hu9956, #868: the // only way to close it was the button under the list, out of sight // once it was open, and the editor read as one long run of settings) const head = el("div", "mnhead"); const fold = el("button", "text action", t("Fold")); fold.title = t("Fold Names & levels"); fold.onclick = (e) => { e.stopPropagation(); naming = null; rename.classList.remove("on"); drawNames(); rename.focus({ preventScroll: true }); }; head.append(el("b", "", t("Names & levels")), fold); names.append(head); const ids = servedIds(p); if (!ids.length) { names.append(el("span", "hint", t("Pick a model first."))); return; } const prefs = draft.modelPrefs = draft.modelPrefs || {}; draft.onModelPrefs = drawNames; // how the agents' lists will call them, and the setting that says so // (#868), above the names given here const sfx = el("div", "msuffix"); const sfxSaid = el("span", "hint"); const first = p.models.find((x) => x.id === ids[0]) || { id: ids[0], name: ids[0] }; const sayLabel = (mode) => { const name = prefs[first.id]?.name ?? (first.default ? first.name : ""); const base = name || first.default || first.name || first.id; let label = suffixed(base, p.name || p.id, !!name, mode); // a remote magpie's model, named there with its provider after it, // is that name alone when none is put after it here (ARNO on Discord) if (!name && first.plain && label === base) label = first.plain; sfxSaid.textContent = t("Agents’ lists show “{label}”", { label }); }; sayLabel(); sfx.append(el("span", "", t("Provider in model names")), suffixSegs(sayLabel), sfxSaid); sfx.append(noNamesLine("span", "said")); names.append(sfx); // the APIs a model can be asked on alone: those of a key's provider // it has a URL for, when it has more than one (01huadalang on Discord: // 一个 api 里有很多模型但是不同协议) const apis = modelAPIs(p); for (const id of ids) { const m = p.models.find((x) => x.id === id) || { id, name: id }; const own = m.default || m.name || m.id; // what is staged for it, and what it is saved as const pref = () => prefs[id] = prefs[id] || {}; const savedName = m.default ? m.name : ""; const levels = m.efforts || []; const savedKept = m.kept?.length || m.given ? m.kept || [] : levels; const nameNow = () => prefs[id]?.name ?? savedName; const keptNow = () => prefs[id]?.efforts ? (prefs[id].efforts.length || m.given ? prefs[id].efforts : levels) : savedKept; const imagesNow = () => prefs[id]?.ownImages ? !!m.ownImages : prefs[id]?.images ?? !!m.images; const row = el("div", "mname"); const name = input(nameNow(), own); name.title = t("The name agents and magpie show for {id}; empty for its own", { id: m.id }); name.onchange = () => { const v = name.value.trim(); if (v === savedName) delete pref().name; else pref().name = v; drawReset(); }; name.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") name.blur(); else if (e.key === "Escape") { name.value = nameNow(); name.blur(); } }; const who = el("div", "mwho"); who.append(name, el("code", "", m.id)); row.append(who); // the model of other providers' it is, for the routing groups magpie // finds, when its id is one no rule matches up with theirs // (Volcengine's deepseek-v4-1-flash-260910 and others' // deepseek-v4.1-flash, #583); empty merges it by its own id, which // the box shows as it is merged const sameNow = () => prefs[id]?.same ?? m.same ?? ""; const sameBox = el("label", "msame"); const same = input(sameNow(), m.merge || m.id); same.title = t("The model other providers serve that {id} is the same as: the routing groups magpie finds put them together. Empty: by its own id", { id: m.id }); same.spellcheck = false; same.onchange = () => { const v = same.value.trim(); if (v === (m.same || "")) delete pref().same; else pref().same = v; drawReset(); }; same.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") same.blur(); else if (e.key === "Escape") { same.value = sameNow(); same.blur(); } }; sameBox.append(el("span", "", t("Same as")), same); row.append(sameBox); // what it costs the user, in dollars per million tokens, as the // Usage page counts it (#819: only `magpie model price` set it): // each box shows its list price until a price is given, a part left // empty is the list's, and every part empty is its list price again // the 1-hour cache write, empty, is 2× input as Anthropic bills it, // and only a Claude model (or one priced with one) has the box: no // other vendor has 1-hour writes (PAMI on Discord); // a long-context price (OpenAI's over 272K) is what the whole request // costs when its input is over its size, empty parts its list's const parts = [["input", "Input"], ["output", "Output"], ["cache_read", "Cache read"], ["cache_write", "Cache write"], ["cache_write_1h", "Cache write 1h"]]; const tierParts = parts.slice(0, 4); const priceNow = () => prefs[id]?.ownPrice ? null : prefs[id]?.price ?? m.price ?? null; const shown = (n) => String(Math.round(n * 1e6) / 1e6); const listTier = m.list?.tiers?.[0]; const priceBox = el("div", "mprice"); // a Remote magpie's model is listed at what that magpie counts it at priceBox.title = m.remoteList ? t("What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: what the other magpie counts it at, shown greyed. A price set here isn't multiplied by the provider's price rate", { id: m.id }) : t("What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate", { id: m.id }); priceBox.append(el("span", "", t("Price, $ / 1M tokens"))); const typed = draft.priceTyped?.[id]; const cell = (value, placeholder, k, label) => { const i = input(value, placeholder); i.defaultValue = i.value; i.inputMode = "decimal"; i.dataset.part = k; i.setAttribute("aria-label", label); i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") i.blur(); }; i.onchange = () => takePrice(); return i; }; const oneHour = (pr) => pr ? pr.cache_write_1h || 2 * pr.input : 0; const cells = parts.map(([k, l], n) => { const box = el("label", "mpart"); const pr = priceNow(); const value = typed ? typed[n] : !pr ? "" : k === "cache_write_1h" ? pr.cache_write_1h ? shown(pr.cache_write_1h) : "" : shown(pr[k]); const placeholder = !m.list ? "" : k === "cache_write_1h" ? shown(oneHour(m.list)) : shown(m.list[k]); const i = cell(value, placeholder, k, t(l)); if (k === "cache_write_1h") { box.title = t("A cache write kept for an hour, as Anthropic bills it; empty: 2× input"); box.hidden = !/claude/i.test(m.id) && !m.list?.cache_write_1h && !pr?.cache_write_1h && !(typed && typed[n]); } box.append(el("span", "", t(l)), i); priceBox.append(box); return i; }); // the long-context price, a quiet row of its own: shown where there is // one, else behind a link const tierRow = el("div", "mtier"); tierRow.title = t("What the whole request costs when its input — cached tokens and cache writes included — is over this many tokens, as OpenAI bills gpt-6-astra over 272K; empty: the list's"); const tierNow = () => priceNow()?.tiers?.[0]; const above = cell(typed ? typed[parts.length] : tierNow() ? tokenSize(tierNow().above) : "", listTier ? tokenSize(listTier.above) : "272K", "above", t("Over input tokens")); above.classList.add("mabove"); const overBox = el("label", "mpart"); overBox.append(el("span", "", t("Long-context price, over")), above); tierRow.append(overBox); const tierCells = tierParts.map(([k, l], n) => { const box = el("label", "mpart"); const i = cell(typed ? typed[parts.length + 1 + n] : tierNow() ? shown(tierNow()[k]) : "", listTier ? shown(listTier[k]) : "", "tier_" + k, t("Long-context price") + " · " + t(l)); box.append(el("span", "", t(l)), i); tierRow.append(box); return i; }); const moreTier = el("button", "text action mtier-add", t("Long-context price")); moreTier.title = tierRow.title; let tierOpen = false; moreTier.onclick = (e) => { e.preventDefault(); tierOpen = true; drawTier(); above.focus({ preventScroll: true }); }; const drawTier = () => { tierRow.hidden = !tierOpen && !tierNow() && !listTier; moreTier.hidden = !tierRow.hidden; }; priceBox.append(moreTier, tierRow); drawTier(); const showPrice = () => { const pr = priceNow(); cells.forEach((c, i) => { const k = parts[i][0]; c.value = !pr ? "" : k === "cache_write_1h" ? pr.cache_write_1h ? shown(pr.cache_write_1h) : "" : shown(pr[k]); }); const tr = tierNow(); above.value = tr ? tokenSize(tr.above) : ""; tierCells.forEach((c, i) => { c.value = tr ? shown(tr[tierParts[i][0]]) : ""; }); drawTier(); }; const takePrice = () => { const v = cells.map((c) => c.value.trim()); const tv = [above, ...tierCells].map((c) => c.value.trim()); const x = pref(); delete x.price; delete x.ownPrice; if (draft.priceTyped) delete draft.priceTyped[id]; if (v.every((s) => s === "") && tv.every((s) => s === "")) { if (m.price) x.ownPrice = true; drawReset(); return; } const bad = (msg) => { status(msg, "err"); showPrice(); drawReset(); }; const price = {}; for (const [i, [k]] of tierParts.entries()) { const n = v[i] === "" ? m.list?.[k] ?? (k.startsWith("cache") ? 0 : NaN) : decimalOf(v[i]); // a model with no list price is given its input and output one // box at a time: what is typed stays, waiting for the other, and // the Save asks for it (PAMI on Discord: each box typed was // emptied again, so a price could never be set) if (Number.isNaN(n) && v[i] === "" && v.every((s) => s === "" || decimalOf(s) >= 0)) { (draft.priceTyped = draft.priceTyped || {})[id] = [...v, ...tv]; status(t("{id} has no list price: give its input and output prices", { id: m.id }), "warn"); drawReset(); return; } if (!Number.isFinite(n) || n < 0) return bad(Number.isNaN(n) && v[i] === "" ? t("{id} has no list price: give its input and output prices", { id: m.id }) : t("A price is a number of dollars, 0 or more")); price[k] = n; } if (v[4] !== "") { const n = decimalOf(v[4]); if (!(n >= 0)) return bad(t("A price is a number of dollars, 0 or more")); if (n > 0) price.cache_write_1h = n; } // the long-context price: its parts typed, else the list's, else the // price's own; none typed, the list's as it is const from = tierNow() || listTier; if (tv.some((s) => s !== "")) { const size = tv[0] === "" ? from?.above : tokensTyped(tv[0]); if (!(size > 0)) return bad(t("A long-context price starts over a number of input tokens, like 272K")); const tier = { above: size }; for (const [i, [k]] of tierParts.entries()) { const n = tv[i + 1] === "" ? from?.[k] ?? price[k] : decimalOf(tv[i + 1]); if (!(n >= 0)) return bad(t("A price is a number of dollars, 0 or more")); tier[k] = n; } price.tiers = [tier, ...((priceNow() || m.list)?.tiers || []).slice(1).filter((x) => x.above > size)]; } else if (m.list?.tiers?.length) price.tiers = m.list.tiers; if (!m.price || !samePrice(m.price, price)) x.price = price; showPrice(); drawReset(); }; row.append(priceBox); const [img, imgCb] = tick(t("Accepts images"), imagesNow()); img.title = t("Whether agents are told {id} can see images", { id: m.id }); imgCb.onchange = () => { const x = pref(); delete x.ownImages; if (imgCb.checked === !!m.images) delete x.images; else x.images = imgCb.checked; drawReset(); }; row.append(img); const apiNow = () => prefs[id]?.api ?? m.api ?? ""; let apiSeg = null; if (apis.length || m.api) { const items = [["", t("Auto")], ...apis.map(([k, l]) => [k, l])]; if (m.api && !items.some(([k]) => k === m.api)) items.push([m.api, (PROTOS.find(([k]) => k === m.api) || [])[1] || m.api]); apiSeg = segs(items, apiNow(), (v) => { if (v === (m.api || "")) delete pref().api; else pref().api = v; drawReset(); }); apiSeg.classList.add("mapi"); apiSeg.title = t("The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only", { id: m.id }); for (const [i, b] of [...apiSeg.querySelectorAll(".opt")].entries()) { b.dataset.api = items[i][0]; if (items[i][0]) b.title = t((PROTOS.find(([k]) => k === items[i][0]) || [])[2] || ""); } row.append(apiSeg); } // a model whose levels aren't known (m.given) can be given any // of them, and none again const boxes = []; if (levels.length > 1) { const lv = el("div", "mlevels"); lv.title = t(m.given ? "Its reasoning levels aren't known: tick the ones it takes" : "Reasoning levels agents are offered"); for (const l of levels) { const [tk, cb] = tick(t(l), keptNow().includes(l)); cb.onchange = () => { const kept = keptNow(); const next = levels.filter((x) => x === l ? cb.checked : kept.includes(x)); if (!next.length && !m.given) { cb.checked = true; status(t("Keep at least one level"), "err"); return; } const all = next.length === levels.length && !m.given; if (all ? !m.kept?.length : next.join() === savedKept.join()) delete pref().efforts; else pref().efforts = all ? [] : next; drawReset(); }; boxes.push([l, cb]); lv.append(tk); } row.append(lv); } // what the Save will make of it differs from what it is: said beside // it, so a change not yet saved isn't taken for one made const unsaved = el("span", "hint munsaved", t("unsaved")); unsaved.title = t("Made when the provider is saved; Cancel drops it"); const reset = el("button", "text action", t("Restore default")); reset.title = t("Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price"); reset.onclick = () => { prefs[id] = {}; if (draft.priceTyped) delete draft.priceTyped[id]; if (m.default) prefs[id].name = ""; if (m.kept?.length) prefs[id].efforts = []; if (m.imageSet) prefs[id].ownImages = true; name.value = nameNow(); imgCb.checked = imagesNow(); for (const [l, cb] of boxes) cb.checked = keptNow().includes(l); if (m.api) prefs[id].api = ""; if (m.same) prefs[id].same = ""; same.value = sameNow(); if (m.price) prefs[id].ownPrice = true; showPrice(); if (apiSeg) { for (const b of apiSeg.querySelectorAll(".opt")) b.classList.toggle("on", b.dataset.api === apiNow()); slide(apiSeg, "api"); } drawReset(); }; const drawReset = () => { const x = prefs[id]; if (x && !Object.keys(x).length) delete prefs[id]; unsaved.hidden = !prefs[id] && !draft.priceTyped?.[id]; // staged back to its own already, there is nothing to restore const images = prefs[id]?.ownImages ? false : prefs[id]?.images !== undefined ? prefs[id].images !== !!m.ownImages : !!m.imageSet; const custom = nameNow() !== "" || (prefs[id]?.efforts ? prefs[id].efforts.length > 0 : !!m.kept?.length) || images || apiNow() !== "" || sameNow() !== "" || priceNow() !== null || !!draft.priceTyped?.[id]; reset.hidden = !custom; }; row.append(unsaved, reset); drawReset(); names.append(row); } names.scrollTop = top; }; // every model at once (those the filter shows, when there is one), or none const bulk = el("div", "mbulk"); const allOn = el("button", "text action", t("Select all")); allOn.title = t("Pick every model listed (those the filter shows)"); allOn.onclick = () => { const f = (q?.value || "").trim().toLowerCase(); const ids = p.models.filter((m) => !f || m.id.toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f) || (m.default || "").toLowerCase().includes(f)).map((m) => m.id); draft.chosen = [...draft.chosen, ...ids.filter((id) => !draft.chosen.includes(id))]; draw(); }; const allOff = el("button", "text action", t("Select none")); allOff.title = t("Unpick every model"); allOff.onclick = () => { draft.chosen = []; draft.none = true; draw(); }; bulk.append(allOn, allOff); // just the free ones (Discord: 是否可以支持只选择免费模型), offered only // when the list has both free and paid models: with none free it would // pick nothing, with all free it is Select all const isFree = (m) => m.free || namedFree(m.id, m.name); if (p.models.some(isFree) && !p.models.every(isFree)) { const freeOn = el("button", "text action", t("Free only")); freeOn.title = t("Pick only the free models (those the filter shows), unpicking the others"); freeOn.onclick = () => { const f = (q?.value || "").trim().toLowerCase(); draft.chosen = p.models.filter((m) => isFree(m) && (!f || m.id.toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f) || (m.default || "").toLowerCase().includes(f))).map((m) => m.id); draw(); }; bulk.append(freeOn); } // the picks that answered Test models (H20 on Discord: 测试完很多不可用, // 只能一个个取消): those whose last test failed are unpicked, the rest // stay, an untested one too, as nothing says it doesn't work. Offered // once a test has answered; with none picked, the served list it tested // stands in for the picks const workOn = el("button", "text action works-only", t("Working only")); const failedPicks = () => { const got = modelTests[p.id] || {}; const ids = servedIds(p); return [ids, ids.filter((id) => got[id] && !got[id].ok)]; }; workOn.onclick = () => { const [ids, bad] = failedPicks(); if (!bad.length) return; draft.chosen = ids.filter((id) => !bad.includes(id)); draw(); status(t(bad.length === 1 ? "Unpicked 1 model that didn't answer" : "Unpicked {n} models that didn't answer", { n: bad.length }), "ok"); }; const drawWorkOn = () => { // in the row only once a test has answered, not there hidden till then if (!Object.values(modelTests[p.id] || {}).some((x) => x)) { workOn.remove(); return; } if (!workOn.isConnected) bulk.append(workOn); const bad = failedPicks()[1].length; workOn.disabled = !bad; workOn.title = bad ? t("Unpick the models whose last test failed; those that answered, and those not tested, stay picked") : t("Every picked model that was tested answered"); }; if (q || p.models.length > 1) { if (q) { q.oninput = draw; bulk.prepend(q); } box.append(bulk); } box.append(chips, fold, names); const foot = el("div", "mfoot"); // a model the vendor's list leaves out is added by its id (Tom on X asked // for this, not seeing the box alone was for it): typed, then Enter or Add const add = input(draft.typed || "", t("add a model id…")); const addOne = el("button", "text action", t("Add model")); addOne.title = t("Add a model the list doesn't have, by its id (several: comma separated)"); addOne.disabled = !add.value.trim(); const take = () => { if (!add.value.trim()) return; draft.chosen = chosenIds(); draft.typed = add.value = ""; addOne.disabled = true; draw(); }; addOne.onclick = take; add.oninput = () => { draft.typed = add.value; addOne.disabled = !add.value.trim(); }; add.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") take(); else if (e.key === "Escape") cancelEdit(); }; // named as the add form's Fetch models is, the button there before the // Save (耍赖天都爱 on Discord: 模型拉取一次就没有这个按钮了 — a key moved // to another group on a relay serves another list), and "again" once a // list was fetched. It asks with the key typed (asTyped), and merges as // Refetch does: picks the new list lacks go, ids added by hand stay const refresh = el("button", "text action fetch-models", t(p.fetched ? "Fetch models again" : "Fetch models")); refresh.title = t("Ask the vendor for its model list with the key typed here, and again after the key moves to another group: picks it no longer lists are dropped, ids added by hand stay"); refresh.onclick = async () => { refresh.classList.add("busy"); try { const r = await api("provider/models", { ...asTyped(), id: p.id }); status(t("{p}: {n} models", { p: p.name, n: r.count }), "ok"); // picks the vendor no longer lists were dropped from the saved // provider: out of this editor's draft too, if it is still this // provider's, or its Save put them back if (r.dropped?.length && editing === p.id && draft) draft.chosen = draft.chosen.filter((x) => !r.dropped.includes(x)); // the redraw keeps the editor's draft, the picks in it with it: none // are put back by hand, which put them in whichever editor was open // by then, another provider's too (#464) await loadProviders(); } catch (e) { status(e.message, "err"); refresh.classList.remove("busy"); } }; // each model the agents see gets a tiny request of its own: a vendor // that answers can still have a model that doesn't const testAll = el("button", "text action", t("Test models")); testAll.title = t("Send a tiny request to each model agents see, to find the ones that don't answer") + "\n" + t("Right-click a model to test just it"); testAll.onclick = async () => { const ids = servedIds(p).filter((id) => p.decideTest || !decidesModel(p, id)); if (!ids.length) { status(t("Pick a model first."), "err"); return; } testAll.classList.add("busy"); const got = modelTests[p.id] = {}; for (const id of ids) got[id] = null; draw(); try { const r = await api("provider/test", { ...asTyped(), id: p.id, test: ids }); r.results.forEach((x, i) => { got[ids[i]] = x; }); const bad = r.results.filter((x) => !x.ok).length; status(bad ? t("{n} of {all} models didn't answer", { n: bad, all: ids.length }) : t("All {n} models answered", { n: ids.length }), bad ? "err" : "ok"); } catch (e) { delete modelTests[p.id]; status(e.message, "err"); } testAll.classList.remove("busy"); draw(); }; // one model, its dot and title as Test models leaves them, the others' // results kept const testOne = async (id, as) => { const got = modelTests[p.id] = modelTests[p.id] || {}; got[id] = null; draw(); try { const r = await api("provider/test", { ...asTyped(), id: p.id, test: [id], ...(as ? { as } : {}) }); const x = got[id] = r.results[0]; const via = x.protocol ? apiLabel(x.protocol) : ""; const error = (x.status ? x.status + " · " : "") + x.error; status(x.ok ? (via ? t("{model} answered via {api} in {took}", { model: id, api: via, took: ledTook(x.ms) }) : t("{model} answered in {took}", { model: id, took: ledTook(x.ms) })) : via ? t("{model} didn't answer via {api}: {error}", { model: id, api: via, error }) : t("{model} didn't answer: {error}", { model: id, error }), x.ok ? "ok" : "err"); } catch (e) { delete got[id]; status(e.message, "err"); } draw(); }; const rename = el("button", "text action" + (naming === p.id ? " on" : ""), t("Names & levels")); rename.title = t("Rename the models agents see, or offer fewer of their reasoning levels"); rename.onclick = () => { naming = naming === p.id ? null : p.id; rename.classList.toggle("on", naming === p.id); drawNames(); }; foot.append(add, addOne, refresh); if (noTest) { testAll.disabled = true; testAll.title = noTest; } foot.append(testAll); foot.append(rename); // a plugin's list that failed is its defaults, not the vendor's if (p.fetched && !p.listError) foot.append(el("span", "hint", t("vendor list · {when}", { when: ago(p.fetched) }))); // a signed-in account's list, until the vendor gives one, is magpie's own else if (p.models.length) foot.append(el("span", "hint", t(p.account ? "magpie's list · Fetch models asks the vendor" : decideOnly(p) ? "Jev's names · Fetch models asks the vendor" : "from models.dev · Fetch models asks the vendor"))); if (p.fetched && !p.account) { // the fetched list stands in for the picks when none are made const forget = el("button", "text action", t("Forget")); forget.title = t("Drop the list fetched from the vendor; the models.dev one is used until models are fetched again"); forget.onclick = async () => { forget.classList.add("busy"); try { await api("provider/unfetch", { id: p.id }); await loadProviders(); } // the picks stay in the draft, as on a Fetch models catch (e) { status(e.message, "err"); forget.classList.remove("busy"); } }; foot.append(forget); } box.append(foot); // a plugin whose list failed shows its defaults (Cursor's Auto alone): // why, rather than a short list that looks like the account's if (p.listError) box.append(el("div", "hint model-hint warn list-error", t("{p} couldn't list its models: {error}", { p: p.name, error: p.listError }))); const why = el("div", "hint"); const [tk, cb] = tick(t("Only through routing groups"), !!draft.unlisted); cb.onchange = () => { draft.unlisted = cb.checked; draw(); }; tk.title = t("Its models leave the list agents pick from; the routing groups they are in still use them"); if (!decideOnly(p)) box.append(tk); const lost = el("div", "hint model-hint warn"); box.append(why, lost); draw(); return box; } // renderDrawers: the provider's image models. Agents don't chat with them, // so they aren't among its Models; they are listed to say they are there, // and one is picked in Settings → Images. function renderDrawers(p) { const chips = el("div", "mchips"); for (const id of p.drawIds) chips.append(el("span", "mchip ro", id)); return field(t("Image models"), chips, t("Agents don't chat with these, so they aren't among its models: the one that draws is picked in Settings → Images.")); } // renderRouting: how the gateway spreads requests over the keys or // accounts a provider has on, and how long a conversation stays with the // one that answered it. Both are staged in the editor's draft (routing, // affinity) and made with its Save, as the rest of the editor is: a click // shows the option and what it does, nothing is sent or redrawn, and // Cancel drops it (01huadalang on Discord: each click saved and redrew, // so looking through what each says lagged). const ROUTINGS = [ ["", "Smart", "The first takes requests while it has quota to spare; when it runs low, the one with the most left takes over. One out of credit sits out half an hour, one out of quota until it resets, one rate limited as long as the vendor asks, and one that fails a minute, longer each time it fails again."], ["order", "In order", "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails."], ["rotate", "In turn", "Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests."], ["usage", "Least used first", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours."], ["pace", "Weekly pace", "Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours."], ["weight", "By weight", "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says."], ]; // weight is a key's share: offered for a provider with keys only const routingsOf = (p) => p.account ? ROUTINGS.filter(([id]) => id !== "weight") : ROUTINGS; // as on the Routing page's list of these (routing.js AFF_OPTS) const STAYS = [ ["", "Auto", "A conversation stays with the account or key that answered it while what the vendor cached of it is worth keeping — within a turn always, across turns while it's fresh."], ["session", "Session", "A conversation stays with the account or key that answered it for the whole session, while it can answer."], ["turn", "Within a turn", "A conversation stays put within a turn, while the agent sends tool results back; when you speak again, routing decides afresh."], ["off", "Off", "Every request is routed afresh, whoever answered its conversation before."], ["strict", "Strict", "A conversation stays with the account or key that answered it and never moves to another, even past its usage cap: when that one is rate limited or out of quota, the error goes to the agent. New conversations are routed as usual."], ]; // what one rate limited while it still has quota does then (provider.Sink, // 01huadalang): keeps its place, back first once its rest ends, or goes to // the back of the order so the load goes round — as on the Routing page // (routing.js SINK_OPTS) const SINKS = [ [false, "Keeps its place", "One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again."], [true, "Goes to the back", "One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts."], ]; // routingOfDraft: what the editor's Save sends of them — only what was // picked and differs from what is saved function routingOfDraft(p) { const out = {}; if (draft?.routing !== undefined && draft.routing !== (p.routing || "")) out.routing = draft.routing; if (draft?.affinity !== undefined && draft.affinity !== (p.affinity || "")) out.affinity = draft.affinity; if (draft?.sink !== undefined && draft.sink !== !!p.sink) out.sink = draft.sink; return out; } function renderRouting(p) { const routingNow = () => draft.routing ?? (p.routing || ""); const affinityNow = () => draft.affinity ?? (p.affinity || ""); const sinkNow = () => draft.sink ?? !!p.sink; // what Codex or Claude Code sends past magpie goes to the account it is // signed in to, which magpie moves on once Smart would count it spent // and back once the first has room (provider.KeepOnAnAccountWithRoom, // #209, #408) const a = p.account; // — at 98%, In order once used up (#530), never when kept on the first (#524) const own = (routing) => !a || (a.agent !== "codex" && a.agent !== "claude") ? "" : " " + (keptLogin(p) ? t("Routing picks the account for each request through magpie, in the accounts' order; {agent} on its own stays signed in to {user}, whatever it has left.", { agent: a.agentName, user: keptLogin(p) }) : p.keepLogin ? t("Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.", { agent: a.agentName }) : routing === "order" ? t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.", { agent: a.agentName }) : t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and back to the first once that has room again.", { agent: a.agentName })); // what the Save will make of it differs from what it is: said beside it const unsaved = () => { const u = el("span", "hint munsaved", t("unsaved")); u.title = t("Made when the provider is saved; Cancel drops it"); return u; }; const rHint = el("div", "hint"), rUnsaved = unsaved(); const drawRouting = () => { const cur = ROUTINGS.find(([id]) => id === routingNow()) || ROUTINGS[0]; rHint.textContent = t(cur[2]) + own(cur[0]); rUnsaved.hidden = routingNow() === (p.routing || ""); // in turn and by weight go round already kLabel.hidden = kWrap.hidden = routingNow() === "rotate" || routingNow() === "weight"; // each key's weight shows beside it while the routing is by weight for (const l of document.querySelectorAll(".accts.keys")) if (l.dataset.provider === p.id) l.classList.toggle("weighted", routingNow() === "weight"); }; const rPick = segs(routingsOf(p).map(([id, name]) => [id, t(name)]), routingNow(), (routing) => { draft.routing = routing; drawRouting(); }); const rRow = el("div", "route-pick"); rRow.append(rPick, rUnsaved); const rWrap = el("div"); rWrap.append(rRow, rHint); const kHint = el("div", "hint"), kUnsaved = unsaved(); const drawSink = () => { kHint.textContent = t(SINKS[sinkNow() ? 1 : 0][2]); kUnsaved.hidden = sinkNow() === !!p.sink; }; const kPick = segs(SINKS.map(([on, name]) => [on ? "sink" : "", t(name)]), sinkNow() ? "sink" : "", (v) => { draft.sink = v === "sink"; drawSink(); }); kPick.classList.add("sink-pick"); const kRow = el("div", "route-pick"); kRow.append(kPick, kUnsaved); const kWrap = el("div", "sink-wrap"), kLabel = el("label", "", t("Rate limited")); kWrap.append(kRow, kHint); const sHint = el("div", "hint"), sUnsaved = unsaved(); const drawStays = () => { const cur = STAYS.find(([id]) => id === affinityNow()) || STAYS[0]; sHint.textContent = t(cur[2]); sUnsaved.hidden = affinityNow() === (p.affinity || ""); }; const sPick = segs(STAYS.map(([id, name]) => [id, t(name)]), affinityNow(), (affinity) => { draft.affinity = affinity; drawStays(); }); const sRow = el("div", "route-pick"); sRow.append(sPick, sUnsaved); const sWrap = el("div"); sWrap.append(sRow, sHint); drawRouting(); drawSink(); drawStays(); return [el("label", "", t("Routing")), rWrap, kLabel, kWrap, el("label", "", t("Stays")), sWrap]; } // renderFallback: where requests go when this provider can't take them — // out of quota, rate limited, overloaded or down — tried top to bottom. function renderFallback(p) { const box = el("div", "fallback"); const list = el("div", "fbl"); const sugg = el("div", "mchips"); const q = input("", t("add a model: filter, or type provider/model…")); const all = []; for (const o of providers.providers) { if (!o.ready || o.off) continue; for (const m of o.models) if (m.on) all.push({ id: o.id + "/" + m.id, label: o.name + " · " + (m.name || m.id), icon: o.icon }); } let open = false; const add = (id) => { if (id && !draft.fallback.includes(id)) draft.fallback.push(id); q.value = ""; draw(); }; const draw = () => { list.replaceChildren(); draft.fallback.forEach((id, i) => { const known = all.find((x) => x.id === id); const row = el("div", "fbrow"); row.append(el("span", "i", String(i + 1)), icon(known?.icon || "generic"), el("span", "n", known ? known.label : id), el("span", "grow")); if (!known) row.title = t("No provider serves {id} now; it is skipped", { id }); if (i) { const up = el("button", "text", t("Up")); up.onclick = () => { draft.fallback.splice(i - 1, 0, draft.fallback.splice(i, 1)[0]); draw(); }; row.append(up); } const rm = el("button", "text", t("Remove")); rm.onclick = () => { draft.fallback.splice(i, 1); draw(); }; row.append(rm); list.append(row); }); sugg.replaceChildren(); if (!open && !q.value.trim()) return; const f = q.value.trim().toLowerCase(); const hits = all.filter((x) => !draft.fallback.includes(x.id) && !x.id.startsWith(p.id + "/") && (x.id + " " + x.label).toLowerCase().includes(f)); for (const x of hits.slice(0, 12)) { const c = el("button", "mchip"); c.append(el("span", "", x.label)); c.title = x.id; c.onmousedown = (e) => e.preventDefault(); // keep the box focused c.onclick = () => add(x.id); sugg.append(c); } // only the first dozen are drawn: the rest are said to be there if (hits.length > 12) sugg.append(el("span", "hint", t("{n} more — type to narrow", { n: hits.length - 12 }))); if (!hits.length && f) sugg.append(el("span", "hint", f.includes("/") ? t("Enter adds {id}", { id: q.value.trim() }) : t("No model matches"))); }; q.onfocus = () => { open = true; draw(); }; q.onblur = () => { open = false; draw(); }; q.oninput = draw; q.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter" && q.value.trim()) add(q.value.trim().includes("/") ? q.value.trim() : sugg.querySelector(".mchip")?.title); else if (e.key === "Escape") cancelEdit(); }; box.append(list, q, sugg); draw(); return box; } function fallbackHint(p) { return t("When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.", { name: p.name }); } // ---------- subscriptions ---------- // // A Claude or ChatGPT subscription is added here, not in a terminal: magpie // opens the vendor's own sign-in in the browser, takes the account when it // comes back, and lists it with the others — any of them one click from // being the one in use. // // Some of these are deprecated: once moved onto their community plugin // (providers.onPlugins, the default for a new sign-in), the plugin signs in // and serves them, and subOf hands back the plugin's sign-in. A change to // such a built-in's sign-in on the Go side doesn't reach those users; see // AGENTS.md (PLUGIN-SERVED). const SUBS = [ // both can also come from CLIProxyAPI's auth files or the agent's own (importing below) // Anthropic has banned accounts it saw used from other tools: said before one is added { agent: "claude", name: "Claude", icon: "claude-color", plans: "Pro · Max · Team", importable: true, risk: true, riskNote: "Anthropic may suspend or ban a Claude account it sees used outside its own apps. magpie sends requests through Claude Code, but Anthropic may still act on them; you use it at your own risk. Use an account you can afford to lose." }, { agent: "codex", name: "ChatGPT", icon: "openai", plans: "Plus · Pro · Business", importable: true }, // OpenAI's Sign in with ChatGPT: the plan asked on api.openai.com, with the agent's own instructions (#933) { agent: "chatgpt-api", name: "ChatGPT API", icon: "openai", plans: "Plus · Pro · Business", own: true, hint: "Sign in with ChatGPT: your plan on OpenAI's own API, with your agent's own instructions rather than Codex's." }, // cursor-agent keeps one account; signing in again replaces it { agent: "cursor", name: "Cursor", icon: "cursor", plans: "Pro · Ultra · Teams", single: true }, // so does Grok Build { agent: "grok", name: "Grok (SuperGrok)", icon: "xai", plans: "SuperGrok · X Premium+", own: true }, // signed in with GitHub's device code; the editors' own sign-in stays theirs { agent: "copilot", name: "Copilot", icon: "githubcopilot", plans: "Free · Education · Pro · Pro+ · Max · Business · Enterprise", own: true }, // Z.ai's GLM Coding Plan, signed in as ZCode does; ZCode's own account is read too // sites: where the account is, Z.ai's or BigModel's (智谱), asked before // the sign-in opens; a team's plan (团队套餐) is signed in on its site too { agent: "zcode", name: "ZCode (GLM Coding Plan)", icon: "zcode", plans: "Lite · Pro · Max · Team", own: true, sites: [["zai", "Z.ai", "z.ai"], ["bigmodel", "BigModel (智谱)", "bigmodel.cn"]] }, // Tencent's CodeBuddy plan, signed in as WorkBuddy does; WorkBuddy's own account is read too { agent: "workbuddy", name: "WorkBuddy (CodeBuddy)", icon: "workbuddy-color", plans: "Free · Pro", own: true }, // the same plan sold abroad, WorkBuddy AI (workbuddy.ai / codebuddy.ai), its accounts its own { agent: "workbuddy-ai", get name() { return t("WorkBuddy AI (international)"); }, icon: "workbuddy-color", plans: "Free · Pro", own: true }, // a commandcode.ai plan, signed in as its CLI does; the CLI's own key is read too // a Go plan is asked at the CLI's private /alpha/generate, which Command Code // said on X may get an account banned when used from other tools { agent: "commandcode-plan", name: "Command Code", icon: "commandcode", plans: "Go · Pro · GOAT · Max · Ultra", own: true, risk: true, riskNote: "A Go plan account is used through Command Code's private interface, which Command Code may treat as a breach of its terms and ban the account for. Pro, Max and the other plans use its Provider API. Use a Go account you can afford to lose." }, // Qoder's two sites: qoder.com, and Qoder CN (qoder.cn), where accounts made // with Alibaba Cloud or a phone number live and can't sign in on qoder.com; // hint says which accounts each is for { agent: "qoder", get name() { return t("Qoder (international)"); }, icon: "qoder", plans: "Pro", own: true, risk: true, hint: "For accounts on qoder.com, the international site.", riskNote: "Qoder has no public API for this; magpie signs requests as its desktop client would, which Qoder may treat as third-party use and act on. Use an account you can afford to lose." }, { agent: "qoder-cn", name: "Qoder CN", icon: "qoder", plans: "Pro", own: true, risk: true, hint: "For accounts on qoder.cn: signed in with an Alibaba Cloud account or a phone number.", riskNote: "Qoder has no public API for this; magpie signs requests as its desktop client would, which Qoder may treat as third-party use and act on. Use an account you can afford to lose." }, // the devin CLI's own account is read; more are signed in beside it, each in a data folder of magpie's { agent: "devin", name: "Devin", icon: "devin", plans: "Pro · Enterprise", own: true }, // Zed's hosted models (Zed Pro, its trial), signed in at zed.dev as the editor is { agent: "zed", name: "Zed", icon: "zed", plans: "Pro · Student · Business", own: true, risk: true, riskNote: "Zed serves these models to its own editor; magpie signs requests as the editor would, which Zed may treat as third-party use and act on. Use an account you can afford to lose." }, // Factory's plans (Droid's account), signed in with WorkOS's device code as droid does; droid's own login stays its own // or added by an API key (fk-…), as droid takes FACTORY_API_KEY (the import box) { agent: "factory", name: "Factory", icon: "factory", plans: "Pro · Plus · Max", own: true, risk: true, importable: true, riskNote: "Factory serves these models to its own Droid CLI; magpie signs requests as Droid would, which Factory may treat as third-party use and act on. Use an account you can afford to lose." }, // Xiaomi MiMo's models (its free offer, MiMo plans), signed in at account.xiaomi.com as MiMo's app is { agent: "mimo-app", name: "Xiaomi MiMo", icon: "mimocode", plans: "Free · Starter · Plus · Pro · Ultra", own: true, risk: true, riskNote: "Xiaomi serves these models to its own MiMo app; magpie signs requests as the app would, which Xiaomi may treat as third-party use and act on. Use an account you can afford to lose." }, // Kiro's own sign-in page (Google, GitHub, Builder ID, Identity Center); kiro-cli's or the IDE's is read too { agent: "kiro", name: "Kiro", icon: "kiro-color", plans: "Free · Pro · Pro+ · Power", own: true }, // Google's sign-ins; Gemini CLI's own account is read too { agent: "gemini", name: "Gemini CLI", icon: "geminicli-color", plans: "Code Assist Standard · Enterprise", own: true }, // accounts can also come from another tool's export (Antigravity Cockpit, Antigravity Manager, CLIProxyAPI) { agent: "antigravity", name: "Antigravity", icon: "antigravity-color", plans: "Google AI Pro · Ultra · free", risk: true, importable: true }, ]; // subOf: the subscription an agent id is. One moved onto its plugin signs // in through the plugin, still named, drawn, warned about and asked where // as it was; it keeps as many accounts as the plugin does (Cursor's took // one, its plugin takes more). const subOf = (agent) => { const own = SUBS.find((x) => x.agent === agent); const pl = pluginSubs().find((x) => x.agent === agent); if (own && pl && movedSub(agent)) { const { name, icon, plans, risk, riskNote, hint, sites, importable } = own; // a Factory API key is kept by the built-in, which the plugin replaces return { ...pl, name, icon, plans, risk, riskNote, hint, sites, importable: importable && agent !== "factory", moved: true }; } return own || pl; }; const movedSub = (agent) => (providers?.onPlugins || []).includes(agent); // pluginMethod: the plugin's way to sign in a moved built-in takes when // the built-in had one click — its first, the browser's, or on a site the // one for that site (ZCode's "ZCode: Z.ai GLM Coding Plan"). None for a // plugin's own provider, which asks. function pluginMethod(sub, site) { if (!sub.moved) return undefined; const label = (sub.sites || []).find(([id]) => id === site)?.[1]; const at = label ? sub.plugin.methods.findIndex((m) => (m.label || "").includes(label)) : -1; return at < 0 ? 0 : at; } // pluginSubs: the providers OpenCode plugins sign in to (Settings → // Plugins), as subscriptions like the built-in ones. The plugin, not // magpie, signs in and carries the requests. function pluginSubs() { return (providers.plugins || []).map((x) => ({ agent: x.id, pid: x.pid, name: x.name, icon: x.icon, plugin: x, own: true, get plans() { return t("from the plugin {spec}", { spec: x.spec }); }, })); } // importSay: what the import of an app's accounts says — where its files // come from, and who they are checked with. A ChatGPT sign-in is refreshed // as it comes in, which spends the file's refresh token; a Claude one is // kept as it came and spent when Claude Code first renews it (#1453: the // tool a file came from is told it loses the account either way). function importSay(agent) { if (agent === "factory") { return { from: t("Add accounts by their Factory API keys (fk-…), as Droid takes FACTORY_API_KEY"), title: t("Add Factory accounts by API key"), intro: t("Paste one or more Factory API keys (fk-…, from app.factory.ai/settings/api-keys), one a line, or choose a file with them. Each key is checked with Factory before it is added."), checking: t("Checking the keys with Factory…"), checks: t("Each key is asked whose account it is, as Droid does with FACTORY_API_KEY."), instead: t("Use an API key instead…"), row: t("Add an account by API key…"), }; } if (agent === "codex") { // codexbar's config.json; Cockpit Tools exports in its own shape // (CLIProxyAPI's), Codex's auth.json, CPA and Sub2API: all read // (login_import.go) return { from: t("Bring in accounts from Codex's auth.json, codexbar's config.json, or exports from Cockpit Tools, CLIProxyAPI or Sub2API"), intro: t("Choose or paste one or more files: Codex's auth.json, codexbar's config.json (in ~/.codexbar), or an export from Cockpit Tools, CLIProxyAPI or Sub2API. Each account's sign-in is refreshed with ChatGPT before it is added."), spent: t("This takes the sign-in over: the tool the file came from (Codex on another computer, codexbar, Cockpit Tools, CLIProxyAPI) is signed out of that account and has to sign in again. The file itself is only read."), checking: t("Checking the accounts with {vendor}…", { vendor: "ChatGPT" }), checks: t("Each account's sign-in is refreshed and its account looked up, as signing in does."), }; } if (agent === "claude") { // nothing is asked of Anthropic: the sign-in is kept as the file has it return { from: t("Bring in accounts from CLIProxyAPI's auth files or {own}", { own: "Claude Code's .credentials.json" }), intro: t("Choose or paste CLIProxyAPI's auth files (JSON) or {own}. Each account is kept as the file has it.", { own: "Claude Code's .credentials.json" }), spent: t("Claude Code renews the sign-in the first time it uses it, and the file's copy then stops working: the tool it came from has to sign in again."), checking: t("Adding the accounts…"), checks: t("Each account is kept as the file has it; nothing is asked of Claude."), }; } return { from: t("Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI"), intro: t("Choose or paste an export from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI — JSON, or refresh tokens one a line. Each account is checked with Google before it is added."), checking: t("Checking the accounts with Google…"), checks: t("Each account's sign-in is refreshed and its project looked up, as signing in does."), }; } let signing = null; // the sign-in under way: { id, agent, url, state, installing, error } const signingOpen = () => signing?.state === "waiting" || signing?.state === "installing"; let justAdded = ""; // the account that just came in, to greet it // o: { user } signing that account in again, { proxy } the one picked to // sign in through (#1663): none picked, the one the account's requests go // through async function startSignIn(agent, risky, site, o = {}) { if (signingOpen()) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); // an account Google may suspend is added only once that is said if (subOf(agent)?.risk && !risky) { signing = { agent, state: "risk", forUser: o.user, picked: o.proxy }; renderProviders(); return; } // one on more than one site says which first if (subOf(agent)?.sites && !site) { signing = { agent, state: "site", forUser: o.user, picked: o.proxy }; renderProviders(); return; } if (subOf(agent)?.plugin) return startPluginSignIn(subOf(agent), pluginMethod(subOf(agent), site), {}, o); const keep = { site, forUser: o.user, picked: o.proxy }; signing = { agent, ...keep, proxy: o.proxy ?? signInProxyOf(agent, o.user), state: "starting" }; renderProviders(); try { const body = { agent }; if (site) body.site = site; if (o.user) body.user = o.user; if (o.proxy != null) body.proxy = o.proxy; signing = { ...(await api("signin", body)), ...keep }; if (web && signing.url) api("open", { url: signing.url }); renderProviders(); followSignIn(signing.id); } catch (e) { signing = { agent, ...keep, proxy: o.proxy ?? signInProxyOf(agent, o.user), state: "failed", error: e.message }; renderProviders(); } } async function followSignIn(id) { while (signing?.id === id && signingOpen()) { await new Promise((r) => setTimeout(r, 800)); let st; try { st = await api("signin/" + id); } catch { continue; } if (signing?.id !== id) continue; if (st.state === "waiting" || st.state === "installing") { // the CLI it needed is in: now the vendor's page can open if (signing.state === "installing" && st.state === "waiting" && st.url) api("open", { url: st.url }).catch(() => {}); if (signing.state !== st.state || signing.url !== st.url || signing.code !== st.code) { signing = { ...st, ...signingKept() }; renderProviders(); } continue; } if (st.state === "done") return signedIn(st); // a failed one keeps its site and way, for Try again signing = st.state === "canceled" ? null : { ...st, ...signingKept() }; renderProviders(); } } // signingKept: what a sign-in under way keeps across its updates, for Try // again and a proxy picked for it — its site and way, the account signed // in to again, the proxy picked function signingKept() { return { site: signing.site, method: signing.method, inputs: signing.inputs, forUser: signing.forUser, picked: signing.picked, askProxy: signing.askProxy, customProxy: signing.customProxy }; } // signInProxyOf: the proxy an account's sign-in goes through when none is // picked, as the server picks it (#1663): the account's own, else its // subscription's, else the global one ("") function signInProxyOf(agent, user) { const p = providers?.providers?.find((x) => x.account?.agent === agent); const own = user && p?.accountProxies?.[String(user).trim().toLowerCase()]; return own || (p?.proxy || "").trim(); } // signedIn: a sign-in done — the account opened in the editor. async function signedIn(st) { signing = null; justAdded = st.user; delete loginUsage[st.agent]; // what was fetched before has nothing on the new account providers = await api("providers?wait=1"); // with its vendor's list (#204) const p = providers.providers.find((x) => x.account?.agent === st.agent); if (p) { editing = p.id; draft = null; adding = false; presetQuery = ""; } renderProviders(); const who = st.user || subOf(st.agent)?.name || st.agent; // signed in but listed nowhere (#155): say so rather than "added" if (!p) status(t("{user} signed in, but magpie can't list it — please report this", { user: who }), "err"); // an account listed already is said to be, not added (#413) else if (st.again) status(t("{user} is already listed — its sign-in was renewed", { user: who }), "ok"); else status(st.using ? t("Signed in as {user}", { user: who }) : t("{user} added — switch to it any time", { user: who }), "ok"); state = await api("state"); renderAgents(); setTimeout(() => { justAdded = ""; }, 2000); } // startPluginSignIn: a plugin's provider signed in to as OpenCode's // `auth login` does — the way to sign in, the questions that way asks, // then the browser (and the code its page shows, pasted back) or a key. async function startPluginSignIn(sub, method, inputs = {}, o = {}) { const ms = sub.plugin.methods || []; if (!ms.length) { signing = { agent: sub.agent, state: "failed", error: t("The plugin has no way to sign in to {name}", { name: sub.name }) }; return renderProviders(); } if (method == null) { if (ms.length > 1) { signing = { agent: sub.agent, state: "method", forUser: o.user, picked: o.proxy }; return renderProviders(); } method = 0; } const keep = { method, inputs, forUser: o.user, picked: o.proxy }; signing = { agent: sub.agent, ...keep, proxy: o.proxy ?? signInProxyOf(sub.agent, o.user), state: "starting" }; renderProviders(); try { const r = await api("plugin-signin/prompt", { provider: sub.pid, method, inputs }); if (signing?.agent !== sub.agent) return; if (r.prompt) { signing = { agent: sub.agent, ...keep, prompt: r.prompt, state: "prompt" }; return renderProviders(); } if (ms[method].type === "api") { signing = { agent: sub.agent, ...keep, state: "key" }; return renderProviders(); } const body = { provider: sub.pid, method, inputs }; if (o.user) body.user = o.user; if (o.proxy != null) body.proxy = o.proxy; signing = { ...(await api("plugin-signin", body)), ...keep }; if (web && signing.url) api("open", { url: signing.url }); renderProviders(); followSignIn(signing.id); } catch (e) { if (signing?.agent !== sub.agent) return; signing = { agent: sub.agent, ...keep, proxy: o.proxy ?? signInProxyOf(sub.agent, o.user), state: "failed", error: e.message }; renderProviders(); } } // pluginAnswer: one of a sign-in method's questions answered, checked by // the plugin before the next is asked. async function pluginAnswer(sub, value) { const flow = signing; try { const r = await api("plugin-signin/prompt", { provider: sub.pid, method: flow.method, inputs: flow.inputs, key: flow.prompt.key, value }); if (signing !== flow) return; if (r.error) { signing = { ...flow, error: r.error, value }; return renderProviders(); } startPluginSignIn(sub, flow.method, r.inputs, { user: flow.forUser, proxy: flow.picked }); } catch (e) { if (signing === flow) { signing = { ...flow, error: e.message, value }; renderProviders(); } } } // pluginKey: an "api" method's key, which the plugin keeps. async function pluginKey(sub, key) { const flow = signing; signing = { ...flow, busy: true }; renderProviders(); try { const st = await api("plugin-signin", { provider: sub.pid, method: flow.method, inputs: flow.inputs, key }); if (signing?.agent === sub.agent) signedIn(st); } catch (e) { if (signing?.agent === sub.agent) { signing = { ...flow, error: e.message }; renderProviders(); } } } // renderPluginAsk: a plugin sign-in's step before the browser — the way // to sign in, a question, or the key. function renderPluginAsk(sub) { const box = el("div", "signing plugin-ask"); const tt = el("span", "tt"); box.append(tt); const flow = signing; const close = el("button", "text", t("Cancel")); close.onclick = cancelSignIn; if (signing.state === "method") { tt.append(el("span", "n", t("How do you sign in to {name}?", { name: sub.name })), el("span", "s", t("The plugin {spec} signs in and sends {name}'s requests; magpie only passes them on.", { spec: sub.plugin.spec, name: sub.name }))); const ch = el("div", "choices"); box.append(close, ch); sub.plugin.methods.forEach((m, i) => { const b = el("button", "text primary", m.label || t(m.type === "api" ? "API key" : "Browser")); b.dataset.method = String(i); b.onclick = () => startPluginSignIn(sub, i, {}, { user: flow.forUser, proxy: flow.picked }); ch.append(b); }); return box; } const q = signing.prompt; const form = el("form", "callback-form"); const why = el("span", "s why", flow.error || ""); if (flow.state === "prompt" && q.type === "select") { tt.append(el("span", "n", q.message), why); const ch = el("div", "choices"); box.append(close, ch); for (const o of q.options || []) { const b = el("button", "text primary", o.label); if (o.hint) b.title = o.hint; b.onclick = () => pluginAnswer(sub, o.value); ch.append(b); } return box; } const key = flow.state === "key"; // the key's field is titled by the way's label, as OpenCode's dialog // is, unless that only says "API key"; the plugin's placeholder hints // at what the key looks like const way = key ? sub.plugin.methods?.[flow.method] || {} : {}; const own = (way.label || "").trim(); const label = key ? (own && own.toLowerCase() !== "api key" ? own : t("{name} API key", { name: sub.name })) : q.message; tt.append(el("span", "n", label)); const inp = input(flow.value || "", key ? (way.placeholder || "") : (q.placeholder || ""), key ? "password" : "text"); inp.setAttribute("aria-label", label); inp.autocomplete = "off"; inp.disabled = !!flow.busy; const go = el("button", "text primary", t(key ? "Sign in" : "Next")); go.type = "submit"; go.disabled = !!flow.busy; inp.onkeydown = (e) => e.stopPropagation(); const submit = (e) => { e.preventDefault(); if (signing !== flow || flow.busy) return; if (key) pluginKey(sub, inp.value); else pluginAnswer(sub, inp.value); }; form.onsubmit = submit; go.onclick = submit; form.append(inp, go); tt.append(form, why); box.append(close); setTimeout(() => { if (inp.isConnected && !inp.disabled) inp.focus({ preventScroll: true }); }); return box; } // renderStepPlan: a StepFun provider's platform sign-in, which the user // makes in their own browser and brings here with magpie's bookmarklet function renderStepPlan(sp) { const box = el("div", "stepplan"); if (sp.signedIn) { const row = el("div", "pair"); const side = el("div", "side"); const out = el("button", "text", t("Sign out")); out.onclick = async () => { try { providers = await api("stepfun/" + sp.site + "/signout", {}); renderProviders(); } catch (e) { status(e.message, "err"); } }; side.append(out); row.append(el("span", "state", t("Signed in · the Usage page shows the Step Plan")), side); box.append(row); return box; } const steps = el("ol", "steps"); const s1 = el("li"); const open = el("button", "link", t("Sign in to StepFun in your browser ↗")); open.onclick = () => api("open", { url: sp.url }); s1.append(open); const s2 = el("li"); // dragged to the bookmarks bar it is a bookmark; a click here does nothing const bm = el("a", "bookmarklet", "magpie · StepFun"); bm.href = sp.bookmarklet; bm.onclick = (e) => e.preventDefault(); const cp = el("button", "link", t("copy it")); cp.onclick = () => copy(sp.bookmarklet, t("Bookmarklet"), cp); s2.append(document.createTextNode(t("Drag ")), bm, document.createTextNode(t(" to the bookmarks bar (or ")), cp, document.createTextNode(t(" as a bookmark's URL), then click it on the signed-in page"))); const s3 = el("li"); const pair = el("div", "pair"); const paste = input("", t("paste what it copied"), "password"); const go = el("button", "text", t("Save")); const save = async () => { if (!paste.value.trim()) return; go.disabled = paste.disabled = true; try { providers = await api("stepfun/" + sp.site + "/session", { text: paste.value }); renderProviders(); status(t("Signed in to StepFun"), "ok"); } catch (e) { go.disabled = paste.disabled = false; status(e.message, "err"); } }; go.onclick = save; paste.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save(); }; paste.onpaste = () => setTimeout(save); const side = el("div", "side"); side.append(go); pair.append(paste, side); s3.append(pair); steps.append(s1, s2, s3); box.append(steps); return box; } function cancelSignIn() { if (signing?.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); signing = null; renderProviders(); } // A sign-in goes through the proxy its account's requests will go through, // so the vendor sees the account come from one place (#1663, // demystify0137): the sheet says which, and another can be picked, which // starts it again through that one and is kept as the account's proxy. // proxyShown is a proxy's address without the name and password in it. function proxyShown(u) { return String(u || "").replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]*@/i, "$1"); } function proxyName(v) { return !v ? t("Global proxy") : v === "direct" ? t("Direct") : proxyShown(v); } // signInThrough: the sign-in under way started again through proxy v. function signInThrough(sub, v) { const f = signing; const o = { user: f?.forUser, proxy: v }; if (!sub.plugin) return startSignIn(sub.agent, true, f?.site, o); // which ends this one if (f?.id && signingOpen()) api("signin/" + f.id + "/cancel", {}).catch(() => {}); startPluginSignIn(sub, f?.method, f?.inputs || {}, o); } // signInProxyChoices: the proxies a sign-in can go through — the global // one, none, the subscription's, the ones its other accounts go through, // or one typed in. The global one is left out while the subscription has // a proxy of its own and other accounts: an account can't be kept on the // global proxy then. function signInProxyChoices(sub) { const p = providers?.providers?.find((x) => x.account?.agent === sub.agent); const own = (p?.proxy || "").trim(); const me = String(signing.forUser || "").trim().toLowerCase(); const others = (p?.account?.logins || []).some((l) => String(l.user || "").trim().toLowerCase() !== me); const opts = []; const seen = new Set(["", "direct"]); const add = (v, note) => { if (seen.has(v)) return; seen.add(v); opts.push({ v, name: proxyShown(v), literalName: true, note }); }; if (!own || own === "direct" || !others) opts.push({ v: "", name: "Global proxy", note: "Follows the proxy in Settings" }); opts.push({ v: "direct", name: "Direct", note: "Through no proxy" }); if (own) add(own, t("{name}'s proxy", { name: sub.name })); for (const [u, v] of Object.entries(p?.accountProxies || {})) add((v || "").trim(), t("{user}'s proxy", { user: u })); if (signing.proxy) add(signing.proxy, ""); opts.push({ v: "\x01", name: "Custom…", note: "http://, https:// or socks5://" }); return opts; } // signInProxyLink: the proxy the sign-in goes through, a link that picks // another. function signInProxyLink(sub) { const b = el("button", "link via", t("Proxy: {proxy}", { proxy: proxyName(signing.proxy) })); // the whole address too, which a narrow sheet cuts short b.title = proxyName(signing.proxy) + "\n" + t("The sign-in goes through this proxy, as the account's requests will. One picked here is kept as the account's."); b.setAttribute("aria-haspopup", "menu"); b.setAttribute("aria-expanded", "false"); b.onclick = (e) => { e.stopPropagation(); const flow = signing; openProtoMenu(b, signInProxyChoices(sub), flow.askProxy ? "\x01" : flow.proxy || "", (v) => { if (signing !== flow) return; if (v === "\x01") { flow.askProxy = true; return renderProviders(); } if (v === (flow.proxy || "") && !flow.askProxy) return; signInThrough(sub, v); }, "Sign in through"); }; return b; } // signInProxyForm: a proxy typed in to sign in through. function signInProxyForm(sub) { const flow = signing; const form = el("form", "callback-form proxy-ask"); const label = t("Proxy"); const inp = input(flow.customProxy || "", "http://127.0.0.1:7890"); inp.setAttribute("aria-label", label); inp.autocomplete = "off"; inp.onkeydown = (e) => e.stopPropagation(); const go = el("button", "text primary", t("Sign in through it")); go.type = "submit"; go.disabled = !inp.value.trim(); inp.oninput = () => { flow.customProxy = inp.value; go.disabled = !inp.value.trim(); }; const submit = (e) => { e.preventDefault(); if (signing !== flow || !inp.value.trim()) return; signInThrough(sub, inp.value.trim()); }; form.onsubmit = submit; go.onclick = submit; form.append(inp, go); setTimeout(() => { if (inp.isConnected) inp.focus({ preventScroll: true }); }); return form; } // A Copilot account on GitHub Enterprise Cloud with data residency signs in // at its enterprise's .ghe.com, not github.com (#723): the device // code's panel offers that, and the host is asked in place of the code. const GHE_HOST = /^(https?:\/\/)?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.ghe\.com\/?$/i; // copilotHostSwitch: the link from a Copilot sign-in to the other place it // can be — an enterprise's GHE.com, or back to github.com. function copilotHostSwitch(sub) { if (sub.agent !== "copilot" || sub.plugin) return null; const site = signing.site; const b = el("button", "link", site ? t("Sign in on github.com instead") : t("Account on GHE.com?")); b.dataset.ghe = site ? "github" : "ghe"; b.title = site ? t("Signing in on {host}", { host: site }) : t("An account of an enterprise on GitHub Enterprise Cloud with data residency signs in at its .ghe.com"); b.onclick = () => { if (site) return startSignIn("copilot", true); // which ends this one if (signing?.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); signing = { agent: "copilot", state: "ghe" }; renderProviders(); }; return b; } // renderCopilotGHE: the enterprise's host asked before its sign-in starts. function renderCopilotGHE(sub) { const box = el("div", "signing copilot-ghe"); const tt = el("span", "tt"); box.append(tt); const flow = signing; const label = t("Your enterprise on GHE.com"); tt.append(el("span", "n", label), el("span", "s", t("The address you sign in to GitHub at, like acme.ghe.com. An account on github.com doesn't need it."))); const form = el("form", "callback-form"); const inp = input(flow.host || "", "acme.ghe.com"); inp.setAttribute("aria-label", label); const go = el("button", "text primary", t("Sign in")); go.type = "submit"; go.disabled = !GHE_HOST.test(inp.value.trim()); const why = el("span", "s why", ""); inp.oninput = () => { flow.host = inp.value; go.disabled = !GHE_HOST.test(inp.value.trim()); why.textContent = ""; }; const submit = (e) => { e.preventDefault(); if (signing !== flow) return; const host = inp.value.trim().replace(/^https?:\/\//i, "").replace(/\/$/, "").toLowerCase(); if (!GHE_HOST.test(host)) { why.textContent = t("Type your enterprise's .ghe.com"); return; } startSignIn("copilot", true, host); }; form.onsubmit = submit; go.onclick = submit; form.append(inp, go); tt.append(form, why); const close = el("button", "text", t("Cancel")); close.onclick = cancelSignIn; const back = el("button", "text", "github.com"); back.title = t("Sign in on github.com instead"); back.onclick = () => startSignIn("copilot", true); box.append(close, back); setTimeout(() => { if (inp.isConnected) inp.focus({ preventScroll: true }); }); return box; } // dropSigningIn: the editor of provider id closing (Cancel, Save, Remove) // leaves no sign-in of its account waiting behind it, to come back with the // editor (#526: 无论我点击底部的移除、取消、保存都没办法); an import being // read is left to finish. function dropSigningIn(id) { const p = typeof id === "string" && providers?.providers?.find((x) => x.id === id); if (!p?.account || !signing || signing.agent !== p.account.agent || signing.state === "importing") return; if (signing.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); signing = null; } // renderSigning: where a sign-in stands, in place of the button that // started it — waiting on the browser, or what went wrong. function renderSigning(sub) { const box = el("div", "signing" + (signing.state === "failed" ? " failed" : "")); const tt = el("span", "tt"); if (signing.state === "risk") { box.append(el("span", "mark", "!")); tt.append(el("span", "n", t("{name} accounts can be suspended", { name: sub.name }))); if (sub.hint) tt.append(el("span", "s", t(sub.hint))); tt.append(el("span", "s", t(sub.riskNote || "Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose."))); box.append(tt); const go = el("button", "text primary", t("Sign in anyway")); const o = { user: signing.forUser, proxy: signing.picked }; go.onclick = () => startSignIn(sub.agent, true, undefined, o); const close = el("button", "text", t("Cancel")); close.onclick = cancelSignIn; if (sub.importable) { const imp = el("button", "text", importSay(sub.agent).instead || t("Import instead…")); imp.title = importSay(sub.agent).from; imp.onclick = () => startImport(sub.agent); box.append(close, imp, go); } else box.append(close, go); return box; } if (signing.state === "site") { // ZCode: a Z.ai account or a BigModel (智谱) one, a team's seat included tt.append(el("span", "n", t("Where is your {name} account?", { name: sub.name })), el("span", "s", t("Sign in where your GLM Coding Plan was bought, a team's plan too: z.ai, or bigmodel.cn for 智谱."))); // the question keeps the row's width, Cancel beside it; the sites go // under it as one group and a plugin's other ways under them as links, // each line wrapping (361: four buttons in its row left the question a // strip a character or two wide) box.classList.add("site-pick"); box.append(tt); const close = el("button", "text", t("Cancel")); close.onclick = cancelSignIn; box.append(close); const sites = el("div", "sites"); const flow = signing; for (const [id, label, host] of sub.sites) { const b = el("button", "text primary", t(label)); b.dataset.site = id; b.title = host; b.onclick = () => startSignIn(sub.agent, true, id, { user: flow.forUser, proxy: flow.picked }); sites.append(b); } box.append(sites); // a plugin's other ways, after the sites: ZCode's app's own sign-in // (Jinyu: use the account ZCode is signed in to), its API key if (sub.plugin && sub.moved) { const labels = sub.sites.map(([, label]) => label); const ways = el("div", "ways"); sub.plugin.methods.forEach((m, i) => { if (labels.some((l) => (m.label || "").includes(l))) return; const b = el("button", "link", t(m.label || (m.type === "api" ? "API key" : "Browser"))); b.dataset.method = String(i); b.onclick = () => startPluginSignIn(sub, i, {}, { user: flow.forUser, proxy: flow.picked }); ways.append(b); }); if (ways.childElementCount) box.append(ways); } return box; } if (signing.state === "ghe") return renderCopilotGHE(sub); if (signing.state === "import" || signing.state === "importing" || signing.state === "imported") return renderLoginImport(sub); if (signing.state === "method" || signing.state === "prompt" || signing.state === "key") return renderPluginAsk(sub); if (signing.state === "failed") { box.append(el("span", "mark", "!")); tt.append(el("span", "n", t("Sign-in didn't finish")), el("span", "s", signing.error || "")); box.append(tt); const again = el("button", "text primary", t("Try again")); const o = { user: signing.forUser, proxy: signing.picked }; again.onclick = () => sub.plugin ? startPluginSignIn(sub, signing.method, signing.inputs || {}, o) : startSignIn(sub.agent, true, signing.site, o); const close = el("button", "text", t("Cancel")); close.onclick = cancelSignIn; const acts = el("span", "acts"); const ghe = copilotHostSwitch(sub); if (ghe) acts.append(ghe); acts.append(signInProxyLink(sub)); tt.append(acts); if (signing.askProxy) tt.append(signInProxyForm(sub)); box.append(close, again); return box; } box.append(el("span", "spinner")); if (signing.state === "installing") { tt.append(el("span", "n", t("Installing {cli}…", { cli: signing.installing })), el("span", "s", t("{name} is used through its own CLI, which isn't on this computer yet. magpie is installing it with the official installer; the sign-in page opens as soon as it's done.", { name: sub.name }))); box.append(tt); const x = el("button", "text", t("Cancel")); x.onclick = cancelSignIn; box.append(x); return box; } tt.append(el("span", "n", t("Finish signing in to {name} in your browser", { name: sub.name })), el("span", "s", signing.state === "starting" ? t("Starting the sign-in…") : sub.plugin ? (signing.instructions || (signing.pasteCode ? t("magpie opened the sign-in page. Paste the code it shows below.") : t("magpie opened the sign-in page. The account shows up here as soon as you're done."))) : signing.pasteCode ? t("magpie opened the sign-in page. Paste the code it shows below.") : signing.code && sub.agent === "factory" ? t("magpie opened Factory's sign-in page. Check it shows this code and confirm it; the account shows up here as soon as you're done.") : signing.code ? t("magpie opened GitHub's device page. Enter this code there; the account shows up here as soon as you're done.") : t("magpie opened the sign-in page. The account shows up here as soon as you're done."))); if (signing.code) { const code = el("span", "devcode"); code.append(el("code", "", signing.code), copyBtn(signing.code, t("Code"))); tt.append(code); } box.append(tt); if (signing.url) { // the link itself, to select or copy into another browser or profile // than the one magpie opened it in const link = el("span", "signlink"); const u = el("code", "", signing.url); u.title = t("Open it in another browser or profile: copy it there"); const cp = copyBtn(signing.url, t("Sign-in link")); cp.title = t("Copy link"); link.append(u, cp); tt.append(link); const acts = el("span", "acts"); const open = el("button", "link", t("Open again")); open.onclick = () => api("open", { url: signing.url }).catch(() => {}); acts.append(open); const ghe = copilotHostSwitch(sub); if (ghe) acts.append(ghe); acts.append(signInProxyLink(sub)); tt.append(acts); if (signing.askProxy) tt.append(signInProxyForm(sub)); } else if (signing.state === "waiting") { // a sign-in run by the vendor's CLI, no page of magpie's to show tt.append(el("span", "acts", signInProxyLink(sub))); if (signing.askProxy) tt.append(signInProxyForm(sub)); } if (signing.pasteCallback || signing.pasteCode || signing.pasteKey) { const flow = signing; const what = flow.pasteCode ? t("Code") : flow.pasteKey ? t("API key") : t("Callback URL"); if (flow.pasteKey) { // Command Code's page posts its key to magpie unseen: a browser that // can't reach magpie (Docker) has no address to paste, so a key made // on the keys page finishes it, as Command Code's CLI takes one const s = el("span", "s", t("If the page can't reach magpie (it runs on a server or in Docker), make an API key on {name}'s keys page and paste it here.", { name: sub.name }) + " "); if (flow.keysURL) { const keys = el("button", "link", t("Open the keys page")); keys.onclick = () => api("open", { url: flow.keysURL }).catch(() => {}); s.append(keys); } tt.append(s); } else if (flow.callbackBlocked) { // the port the page sends the browser back to couldn't be opened, so // only the pasted address finishes this sign-in (#1782) tt.append(el("span", "s port-blocked", flow.callbackBlocked === "reserved" ? t("Windows keeps port {port}, where the sign-in comes back, for Hyper-V, WSL or Docker, so the page the browser ends on won't load. Copy its whole address and paste it here.", { port: flow.callbackPort }) : t("Another program has port {port}, where the sign-in comes back, so the page the browser ends on won't finish the sign-in. Copy its whole address and paste it here.", { port: flow.callbackPort }))); } else if (!flow.pasteCode) tt.append(el("span", "s", t("If the page the browser ends on won't load (magpie runs on a server or in Docker), copy its whole address and paste it here."))); const form = el("form", "callback-form"); const url = input(flow.callbackURL || "", what, flow.pasteKey ? "password" : "text"); url.setAttribute("aria-label", what); url.autocomplete = "off"; url.disabled = !!flow.callbackSubmitted || !!flow.callbackSubmitting; const submit = el("button", "text primary", t("Finish sign-in")); submit.type = "submit"; submit.disabled = url.disabled || !url.value.trim(); const why = el("span", "s why", flow.callbackError || ""); url.oninput = () => { flow.callbackURL = url.value; submit.disabled = !!flow.callbackSubmitted || !!flow.callbackSubmitting || !url.value.trim(); }; const finish = async (e) => { e.preventDefault(); if (flow.callbackSubmitted || flow.callbackSubmitting || signing !== flow) return; flow.callbackSubmitting = true; submit.disabled = true; url.disabled = true; why.textContent = ""; try { await api("signin/" + flow.id + "/callback", { url: url.value }); flow.callbackSubmitted = true; url.disabled = true; } catch (err) { if (signing !== flow) return; flow.callbackError = why.textContent = err.message; url.disabled = false; submit.disabled = !url.value.trim(); } finally { flow.callbackSubmitting = false; } }; form.onsubmit = finish; submit.onclick = finish; form.append(url, submit); tt.append(form, why); } // a plugin's browser sign-in whose page can't reach magpie (Docker: the // Command Code plugin's Studio posts its key to 127.0.0.1) can be left // for the plugin's own API key way, without starting over const keyWay = sub.plugin && signing.method != null && !signing.pasteCode && signing.state === "waiting" ? (sub.plugin.methods || []).findIndex((m) => m.type === "api") : -1; if (keyWay >= 0 && keyWay !== signing.method) { const acts = tt.querySelector(".acts") || tt.appendChild(el("span", "acts")); const k = el("button", "link", t("Use an API key instead")); k.title = t("If the page can't reach magpie (it runs on a server or in Docker)"); k.onclick = () => { if (signing?.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); startPluginSignIn(sub, keyWay); }; acts.append(k); } // a moved subscription goes straight to its plugin's usual way (#777: // one click, as the built-in did); ways other than that one and the key // above (ZCode's app's own sign-in) are a link away const others = sub.plugin && sub.moved && signing.state === "waiting" ? (sub.plugin.methods || []).filter((_, i) => i !== signing.method && i !== keyWay).length : 0; if (others) { const acts = tt.querySelector(".acts") || tt.appendChild(el("span", "acts")); const other = el("button", "link other-ways", t("Other ways to sign in…")); other.onclick = () => { if (signing?.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); signing = { agent: sub.agent, state: "method" }; renderProviders(); }; acts.append(other); } if (sub.importable) { // an account another tool is signed in to comes in from its file const imp = el("button", "link", importSay(sub.agent).instead || t("Import from a file instead…")); imp.title = importSay(sub.agent).from; imp.onclick = () => startImport(sub.agent); const acts = tt.querySelector(".acts") || tt.appendChild(el("span", "acts")); acts.append(imp); } // the one way to put it away (#526): a Close beside Open again did what // this does, two buttons for one thing const x = el("button", "text", t("Cancel")); x.title = t("Stop waiting for this sign-in"); x.onclick = cancelSignIn; box.append(x); return box; } // The backend returns the native key/login order and the new First account. // Do not keep a second display order that can disagree with routing. let accountArranging = false, accountSaving = false, accountRenderPending = false; function accountArrangementDone() { accountArranging = false; if (accountRenderPending) { accountRenderPending = false; renderProviders(); } } function arrangeAccountRows(list, p) { const rows = [...list.children].filter((r) => r.dataset.accountId); if (rows.length < 2) return; list.classList.add("reorderable"); const move = async (row, to) => { const current = [...list.children].filter((r) => r.dataset.accountId); const from = current.indexOf(row); if (accountSaving || to < 0 || to >= current.length || to === from) return; accountSaving = accountArranging = true; list.setAttribute("aria-busy", "true"); const before = [...list.children]; const focus = document.activeElement === row; list.insertBefore(row, to > from ? current[to].nextSibling : current[to]); current.splice(to, 0, ...current.splice(from, 1)); if (focus) row.focus({ preventScroll: true }); let order = current.map((r) => r.dataset.accountId); // a folded list (keyFold) sends every key: the shown ones take the // places they had among them, the others stay where they were if (list.accountOrder) { const shown = new Set(order), next = [...order]; order = list.accountOrder.map((id) => (shown.has(id) ? next.shift() : id)); } try { providers = await api("provider/arrange", { id: p.id, accountOrder: order }); accountRenderPending = true; status(t("Account order saved"), "ok"); } catch (e) { list.replaceChildren(...before); // A failed account switch can still have refreshed the agent's sign-in. // Reconcile with the backend rather than claiming a local rollback undid it. try { providers = await api("providers"); } catch (_) { /* keep the last known list */ } accountRenderPending = true; status(e.message, "err"); } finally { accountSaving = false; list.removeAttribute("aria-busy"); accountArrangementDone(); if (focus) document.querySelector(`.accts [data-account-id="${CSS.escape(row.dataset.accountId)}"]`)?.focus({ preventScroll: true }); } }; for (const row of rows) { row.tabIndex = 0; row.setAttribute("role", "group"); row.setAttribute("aria-label", row.querySelector(".n").textContent + " · " + t("Drag to reorder · Alt+↑/↓ to move")); row.title = t("Drag to reorder · Alt+↑/↓ to move"); row.addEventListener("click", (e) => { if (row.dataset.dragged) { e.preventDefault(); e.stopImmediatePropagation(); } }, true); row.onkeydown = (e) => { if (e.target !== row || !e.altKey || !["ArrowUp", "ArrowDown"].includes(e.key) || accountArranging) return; e.preventDefault(); e.stopPropagation(); const current = [...list.children].filter((r) => r.dataset.accountId); move(row, current.indexOf(row) + (e.key === "ArrowUp" ? -1 : 1)); }; row.onpointerdown = (e) => { if (accountArranging || e.target.closest("input, textarea, select, a, [contenteditable=true], button:not(.rename)")) return; // Text selection is native; drag the row's background/empty space instead. if (e.target.closest(".n:not(button), .plan, .aq, .acct-models")) return; const current = [...list.children].filter((r) => r.dataset.accountId); accountArranging = dragRows(e, row, row, list, current, (to) => move(row, to), () => {}, () => { if (!accountSaving) accountArrangementDone(); }); }; } } // renderAccounts: every account of an agent magpie has, the one the agent // is signed in to first, and a way to add another. Like keys, any number // can be ticked: the gateway moves to the next ticked account when the // first is out of quota. Each shows how much of its allowance is used, so // which one to go to next is plain to see. // forgetOwnTitle: what Remove does to the agent's own sign-in, which magpie // only reads — it is hidden, and shows again when the agent signs in anew. function forgetOwnTitle(a) { return t("magpie stops showing and using {agent}'s own sign-in; its files are left as they are, and it shows again when {agent} signs in anew", { agent: a.agentName }); } // keptLogin: the account Codex or Claude Code is kept signed in to in // place of the first (#524), "" when none — the gateway then tries the // accounts in their order, the one signed in to at its own place function keptLogin(p) { const a = p?.account; if (!a || (a.agent !== "codex" && a.agent !== "claude") || !p.keepLogin || !p.keepLoginAs) return ""; const as = p.keepLoginAs.toLowerCase(); return (a.logins || []).find((l) => (l.user || "").toLowerCase() === as)?.user || ""; } // loginsInOrder: an agent's accounts as its provider lists them and the // gateway tries them, the one it is signed in to first — unless it is // kept signed in to one of the user's choosing (p given), when the order // is the accounts' own function loginsInOrder(a, p) { const ls = a.logins?.length ? [...a.logins] : [{ user: a.user, plan: a.plan, active: true, on: true }]; if (p && keptLogin(p)) return ls; return ls.sort((x, y) => (y.active ? 1 : 0) - (x.active ? 1 : 0)); } function renderAccounts(a, p) { const sub = subOf(a.agent); const list = el("div", "accts"); const ls = loginsInOrder(a, p); // a Claude account whose sign-in Anthropic refused, or that has none, // can't be used till it is signed in again; another subscription's lapse // shows on its quota line only, as before const unusable = (l) => a.agent === "claude" && !!l.lapsed; // a plugin's account whose sign-in its vendor refused (#1363: Grok after // a restart): marked lapsed, or its allowance read saying so. Whatever // else it is (in use, the agent's own), it keeps a way to sign in again // and its Remove, and the reason never stands in their place. // A built-in Copilot account whose GitHub token GitHub refused (echo_ts // on Discord: a revoked token) is the same, marked lapsed by magpie, and // signed in again in place. So is any other built-in account whose // sign-in its vendor revoked (#1793: ChatGPT's 401 token_revoked) or // refused to refresh: the gateway passes over it till then. const signedOut = (l) => !unusable(l) && (sub?.plugin ? !!l.lapsed || SIGN_IN_GONE.test(quota?.[l.user]?.error || "") : (a.agent === "copilot" && !!l.lapsed) || SIGN_IN_GONE.test(l.lapsed || "")); // a Copilot account on an enterprise's GHE.com is named login@host, and // signs in again there const againSite = (l) => !sub?.plugin && a.agent === "copilot" && String(l.user).includes("@") ? String(l.user).split("@").pop() : undefined; const several = ls.filter((l) => !unusable(l) && ((l.active && !l.paused) || l.on)).length > 1; // kept signed in to one of the user's choosing (#524), the first is the // first in use in the order, which Make first sets without a sign-in const kept = keptLogin(p); const firstUser = kept ? ls.find((l) => (l.active || l.on) && !l.paused && !l.lapsed)?.user : ls.find((l) => l.active)?.user; const makeFirst = (l) => { const b = el("button", "text", t("Make first")); b.title = t("The gateway uses this account first; {agent} stays signed in to {user}", { agent: a.agentName, user: kept }); b.onclick = () => { b.classList.add("busy"); accountAction("provider/arrange", { id: p.id, accountOrder: [l.user, ...ls.filter((x) => x !== l).map((x) => x.user)] }, t("The gateway now uses {user} first", { user: l.user })); }; return b; }; // the account Claude Code or Codex is signed in to can be paused while // another is on: the gateway passes over it, the agent staying signed in // to it (#263) const pausable = (a.agent === "claude" || a.agent === "codex") && ls.some((l) => !unusable(l) && !l.active && l.on); const quota = loginUsageOf(a.agent); // the first, which magpie signed the agent out of while it was spent: // it is signed back in once it has room (#408) const back = ls.find((l) => l.returns && !l.active); for (const l of ls) { const on = !unusable(l) && !l.paused && (l.active || l.on); const row = el("div", "acc" + (on ? " in-use" : " off") + (l.user === justAdded ? " new" : "")); row.dataset.accountId = l.user; const dot = el("button", "dot tick"); if (on) dot.append(svg(CHECK, 10, 2.2)); if (unusable(l)) { dot.disabled = true; dot.title = t("Sign in again to use this account"); } else if (l.active && (pausable || l.paused)) { dot.title = l.paused ? t("Resume: the gateway uses this account first again") : t("Pause: the gateway uses the other accounts, {agent} stays signed in to this one", { agent: a.agentName }); dot.onclick = () => accountAction("login/" + (l.paused ? "on" : "off"), { agent: a.agent, user: l.user }); } else if (l.active) { dot.title = sub?.own ? t("The gateway uses this account first") : t("{agent} is signed in to this account", { agent: a.agentName }); dot.classList.add("fixed"); } else { dot.title = on ? t("Stop using this account") : t("Use this account too"); dot.onclick = () => accountAction("login/" + (on ? "off" : "on"), { agent: a.agent, user: l.user }); } row.append(dot, accountNameButton(p, l.user), el("span", "plan", accountPlan({ agent: a.agent, builtin: a.builtin, plan: l.plan }))); // its own models (#474), when there is another account to send the rest to const [amPill, amBox] = ls.length > 1 || accountModelsOf(p, l.user).length ? accountModels(p, l.user, false, l.user) : []; if (amPill) row.append(amPill); // its usage cap: the share of each window it is used to at most const cap = accountCapOf(p, l.user); // Claude Code or Codex signed in to it asks its vendor itself, not // through magpie: with no other account to sign it in to, the cap // holds back only what goes through magpie (𝕏 on Discord: a 90% cap // and the five hours run to 100%) const direct = l.active && !several && (a.agent === "claude" || a.agent === "codex") ? a.agentName : ""; if (p) row.append(accountCapPill(p, l.user, cap, direct)); // and each window's own, set on its meter (willz on Discord) const capFor = (w) => windowCapOf(p, l.user, w); // how many requests it has out at once, and waiting (#892) if (p) row.append(laneLimitPill(p, l.user, p.id + "@" + String(l.user).toLowerCase(), l.user)); const held = capHeldOf(quota?.[l.user], capFor); if (held) row.append(capHeldNote(held, held.cap, several, direct)); row.append(el("span", "grow")); if (unusable(l)) { row.classList.add("signed-out"); row.append(el("span", "using", t("Sign-in required"))); const again = el("button", "text", t("Sign in again")); again.onclick = () => startSignIn(a.agent, false, undefined, { user: l.user }); row.append(again); // the one Claude Code is signed in to can't be forgotten (ForgetLogin) if (!l.active) { const forget = el("button", "text quiet", t("Remove")); forget.onclick = () => accountAction("login/forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user })); row.append(forget); } } else if (signedOut(l)) { row.classList.add("signed-out"); row.append(el("span", "using", t("Sign-in required"))); const again = el("button", "text", t("Sign in again")); again.onclick = () => startSignIn(a.agent, false, againSite(l), { user: l.user }); const forget = el("button", "text quiet", t("Remove")); forget.title = l.own ? forgetOwnTitle(a) : t("magpie forgets this account's sign-in; the account itself is untouched"); forget.onclick = () => accountAction("login/forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user })); row.append(again, forget); } else if (l.active && kept && l.user !== firstUser) { // signed in to, kept so, and tried at its place in the order const signed = el("span", "using", l.paused ? t("Paused") : t("Signed in")); signed.title = t("{agent} is kept signed in to this account; requests through magpie go to the accounts in their order", { agent: a.agentName }); row.append(signed); if (on) row.append(makeFirst(l)); } else if (l.active) { const using = el("span", "using", l.paused ? t("Paused") : back ? t("First for now") : several ? t("First") : t("In use")); if (back && !l.paused) using.title = t("{user} was nearly used up, so magpie signed {agent} in to this one; it goes back to {user} once that has room again", { user: back.user, agent: a.agentName }); row.append(using); if (a.agent === "qoder" || a.agent === "qoder-cn" || l.own) { const forget = el("button", "text quiet", t("Remove")); if (l.own) forget.title = forgetOwnTitle(a); forget.onclick = () => accountAction("login/forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user })); row.append(forget); } else if (a.agent === "codex" && ls.length === 1) { // Codex's only account: no other to sign it in to first, so it is // signed out, as codex logout does (ForgetLogin) const out = el("button", "text quiet", t("Sign out")); out.title = t("Signs Codex out of this account, as codex logout does"); out.onclick = () => askSignOutLogin(a, l); row.append(out); } else if (a.agent === "codex") { // Codex is signed in to another of its accounts first, then this // one goes (ForgetLogin), rather than Codex signed out const forget = el("button", "text quiet", t("Remove")); forget.title = t("Codex is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched"); forget.onclick = () => accountAction("login/forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user })); row.append(forget); } } else { const forget = el("button", "text quiet", t("Remove")); forget.title = l.own ? forgetOwnTitle(a) : t("magpie forgets this account's sign-in; the account itself is untouched"); forget.onclick = () => accountAction("login/forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user })); if (l === back) { const again = el("span", "using", t("First again once it has room")); again.title = t("magpie signs {agent} back in to this account once it has room again", { agent: a.agentName }); row.append(again); } if (kept) { // the sign-in stays where it is kept: Make first is the order's, // and an account not in use is ticked on by its dot row.append(forget); if (l.user === firstUser) row.append(el("span", "using", t("First"))); else if (on) row.append(makeFirst(l)); } else { const use = el("button", "text", on ? t("Make first") : t("Use")); use.title = sub?.own ? t("The gateway uses this account first") : t("Sign {agent} in to this account", { agent: a.agentName }); use.onclick = () => { use.classList.add("busy"); accountAction("login/switch", { agent: a.agent, user: l.user }, sub?.own ? t("The gateway now uses {user} first", { user: l.user }) : t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user })); }; row.append(forget, use); } } row.append(accountQuota(l.lapsed ? { [l.user]: { error: t(l.lapsed) } } : quota, l.user, capFor, p ? (m, w) => windowCapMeter(m, p, l.user, w) : null)); row.classList.add("with-aq"); // not :has(.aq), which Safari 15.0 lacks (#220) if (amBox) row.append(amBox); list.append(row); } // magpie signs Codex or Claude Code in to the next account when the // first runs low (#209, #408); this keeps it on the first instead, or on // an account of the user's choosing, the gateway still spreading requests // over the ticked ones in their order (#524) if ((a.agent === "codex" || a.agent === "claude") && several && p) { const box = el("div", "keep-login"); const [keep, cb] = tick(t("Keep {agent} signed in to", { agent: a.agentName }), !!p.keepLogin); keep.title = t("magpie won't sign {agent} in to another account when the first runs low; requests through magpie still go to the other ticked accounts as Routing says", { agent: a.agentName }); // the app's own menu, as every other pick in it, not a native select let keepAs = kept; const opts = [{ v: "", name: t("the first account"), note: "", literalName: true }]; for (const l of ls) if (!l.lapsed) opts.push({ v: l.user, name: l.user, note: "", literalName: true }); const as = el("button", "sess-pick keep-as" + (keepAs ? " set" : "")); as.type = "button"; as.title = t("The account {agent} stays signed in to; the first is the one the gateway uses first", { agent: a.agentName }); as.dataset.value = keepAs; as.setAttribute("aria-haspopup", "menu"); as.setAttribute("aria-expanded", "false"); as.append(el("span", "", keepAs || t("the first account")), svg(CHEV, 11, 1.6)); const post = (keepLogin) => { const body = { id: p.id, keepLogin }; if (keepLogin && keepAs) body.keepLoginAs = keepAs; accountAction("provider/keeplogin", body, !keepLogin ? t("magpie moves {agent} to an account with room again", { agent: a.agentName }) : keepAs ? t("{agent} stays signed in to {user}", { agent: a.agentName, user: keepAs }) : t("{agent} stays signed in to the first account", { agent: a.agentName })); }; cb.onchange = () => post(cb.checked); // picking one keeps it so, ticked or not as.onclick = (e) => { e.stopPropagation(); if (as.classList.contains("open")) return closeProtoMenu(); openProtoMenu(as, opts, keepAs, (v) => { if (v === keepAs && cb.checked) return; keepAs = v; as.dataset.value = v; as.classList.toggle("set", !!v); as.firstChild.textContent = v || t("the first account"); cb.checked = true; post(true); }, "Account to stay signed in to", "sess-menu"); }; box.append(keep, as); list.append(box); } // with more of its accounts on, magpie sends Codex's own requests through // the gateway to fail over between them (#1385); this has it only switch // Codex's own sign-in instead, its requests going straight to OpenAI // (#1907: Codex Desktop and the CLI on their own subscription alone) if (a.agent === "codex" && several && p) { const box = el("div", "switch-only"); const [only, cb] = tick(t("Only switch {agent}'s sign-in", { agent: a.agentName }), !!p.switchOnly); only.title = t("magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.", { agent: a.agentName }); cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked ? t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", { agent: a.agentName }) : t("{agent}'s requests go through magpie to fail over to your other accounts again", { agent: a.agentName })); box.append(only); list.append(box); } if (a.agent === "codex" && providers?.codexDaemon) list.append(renderCodexDaemon(providers.codexDaemon)); if (a.agent === "codex" && providers?.codexApp) list.append(renderCodexApp(providers.codexApp)); if (signing?.agent === a.agent) list.append(renderSigning(sub)); else { const add = el("button", "acc add"); const ic = el("span", "dot"); ic.append(svg(PLUS, 10, 1.8)); add.append(ic, el("span", "n", t(sub.single ? "Sign in to another {name} account" : "Add another {name} account", { name: sub.name }))); add.onclick = () => startSignIn(a.agent); list.append(add); if (sub.importable) { const imp = el("button", "acc add"); const ic2 = el("span", "dot"); ic2.append(svg(PLUS, 10, 1.8)); imp.append(ic2, el("span", "n", importSay(a.agent).row || t("Import accounts from a file…"))); imp.title = importSay(a.agent).from; imp.onclick = () => startImport(a.agent); list.append(imp); } } arrangeAccountRows(list, p); return list; } // renderCodexDaemon: Codex's background app-server read the sign-in when it // started, so after a switch the Codex sessions that attach to it are still // on the account before (user) until it restarts. magpie doesn't restart it // unasked: that ends the Codex sessions running on it. function renderCodexDaemon(user) { const box = el("div", "signing daemon"); box.append(el("span", "mark", "!")); const tt = el("span", "tt"); tt.append(el("span", "n", t("Codex's background service is still signed in as {user}", { user })), el("span", "s", t("Restart it to use the new account. Running Codex sessions will be interrupted."))); box.append(tt); const later = el("button", "text", t("Later")); later.onclick = () => accountAction("codex/daemon/dismiss", {}); const go = el("button", "text primary", t("Restart")); go.title = "codex app-server daemon restart"; go.onclick = () => { go.classList.add("busy"); accountAction("codex/daemon/restart", {}, t("Codex's background service restarted")); }; box.append(later, go); return box; } // renderCodexApp: the Codex desktop app reads the sign-in only when it // opens, so after a switch it stays on the account before (user): it shows // that account's limits and, once they are spent, sends in no thread. Only // quitting and opening it again moves it; magpie doesn't quit it unasked. function renderCodexApp(user) { const box = el("div", "signing daemon"); box.append(el("span", "mark", "!")); const tt = el("span", "tt"); tt.append(el("span", "n", t("The Codex app is still signed in as {user}", { user })), el("span", "s", t("It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account."))); box.append(tt); const ok = el("button", "text", t("Got it")); ok.onclick = () => accountAction("codex/daemon/dismiss-app", {}); box.append(ok); return box; } // Accounts brought in from another tool's export instead of signing in // again: the files' text (or what is pasted) goes to magpie, which checks // each account with the vendor before keeping it, and says what became of // each. What is read stays here only until it is sent; the box masks it. function startImport(agent) { if (signingOpen()) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); signing = { agent, state: "import", text: "", files: [] }; renderProviders(); document.querySelector(".signing.import textarea")?.focus(); } async function runImport(agent) { const files = signing.files.map((f) => f.text); // each file's name, to say which one held no account (a result's file) const names = signing.files.map((f) => f.name); if (signing.text.trim()) { files.push(signing.text); names.push(t("The pasted text")); } if (!files.length) return; signing = { agent, state: "importing", names }; renderProviders(); try { const r = await api("signin/import", { agent, files }); if (signing?.agent !== agent) return; providers = r.providers; const added = r.results.filter((x) => x.status === "added" || x.status === "updated"); signing = { agent, state: "imported", results: r.results, names }; delete loginUsage[agent]; const p = providers.providers.find((x) => x.account?.agent === agent); if (p && added.length) { editing = p.id; draft = null; adding = false; presetQuery = ""; justAdded = added[0].user; setTimeout(() => { justAdded = ""; }, 2000); } renderProviders(); const failed = r.results.filter((x) => x.status === "failed").length; status(t("{n} added, {m} not added", { n: added.length, m: failed }), added.length || !failed ? "ok" : "err"); state = await api("state"); renderAgents(); } catch (e) { if (signing?.agent !== agent) return; signing = { agent, state: "import", text: "", files: [], error: e.message }; renderProviders(); } } const importStatus = { added: "Added", updated: "Updated with this sign-in", exists: "Already in magpie", failed: "Not added" }; function renderLoginImport(sub) { const box = el("div", "signing import"); const tt = el("span", "tt"); if (signing.state === "importing") { box.append(el("span", "spinner")); const say = importSay(sub.agent); tt.append(el("span", "n", say.checking), el("span", "s", say.checks)); box.append(tt); return box; } if (signing.state === "imported") { box.append(el("span", "mark", "✓")); tt.append(el("span", "n", t("Import finished"))); const rs = el("span", "results"); for (const r of signing.results || []) { const row = el("span", "res " + r.status); // a file that held no account is named, not passed over const who = r.user || (r.file && signing.names?.[r.file - 1]) || ""; row.append(el("span", "u", who), el("span", "st", t(importStatus[r.status] || r.status))); if (r.error) { row.title = r.error; row.append(el("span", "why", r.error)); } rs.append(row); } tt.append(rs); box.append(tt); const done = el("button", "text", t("Done")); done.onclick = cancelSignIn; box.append(done); return box; } box.append(el("span", "mark", "↑")); const say = importSay(sub.agent); tt.append(el("span", "n", say.title || t("Import {name} accounts", { name: sub.name })), el("span", "s", say.intro)); if (say.spent) tt.append(el("span", "s", say.spent)); if (sub.risk) tt.append(el("span", "s", t(sub.riskNote || "Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose."))); const area = el("textarea"); area.rows = 3; area.spellcheck = false; area.autocomplete = "off"; area.placeholder = t("…or paste it here"); area.value = signing.text || ""; const file = el("input"); file.type = "file"; file.multiple = true; file.accept = ".json,.txt,application/json,text/plain"; file.hidden = true; const names = el("span", "fname", signing.files.map((f) => f.name).join(", ")); const go = el("button", "text primary", t("Import")); const ready = () => { go.disabled = !(signing.files.length || signing.text.trim()); }; area.oninput = () => { signing.text = area.value; ready(); }; file.onchange = async () => { const picked = []; for (const f of file.files) { if (f.size > 4 << 20) { status(t("{name} is too big to be an export", { name: f.name }), "err"); continue; } picked.push({ name: f.name, text: await f.text() }); } signing.files = picked; names.textContent = picked.map((f) => f.name).join(", "); ready(); }; const pick = el("button", "link", t("Choose files…")); pick.onclick = () => file.click(); const acts = el("span", "acts"); acts.append(pick, names, file); tt.append(acts, area); if (signing.error) tt.append(el("span", "s why", signing.error)); box.append(tt); go.onclick = () => runImport(sub.agent); ready(); const close = el("button", "text", t("Cancel")); close.onclick = cancelSignIn; box.append(close, go); return box; } // Each account's allowance comes from the vendor and takes a moment, so it // loads on its own and fills the rows in when it's there. const loginUsage = {}; // agent → { at, data: { user: quota }, loading } function loginUsageOf(agent) { const u = (loginUsage[agent] ||= {}); if (!u.loading && !(Date.now() - (u.at || 0) < 60000)) { u.loading = api("login/usage?agent=" + agent) .then((d) => { u.data = d || {}; }, () => { u.data = u.data || {}; }) .finally(() => { u.at = Date.now(); u.loading = null; if (providers?.providers.find((p) => p.id === editing)?.account?.agent === agent && !document.querySelector(".editor .rename-in, .editor input:focus, .signing.import textarea:focus")) renderProviders(); }); } return u.data; } // quotaError says why an allowance can't be read: a Google account with // no Cloud project named can't be used at all until one is, so that is // said outright; anything else is in the tooltip. // SIGN_IN_GONE: an allowance read saying the account's sign-in is gone, // as the gateway reads a plugin's (signInGone, plugin_usage.go) const SIGN_IN_GONE = /sign-in has (expired|lapsed)|sign in again/i; function quotaError(err) { if (/sign-in has expired/.test(err)) return t("Signed out — add this account again to use it"); // a Copilot account GitHub refused the token of (copilot_lapsed.go), as // its row says it, in English or already in the user's language const copilotLapsed = "GitHub refused this Copilot sign-in; sign in again"; if (err === copilotLapsed || err === t(copilotLapsed)) return t(copilotLapsed); // an account whose sign-in its vendor revoked (signin_revoked.go, #1793) if (/'s sign-in was revoked; sign in again$/.test(err)) return t("The vendor revoked this sign-in; sign in again"); if (/no longer supported for Gemini Code Assist for individuals/.test(err)) return t("Google no longer serves personal accounts to Gemini CLI — hover for more"); if (/magpie accounts project/.test(err)) return t("Needs a Google Cloud project — hover for how"); if (/^Antigravity (hasn't set|won't serve)/.test(err)) return t("Antigravity hasn't set this account up — hover for why"); if (/violation of Terms of Service/i.test(err)) return t("Google has suspended this account — hover for details"); if (/access token is invalid or expired|didn't take the access token/.test(err)) return t("AiHubMix didn't take the access token — paste a new one in the provider's settings"); if (/this key has no limit/.test(err)) return t("This key has no limit — add the account's access token in the provider's settings to see its balance"); // a Volcengine or Tencent plan whose provider has no access key to read // it with (accessKeyCard, #1821): the card used to be left out unsaid if (/^this plan's usage is read with the account's access key: give its SecretId/.test(err)) return t("This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings"); if (/^this plan's usage is read with the account's access key/.test(err)) return t("This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings"); // ZCode with no GLM Coding Plan and no Start Plan left: the account has // nothing to spend, which is not a reading that failed (#1001). Both the // built-in (zcodeStartQuota, internal/provider/zcode_start.go) and the // plugin (NO_START, packages/zcode) put these words on the card — the // same string, byte for byte — and neither names a way out: the // "subscribe at …" wording is in the sign-in errors (zcodeSignedIn / // signedIn), which never reach this card. So the action is said here, on // the card. "has ended" would also be wrong for an account that never // started one, hence "no free Start Plan". "could not be read" is the // other one: that is a reading that failed. The match is anchored on the whole // card sentence, so the sign-in errors — which name the address themselves — // and "could not be read" are left alone. if (/^this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started$/.test(err)) return t("ZCode: no GLM Coding Plan, and no free Start Plan — subscribe to a GLM Coding Plan to use this account"); // an OpenCode Go key's windows (planWindows, planquota.go): Go is the // subscribing member's, in their workspace, so a key from anyone else // reads none — said with the way out, as a phone can't hover for it if (/^this key has no OpenCode Go subscription/.test(err)) return t("No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace"); if (/^OpenCode didn't take this key/.test(err)) return t("OpenCode didn't take this key — paste a current one in the provider's settings"); if (/^OpenCode Go's reply has no rolling/.test(err)) return t("OpenCode Go answered in a form magpie doesn't read — hover for what it sent"); // a remote magpie's card (remote_quotas.go) if (/^nothing read on that magpie yet/.test(err)) return t("Nothing read on that computer yet — refresh this card to have it read"); if (/^remote magpie doesn't share its quotas/.test(err)) return t("That computer's magpie doesn't share its quotas yet — update magpie there"); if (/^remote magpie isn't shared/.test(err)) return t("That computer's magpie isn't shared — turn on Settings → Share on local network there"); if (/^remote magpie didn't take this key/.test(err)) return t("That computer's magpie didn't take this key — use one of its gateway keys in this provider"); if (/^couldn't reach the remote magpie/.test(err)) return t("Couldn't reach that computer's magpie — check that it is running and its address"); // a remote magpie's gateway key card (#1547, remote_key_limits.go) if (/^remote magpie is too old to tell this key's limit/.test(err)) return t("That computer's magpie is too old to tell this key's limit — update magpie there"); if (/answered its key's limit in a form magpie doesn't read$/.test(err)) return t("That computer answered this key's limit in a form magpie doesn't read — hover for more"); // a ClinePass card with its balance but not its limits (#79): the // built-in key card (clineLimitsUnread, cline_usage.go) and the Cline // plugin both begin their error with these words if (/^ClinePass limits couldn't be read/.test(err)) return t("ClinePass limits couldn't be read — hover for why"); return balanceError(err) || t("Allowance unavailable"); } // the Balance field magpie reads, left empty, from a query whose reply it // knows (balancePathOf in balance.go), shown as the field's placeholder function balanceFieldOf(raw) { let path = ""; try { path = new URL((raw || "").trim()).pathname.replace(/\/+$/, ""); } catch { return "data.balance"; } if (path === "/api/user/self") return "$data.quota / 500000"; if (path === "/api/usage/token") return "$data.total_available / 500000"; if (path === "/api/v1/user/profile") return "$data.balance"; if (path === "/v1/usage") return "$remaining"; if (path.endsWith("/dashboard/billing/credit_grants")) return "$total_available"; return "data.balance"; } // balanceError: a balance that couldn't be read, said plainly where magpie // knows the fix (see balance.go); "" for any other. function balanceError(err) { if (/takes the API key, not the access token/.test(err)) return t("The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings"); if (/New-Api-User/i.test(err)) return t("Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers"); return ""; } // An account token is unused without a Balance URL and can't authenticate // /api/usage/token, which takes API keys only. Other URLs may belong to // another relay and are left alone; both new-api and sub2api issue JWTs. function balanceFix(p) { const box = el("div", "bal-fix"); const origin = (u) => { try { const x = new URL(u); return /^https?:$/.test(x.protocol) ? x.origin : ""; } catch { return ""; } }; box.refresh = () => { box.replaceChildren(); box.className = "bal-fix"; const tok = !!draft.balanceToken || (!!p?.balanceToken?.set && !draft.clearBalanceToken); if (!tok) return; const u = (draft.balanceURL || "").trim(); let path = ""; try { path = new URL(u).pathname.replace(/\/+$/, ""); } catch {} let why = ""; if (path === "/api/usage/token") why = t("…/api/usage/token takes the API key, not this token: for the account's balance, new-api uses /api/user/self; sub2api uses /api/v1/user/profile."); else if (!u) why = t("The token needs a Balance URL: a new-api relay uses /api/user/self; a sub2api panel uses /api/v1/user/profile to read the account's balance."); if (why) { box.classList.add("warn"); box.append(el("span", "", why)); const site = origin(u) || origin(draft.chat || draft.anthropic || draft.responses || ""); if (!site) return; for (const path of ["/api/user/self", "/api/v1/user/profile"]) { const to = site + path; const use = el("button", "text action", t("Use {url}", { url: to })); use.onclick = () => { draft.balanceURL = to; // An unrelated expression belongs to the user, so changing the // endpoint must not overwrite it. if (!(draft.balancePath || "").trim() || /total_(available|granted|used)|unlimited_quota/.test(draft.balancePath)) draft.balancePath = balanceFieldOf(to); const ed = box.closest(".editor"); const bal = ed?.querySelector(".bal-url"); const field = ed?.querySelector(".bal-path"); if (bal) bal.value = draft.balanceURL; if (field) { field.value = draft.balancePath; field.placeholder = balanceFieldOf(draft.balanceURL); } const more = ed?.querySelector("details.more"); if (more) more.open = true; box.refresh(); }; box.append(use); } return; } if (path === "/api/user/self" && !(draft.headers || []).some((h) => (h[0] || "").trim().toLowerCase() === "new-api-user" && (h[1] || "").trim())) { box.append(el("span", "", t("A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers."))); } }; box.refresh(); return box; } // accountQuota: an account's allowance as a line of small meters under its // name, the reset time on the ones nearly used up, credits and held resets. function accountQuota(data, user, capFor = () => 0, settable = null) { const line = el("div", "aq"); if (!data) { line.append(el("span", "skeleton sk-aq"), el("span", "skeleton sk-aq")); return line; } const q = data[user]; if (q?.asOf && !q.error) { line.classList.add("stale"); line.append(el("span", "aq-asof", asOfText(q))); } if (q?.resets?.count && !q.error) { const words = resetsWords(q.resets); const resets = el("span", "aq-w aq-resets"); resets.title = [words.textContent, words.title].filter(Boolean).join("\n"); resets.append(words.querySelector(".resets-n")); line.append(resets); } // an account on no plan says so, whatever else can be read of it const noPlan = q?.plan === "No plan" ? [t("No plan")] : []; if (q && !q.error && !q.windows?.length && q.balance) { // no rolling limits, only what is left to spend line.append(el("span", "aq-none", [...noPlan, t("Balance") + " " + q.balance].join(" · "))); return line; } if (!q || q.error || !q.windows?.length) { line.append(el("span", "aq-none", [...noPlan, q?.error ? quotaError(q.error) : t("No allowance reported")].join(" · "))); if (q?.error) line.title = q.error; return line; } if (q.balance) { const balance = el("span", "aq-w aq-balance"); balance.title = t("What is left on the account besides its windows"); balance.append(el("span", "aq-n", t("Balance")), el("b", "", q.balance)); line.append(balance); } // the two rolling windows fit a line; the per-model ones go in its // tooltip; per-model windows of a family are the family's one const counted = q.windows.filter((w) => !w.unlimited); const ws = familyWindows(counted); if (!ws.length) { line.append(el("span", "aq-none", t("Unlimited"))); return line; } if (ws.some((w) => w.members)) return poolLine(line, ws, q, capFor, settable); line.title = ws.slice(2).map((w) => w.tiers ? tiersText(w) : t(w.name) + " " + quotaText(w)).join(ws !== counted ? "\n" : " · "); if (q.asOf) line.title = [line.title, asOfText(q)].filter(Boolean).join("\n"); for (const w of ws.slice(0, 2)) { const used = Math.max(0, Math.min(100, w.used)); const m = el("span", "aq-w" + (used >= 90 ? " full" : "")); const track = el("span", "aq-track"); const fill = el("i"); fill.style.width = quotaFill(w) + "%"; track.append(fill); capMark(track, w, capFor(w)); m.append(el("span", "aq-n", t(w.name)), track, el("b", "", quotaText(w))); if (w.resetsAt) { const at = new Date(w.resetsAt); m.title = resetText(at, at.toLocaleString(intlLang())); if (used >= 80) m.append(el("span", "aq-r", resetInText(at))); } const out = runsOutText(w, (at) => at.toLocaleString(intlLang())); if (out) m.title = [m.title, out].filter(Boolean).join("\n"); if (w.tiers) m.title = tiersText(w); line.append(settable ? settable(m, w) : m); } return line; } // poolLine: an account row's pools, each its name then its 5-hour and // weekly meters (Gemini 5h ▬ 95% 7d ▬ 75%), two pools on the line and the // rest in its tooltip. function poolLine(line, ws, q, capFor = () => 0, settable = null) { const pools = []; for (const w of ws) { const k = w.members ? w.pool : "\0" + pools.length; const p = pools.find((x) => x.k === k); if (p) p.ws.push(w); else pools.push({ k, name: w.members ? w.pool : t(w.name), ws: [w] }); } line.title = pools.slice(2).map((p) => p.ws.map((w) => t(w.name) + " " + quotaText(w)).join(" · ")).join("\n"); if (q.asOf) line.title = [line.title, asOfText(q)].filter(Boolean).join("\n"); for (const p of pools.slice(0, 2)) { const m = el("span", "aq-w aq-pool" + (p.ws.some((w) => w.used >= 90) ? " full" : "")); m.append(el("span", "aq-n", p.name)); for (const w of p.ws) { const track = el("span", "aq-track"); const fill = el("i"); fill.style.width = quotaFill(w) + "%"; track.append(fill); capMark(track, w, capFor(w)); // each of a pool's windows is set apart: its own part of the meter const part = el("span", "aq-win"); part.append(el("span", "aq-k", w.window ? shortWindow(w.window) : ""), track, el("b", "", quotaText(w))); m.append(settable ? settable(part, w) : part); } const w = p.ws[0]; m.title = p.ws.map((x) => t(x.name) + " " + quotaText(x) + (x.resetsAt ? " · " + resetText(new Date(x.resetsAt), new Date(x.resetsAt).toLocaleString(intlLang())) : "")).join("\n") + (w.members ? "\n\n" + poolTip(w) : w.tiers ? "\n\n" + tiersText(w) : ""); line.append(m); } return line; } // An account's usage cap (provider.AccountCaps): the share of each of its // windows it is used to at most — a new account kept to 70% of its five // hours and its week. At it, routing takes the account for used up and // goes on to the others until the window renews. The pill on its row says // the cap and opens the app's menu of shares; a mark on each meter the cap // counts shows where it is, and a note says when it holds the account. const CAP_SHARES = [50, 60, 70, 80, 90]; // An account's name of the user's own (#1515): a team's GLM seats under // masked emails told apart. Kept by magpie (provider.AccountNames), never // in the vendor's or plugin's sign-in. accountSeatOf is the key plan the // account was found to stand in for, the name it goes by till it has one. function accountNameOf(p, user) { return p?.accountNames?.[String(user).toLowerCase()] || ""; } function accountSeatOf(p, user) { return p?.accountSeats?.[String(user).toLowerCase()] || ""; } // accountNameButton is the account's name on its editor row: the name of // its own, the account beside it, and a click renames it. function accountNameButton(p, user) { const own = accountNameOf(p, user), seat = accountSeatOf(p, user); if (!p) return el("span", "n", user); const wrap = el("span", "acct-who"); // a span, not a button: the address stays selectable, and a drag that // selects it renames nothing const name = el("span", "n rename", own || user); name.tabIndex = 0; name.setAttribute("role", "button"); name.title = own ? t("{user} · click to rename", { user }) : t("Name this account"); name.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); name.onclick(); } }; name.onclick = () => { if (String(getSelection?.() || "").length) return; const i = input(own, seat || t("Name, e.g. Personal or Team")); i.className = "rename-in"; i.maxLength = 64; // once: Enter re-renders the row, and the input's blur then follows let over = false; const done = (save) => { if (over) return; over = true; if (save && i.value.trim() !== own) accountAction("provider/accountname", { id: p.id, account: user, alias: i.value }); else renderProviders(); }; i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") done(true); else if (e.key === "Escape") done(false); }; i.onblur = () => done(true); wrap.replaceWith(i); i.focus(); }; wrap.append(name); if (own) wrap.append(el("span", "acct-user", user)); else if (seat) { const s = el("span", "acct-seat", "≡ " + seat); s.title = t("The same seat as the key plan {name}, shown once, on this account's card", { name: seat }); wrap.append(s); } return wrap; } function accountCapOf(p, user) { return p?.accountCaps?.[String(user).toLowerCase()] || 0; } // A window's own cap (provider.AccountWindowCaps, willz on Discord): a // friend's account stops at 50% of its five hours while its week may go to // 40%. Kept by the account and the window's capId, 1–99, or 100 for no cap // on that window; a window with none of its own takes the account's cap. // windowOwnCapOf is the window's own, 0 when it follows the account's. function windowOwnCapOf(p, user, w) { return (w?.capId && p?.accountWindowCaps?.[String(user).toLowerCase()]?.[w.capId]) || 0; } function windowCapsOf(p, user) { return Object.keys(p?.accountWindowCaps?.[String(user).toLowerCase()] || {}).length; } // windowCapOf: the share the window holds the account at, 0 for none function windowCapOf(p, user, w) { const own = windowOwnCapOf(p, user, w); if (own) return own >= 100 ? 0 : own; return accountCapOf(p, user); } // capHeldOf: how the account is held at cap, as the gateway reads it — // a window at or past its cap (capFor: its own, else the account's), not // yet renewed — or null: the fullest such window's share and its cap, and // when the last of them renews (0 when one doesn't say). function capHeldOf(q, capFor) { if (!q || q.error || !q.windows?.length) return null; const now = Date.now(); // a window of some models only (Opus's week, a pool's) holds the account // for those alone (#760): the account's own windows say when it is back // when one of them holds it, else those windows do and are named const all = { used: 0, cap: 0, back: 0, unknown: false, n: 0 }, some = { used: 0, cap: 0, back: 0, unknown: false, n: 0, names: [] }; for (const w of q.windows) { const cap = w.capped ? capFor(w) : 0; if (!cap || w.used < cap) continue; const r = w.resetsAt ? Date.parse(w.resetsAt) : 0; if (r && r <= now) continue; // renewed since it was read const h = w.capsSome ? some : all; h.n++; if (w.used >= h.used) { h.used = w.used; h.cap = cap; } if (w.capsSome && !some.names.includes(w.name)) some.names.push(w.name); if (!r) h.unknown = true; else h.back = Math.max(h.back, r); } const h = all.n ? all : some.n ? some : null; return h && { used: h.used, cap: h.cap, back: h.unknown ? 0 : h.back, all: h === all, some: some.names }; } // directNote: why the cap can't stop agent, signed in to the account and // asking its vendor itself, with no other account on to move it to function directNote(agent) { return t("{agent} is signed in to this account and asks its vendor itself, not through magpie, so with no other account on to move it to, {agent} goes on using it past the cap. Add another account, or pick {agent}'s models via magpie, for the cap to hold it", { agent }); } function capHeldNote(held, cap, several, direct) { if (direct) { // the account is held for what goes through magpie, but the agent // signed in to it isn't: the note doesn't say it is safe at its cap const n = el("span", "using acap-held acap-direct", t("At its cap · {agent} still uses it", { agent: direct })); n.title = t("A usage window is at {n}%, past this account's {cap}% cap: requests through magpie are refused with a usage-cap error until it renews", { n: Math.round(held.used), cap }) + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString(intlLang())) : "") + "\n" + directNote(direct); return n; } if (!held.all) { const names = held.some.join(", "); const n = el("span", "using acap-held", held.back ? t("{names} at its cap · back {in}", { names, in: untilText(held.back) }) : t("{names} at its cap", { names })); n.title = t("{names} is at {n}%, past this account's {cap}% cap, so magpie sends the requests it counts to the other accounts until it renews; other models still use this account", { names, n: Math.round(held.used), cap }) + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString(intlLang())) : "") + (several ? "" : "\n" + t("With no other account on, those requests are refused with a usage-cap error until then")); return n; } const n = el("span", "using acap-held", held.back ? t("At its cap · back {in}", { in: untilText(held.back) }) : t("At its cap")); n.title = t("A usage window is at {n}%, past this account's {cap}% cap, so magpie counts it as used up and sends requests to the other accounts until that window renews", { n: Math.round(held.used), cap }) + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString(intlLang())) : "") + (several ? "" : "\n" + t("With no other account on, requests are refused with a usage-cap error until then")); return n; } function capMark(track, w, cap) { if (!cap || !w.capped) return; const mk = el("span", "aq-cap"); mk.style.left = (quotaLeft ? 100 - cap : cap) + "%"; mk.title = t("Usage cap {n}%", { n: cap }); track.classList.add("capped"); track.append(mk); } // windowCapMeter: a window's meter on an account's row as the button that // sets the window's own cap, in the app's menu: the account's cap, none on // this window, a share, or one typed in place. A window of a model family // shown as one figure (tiers) stands for several windows and isn't set // here; one the cap doesn't count (on-demand) has none to set. function windowCapMeter(m, p, user, w) { if (!w.capId || w.tiers) return m; const own = windowOwnCapOf(p, user, w), cap = accountCapOf(p, user); const name = t(w.name); // a span acting as the button: a