diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 4c7ca8a6d..2a357d2c4 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -1,4 +1,4 @@ -# Library: instructions, MCP servers, skills, hooks, subagents and RTK +# Library: instructions, MCP servers, skills, hooks, subagents, RTK and billion-context The library keeps what every agent should know in one place: the instructions each agent reads before a conversation, the MCP servers it can @@ -8,7 +8,9 @@ magpie writes these into each agent's own files in that agent's format, and takes back only what it wrote. Everything else in those files stays as it was. Package `internal/library` also gives agents RTK, a CLI that cuts shell output down before the model reads it, -and lists, switches and copies each Pi's extensions and packages. +and billion-context's plugin, which folds a long session's older turns into +summaries the model can open again, and lists, switches and copies each +Pi's extensions and packages. ## Responsibilities and sources of truth @@ -34,6 +36,7 @@ and lists, switches and copies each Pi's extensions and packages. | Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) | | RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. Factory's Droid (lml0664 on Discord) gets rtk's own `rtk init -g --agent droid`, given Droid's folder as `FACTORY_HOME_OVERRIDE`; rtk puts its `Execute` group (`rtk hook droid`) in the root `hooks.json`, or in `settings.json`'s `hooks.PreToolUse` where Droid's hooks already are, so `droidHookFiles` reads and switches off all three places rtk 1.1.0 may use (`hooks.json`, `hooks/hooks.json`, `settings.json`), leaving the user's own hooks. rtk before 0.44 has no Droid agent, so it is `blocked` (`droidBlocked`). A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off; Qoder and Qoder CN: rtk 1.1.0 has no Qoder agent; Cline and Kimi Code: `rtk init --agent cline|kimi` writes only one project's `.clinerules` or `AGENTS.md`, instructions with no hook, and Kimi's refuses `-g`). RTK 1.1.0's Trae, Windsurf, Kilo Code and Mistral Vibe have no magpie agent. The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136, Qoder and Qoder CN #1327, Cline #3841), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) | | RTK in WSL | An agent in a WSL distro (`claude@wsl:Ubuntu`) is listed by its kind (`rtkKind`), and its hook runs in the distro, where Windows' rtk.exe is no command, so it gets the distro's own rtk (lex on Discord). `rtkDistroOf` asks the distro with `wsl.exe -d -e sh -lc` where rtk is (a login or interactive shell's PATH; else `~/.local/bin` or `~/.cargo/bin`, `offPath`), kept 15s; `ReadRTK` lists one `RTKDistro` for each distro its agents are in. Install RTK in WSL `` (`InstallRTKIn`, `POST /api/library/rtk/install` with `distro`, `magpie library rtk install `) runs RTK's own Linux installer in the distro (`curl -fsSL …/install.sh \| sh`, wget where there's no curl). Switching an agent on runs the distro's rtk there (`rtkInstallWSL`: `rtk init -g …` with its folder on PATH, Claude Code pointed at a folder of its own for the OpenCode and Cursor installers), and reads and edits its files under the distro's home as magpie opens it (`rtkClaudeDir`, `rtkCodexDir`, `rtkHome`). A distro that isn't running is never started (#3896): `rtkWSLLive` and `rtkDistroOf` check `agent.WSLRunning` first, its agents are listed `asleep` with the switch off, and switching or installing says to start it (`TestRTKWSLAsleep`). The page gives each distro a card (`rtkDistroCard` in plugins/library/client.js; library-rtk-wsl.test.cjs). | [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) | +| billion-context | `SetBili` runs bili's own `bili plugin install ` for an agent switched on and `bili plugin remove ` for one switched off; `ReadBili` reads `bili plugin list` (the agent column, then the status; `installed…` is on, `not installed` off, anything else shown as it is). `InstallBili` runs its README's `npm install -g billion-context --prefix=~/.local` (`npm install -g billion-context` on Windows), and `biliPath` finds bili there when it isn't on PATH. Offered only where bili's plugin works with magpie in front (`biliLanes`): Pi, omp and OpenCode load it in process and still send to magpie, and Claude Code goes through bili's proxy, which forwards to the gateway (`ANTHROPIC_BASE_URL` `…/bili/`). Codex's lane is an MCP server only, ZCode's routes only its own provider, Kimi Code's renames `default_model` to `bili-kimi` at every start, dsh's install failed through dsh's pnpm and Hermes' can't be tried in a sandbox HOME, so none of those is offered; neither is an agent in WSL. bili's remove doesn't restore a file: it leaves `"packages": []` in Pi's settings and `extensions:` in omp's config, and after magpie rewrote Claude Code's settings.json it deleted `ANTHROPIC_BASE_URL` (Claude Code then went to Anthropic) and put back its own `DISABLE_AUTO_COMPACT`. So switching on keeps each file it writes as it was before and after (`bili-plugins.json` in magpie's config folder), and `biliRestore` after the remove writes the file before back byte for byte when nothing changed it since, else merges JSON (`biliMergeJSON`): what the install changed and is still as installed goes back, a value changed since stays, and what the remove changed beyond the install is put back. Without a record (bili installed outside magpie), only a Claude Code `ANTHROPIC_BASE_URL` the remove took out goes back to the address bili forwarded to. The `.bili-bak` and `.bili-last` files bili leaves beside each file go with it. `TestBiliOnOffExact`, `TestBiliClaudeKeepsMagpiesRoute`, `TestBiliOffWithoutRecord`; the page's tab is `renderBili` (library-bili.test.cjs). | [`bili.go`](../../internal/library/bili.go) | | Pi extensions | Each Pi here, this computer's and each WSL distro's (`piPlaces`), with the extensions and packages it loads, read by Pi's own rules (`@earendil-works/pi-coding-agent` 1.4: `resolveExtensionEntries`, `isEnabledByOverrides`, `applyPatterns`). An extension is a `.ts`/`.js` file or a folder (package.json `pi.extensions`, else `index.ts`, else `index.js`) in `/extensions`, or a path its settings.json `extensions` lists; a package is an entry of settings.json `packages`. Built-in extensions (`builtin:mcp` and the rest) aren't listed: `builtin:mcp` carries the MCP servers magpie gives Pi. `SetPiExtension` writes what `pi config` writes (`-path` off; the `-` taken out and `+path` only where still excluded, on); `SetPiPackage` sets a package's four filters to `[]` (off) or takes them out (on), and refuses an entry that already picks some parts (`filtered`, changed in `pi config`). `CopyPi` gives a package to another Pi as its settings.json entry, which Pi installs itself when it next starts (npm into `/npm`, git into `/git`), never as copied files; it refuses a local package, and one the other Pi has already by Pi's identity (npm name, git host/path). An extension is copied as its file or folder into the other's `extensions`, leaving out `node_modules`, `.git` and symlinks, never over one of the same name, and the page says to run `npm install` there when it has dependencies (leokon3 on Discord). A settings.json that can't be parsed lists nothing and is never written; a stopped distro is never started (`asleep`); every write is backed up first. `GET`/`POST /api/library/pi`, `POST /api/library/pi/copy`; the Library's Pi packages tab, shown while a Pi is here (`renderPi` in plugins/library/client.js; library-pi-extensions.test.cjs). | [`piext.go`](../../internal/library/piext.go) | ## Runtime path @@ -110,6 +113,7 @@ go test -race ./internal/mcpauth go test -tags nogui ./internal/library go test -tags nogui ./internal/library -run 'TestWSLStopped' go test -tags nogui ./internal/library -run 'TestRTKWSL' +go test -tags nogui ./internal/library -run 'TestBili|TestParseBiliList' go test -tags nogui ./internal/library -run 'TestPi' node --test internal/gui/tests/library-pi-extensions.test.cjs node --test internal/gui/tests/library-rtk-wsl.test.cjs diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 44e6a24da..91af8add6 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -338,6 +338,7 @@ var notYet = map[string]string{ "POST /api/masking/clear": U, // masking.go "POST /api/masking/preview": U, // masking.go "POST /api/masking/values": U, // masking.go + "GET /api/library/bili": L, // library.go "GET /api/library/icon": W, // library.go "GET /api/library/market/servers": L, // library.go "GET /api/library/market/skills": L, // library.go @@ -345,6 +346,8 @@ var notYet = map[string]string{ "GET /api/library/pi": L, // library.go "GET /api/library/rtk": L, // library.go "GET /api/library/skill": L, // library.go + "POST /api/library/bili": L, // library.go + "POST /api/library/bili/install": L, // library.go "POST /api/library/market/about": L, // library.go "POST /api/library/mcp-signin": L, // library.go "POST /api/library/mcp-signin/{id}/cancel": L, // library.go diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index ff62890af..2d5decf60 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -35,6 +35,8 @@ magpie.plugin("library", (ctx) => { const GLYPH = { cmd: "M3 4.5h10v7H3z M5.5 7l1.5 1.2-1.5 1.3 M8.5 9.5h2", + // two arrows closing on a line: billion-context folding a context + fold: "M8 2v4 M6 4.2 8 6l2-1.8 M8 14v-4 M6 11.8 8 10l2 1.8 M3 8h10", web: "M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11z M2.5 8h11 M8 2.5c1.6 1.7 2.3 3.5 2.3 5.5S9.6 11.8 8 13.5 M8 2.5C6.4 4.2 5.7 6 5.7 8s.7 3.8 2.3 5.5", skill: "M4 2.5h6.5L12 4v9.5H4z M6 6h4 M6 8.5h4 M6 11h2.5", doc: "M4 2.5h5.5L12 5v8.5H4z M9.5 2.5V5H12", @@ -533,8 +535,9 @@ magpie.plugin("library", (ctx) => { // opening the page (its nav clicked, while on it too) draws it again // only for a change, or for RTK's tab, which is asked again: a page // drawn over again replaced the row under the reader's pointer (#3099) - if (quiet === "open" && seen(lib) === was && tab !== "rtk" && page.querySelector(":scope > .lib-body")) return; + if (quiet === "open" && seen(lib) === was && tab !== "rtk" && tab !== "bili" && page.querySelector(":scope > .lib-body")) return; rtk = null; // asked again when its tab is drawn: an agent may have been installed since + bili = null; piView = null; render(); } catch (e) { @@ -808,8 +811,8 @@ magpie.plugin("library", (ctx) => { ch.append(bar("26px", 26, "lib-sk-icon"), bar("150px", 11)); card.append(ch, rows(1, false).firstChild); box.append(card, head("60px"), rows(6, true)); - } else if (which === "rtk") { - box.append(rows(1, false), head("60px"), rows(5, true)); + } else if (which === "rtk" || which === "bili") { + box.append(rows(1, false), head("60px"), rows(which === "rtk" ? 5 : 3, true)); } else if (which === "memory") { box.append(rows(1, true), rows(6, false)); } else if (which === "pi") { @@ -826,6 +829,8 @@ magpie.plugin("library", (ctx) => { // RTK's count read afresh each time its tab is opened: an agent run // since adds to it (#741); the page keeps the last one until then if (id === "rtk" && rtk) loadRTK(); + // and which agents have billion-context's plugin: bili switched outside magpie + if (id === "bili" && bili) loadBili(); // Pi's extensions too: one installed or changed outside magpie since if (id === "pi" && piView) loadPi(); // memory too: agents save to it while the page is open @@ -847,6 +852,7 @@ magpie.plugin("library", (ctx) => { ["hooks", t("Hooks") + n("hooks")], ["subagents", t("Subagents") + n("subagents")], ["rtk", "RTK"], + ["bili", "billion-context"], ...(hasPi() ? [["pi", t("Pi packages")]] : []), ], tab, openTab); tabs.classList.add("lib-tabs"); @@ -915,6 +921,7 @@ magpie.plugin("library", (ctx) => { if (tab === "instructions") renderInstructions(body); else if (tab === "mcp") renderServers(body); else if (tab === "rtk") renderRTK(body); + else if (tab === "bili") renderBili(body); else if (tab === "memory") renderMemory(body); else if (tab === "pi") renderPi(body); else if (tab === "hooks") renderHooks(body); @@ -1449,6 +1456,107 @@ magpie.plugin("library", (ctx) => { rtkBusy.delete(a.id); render(); } + // ---------- billion-context ---------- + + // billion-context (its CLI bili) folds an agent's older turns into + // summaries the model can open again, so a long session stays in the + // window. magpie runs bili's own installer for each agent switched on and + // its remover for one switched off, then puts back what the install + // changed in the agent's files (bili.go). + let bili = null; // /api/library/bili + const biliBusy = new Set(); // agents being switched + let biliLoading = false, biliInstalling = false, biliInstallErr = ""; + async function loadBili() { + if (biliLoading) return; + biliLoading = true; + try { + bili = await api("library/bili"); + } catch (e) { + status(e.message, "err"); + } + biliLoading = false; + if (tab === "bili" && bili) render(); + } + function renderBili(body) { + body.append(intro(t("billion-context folds an agent's older turns into summaries the model can open again, so a long session stays inside its window. Switch it on for an agent and magpie runs billion-context's own installer for it."))); + if (!bili) { + body.append(el("div", "row skeleton")); + loadBili(); + return; + } + const card = el("div", "list lib-card lib-bili"); + const ttl = el("div", "lib-cardhead"); + ttl.append(glyph(GLYPH.fold), el("b", "", "billion-context"), el("span", "grow")); + card.append(ttl); + if (bili.path) { + ttl.append(el("span", "note mono", bili.version ? "v" + bili.version : tilde(bili.path))); + card.append(el("p", "lib-rtk-gain", t("An agent switched on here can't also run billion-context-pi or opencode-acp."))); + if (bili.listErr) card.append(el("p", "lib-rtk-note lib-rtk-err", t("magpie couldn't read which agents have it: {why}", { why: bili.listErr }))); + } else { + card.append(el("p", "lib-rtk-gain", biliInstalling + ? t("Installing billion-context… this can take a minute.") + : t("billion-context isn't installed. magpie can install it for you, or get it from its site."))); + if (bili.install) card.append(el("p", "lib-rtk-cmd", bili.install)); + if (biliInstallErr && !biliInstalling) card.append(el("p", "lib-rtk-note lib-rtk-err lib-bili-install-err", t("The install failed: {why}", { why: biliInstallErr }))); + const acts = el("div", "lib-acts"); + if (bili.install) { + const ib = button(biliInstalling ? t("Installing…") : t("Install billion-context"), "action", installBili); + ib.disabled = biliInstalling; + acts.append(ib); + } + acts.append(button(t("Get billion-context"), bili.install ? "" : "action", () => browse(bili.url)), button(t("Check again"), "", () => { bili = null; render(); })); + card.append(acts); + } + body.append(card); + const rh = el("div", "row-head"); + rh.append(el("span", "label", t("Agents")), el("span", "grow"), el("span", "note", t("restart an agent after switching it"))); + body.append(rh); + const list = el("div", "list lib-list"); + const rows = bili.agents.filter((a) => !isHidden(a)); + for (const a of rows) { + const row = el("div", "row lib-row"); + const who = el("div", "who"); + who.append(el("div", "name", a.name)); + row.append(icon(a.icon), who, el("span", "grow")); + // bili lists it as neither on nor off: partly there, broken + if (a.status) row.append(tag(t("Not whole"), "warn", t("bili plugin list says: {status}. Switch it off to take out what is there.", { status: a.status }))); + const on = a.on || !!a.status; + const sw = toggle(on, t("{agent} folds its context with billion-context", { agent: a.name }), (v) => setBili(a, v)); + if ((!bili.path) || biliBusy.has(a.id) || biliInstalling) sw.disabled = true; + row.append(sw); + list.append(row); + } + if (!rows.length) list.append(el("div", "lib-none", t("None of your agents is one billion-context has a plugin for that works with magpie: Pi, omp, OpenCode or Claude Code."))); + body.append(list); + } + async function setBili(a, on) { + biliBusy.add(a.id); + render(); + try { + bili = await api("library/bili", { agent: a.id, on }); + const names = (bili.restart || [a.id]).map((id) => bili.agents.find((x) => x.id === id)?.name || id).join(", "); + status(on ? t("billion-context is on for {agent} — restart it to use it", { agent: names }) : t("billion-context is off for {agent} — restart it to see it", { agent: names }), "ok", 6000); + } catch (e) { + status(e.message, "err", 8000); + } + biliBusy.delete(a.id); + render(); + } + async function installBili() { + biliInstalling = true; + biliInstallErr = ""; + render(); + try { + bili = await api("library/bili/install", {}); + status(t("billion-context is installed — switch it on for your agents below"), "ok", 6000); + } catch (e) { + biliInstallErr = e.message; + status(e.message, "err", 10000); + } + biliInstalling = false; + render(); + } + // ---------- Pi extensions ---------- // Each Pi here (this computer's, and each WSL distro's) with the diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 41975ef10..cb83c9da4 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -881,6 +881,20 @@ magpie.strings({ "{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} 已加入 {agent} 的包:Pi 下次启动时安装它", "{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} 已复制到 {agent}。它需要自己的依赖包:请在那里的 {dir} 中运行 npm install", "{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已复制到 {agent}:Pi 下次启动或 /reload 时加载它", + "billion-context folds an agent's older turns into summaries the model can open again, so a long session stays inside its window. Switch it on for an agent and magpie runs billion-context's own installer for it.": "billion-context 把 Agent 较早的对话折叠成模型可以再展开的摘要,让长会话始终留在上下文窗口内。为某个 Agent 打开它,magpie 会为它运行 billion-context 自己的安装程序。", + "An agent switched on here can't also run billion-context-pi or opencode-acp.": "在这里打开的 Agent 不能再同时使用 billion-context-pi 或 opencode-acp。", + "magpie couldn't read which agents have it: {why}": "magpie 读不出哪些 Agent 装了它:{why}", + "Installing billion-context… this can take a minute.": "正在安装 billion-context… 可能需要一分钟。", + "billion-context isn't installed. magpie can install it for you, or get it from its site.": "billion-context 尚未安装。magpie 可以为你安装,也可以去它的网站获取。", + "Install billion-context": "安装 billion-context", + "Get billion-context": "获取 billion-context", + "Not whole": "不完整", + "bili plugin list says: {status}. Switch it off to take out what is there.": "bili plugin list 显示:{status}。关闭此开关可移除已有的部分。", + "{agent} folds its context with billion-context": "{agent} 用 billion-context 折叠上下文", + "None of your agents is one billion-context has a plugin for that works with magpie: Pi, omp, OpenCode or Claude Code.": "你的 Agent 里没有 billion-context 的插件能配合 magpie 使用的:Pi、omp、OpenCode 或 Claude Code。", + "billion-context is on for {agent} — restart it to use it": "{agent} 已打开 billion-context — 重启后生效", + "billion-context is off for {agent} — restart it to see it": "{agent} 已关闭 billion-context — 重启后生效", + "billion-context is installed — switch it on for your agents below": "billion-context 已安装 — 在下方为你的 Agent 打开它", }, "zh-TW": { "Learn from conversations": "從對話中學習", @@ -1762,6 +1776,20 @@ magpie.strings({ "{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} 已加入 {agent} 的套件:Pi 下次啟動時安裝它", "{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} 已複製到 {agent}。它需要自己的相依套件:請在那裡的 {dir} 中執行 npm install", "{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已複製到 {agent}:Pi 下次啟動或 /reload 時載入它", + "billion-context folds an agent's older turns into summaries the model can open again, so a long session stays inside its window. Switch it on for an agent and magpie runs billion-context's own installer for it.": "billion-context 把 Agent 較早的對話摺疊成模型可以再展開的摘要,讓長工作階段始終留在上下文視窗內。為某個 Agent 開啟它,magpie 會為它執行 billion-context 自己的安裝程式。", + "An agent switched on here can't also run billion-context-pi or opencode-acp.": "在這裡開啟的 Agent 不能再同時使用 billion-context-pi 或 opencode-acp。", + "magpie couldn't read which agents have it: {why}": "magpie 讀不出哪些 Agent 裝了它:{why}", + "Installing billion-context… this can take a minute.": "正在安裝 billion-context… 可能需要一分鐘。", + "billion-context isn't installed. magpie can install it for you, or get it from its site.": "billion-context 尚未安裝。magpie 可以為你安裝,也可以去它的網站取得。", + "Install billion-context": "安裝 billion-context", + "Get billion-context": "取得 billion-context", + "Not whole": "不完整", + "bili plugin list says: {status}. Switch it off to take out what is there.": "bili plugin list 顯示:{status}。關閉此開關可移除已有的部分。", + "{agent} folds its context with billion-context": "{agent} 用 billion-context 摺疊上下文", + "None of your agents is one billion-context has a plugin for that works with magpie: Pi, omp, OpenCode or Claude Code.": "你的 Agent 裡沒有 billion-context 的外掛能配合 magpie 使用的:Pi、omp、OpenCode 或 Claude Code。", + "billion-context is on for {agent} — restart it to use it": "{agent} 已開啟 billion-context — 重啟後生效", + "billion-context is off for {agent} — restart it to see it": "{agent} 已關閉 billion-context — 重啟後生效", + "billion-context is installed — switch it on for your agents below": "billion-context 已安裝 — 在下方為你的 Agent 開啟它", }, ja: { "Learn from conversations": "会話から学ぶ", @@ -2643,6 +2671,20 @@ magpie.strings({ "{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} を {agent} のパッケージに追加しました。Pi が次回起動時にインストールします", "{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} を {agent} にコピーしました。依存パッケージが必要です: そちらの {dir} で npm install を実行してください", "{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} を {agent} にコピーしました。Pi は次回起動時か /reload で読み込みます", + "billion-context folds an agent's older turns into summaries the model can open again, so a long session stays inside its window. Switch it on for an agent and magpie runs billion-context's own installer for it.": "billion-context はエージェントの古いやり取りを、モデルが再び開ける要約に畳み込み、長いセッションをコンテキストウィンドウに収めます。エージェントでオンにすると、magpie が billion-context 自身のインストーラーを実行します。", + "An agent switched on here can't also run billion-context-pi or opencode-acp.": "ここでオンにしたエージェントでは、billion-context-pi や opencode-acp を併用できません。", + "magpie couldn't read which agents have it: {why}": "magpie はどのエージェントに入っているか読み取れませんでした:{why}", + "Installing billion-context… this can take a minute.": "billion-context をインストール中… 1 分ほどかかることがあります。", + "billion-context isn't installed. magpie can install it for you, or get it from its site.": "billion-context はインストールされていません。magpie でインストールするか、サイトから入手できます。", + "Install billion-context": "billion-context をインストール", + "Get billion-context": "billion-context を入手", + "Not whole": "不完全", + "bili plugin list says: {status}. Switch it off to take out what is there.": "bili plugin list の表示:{status}。オフにすると残っている部分を取り除きます。", + "{agent} folds its context with billion-context": "{agent} のコンテキストを billion-context で畳み込む", + "None of your agents is one billion-context has a plugin for that works with magpie: Pi, omp, OpenCode or Claude Code.": "billion-context のプラグインが magpie と使えるエージェントがありません:Pi、omp、OpenCode、Claude Code。", + "billion-context is on for {agent} — restart it to use it": "{agent} で billion-context をオンにしました — 再起動すると使えます", + "billion-context is off for {agent} — restart it to see it": "{agent} で billion-context をオフにしました — 再起動すると反映されます", + "billion-context is installed — switch it on for your agents below": "billion-context をインストールしました — 下でエージェントごとにオンにしてください", }, de: { "Learn from conversations": "Aus Unterhaltungen lernen", @@ -3524,5 +3566,19 @@ magpie.strings({ "{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} ist jetzt in den Paketen von {agent}: Pi installiert es beim nächsten Start", "{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} ist nach {agent} kopiert. Es braucht seine Pakete: Führe dort in {dir} npm install aus", "{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} ist nach {agent} kopiert: Pi lädt es beim nächsten Start oder bei /reload", + "billion-context folds an agent's older turns into summaries the model can open again, so a long session stays inside its window. Switch it on for an agent and magpie runs billion-context's own installer for it.": "billion-context faltet ältere Runden eines Agenten zu Zusammenfassungen, die das Modell wieder öffnen kann, damit eine lange Sitzung in sein Fenster passt. Schalte es für einen Agenten ein, und magpie führt den eigenen Installer von billion-context für ihn aus.", + "An agent switched on here can't also run billion-context-pi or opencode-acp.": "Ein hier eingeschalteter Agent kann nicht zusätzlich billion-context-pi oder opencode-acp nutzen.", + "magpie couldn't read which agents have it: {why}": "magpie konnte nicht lesen, welche Agenten es haben: {why}", + "Installing billion-context… this can take a minute.": "billion-context wird installiert… das kann eine Minute dauern.", + "billion-context isn't installed. magpie can install it for you, or get it from its site.": "billion-context ist nicht installiert. magpie kann es für dich installieren, oder du holst es von seiner Website.", + "Install billion-context": "billion-context installieren", + "Get billion-context": "billion-context holen", + "Not whole": "Unvollständig", + "bili plugin list says: {status}. Switch it off to take out what is there.": "bili plugin list sagt: {status}. Schalte es aus, um zu entfernen, was da ist.", + "{agent} folds its context with billion-context": "{agent} faltet seinen Kontext mit billion-context", + "None of your agents is one billion-context has a plugin for that works with magpie: Pi, omp, OpenCode or Claude Code.": "Keiner deiner Agenten hat ein billion-context-Plugin, das mit magpie funktioniert: Pi, omp, OpenCode oder Claude Code.", + "billion-context is on for {agent} — restart it to use it": "billion-context ist für {agent} an — starte ihn neu, um es zu nutzen", + "billion-context is off for {agent} — restart it to see it": "billion-context ist für {agent} aus — starte ihn neu, damit es wirkt", + "billion-context is installed — switch it on for your agents below": "billion-context ist installiert — schalte es unten für deine Agenten ein", }, }); diff --git a/internal/gui/library.go b/internal/gui/library.go index ae4254b16..b0f67b364 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -397,6 +397,35 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { } writeJSON(rw, v) }) + // billion-context: which agents have its plugin, switching one on or + // off, and installing bili when the page is asked to + mux.HandleFunc("GET /api/library/bili", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, library.ReadBili()) + }) + mux.HandleFunc("POST /api/library/bili", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Agent string + On bool + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + v, err := library.SetBili(in.Agent, in.On) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, v) + }) + mux.HandleFunc("POST /api/library/bili/install", func(rw http.ResponseWriter, r *http.Request) { + v, err := library.InstallBili() + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, v) + }) // a project's folder, from the system's picker; "" when it's cancelled mux.HandleFunc("POST /api/library/projects/choose", func(rw http.ResponseWriter, r *http.Request) { dir, err := w.ChooseFolder("Choose a project") diff --git a/internal/gui/tests/library-bili.test.cjs b/internal/gui/tests/library-bili.test.cjs new file mode 100644 index 000000000..920160f1f --- /dev/null +++ b/internal/gui/tests/library-bili.test.cjs @@ -0,0 +1,128 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// billion-context in the Library (@Kling__Lab on X): a tab beside RTK. With +// no bili the card shows billion-context's own npm install and Install +// billion-context; once it is installed the card shows its version and that +// an agent switched on can't also run billion-context-pi or opencode-acp, +// and each agent's switch posts {agent, on} and is held while it runs. +// Every language, Chromium and WebKit, 1100 and 420 wide, nothing sideways. +// No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/aimer"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); +const lib = () => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code"), agent("pi", "Pi")], + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [], +}); +const npm = `npm install -g billion-context --prefix=${HOME}/.local`; +const view = (st) => st.installed + ? { path: `${HOME}/.local/bin/bili`, version: "0.1.213", url: "https://github.com/ranxianglei/billion-context", + agents: [{ id: "claude", name: "Claude Code", icon: "", on: st.on.claude }, { id: "pi", name: "Pi", icon: "", on: st.on.pi }], restart: st.restart } + : { url: "https://github.com/ranxianglei/billion-context", install: npm, agents: [{ id: "claude", name: "Claude Code", icon: "", on: false }, { id: "pi", name: "Pi", icon: "", on: false }] }; + +function server(lang, st) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib() }); + if (url.pathname === "/api/library/bili" && req.method() === "GET") return route.fulfill({ json: view(st) }); + if (url.pathname === "/api/library/bili") { + const body = JSON.parse(req.postData()); + st.posts.push(body); + await st.hold; + st.on[body.agent] = body.on; + st.restart = [body.agent]; + return route.fulfill({ json: view(st) }); + } + if (url.pathname === "/api/library/bili/install") { + st.installs++; + st.installed = true; + return route.fulfill({ json: view(st) }); + } + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const LANGS = ["en", "zh", "zh-TW", "ja", "de"]; +const english = "An agent switched on here can't also run billion-context-pi or opencode-acp."; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": billion-context installs from its tab and switches each agent", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of LANGS) for (const width of [1100, 420]) { + await t.test(`${lang} ${width}`, async () => { + let release; + const st = { installed: false, installs: 0, on: { claude: false, pi: false }, posts: [], hold: new Promise((r) => { release = r; }) }; + const ctx = await browser.newContext({ viewport: { width, height: 800 } }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, st)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + // its tab, right after RTK's + // the page's tabs, or the side nav's at a wide window + const tabs = page.locator(":is(#view-library .lib-tabs .opt, .nav-s):visible"); + await tabs.first().waitFor(); + const names = await tabs.allTextContents(); + assert.equal(names[names.indexOf("RTK") + 1], "billion-context"); + await tabs.nth(names.indexOf("billion-context")).click(); + + // not installed: the npm command, and Install billion-context + const cmd = v.locator(".lib-bili .lib-rtk-cmd"); + await cmd.waitFor(); + assert.equal(await cmd.textContent(), npm); + const sw = v.locator(".lib-list .lib-switch"); + assert.equal(await sw.count(), 2); + assert(await sw.first().isDisabled(), "a switch works with no bili"); + await v.locator(".lib-bili .lib-acts button").first().click(); + + // installed: its version, the note, and the switches + await v.locator(".lib-bili .note.mono").waitFor(); + assert.equal(await v.locator(".lib-bili .note.mono").textContent(), "v0.1.213"); + assert.equal(st.installs, 1); + const note = await v.locator(".lib-bili .lib-rtk-gain").textContent(); + assert(note.includes("billion-context-pi") && note.includes("opencode-acp"), note); + if (lang !== "en") assert.notEqual(note, english); + const intro = await v.locator(".lib-body > .lib-intro").textContent(); + if (lang !== "en") assert(!intro.startsWith("billion-context folds"), intro); + assert.equal(await sw.first().isDisabled(), false); + + // Pi switched on: held while it runs, then on + await sw.nth(1).click(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-list .lib-switch")[1]?.disabled); + release(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-list .lib-switch")[1]?.getAttribute("aria-checked") === "true"); + assert.deepEqual(st.posts, [{ agent: "pi", on: true }]); + assert.equal(await sw.first().getAttribute("aria-checked"), "false"); + const sideways = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(sideways <= 0, `the page scrolls sideways by ${sideways}px`); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/bili.go b/internal/library/bili.go new file mode 100644 index 000000000..24e54f36b --- /dev/null +++ b/internal/library/bili.go @@ -0,0 +1,632 @@ +package library + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "runtime" + "slices" + "strings" + "sync" + "time" + + "github.com/tidwall/jsonc" + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/settings" +) + +// billion-context (npm billion-context, its CLI bili) compresses an +// agent's context as it runs: old turns are folded into summaries the +// model can open again (compress, decompress, search_context), so a long +// session stays under the window. Its native plugins are written into an +// agent's own files by its own installer (bili plugin install ); +// magpie runs that for the agents switched on, and bili plugin remove for +// those switched off. +// +// Only the agents where bili's plugin works with magpie in front are +// offered: Pi, omp and OpenCode load it in process, and their requests +// still go to magpie with bili's tools added; Claude Code's goes through +// bili's local proxy, which forwards to the gateway (ANTHROPIC_BASE_URL +// .../bili/). Codex's lane is an MCP server only, ZCode's +// routes only its own provider, Kimi Code's renames the default model in +// config.toml at each start (bili-kimi), dsh's installs through dsh's +// package manager, and Hermes' can't be tried without touching its +// launcher: none of those is offered. +// +// bili's remove doesn't put a file back as it was: it leaves "packages": [] +// in Pi's settings.json and "extensions:" in omp's config.yml, and after +// magpie rewrote Claude Code's settings.json it took ANTHROPIC_BASE_URL out +// altogether (the agent then went to Anthropic) and put back the +// DISABLE_AUTO_COMPACT it had added. So magpie keeps each file as it was +// before the install and as the install left it, and after a remove puts +// back what the install changed and nothing changed since (biliRestore). + +// BiliURL is billion-context's page. +const BiliURL = "https://github.com/ranxianglei/billion-context" + +// biliPackage is its npm package. +const biliPackage = "billion-context" + +// biliLanes are the agents (magpie's ids) bili's plugin is offered for, +// each with the files its install writes that magpie puts back. +var biliLanes = map[string]func(a *agent.Agent) []string{ + "pi": func(a *agent.Agent) []string { return []string{a.Path} }, + "omp": func(a *agent.Agent) []string { return []string{a.Path} }, + "opencode": func(a *agent.Agent) []string { return []string{a.Path} }, + "claude": func(a *agent.Agent) []string { + return []string{a.Path, filepath.Join(filepath.Dir(a.Path), "commands", "acp-cache.md")} + }, +} + +// BiliAgent is one agent bili's plugin can be given to. +type BiliAgent struct { + ID string `json:"id"` + Name string `json:"name"` + Icon string `json:"icon"` + On bool `json:"on"` + // Status is what bili plugin list says of it when that isn't simply + // installed or not: partly installed, broken, an error + Status string `json:"status,omitempty"` +} + +// BiliView is the billion-context part of the Library page. +type BiliView struct { + Path string `json:"path,omitempty"` // "" when bili isn't installed + Version string `json:"version,omitempty"` + Agents []BiliAgent `json:"agents"` + URL string `json:"url"` + // Install is the command Install runs, "" when there is no npm + Install string `json:"install,omitempty"` + // ListErr is why bili plugin list said nothing magpie could read + ListErr string `json:"listErr,omitempty"` + Restart []string `json:"restart,omitempty"` + Backup string `json:"backup,omitempty"` +} + +var biliMu sync.Mutex + +// biliPath is bili's, "" when it isn't installed: on PATH, or where its +// documented install (npm -g with ~/.local as the prefix) puts it, which +// may not be on magpie's PATH yet. +var biliPath = func() string { + name := "bili" + if runtime.GOOS == "windows" { + name = "bili.cmd" + } + if p, err := proc.Look(name); err == nil { + return p + } + dirs := []string{filepath.Join(home(), ".local", "bin")} + if runtime.GOOS == "windows" { + dirs = []string{filepath.Join(appdir.Getenv("APPDATA"), "npm")} + } + for _, d := range dirs { + if p := filepath.Join(d, name); exists(p) { + return p + } + } + return "" +} + +// biliInstaller is billion-context's documented install: npm's global +// install with ~/.local as the prefix, so it needs no administrator; on +// Windows npm's own global folder, which is the user's. nil without npm. +var biliInstaller = func() []string { + npm, err := proc.Look("npm") + if err != nil { + return nil + } + if runtime.GOOS == "windows" { + return []string{npm, "install", "-g", biliPackage} + } + return []string{npm, "install", "-g", biliPackage, "--prefix=" + filepath.Join(home(), ".local")} +} + +// biliRun runs bili with nothing to answer it. +var biliRun = func(bin string, timeout time.Duration, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cmd := proc.CommandContext(ctx, bin, args...) + cmd.Stdin = nil + // a bili in ~/.local/bin is a node script: its folder goes first, and + // node is found where the user's shell finds it + cmd.Env = append(os.Environ(), "PATH="+filepath.Dir(bin)+string(os.PathListSeparator)+os.Getenv("PATH")) + out, err := cmd.CombinedOutput() + text := strings.TrimSpace(string(out)) + if err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return text, fmt.Errorf("bili %s didn't finish in %s", strings.Join(args, " "), timeout) + } + if text == "" { + text = err.Error() + } + return text, fmt.Errorf("bili %s: %s", strings.Join(args, " "), lastLines(text, 4)) + } + return text, nil +} + +// biliAgents are the agents here bili's plugin can be given to. One in +// WSL isn't: bili there is the distro's, and magpie runs this machine's. +func biliAgents(agents []*agent.Agent) []*agent.Agent { + if agents == nil { + agents = detected() + } + var out []*agent.Agent + for _, a := range agents { + if _, ok := biliLanes[a.ID]; ok && a.WSL == "" && !a.CLIMissing() { + out = append(out, a) + } + } + return out +} + +// biliStatusLine is a row of bili plugin list: the agent, then its +// status, then the version and how it updates, apart by two spaces or more. +var biliColumns = regexp.MustCompile(`\s{2,}`) + +// parseBiliList is each agent's status as bili plugin list prints it. +func parseBiliList(out string) map[string]string { + st := map[string]string{} + for _, line := range strings.Split(out, "\n") { + cols := biliColumns.Split(strings.TrimSpace(line), -1) + if len(cols) < 2 || cols[0] == "agent" { + continue + } + st[cols[0]] = cols[1] + } + return st +} + +// biliOn is whether a status says the plugin is there and whole. +func biliOn(status string) bool { + return status == "installed" || strings.HasPrefix(status, "installed (") +} + +// ReadBili says whether bili is installed and which agents have its plugin. +func ReadBili() *BiliView { + return readBili(detected()) +} + +func readBili(agents []*agent.Agent) *BiliView { + v := &BiliView{Agents: []BiliAgent{}, URL: BiliURL, Path: biliPath()} + var st map[string]string + if v.Path == "" { + if c := biliInstaller(); c != nil { + v.Install = biliShown(c) + } + } else { + if out, err := biliRun(v.Path, 30*time.Second, "--version"); err == nil { + v.Version, _, _ = strings.Cut(strings.TrimSpace(out), " ") + } + out, err := biliRun(v.Path, 30*time.Second, "plugin", "list") + if st = parseBiliList(out); err != nil || len(st) == 0 { + v.ListErr = lastLines(out, 2) + if err != nil { + v.ListErr = err.Error() + } + } + } + for _, a := range biliAgents(agents) { + ba := BiliAgent{ID: a.ID, Name: a.Name, Icon: a.Icon} + if s, ok := st[a.ID]; ok { + ba.On = biliOn(s) + if !ba.On && s != "not installed" { + ba.Status = s + } + } + v.Agents = append(v.Agents, ba) + } + return v +} + +// biliShown is the install command as the page shows it: npm by name. +func biliShown(c []string) string { + c = slices.Clone(c) + c[0] = strings.TrimSuffix(filepath.Base(c[0]), ".cmd") + return strings.Join(c, " ") +} + +// biliState is each file of an agent bili's install wrote, as it was +// before (nil: not there) and as the install left it. +type biliFile struct { + Path string `json:"path"` + Before *string `json:"before"` + After *string `json:"after"` + // Marks are the .bili-bak and .bili-last bili keeps beside it that + // weren't there before the install: taken away with it + Marks []string `json:"marks,omitempty"` +} + +func biliStateFile() string { return filepath.Join(settings.Dir(), "bili-plugins.json") } + +func readBiliState() map[string][]biliFile { + m := map[string][]biliFile{} + if b, err := os.ReadFile(biliStateFile()); err == nil { + _ = json.Unmarshal(b, &m) + } + return m +} + +func writeBiliState(m map[string][]biliFile) error { + b, err := json.MarshalIndent(m, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(biliStateFile()), 0o700); err != nil { + return err + } + return edit.WriteAtomic(biliStateFile(), b) +} + +func biliRead(path string) *string { + b, err := os.ReadFile(path) + if err != nil { + return nil + } + s := string(b) + return &s +} + +// SetBili gives bili's plugin to an agent with bili's own installer, or +// takes it away with bili's own remover and puts back what the install +// changed in the agent's files. +func SetBili(id string, on bool) (*BiliView, error) { + biliMu.Lock() + defer biliMu.Unlock() + agents := detected() + var a *agent.Agent + for _, x := range biliAgents(agents) { + if x.ID == id { + a = x + } + } + files, ok := biliLanes[id] + switch { + case !ok: + return nil, fmt.Errorf("billion-context isn't offered for %s", id) + case a == nil: + return nil, fmt.Errorf("%s isn't installed", id) + } + bin := biliPath() + if bin == "" { + return nil, fmt.Errorf("billion-context isn't installed — install it first (%s)", BiliURL) + } + paths := files(a) + b := newBackups() + for _, p := range append(slices.Clone(paths), claudeJSON()) { + if a.ID != "claude" && p == claudeJSON() { + continue + } + if err := b.keep(a.ID, p); err != nil { + return nil, err + } + } + state := readBiliState() + if on { + var snap []biliFile + for _, p := range paths { + f := biliFile{Path: p, Before: biliRead(p)} + for _, m := range []string{p + ".bili-bak", p + ".bili-last"} { + if !exists(m) { + f.Marks = append(f.Marks, m) + } + } + snap = append(snap, f) + } + out, err := biliRun(bin, 2*time.Minute, "plugin", "install", biliLane(id)) + if err != nil { + return nil, err + } + for i := range snap { + snap[i].After = biliRead(snap[i].Path) + } + state[id] = snap + if err := writeBiliState(state); err != nil { + return nil, err + } + v := readBili(agents) + if !slices.ContainsFunc(v.Agents, func(x BiliAgent) bool { return x.ID == id && x.On }) { + return nil, fmt.Errorf("bili plugin install %s ran, but bili doesn't list it as installed: %s", biliLane(id), lastLines(out, 3)) + } + v.Restart, v.Backup = []string{id}, b.dir + if b.dir != "" { + pruneBackups() + } + return v, nil + } + cur := map[string]*string{} + for _, p := range paths { + cur[p] = biliRead(p) + } + if _, err := biliRun(bin, 2*time.Minute, "plugin", "remove", biliLane(id)); err != nil { + return nil, err + } + snap := state[id] + var errs []error + for _, p := range paths { + var f *biliFile + for i := range snap { + if snap[i].Path == p { + f = &snap[i] + } + } + if err := biliRestore(p, f, cur[p], biliRead(p)); err != nil { + errs = append(errs, err) + } + if f != nil { + for _, m := range f.Marks { + if err := os.Remove(m); err != nil && !os.IsNotExist(err) { + errs = append(errs, err) + } + } + } + } + if err := errors.Join(errs...); err != nil { + return nil, err + } + delete(state, id) + if err := writeBiliState(state); err != nil { + return nil, err + } + v := readBili(agents) + v.Restart, v.Backup = []string{id}, b.dir + if b.dir != "" { + pruneBackups() + } + return v, nil +} + +// biliLane is bili's name of an agent's plugin: magpie's id, as both use it. +func biliLane(id string) string { return id } + +// biliRestore writes p after bili's remove: f is the file before and after +// the install (nil when magpie didn't install it), cur as it was just +// before the remove and now as the remove left it. What the install changed +// and nothing has changed since goes back to what it was; what was changed +// since (magpie picking another model, the user) stays as the remove left +// it; and what the remove changed that the install hadn't goes back. +func biliRestore(p string, f *biliFile, cur, now *string) error { + var out *string + switch { + case f != nil && same(cur, f.After): + // nothing touched it since the install: as it was before, byte for byte + out = f.Before + case strings.HasSuffix(p, ".json") || strings.HasSuffix(p, ".jsonc"): + var before, after *string + if f != nil { + before, after = f.Before, f.After + } + s, err := biliMergeJSON(before, after, cur, now) + if err != nil { + // a file magpie can't read as JSON is left as bili left it + return nil + } + out = s + if f != nil && f.Before != nil && out != nil && sameJSON(*out, *f.Before) { + out = f.Before + } + default: + return nil + } + if same(out, now) { + return nil + } + if out == nil { + if err := os.Remove(p); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + return edit.WriteAtomic(p, []byte(*out)) +} + +func same(a, b *string) bool { + if a == nil || b == nil { + return a == b + } + return *a == *b +} + +func parseJSONC(s *string) (map[string]any, bool) { + if s == nil || strings.TrimSpace(*s) == "" { + return map[string]any{}, true + } + var m map[string]any + if json.Unmarshal(jsonc.ToJSON(edit.TrimBOM([]byte(*s))), &m) != nil || m == nil { + return nil, false + } + return m, true +} + +func sameJSON(a, b string) bool { + x, ok1 := parseJSONC(&a) + y, ok2 := parseJSONC(&b) + return ok1 && ok2 && jsonEqual(x, y) +} + +func jsonEqual(a, b any) bool { + x, _ := json.Marshal(a) + y, _ := json.Marshal(b) + return bytes.Equal(x, y) +} + +// jsonAt is the value at path in m, and whether there is one. +func jsonAt(m map[string]any, path []string) (any, bool) { + var v any = m + for _, k := range path { + o, ok := v.(map[string]any) + if !ok { + return nil, false + } + if v, ok = o[k]; !ok { + return nil, false + } + } + return v, true +} + +// jsonDiffs are the paths where a and b differ: down through objects both +// have, an object, array or value that differs as a whole below that. +func jsonDiffs(a, b map[string]any, at []string, out *[][]string) { + keys := map[string]bool{} + for k := range a { + keys[k] = true + } + for k := range b { + keys[k] = true + } + for k := range keys { + p := append(slices.Clone(at), k) + x, okx := a[k] + y, oky := b[k] + xm, isx := x.(map[string]any) + ym, isy := y.(map[string]any) + switch { + case okx && oky && isx && isy: + jsonDiffs(xm, ym, p, out) + case okx != oky || !jsonEqual(x, y): + *out = append(*out, p) + } + } +} + +func under(p, q []string) bool { + return len(p) >= len(q) && slices.Equal(p[:len(q)], q) +} + +// keyPath is p as edit's key paths spell it, false when a key has a +// character they can't hold. +func keyPath(p []string) (string, bool) { + parts := make([]string, len(p)) + for i, k := range p { + if k == "" || strings.ContainsAny(k, `*?|#@\!=<>%`) { + return "", false + } + parts[i] = strings.ReplaceAll(k, ".", `\.`) + } + return strings.Join(parts, "."), true +} + +// biliURL is the ANTHROPIC_BASE_URL bili's Claude Code plugin writes: its +// proxy, then the URL it forwards to. +var biliURL = regexp.MustCompile(`^https?://(?:127\.0\.0\.1|localhost|\[::1\]):\d+/bili/(https?://.+)$`) + +// biliMergeJSON is now with what the install changed (before → after) and +// nothing changed since (cur still has it) put back as before, and what +// the remove changed beyond that (cur → now) put back as cur. Without a +// record of the install, a Claude Code base URL the remove took out goes +// back to the address bili forwarded to. +func biliMergeJSON(before, after, cur, now *string) (*string, error) { + B, ok1 := parseJSONC(before) + I, ok2 := parseJSONC(after) + C, ok3 := parseJSONC(cur) + R, ok4 := parseJSONC(now) + if !ok1 || !ok2 || !ok3 || !ok4 { + return nil, errors.New("not JSON") + } + type change struct { + path []string + v any + has bool + } + var changes []change + var installed [][]string + if after != nil { + jsonDiffs(B, I, nil, &installed) + } + for _, p := range installed { + ci, hc := jsonAt(C, p) + ii, hi := jsonAt(I, p) + if hc == hi && jsonEqual(ci, ii) { + v, has := jsonAt(B, p) + changes = append(changes, change{p, v, has}) + } + } + if after == nil { + // no record of the install: all the remove took out may be bili's, + // except the address Claude Code was sent to before bili's proxy + base := []string{"env", "ANTHROPIC_BASE_URL"} + c, hc := jsonAt(C, base) + _, hr := jsonAt(R, base) + if s, ok := c.(string); ok && hc && !hr { + if m := biliURL.FindStringSubmatch(s); m != nil { + changes = append(changes, change{base, m[1], true}) + } + } + } else { + var removed [][]string + jsonDiffs(C, R, nil, &removed) + for _, p := range removed { + if slices.ContainsFunc(installed, func(q []string) bool { return under(p, q) || under(q, p) }) { + continue + } + v, has := jsonAt(C, p) + changes = append(changes, change{p, v, has}) + } + } + if len(changes) == 0 { + return now, nil + } + raw := []byte("{}\n") + if now != nil { + raw = []byte(*now) + } + var set []edit.KV + var del []string + for _, c := range changes { + kp, ok := keyPath(c.path) + if !ok { + continue + } + if !c.has { + del = append(del, kp) + continue + } + b, err := json.Marshal(c.v) + if err != nil { + return nil, err + } + set = append(set, edit.KV{Path: kp, Value: json.RawMessage(b)}) + } + out, err := edit.PatchJSON(raw, set, del) + if err != nil { + return nil, err + } + // an object the remove emptied that wasn't there before goes too + s := string(out) + if now == nil && len(set) == 0 { + return nil, nil + } + return &s, nil +} + +// InstallBili installs billion-context the way its README says. +func InstallBili() (*BiliView, error) { + biliMu.Lock() + defer biliMu.Unlock() + if biliPath() != "" { + return ReadBili(), nil + } + c := biliInstaller() + if c == nil { + return nil, fmt.Errorf("npm isn't installed — install Node.js first, or see %s", BiliURL) + } + out, err := runPlain(c, 5*time.Minute) + if err != nil { + return nil, err + } + proc.Forget() + v := ReadBili() + if v.Path == "" { + return nil, fmt.Errorf("%s ran, but bili still isn't found: %s", biliShown(c), lastLines(out, 3)) + } + return v, nil +} diff --git a/internal/library/bili_test.go b/internal/library/bili_test.go new file mode 100644 index 000000000..37a84ef4b --- /dev/null +++ b/internal/library/bili_test.go @@ -0,0 +1,368 @@ +package library + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/testenv" +) + +// fakeBili stands in for bili 0.1.213's plugin installer and remover, for +// Pi and Claude Code, as they were seen writing in a sandbox HOME: each +// write leaves .bili-bak (the file before, taken again whenever it +// changed since bili's last write) and .bili-last; Pi's remove leaves +// "packages": [], and Claude Code's deletes ANTHROPIC_BASE_URL outright +// and puts back the DISABLE_AUTO_COMPACT of a backup taken after it. +type fakeBili struct { + t *testing.T + h string + on map[string]bool + runs []string + last map[string]string // each file as bili last wrote it + proxy string +} + +func newFakeBili(t *testing.T, h string) *fakeBili { + f := &fakeBili{t: t, h: h, on: map[string]bool{}, last: map[string]string{}, proxy: "http://127.0.0.1:18787/bili/"} + path, run := biliPath, biliRun + biliPath = func() string { return filepath.Join(h, ".local", "bin", "bili") } + biliRun = func(_ string, _ time.Duration, args ...string) (string, error) { return f.run(args...) } + t.Cleanup(func() { biliPath, biliRun = path, run }) + return f +} + +func (f *fakeBili) settings(id string) string { + if id == "pi" { + return filepath.Join(f.h, ".pi", "agent", "settings.json") + } + return filepath.Join(f.h, ".claude", "settings.json") +} + +func (f *fakeBili) obj(p string) map[string]any { + m := map[string]any{} + if b, err := os.ReadFile(p); err == nil && len(strings.TrimSpace(string(b))) > 0 { + if err := json.Unmarshal(b, &m); err != nil { + f.t.Fatalf("bili reads %s: %v", p, err) + } + } + return m +} + +// write is bili's backupBeforeWrite and its write +func (f *fakeBili) write(p string, m map[string]any) { + cur, err := os.ReadFile(p) + if err == nil && string(cur) != f.last[p] { + write(f.t, p+".bili-bak", string(cur)) + } + b, _ := json.MarshalIndent(m, "", " ") + s := string(b) + "\n" + write(f.t, p, s) + write(f.t, p+".bili-last", "sha256") + f.last[p] = s +} + +func (f *fakeBili) run(args ...string) (string, error) { + f.runs = append(f.runs, strings.Join(args, " ")) + switch strings.Join(args, " ") { + case "--version": + return "0.1.213 (133f3525c)", nil + case "plugin list": + out := "agent status version updates via\n" + for _, id := range []string{"pi", "omp", "opencode", "claude", "codex"} { + st := "not installed" + if f.on[id] { + st = "installed (0.1.213)" + } + out += id + " " + st + " - npm\n" + } + return out, nil + } + if len(args) != 3 || args[0] != "plugin" { + return "", errors.New("unknown: " + strings.Join(args, " ")) + } + id, p := args[2], f.settings(args[2]) + m := f.obj(p) + switch args[1] + " " + id { + case "install pi": + m["packages"] = append(anySlice(m["packages"]), "npm:billion-context") + case "remove pi": + m["packages"] = slices.DeleteFunc(anySlice(m["packages"]), func(v any) bool { return v == "npm:billion-context" }) + case "install claude": + env, _ := m["env"].(map[string]any) + if env == nil { + env = map[string]any{} + } + up, _ := env["ANTHROPIC_BASE_URL"].(string) + if up == "" { + up = "https://api.anthropic.com" + } + env["ANTHROPIC_BASE_URL"] = f.proxy + up + env["DISABLE_AUTO_COMPACT"] = "1" + m["env"] = env + m["hooks"] = map[string]any{"SessionStart": []any{map[string]any{"hooks": []any{map[string]any{"type": "command", "command": "node claude-native-bootstrap.js"}}}}} + write(f.t, filepath.Join(f.h, ".claude", "commands", "acp-cache.md"), "acp cache\n") + case "remove claude": + bak := map[string]any{} + f.write(p, m) // the backup taken again, when magpie wrote since + _ = json.Unmarshal([]byte(read(f.t, p+".bili-bak")), &bak) + env, _ := m["env"].(map[string]any) + delete(env, "ANTHROPIC_BASE_URL") + delete(env, "DISABLE_AUTO_COMPACT") + if be, ok := bak["env"].(map[string]any); ok && be["DISABLE_AUTO_COMPACT"] != nil { + env["DISABLE_AUTO_COMPACT"] = be["DISABLE_AUTO_COMPACT"] + } + delete(m, "hooks") + os.Remove(filepath.Join(f.h, ".claude", "commands", "acp-cache.md")) + default: + return "", errors.New("no lane " + id) + } + f.write(p, m) + f.on[id] = args[1] == "install" + return "done", nil +} + +func anySlice(v any) []any { + s, _ := v.([]any) + return s +} + +func biliOnFor(t *testing.T) map[string]bool { + t.Helper() + m := map[string]bool{} + for _, a := range ReadBili().Agents { + m[a.ID] = a.On + } + return m +} + +// TestBiliOnOffExact: switched on then off, an agent's files are as they +// were byte for byte — bili's remove leaves Pi "packages": [] and its +// .bili-bak and .bili-last beside each file — and Claude Code's command +// file is gone with it. +func TestBiliOnOffExact(t *testing.T) { + h := sandbox(t) + f := newFakeBili(t, h) + pi := filepath.Join(h, ".pi", "agent", "settings.json") + cc := filepath.Join(h, ".claude", "settings.json") + piWas := "{\n \"defaultModel\": \"magpie/gpt-5\", \"theme\": \"dark\"\n}\n" + ccWas := "{\"model\":\"opus\",\n \"env\": {\"ANTHROPIC_BASE_URL\": \"http://127.0.0.1:3425\", \"ANTHROPIC_AUTH_TOKEN\": \"magpie\"}}" + write(t, pi, piWas) + write(t, cc, ccWas) + + v := ReadBili() + if v.Version != "0.1.213" || v.ListErr != "" { + t.Fatalf("version %q, list error %q", v.Version, v.ListErr) + } + var got []string + for _, a := range v.Agents { + got = append(got, a.ID) + } + // codex is here and bili has a lane for it, an MCP server only: not offered + if !slices.Contains(got, "pi") || !slices.Contains(got, "claude") || !slices.Contains(got, "opencode") || slices.Contains(got, "codex") || slices.Contains(got, "gemini") { + t.Fatalf("offered %v", got) + } + for _, id := range []string{"pi", "claude"} { + if _, err := SetBili(id, true); err != nil { + t.Fatal(err) + } + } + if on := biliOnFor(t); !on["pi"] || !on["claude"] || on["opencode"] { + t.Fatalf("on: %v", on) + } + if !strings.Contains(read(t, cc), "/bili/http://127.0.0.1:3425") { + t.Fatalf("Claude Code isn't sent through bili:\n%s", read(t, cc)) + } + for _, id := range []string{"pi", "claude"} { + v, err := SetBili(id, false) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(v.Restart, []string{id}) || v.Backup == "" { + t.Fatalf("restart %v, backup %q", v.Restart, v.Backup) + } + } + if got := read(t, pi); got != piWas { + t.Fatalf("Pi's settings.json:\n%s\nwant\n%s", got, piWas) + } + if got := read(t, cc); got != ccWas { + t.Fatalf("Claude Code's settings.json:\n%s\nwant\n%s", got, ccWas) + } + for _, p := range []string{pi + ".bili-bak", pi + ".bili-last", cc + ".bili-bak", cc + ".bili-last", filepath.Join(h, ".claude", "commands", "acp-cache.md")} { + if exists(p) { + t.Fatalf("%s left behind", p) + } + } + if on := biliOnFor(t); on["pi"] || on["claude"] { + t.Fatalf("on: %v", on) + } + if want := []string{"plugin install pi", "plugin install claude", "plugin remove pi", "plugin remove claude"}; !slices.Equal(filter(f.runs, "plugin install", "plugin remove"), want) { + t.Fatalf("ran %v, want %v", f.runs, want) + } +} + +func filter(runs []string, prefixes ...string) []string { + var out []string + for _, r := range runs { + for _, p := range prefixes { + if strings.HasPrefix(r, p) { + out = append(out, r) + } + } + } + return out +} + +// TestBiliClaudeKeepsMagpiesRoute: magpie rewrote Claude Code's +// settings.json while bili was on (another model picked). bili's remove +// then takes ANTHROPIC_BASE_URL out, which would send Claude Code to +// Anthropic, and puts back the DISABLE_AUTO_COMPACT it added; switched off, +// Claude Code goes to magpie again, without that, with the model picked. +func TestBiliClaudeKeepsMagpiesRoute(t *testing.T) { + h := sandbox(t) + newFakeBili(t, h) + cc := filepath.Join(h, ".claude", "settings.json") + write(t, cc, `{"model":"opus","env":{"ANTHROPIC_BASE_URL":"http://127.0.0.1:3425","ANTHROPIC_AUTH_TOKEN":"magpie"},"permissions":{"allow":["Bash"]}}`) + if _, err := SetBili("claude", true); err != nil { + t.Fatal(err) + } + // magpie picks another model, keeping bili's address in front of it + m := map[string]any{} + if err := json.Unmarshal([]byte(read(t, cc)), &m); err != nil { + t.Fatal(err) + } + m["model"] = "magpie/glm-5" + m["env"].(map[string]any)["ANTHROPIC_MODEL"] = "magpie/glm-5" + b, _ := json.MarshalIndent(m, "", "\t") + write(t, cc, string(b)) + + if _, err := SetBili("claude", false); err != nil { + t.Fatal(err) + } + got := map[string]any{} + if err := json.Unmarshal([]byte(read(t, cc)), &got); err != nil { + t.Fatalf("%v:\n%s", err, read(t, cc)) + } + env, _ := got["env"].(map[string]any) + if env["ANTHROPIC_BASE_URL"] != "http://127.0.0.1:3425" { + t.Fatalf("ANTHROPIC_BASE_URL = %v, want magpie's:\n%s", env["ANTHROPIC_BASE_URL"], read(t, cc)) + } + if _, ok := env["DISABLE_AUTO_COMPACT"]; ok { + t.Fatalf("DISABLE_AUTO_COMPACT left:\n%s", read(t, cc)) + } + if _, ok := got["hooks"]; ok { + t.Fatalf("hooks left:\n%s", read(t, cc)) + } + if got["model"] != "magpie/glm-5" || env["ANTHROPIC_MODEL"] != "magpie/glm-5" || env["ANTHROPIC_AUTH_TOKEN"] != "magpie" || got["permissions"] == nil { + t.Fatalf("magpie's and the user's own values lost:\n%s", read(t, cc)) + } +} + +// TestBiliOffWithoutRecord: a plugin put in outside magpie, with no record +// of the file before it: bili's remove takes Claude Code's +// ANTHROPIC_BASE_URL out, and magpie puts back the address bili forwarded to. +func TestBiliOffWithoutRecord(t *testing.T) { + h := sandbox(t) + f := newFakeBili(t, h) + cc := filepath.Join(h, ".claude", "settings.json") + write(t, cc, `{"env":{"ANTHROPIC_BASE_URL":"http://127.0.0.1:3425"}}`) + if _, err := f.run("plugin", "install", "claude"); err != nil { + t.Fatal(err) + } + if _, err := SetBili("claude", false); err != nil { + t.Fatal(err) + } + got := map[string]any{} + if err := json.Unmarshal([]byte(read(t, cc)), &got); err != nil { + t.Fatal(err) + } + env, _ := got["env"].(map[string]any) + if env["ANTHROPIC_BASE_URL"] != "http://127.0.0.1:3425" { + t.Fatalf("ANTHROPIC_BASE_URL not put back:\n%s", read(t, cc)) + } + if _, ok := env["DISABLE_AUTO_COMPACT"]; ok || got["hooks"] != nil { + t.Fatalf("bili's own values put back:\n%s", read(t, cc)) + } +} + +// TestBiliNotInstalled: no bili, so no switch works, and the page has +// billion-context's own install command when npm is here. +func TestBiliNotInstalled(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fake npm is a shell script") + } + h := sandbox(t) + bin := filepath.Join(h, "bin") + v := ReadBili() + if v.Path != "" || v.Install != "" { + t.Fatalf("path %q, install %q, with no bili and no npm", v.Path, v.Install) + } + if _, err := SetBili("pi", true); err == nil { + t.Fatal("switched on with no bili") + } + if _, err := InstallBili(); err == nil { + t.Fatal("installed with no npm") + } + // npm's global install with ~/.local as the prefix puts bili there + defer proc.Forget() + testenv.Program(t, filepath.Join(bin, "npm"), `#!/bin/sh +[ "$1 $2 $3 $4" = "install -g billion-context --prefix=$HOME/.local" ] || { echo "unknown: $*" >&2; exit 2; } +/bin/mkdir -p "$HOME/.local/bin" +printf '#!/bin/sh\necho "0.1.213 (x)"\n' > "$HOME/.local/bin/bili" +/bin/chmod +x "$HOME/.local/bin/bili" +`) + proc.Forget() + if v := ReadBili(); v.Install != "npm install -g billion-context --prefix="+filepath.Join(h, ".local") { + t.Fatalf("install %q", v.Install) + } + v, err := InstallBili() + if err != nil { + t.Fatal(err) + } + if v.Path != filepath.Join(h, ".local", "bin", "bili") || v.Version != "0.1.213" { + t.Fatalf("path %q, version %q", v.Path, v.Version) + } +} + +// TestParseBiliList: bili plugin list's table, as bili 0.1.213 prints it. +func TestParseBiliList(t *testing.T) { + out := `agent status version updates via +pi installed (0.1.213) 0.1.213 npm (pi update) +claude partially installed — rerun bili plugin install claude - - +opencode not installed - - +omp error: config.yml unreadable - -` + st := parseBiliList(out) + if !biliOn(st["pi"]) || biliOn(st["claude"]) || biliOn(st["opencode"]) || st["opencode"] != "not installed" || st["omp"] != "error: config.yml unreadable" { + t.Fatalf("%q", st) + } +} + +// TestBiliMergeJSON: what the install changed and nothing touched since +// goes back; a value changed since stays; one the remove changed beyond +// the install goes back as it was before the remove. +func TestBiliMergeJSON(t *testing.T) { + s := func(v string) *string { return &v } + before := s(`{"a":1,"keep":"x"}`) + after := s(`{"a":1,"keep":"x","added":true,"plugins":["b"]}`) + cur := s(`{"a":2,"keep":"x","added":true,"plugins":["b","mine"]}`) + now := s(`{"a":2,"plugins":["mine"],"added":true}`) + out, err := biliMergeJSON(before, after, cur, now) + if err != nil { + t.Fatal(err) + } + got := map[string]any{} + if err := json.Unmarshal([]byte(*out), &got); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(got) + if string(b) != `{"a":2,"keep":"x","plugins":["mine"]}` { + t.Fatalf("got %s", b) + } +} diff --git a/site/public/docs/ja/library.html b/site/public/docs/ja/library.html index b76a492a7..2a5c8ffce 100644 --- a/site/public/docs/ja/library.html +++ b/site/public/docs/ja/library.html @@ -92,6 +92,7 @@ サブエージェントのモデル フック RTK + billion-context magpie が触るもの @@ -99,7 +100,7 @@

ドキュメント · ライブラリ

ライブラリ

magpie の ライブラリ は、指示、MCP サーバー、スキル、フック、サブエージェントを一か所にまとめ、チェックしたエージェントそれぞれに、そのエージェント自身のファイルと形式で書き込みます。エージェントはいつもどおりそのファイルを読みます。magpie はエージェントと渡したものの間に層を挟みません。スキル、MCP ツール、サブエージェントをいつ使うかは、エージェント自身が決めます。

-

ページには 指示、MCP サーバー、スキル、フック、サブエージェント、RTK の 6 つのタブがあります。各項目にはエージェントの列があり、チェックすると渡し、外すと取り除きます。エージェントは次に起動したときに変更を読みます。

+

ページには 指示、MCP サーバー、スキル、フック、サブエージェント、RTK、billion-context の 7 つのタブがあります。各項目にはエージェントの列があり、チェックすると渡し、外すと取り除きます。エージェントは次に起動したときに変更を読みます。

保存場所

    @@ -235,6 +236,9 @@ magpie library sync # エージェントに書き直す

    RTK

    RTK タブでは RTK をエージェントごとにオンにします。エージェントのシェルコマンドが RTK を通り、出力が短くなってトークンを節約します。magpie は RTK をインストールでき、RTK がなくてもオフにできます。

    +

    billion-context

    +

    billion-context タブでは billion-context のプラグインをエージェントごとにオンにします。長いセッションの古いやり取りを、モデルが再び開ける要約に畳み込み、セッションをモデルのコンテキストウィンドウに収めます。対象は Pi、omp、OpenCode、Claude Code で、オンにしてもリクエストは magpie を通ります。magpie はインストールでき(npm install -g billion-context --prefix=~/.local)、billion-context 自身のインストーラーとリムーバーを実行します。オフにすると、インストールで変わったエージェントの設定を元に戻します。ここでオンにしたエージェントでは billion-context-pi や opencode-acp を併用できません。

    +

    magpie が触るもの

    • 自分が書いたものだけ:マーカーの間のテキスト、記録したエントリ、自分のものと印を付けたファイル。
    • diff --git a/site/public/docs/library.html b/site/public/docs/library.html index 3267c6b94..1ea76a951 100644 --- a/site/public/docs/library.html +++ b/site/public/docs/library.html @@ -92,6 +92,7 @@ Subagent models Hooks RTK + billion-context What magpie touches @@ -99,7 +100,7 @@

      Docs · Library

      Library

      magpie’s Library keeps instructions, MCP servers, skills, hooks and subagents in one place, and writes each of them into every agent you tick for it, in that agent’s own files and format. The agents read those files as they always do. magpie adds no layer between an agent and what it is given: the agent itself decides when to use a skill, an MCP tool or a subagent.

      -

      The page has six tabs: Instructions, MCP servers, Skills, Hooks, Subagents and RTK. Each item has a row of agents; tick an agent to give it the item, untick it to take it away. An agent reads the change when it starts again.

      +

      The page has seven tabs: Instructions, MCP servers, Skills, Hooks, Subagents, RTK and billion-context. Each item has a row of agents; tick an agent to give it the item, untick it to take it away. An agent reads the change when it starts again.

      Where it is kept

        @@ -235,6 +236,9 @@ magpie library sync # write it into the agents again

        RTK

        The RTK tab turns on RTK per agent: the agent’s shell commands run through RTK, which shortens their output to save tokens. magpie can install RTK for you; turning it off works with RTK gone.

        +

        billion-context

        +

        The billion-context tab turns on billion-context’s plugin per agent: it folds older turns of a long session into summaries the model can open again, so the session stays inside the model’s window. It is offered for Pi, omp, OpenCode and Claude Code, whose requests still go through magpie with it on. magpie can install it for you (npm install -g billion-context --prefix=~/.local) and runs its own installer and remover; turning it off puts back what the install changed in the agent’s settings. An agent turned on here can’t also run billion-context-pi or opencode-acp.

        +

        What magpie touches

        • Only what it wrote: the text between its markers, entries it recorded, files it marked as its own.
        • diff --git a/site/public/docs/zh/library.html b/site/public/docs/zh/library.html index abba59d74..48cdb7cec 100644 --- a/site/public/docs/zh/library.html +++ b/site/public/docs/zh/library.html @@ -92,6 +92,7 @@ 子代理的模型 Hooks RTK + billion-context magpie 会改什么 @@ -99,7 +100,7 @@

          文档 · 资源库

          资源库

          magpie 的 资源库 把指令、MCP 服务器、技能、Hooks 和子代理放在一处,再把每一项写进你勾选的每个 Agent,用的是那个 Agent 自己的文件和格式。Agent 像平常一样读这些文件。magpie 不在 Agent 和这些内容之间加任何一层:什么时候用某个技能、某个 MCP 工具或某个子代理,由 Agent 自己决定。

          -

          页面有六个标签:指令、MCP 服务器、技能、Hooks、子代理 和 RTK。每一项下面有一排 Agent;勾上就给它,取消勾选就拿走。Agent 重启后读到改动。

          +

          页面有七个标签:指令、MCP 服务器、技能、Hooks、子代理、RTK 和 billion-context。每一项下面有一排 Agent;勾上就给它,取消勾选就拿走。Agent 重启后读到改动。

          存放位置

            @@ -235,6 +236,9 @@ magpie library sync # 重新写进各个 Agent

            RTK

            RTK 标签可以按 Agent 打开 RTK:Agent 的 shell 命令经过 RTK 运行,输出被压短以节省 token。magpie 可以帮你安装 RTK;RTK 卸掉后也能关闭。

            +

            billion-context

            +

            billion-context 标签可以按 Agent 打开 billion-context 的插件:它把长会话里较早的对话折叠成模型可以再展开的摘要,让会话始终留在模型的上下文窗口内。支持 Pi、omp、OpenCode 和 Claude Code,打开后它们的请求仍经过 magpie。magpie 可以帮你安装(npm install -g billion-context --prefix=~/.local),并运行它自己的安装和卸载命令;关闭时会把安装改动过的 Agent 设置恢复原样。在这里打开的 Agent 不能再同时使用 billion-context-pi 或 opencode-acp。

            +

            magpie 会改什么

            • 只改它自己写的:标记之间的文字、它记录过的条目、它标记为自己的文件。