diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 23bfede2d..092f611a5 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -7,7 +7,8 @@ the subagents it can hand a task to. 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. +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. ## Responsibilities and sources of truth @@ -33,6 +34,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | 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) | +| 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 @@ -108,6 +110,8 @@ 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 'TestPi' +node --test internal/gui/tests/library-pi-extensions.test.cjs node --test internal/gui/tests/library-rtk-wsl.test.cjs node --test internal/gui/tests/library-wsl-asleep.test.cjs node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/mcp-local-server.test.cjs internal/gui/tests/skill-handover.test.cjs diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index a99a0c391..7e83ffee2 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -341,6 +341,7 @@ var notYet = map[string]string{ "GET /api/library/market/servers": L, // library.go "GET /api/library/market/skills": L, // library.go "GET /api/library/mcp-signin/{id}": L, // library.go + "GET /api/library/pi": L, // library.go "GET /api/library/rtk": L, // library.go "GET /api/library/skill": L, // library.go "POST /api/library/market/about": L, // library.go @@ -349,6 +350,8 @@ var notYet = map[string]string{ "POST /api/library/mcp-signout": L, // library.go "POST /api/library/mcp/check": L, // library.go "POST /api/library/mcp/config": L, // library.go + "POST /api/library/pi": L, // library.go + "POST /api/library/pi/copy": L, // library.go "POST /api/library/projects/choose": W, // library.go "POST /api/library/reveal": W, // library.go "POST /api/library/rtk": L, // library.go diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index fe1dabc63..9e6a01a73 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -535,6 +535,7 @@ magpie.plugin("library", (ctx) => { // drawn over again replaced the row under the reader's pointer (#3099) if (quiet === "open" && seen(lib) === was && tab !== "rtk" && page.querySelector(":scope > .lib-body")) return; rtk = null; // asked again when its tab is drawn: an agent may have been installed since + piView = null; render(); } catch (e) { status(e.message, "err"); @@ -809,6 +810,8 @@ magpie.plugin("library", (ctx) => { box.append(card, head("60px"), rows(6, true)); } else if (which === "rtk") { box.append(rows(1, false), head("60px"), rows(5, true)); + } else if (which === "pi") { + box.append(head("60px"), rows(4, true)); } else { box.append(rows(5, true)); } @@ -821,6 +824,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(); + // Pi's extensions too: one installed or changed outside magpie since + if (id === "pi" && piView) loadPi(); if (!lib) return page.querySelector(":scope > .lib-skel")?.replaceWith(skeleton(id)); render(); syncLists(); } @@ -837,6 +842,7 @@ magpie.plugin("library", (ctx) => { ["hooks", t("Hooks") + n("hooks")], ["subagents", t("Subagents") + n("subagents")], ["rtk", "RTK"], + ...(hasPi() ? [["pi", t("Pi packages")]] : []), ], tab, openTab); tabs.classList.add("lib-tabs"); head.append(tabs); @@ -890,6 +896,8 @@ magpie.plugin("library", (ctx) => { // the MCP servers alone with no agent to write to; the tab the reader // last picked is kept for when there is one if (agentless()) tab = "mcp"; + // Pi's tab only while a Pi is here; the pick is kept for when one is + else if (tab === "pi" && !hasPi()) tab = "instructions"; const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length }); page.append(head); head.classList.toggle("stuck", top > 0); @@ -902,6 +910,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 === "pi") renderPi(body); else if (tab === "hooks") renderHooks(body); else if (tab === "subagents") renderSubagents(body); else renderSkills(body); @@ -1123,6 +1132,119 @@ magpie.plugin("library", (ctx) => { rtkBusy.delete(a.id); render(); } + // ---------- Pi extensions ---------- + + // Each Pi here (this computer's, and each WSL distro's) with the + // extensions and packages it loads (piext.go). One is switched off or on + // in its settings.json the way `pi config` does it, and copied to + // another Pi: a package as its entry in that Pi's settings.json, which + // Pi installs itself when it starts; an extension as its file or folder. + // leokon3 on Discord: moving an extension from the WSL Pi to Windows'. + const hasPi = () => !!lib && !gatewayPage() && lib.agents.some((a) => a.id.split("@")[0] === "pi" && !a.gone && !a.unseen && !isHidden(a)); + let piView = null; // /api/library/pi + const piBusy = new Set(); // " " being switched or copied + let piLoading = false; + async function loadPi() { + if (piLoading) return; + piLoading = true; + try { + piView = await api("library/pi"); + } catch (e) { + status(e.message, "err"); + } + piLoading = false; + if (tab === "pi" && piView) render(); + } + function renderPi(body) { + body.append(intro(t("The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts."))); + if (!piView) { + body.append(el("div", "row skeleton")); + loadPi(); + return; + } + const pis = (piView.pis || []).filter((p) => !isHidden({ id: p.id })); + const live = pis.filter((p) => !p.asleep && !p.err); + for (const p of pis) { + const rh = el("div", "row-head lib-pi-head"); + rh.dataset.pi = p.id; + rh.append(el("span", "label", p.name), el("span", "grow")); + if (p.dir && !p.asleep) rh.append(pathLink(p.dir)); + body.append(rh); + const list = el("div", "list lib-list lib-pi"); + list.dataset.pi = p.id; + const others = live.filter((x) => x.id !== p.id); + if (p.asleep) { + list.append(el("div", "lib-none", t("WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.", { distro: p.wsl, agent: p.name }))); + } else if (p.err) { + list.append(el("div", "lib-none lib-pi-err", t("magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}", { file: "settings.json", why: p.err }))); + } else { + for (const x of p.extensions || []) list.append(piRow(p, others, { ext: x.id }, x.name, tilde(x.path), x.on, null)); + for (const k of p.packages || []) { + const tags = [tag(k.kind)]; + if (!k.installed) tags.push(tag(t("Not installed"), "", t("Pi installs it when it next starts"))); + else if (k.version) tags.push(tag("v" + k.version)); + list.append(piRow(p, others, { pkg: k.source }, k.name, k.source, k.on, tags, k.filtered)); + } + if (!(p.extensions || []).length && !(p.packages || []).length) list.append(el("div", "lib-none", t("No extensions or packages yet."))); + } + body.append(list); + } + } + function piRow(p, others, what, name, sub, on, tags, filtered) { + const key = p.id + " " + (what.ext || what.pkg); + const row = el("div", "row lib-row lib-pi-row"); + row.dataset.id = what.ext || what.pkg; + const who = el("div", "who"); + const n = el("div", "name mono", name); + for (const g of tags || []) n.append(g); + who.append(n, el("div", "sub mono", sub)); + row.append(who); + if (others.length) { + const b = button(t("Copy to…"), "lib-pi-copy", () => { + openProtoMenu(b, others.map((x) => ({ v: x.id, name: x.name, literalName: true, note: "" })), "", (to) => copyPi(p, others.find((x) => x.id === to), what, name), "Copy to another Pi", "", "right"); + }); + b.disabled = piBusy.has(key); + row.append(b); + } + const sw = toggle(on, t("{agent} loads {name}", { agent: p.name, name }), (v) => setPi(p, what, name, v)); + if (filtered) sw.title = t("This entry loads only some of the package; change it with pi config"); + sw.disabled = !!filtered || piBusy.has(key); + row.append(sw); + return row; + } + async function setPi(p, what, name, on) { + const key = p.id + " " + (what.ext || what.pkg); + piBusy.add(key); + render(); + try { + piView = await api("library/pi", { pi: p.id, ...what, on }); + status(on ? t("{name} is on for {agent}: Pi loads it when it next starts, or at /reload", { name, agent: p.name }) : t("{name} is off for {agent}: Pi drops it when it next starts, or at /reload", { name, agent: p.name }), "ok", 6000); + } catch (e) { + status(e.message, "err", 8000); + } + piBusy.delete(key); + render(); + } + async function copyPi(p, to, what, name) { + if (!to) return; + const key = p.id + " " + (what.ext || what.pkg); + piBusy.add(key); + render(); + try { + const v = await api("library/pi/copy", { from: p.id, to: to.id, ...what }); + piView = v; + status(what.pkg + ? t("{name} is in {agent}'s packages now: Pi installs it when it next starts", { name, agent: to.name }) + : v.install + ? t("{name} is copied to {agent}. It needs its packages: run npm install in {dir} there", { name, agent: to.name, dir: v.install }) + : t("{name} is copied to {agent}: Pi loads it when it next starts, or at /reload", { name, agent: to.name }), "ok", v.install ? 12000 : 6000); + } catch (e) { + status(e.message, "err", 8000); + } + piBusy.delete(key); + render(); + } + // what rtk saved day by day (week by week past 92 days), over the last // 30 or 90 days or since it first ran: each bar the commands' whole // output, the part RTK kept from the model on top of what still went diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index b3d0069b3..dfee06e9f 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -827,6 +827,20 @@ magpie.strings({ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} 未运行:点一下,{agent} 会在该发行版下次运行时启用", "WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} 未运行:其中的 Agent 显示的是 magpie 上次看到的内容,你的修改会在它下次运行时写入。", "{agents} can be changed once it runs.": "{agents} 要等它运行后才能修改。", + "Pi packages": "Pi 包", + "The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "每个 Pi 加载的扩展和包。可以关闭其中一个,或复制到另一个 Pi:包会加入那个 Pi 的设置,Pi 下次启动时自行安装。", + "magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie 无法读取 {file},因此这里不列出也不更改任何内容:{why}", + "Pi installs it when it next starts": "Pi 下次启动时安装它", + "No extensions or packages yet.": "还没有扩展或包。", + "Copy to…": "复制到…", + "Copy to another Pi": "复制到另一个 Pi", + "{agent} loads {name}": "{agent} 加载 {name}", + "This entry loads only some of the package; change it with pi config": "这一项只加载包的一部分;请用 pi config 更改", + "{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{name} 已为 {agent} 打开:Pi 下次启动或 /reload 时加载它", + "{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{name} 已为 {agent} 关闭:Pi 下次启动或 /reload 时不再加载它", + "{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 时加载它", }, "zh-TW": { "Skill router": "Skill 路由", @@ -1654,6 +1668,20 @@ magpie.strings({ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} 未執行:點一下,{agent} 會在該發行版下次執行時啟用", "WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} 未執行:其中的 Agent 顯示的是 magpie 上次看到的內容,你的修改會在它下次執行時寫入。", "{agents} can be changed once it runs.": "{agents} 要等它執行後才能修改。", + "Pi packages": "Pi 套件", + "The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "每個 Pi 載入的擴充和套件。可以關閉其中一個,或複製到另一個 Pi:套件會加入那個 Pi 的設定,Pi 下次啟動時自行安裝。", + "magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie 無法讀取 {file},因此這裡不列出也不變更任何內容:{why}", + "Pi installs it when it next starts": "Pi 下次啟動時安裝它", + "No extensions or packages yet.": "還沒有擴充或套件。", + "Copy to…": "複製到…", + "Copy to another Pi": "複製到另一個 Pi", + "{agent} loads {name}": "{agent} 載入 {name}", + "This entry loads only some of the package; change it with pi config": "這一項只載入套件的一部分;請用 pi config 變更", + "{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{name} 已為 {agent} 開啟:Pi 下次啟動或 /reload 時載入它", + "{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{name} 已為 {agent} 關閉:Pi 下次啟動或 /reload 時不再載入它", + "{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 時載入它", }, ja: { "Skill router": "スキルルーター", @@ -2481,6 +2509,20 @@ magpie.strings({ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} は起動していません。クリックすると、ディストリビューションが次に起動したときに {agent} に追加されます", "WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} は起動していません。そのエージェントは magpie が最後に見た内容で表示され、変更は次に起動したときに書き込まれます。", "{agents} can be changed once it runs.": "{agents} は起動後に変更できます。", + "Pi packages": "Pi パッケージ", + "The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "各 Pi が読み込む拡張機能とパッケージです。オフにしたり、別の Pi にコピーしたりできます。パッケージはその Pi の設定に追加され、Pi が次回起動時に自分でインストールします。", + "magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie は {file} を読めなかったため、ここでは何も表示も変更もしません: {why}", + "Pi installs it when it next starts": "Pi が次回起動時にインストールします", + "No extensions or packages yet.": "拡張機能もパッケージもまだありません。", + "Copy to…": "コピー先…", + "Copy to another Pi": "別の Pi にコピー", + "{agent} loads {name}": "{agent} が {name} を読み込む", + "This entry loads only some of the package; change it with pi config": "この項目はパッケージの一部だけを読み込みます。pi config で変更してください", + "{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{agent} で {name} をオンにしました。Pi は次回起動時か /reload で読み込みます", + "{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{agent} で {name} をオフにしました。Pi は次回起動時か /reload で外します", + "{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 で読み込みます", }, de: { "Skill router": "Skill-Router", @@ -3308,5 +3350,19 @@ magpie.strings({ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} läuft nicht: Ein Klick gibt es {agent}, sobald die Distribution das nächste Mal läuft", "WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} läuft nicht: Seine Agenten zeigen, was magpie dort zuletzt gesehen hat, und Änderungen werden beim nächsten Start dorthin geschrieben.", "{agents} can be changed once it runs.": "{agents} lässt sich ändern, sobald sie läuft.", + "Pi packages": "Pi-Pakete", + "The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "Die Erweiterungen und Pakete, die jedes Pi lädt. Schalte eine aus oder kopiere sie zu einem anderen Pi: Ein Paket wird in dessen Einstellungen eingetragen, und Pi installiert es beim nächsten Start.", + "magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie konnte {file} nicht lesen, listet dort daher nichts und ändert nichts: {why}", + "Pi installs it when it next starts": "Pi installiert es beim nächsten Start", + "No extensions or packages yet.": "Noch keine Erweiterungen oder Pakete.", + "Copy to…": "Kopieren nach…", + "Copy to another Pi": "Zu einem anderen Pi kopieren", + "{agent} loads {name}": "{agent} lädt {name}", + "This entry loads only some of the package; change it with pi config": "Dieser Eintrag lädt nur einen Teil des Pakets; ändere ihn mit pi config", + "{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{name} ist für {agent} an: Pi lädt es beim nächsten Start oder bei /reload", + "{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{name} ist für {agent} aus: Pi lässt es beim nächsten Start oder bei /reload weg", + "{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", }, }); diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index da7afcb02..d8712d4a3 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -855,3 +855,7 @@ body.window .lib-list .lib-row { --lib-indent: 38px; } .lib-foundmore span { display: inline-flex; } .lib-foundmore.open .chev { transform: rotate(180deg); } @media (hover: hover) and (pointer: fine) { .lib-foundmore:hover { color: var(--fg); background: var(--card-2); } } +/* Pi's extensions: a heading per Pi, its path beside it */ +.lib-pi-head > .lib-path { flex: 0 1 auto; min-width: 0; } +.lib-pi-row > .lib-pi-copy { flex: none; } +.lib-pi + .lib-pi-head { margin-top: 18px; } diff --git a/internal/gui/library.go b/internal/gui/library.go index c2ae558b9..57d79e840 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -274,6 +274,50 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { Regrouped int `json:"regrouped"` }{v, n}) }) + // Pi's extensions and packages, for each Pi here (this computer's and + // each WSL distro's): switched on or off as Pi itself does it, and + // copied from one Pi to another + mux.HandleFunc("GET /api/library/pi", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, library.ReadPiExtensions()) + }) + mux.HandleFunc("POST /api/library/pi", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Pi, Ext, Pkg string + On bool + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + var v *library.PiExtensions + var err error + switch { + case in.Ext != "" && in.Pkg == "": + v, err = library.SetPiExtension(in.Pi, in.Ext, in.On) + case in.Pkg != "" && in.Ext == "": + v, err = library.SetPiPackage(in.Pi, in.Pkg, in.On) + default: + err = errors.New("name one extension or one package") + } + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, v) + }) + mux.HandleFunc("POST /api/library/pi/copy", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ From, To, Ext, Pkg string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + v, err := library.CopyPi(in.From, in.To, in.Ext, in.Pkg) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, v) + }) // RTK:which agents have its hook, switching one on or off, and // installing rtk when the page is asked to mux.HandleFunc("GET /api/library/rtk", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/tests/library-loading.test.cjs b/internal/gui/tests/library-loading.test.cjs index 5fd79470b..b408eefb9 100644 --- a/internal/gui/tests/library-loading.test.cjs +++ b/internal/gui/tests/library-loading.test.cjs @@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", open(); await v.locator(".lib-head .lib-more:not([disabled])").waitFor(); assert.equal(await v.locator(".lib-skel").count(), 0, "the outline goes"); - assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "MCP servers · 1", "Skills · 1", "Hooks", "Subagents", "RTK"]); + assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "MCP servers · 1", "Skills · 1", "Hooks", "Subagents", "RTK", "Pi packages"]); assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Instructions"); assert.equal(await v.locator(".lib-head .lib-more").getAttribute("title"), "~/.magpie/library"); const after = await v.locator(".lib-tabs").boundingBox(); diff --git a/internal/gui/tests/library-pi-extensions.test.cjs b/internal/gui/tests/library-pi-extensions.test.cjs new file mode 100644 index 000000000..9be720388 --- /dev/null +++ b/internal/gui/tests/library-pi-extensions.test.cjs @@ -0,0 +1,147 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// leokon3 on Discord: Pi on Windows and in WSL, and no way to see or move +// an extension between them. The Library's Pi packages tab lists each +// Pi's extensions and packages with a switch each; a package that picks +// only some of its parts has its switch off limits (pi config changes it); +// Copy to… offers only the other Pis that are running, and sends the pick; +// a stopped distro says so and lists nothing. In every language, both +// engines, at a phone's width too. 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 = "C:\\Users\\leo"; +const lib = () => ({ + dir: `${HOME}\\.magpie\\library`, backups: `${HOME}\\.magpie\\backups`, home: HOME, + agents: [ + { id: "pi", name: "Pi", icon: "", skills: `${HOME}\\.pi\\agent\\skills` }, + { id: "pi@wsl:Ubuntu", name: "Pi · WSL Ubuntu", icon: "", skills: "\\\\wsl.localhost\\Ubuntu\\home\\leo\\.pi\\agent\\skills", wsl: "Ubuntu" }, + ], + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [], +}); +const piView = (on) => ({ + pis: [ + { + id: "pi", name: "Pi", icon: "", dir: `${HOME}\\.pi\\agent`, + extensions: [{ id: "extensions/hello.ts", name: "hello.ts", path: `${HOME}\\.pi\\agent\\extensions\\hello.ts`, on: true }], + packages: [ + { source: "npm:pi-skills@1.2.0", name: "pi-skills", kind: "npm", pin: "1.2.0", on: true, installed: true, version: "1.2.0" }, + { source: "git:github.com/leo/pi-tools", name: "pi-tools", kind: "git", on: true, filtered: true, installed: false }, + ], + }, + { + id: "pi@wsl:Ubuntu", name: "Pi · WSL Ubuntu", icon: "", wsl: "Ubuntu", dir: "\\\\wsl.localhost\\Ubuntu\\home\\leo\\.pi\\agent", + extensions: [{ id: "extensions/todo", name: "todo", path: "/home/leo/.pi/agent/extensions/todo", on, folder: true }], + packages: [], + }, + { id: "pi@wsl:Arch", name: "Pi · WSL Arch", icon: "", wsl: "Arch", asleep: true, extensions: [], packages: [] }, + ], +}); + +function server(lang, calls) { + let on = false; + 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/pi") { + if (req.method() === "POST") { + const b = req.postDataJSON(); + calls.push(["set", b]); + on = b.on; + } + return route.fulfill({ json: piView(on) }); + } + if (url.pathname === "/api/library/pi/copy") { + calls.push(["copy", req.postDataJSON()]); + return route.fulfill({ json: { ...piView(on), install: "~/.pi/agent/extensions/todo" } }); + } + 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 words = { + en: { tab: "Pi packages", copy: "Copy to…", stopped: "WSL Arch isn't running", notInstalled: "Not installed", on: "todo is on for Pi · WSL Ubuntu: Pi loads it when it next starts, or at /reload", copied: "todo is copied to Pi. It needs its packages: run npm install in ~/.pi/agent/extensions/todo there" }, + zh: { tab: "Pi 包", copy: "复制到…", stopped: "WSL Arch 未运行", notInstalled: "未安装", on: "todo 已为 Pi · WSL Ubuntu 打开:Pi 下次启动或 /reload 时加载它", copied: "todo 已复制到 Pi。它需要自己的依赖包:请在那里的 ~/.pi/agent/extensions/todo 中运行 npm install" }, + "zh-TW": { tab: "Pi 套件", copy: "複製到…", stopped: "WSL Arch 未執行", notInstalled: "未安裝", on: "todo 已為 Pi · WSL Ubuntu 開啟:Pi 下次啟動或 /reload 時載入它", copied: "todo 已複製到 Pi。它需要自己的相依套件:請在那裡的 ~/.pi/agent/extensions/todo 中執行 npm install" }, + ja: { tab: "Pi パッケージ", copy: "コピー先…", stopped: "WSL Arch は起動していません", notInstalled: "未インストール", on: "Pi · WSL Ubuntu で todo をオンにしました。Pi は次回起動時か /reload で読み込みます", copied: "todo を Pi にコピーしました。依存パッケージが必要です: そちらの ~/.pi/agent/extensions/todo で npm install を実行してください" }, + de: { tab: "Pi-Pakete", copy: "Kopieren nach…", stopped: "WSL Arch läuft nicht", notInstalled: "Nicht installiert", on: "todo ist für Pi · WSL Ubuntu an: Pi lädt es beim nächsten Start oder bei /reload", copied: "todo ist nach Pi kopiert. Es braucht seine Pakete: Führe dort in ~/.pi/agent/extensions/todo npm install aus" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": each Pi's extensions are listed, switched and copied to another Pi", 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 Object.keys(words)) for (const width of [980, 380]) { + await t.test(`${lang} at ${width}px`, async () => { + const w = words[lang], calls = []; + const ctx = await browser.newContext({ viewport: { width, height: 900 } }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, calls)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + await v.locator(".lib-tabs").getByText(w.tab, { exact: true }).click(); + const lists = v.locator(".lib-list.lib-pi"); + await lists.first().waitFor(); + assert.equal(await lists.count(), 3); + assert.deepEqual(await v.locator(".lib-pi-head .label").allTextContents(), ["Pi", "Pi · WSL Ubuntu", "Pi · WSL Arch"]); + const here = lists.nth(0), ubuntu = lists.nth(1), arch = lists.nth(2); + // a stopped distro is never started to read it + assert((await arch.textContent()).startsWith(w.stopped), await arch.textContent()); + assert.equal(await arch.locator(".lib-row").count(), 0); + const row = (list, id) => list.locator(`.lib-pi-row[data-id="${id}"]`); + assert.equal(await row(here, "extensions/hello.ts").getByRole("switch").getAttribute("aria-checked"), "true"); + assert.deepEqual(await row(here, "npm:pi-skills@1.2.0").locator(".lib-tag").allTextContents(), ["npm", "v1.2.0"]); + assert.deepEqual(await row(here, "git:github.com/leo/pi-tools").locator(".lib-tag").allTextContents(), ["git", w.notInstalled]); + // a package picking some of its parts is changed in pi config + assert.equal(await row(here, "git:github.com/leo/pi-tools").getByRole("switch").isDisabled(), true); + assert.equal(await row(here, "npm:pi-skills@1.2.0").getByRole("switch").isDisabled(), false); + + const todo = row(ubuntu, "extensions/todo"); + await todo.getByRole("switch").click(); + await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.on).catch(() => {}); + assert.equal(await page.locator("#status").textContent(), w.on); + assert.equal(await row(ubuntu, "extensions/todo").getByRole("switch").getAttribute("aria-checked"), "true"); + + // Copy to… offers the running Pis but this one: not the stopped Arch + await row(ubuntu, "extensions/todo").getByRole("button", { name: w.copy, exact: true }).click(); + const items = page.locator(".proto-menu .pm-item .pm-name"); + await items.first().waitFor(); + assert.deepEqual(await items.allTextContents(), ["Pi"]); + await page.locator(".proto-menu .pm-item").first().click(); + await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.copied).catch(() => {}); + assert.equal(await page.locator("#status").textContent(), w.copied); + assert.deepEqual(calls, [ + ["set", { pi: "pi@wsl:Ubuntu", ext: "extensions/todo", on: true }], + ["copy", { from: "pi@wsl:Ubuntu", to: "pi", ext: "extensions/todo" }], + ]); + // nothing runs off the side at a phone's width + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(over <= 0, `the page scrolls sideways by ${over}px`); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/piext.go b/internal/library/piext.go new file mode 100644 index 000000000..4b9188930 --- /dev/null +++ b/internal/library/piext.go @@ -0,0 +1,1032 @@ +package library + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "net/url" + "os" + posix "path" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + + "github.com/tidwall/jsonc" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/edit" +) + +// Pi's extensions and packages, for each Pi magpie knows of: this +// machine's, and one in each WSL distro (leokon3 on Discord, who runs both +// and moves an extension from one to the other). Everything here is read +// and written as Pi's own package manager and `pi config` do it +// (@earendil-works/pi-coding-agent 1.4.0, dist/core/package-manager.js and +// dist/modes/interactive/components/config-selector.js): +// +// - an extension is a .ts or .js file in /extensions, or a +// folder there with a package.json naming its "pi.extensions", or with +// an index.ts or index.js (collectAutoExtensionEntries), or a path +// settings.json's "extensions" lists (resolveLocalEntries); +// - one is switched off by "-" in +// "extensions", and on by taking that out, or by "+" when a "!" +// pattern there still leaves it out (toggleTopLevelResource, +// isEnabledByOverrides); +// - a package is an entry of "packages", a source string or an object +// with that source and filters; Pi installs one it hasn't yet when it +// starts (resolve → installParsedSource), so a package is given to +// another Pi by writing its entry there, not by copying its files. +// +// Pi's built-in extensions (builtin:mcp and the rest) aren't listed: +// turning builtin:mcp off would take away the MCP servers magpie gives Pi. + +// PiExtensions is every Pi here, with its extensions and packages. +type PiExtensions struct { + Pis []PiHere `json:"pis"` +} + +// PiHere is one Pi: this machine's, or one in a WSL distro. +type PiHere struct { + ID string `json:"id"` + Name string `json:"name"` + Icon string `json:"icon"` + WSL string `json:"wsl,omitempty"` + // Asleep: its distro isn't running, and nothing in it is read, as that + // would start it (#3896) + Asleep bool `json:"asleep,omitempty"` + // Dir is its agent folder, as magpie opens it + Dir string `json:"dir,omitempty"` + // Err says why its settings.json can't be read: nothing is listed, + // and nothing is written to it, rather than taking it for empty + Err string `json:"err,omitempty"` + Extensions []PiExt `json:"extensions"` + Packages []PiPackage `json:"packages"` +} + +// PiExt is one extension of a Pi's own: in its extensions folder, or +// listed by path in its settings.json. +type PiExt struct { + // ID names it in a request: "extensions/" for one in the + // extensions folder, the settings.json entry for one listed there + ID string `json:"id"` + Name string `json:"name"` + // Path is where it is, as the Pi's machine names it + Path string `json:"path"` + On bool `json:"on"` + // Listed: settings.json names it, rather than the folder holding it + Listed bool `json:"listed,omitempty"` + // Folder: a folder, not one file + Folder bool `json:"folder,omitempty"` + + keys []string // the files Pi loads of it, by their paths from the agent dir + files []string // those files, as magpie opens them + src string // what a copy copies +} + +// PiPackage is one entry of a Pi's settings.json "packages". +type PiPackage struct { + Source string `json:"source"` + Name string `json:"name"` + // Kind is npm, git or local + Kind string `json:"kind"` + // Pin is the version or ref the source names, if any + Pin string `json:"pin,omitempty"` + On bool `json:"on"` + // Filtered: the entry picks some of the package's resources (filters + // of the user's, or `pi config`'s), which a switch here would lose; + // it is changed in `pi config` + Filtered bool `json:"filtered,omitempty"` + // Installed: Pi has it on disk; one that isn't is installed when Pi + // next starts + Installed bool `json:"installed"` + Version string `json:"version,omitempty"` + + raw json.RawMessage +} + +// piPlace is a Pi as this file reads it: its agent folder, and where its +// own machine's ~ and / are, as magpie opens them. +type piPlace struct { + a *agent.Agent + dir string + home string + root string // a WSL distro's /, "" for this machine + roots []string + asleep bool + err error +} + +// piPlaces are the Pis here; a var for tests. +var piPlaces = func() []piPlace { + var out []piPlace + for _, a := range detected() { + kind, _, _ := strings.Cut(a.ID, "@") + if kind != "pi" || a.CLIMissing() { + continue + } + if a.WSL == "" { + out = append(out, piPlace{a: a, dir: a.Dir, home: home(), roots: piGlobalRoots()}) + continue + } + if isAsleep(a) { + out = append(out, piPlace{a: a, asleep: true}) + continue + } + t := wslTargetOf(a) + if t == nil { + out = append(out, piPlace{a: a, asleep: true}) + continue + } + h := a.Home + p := piPlace{a: a, dir: filepath.Dir(t.Skills), home: h, roots: wslPiRoots(h), err: t.Unreached} + if lh := linuxHome(h); lh != "" && strings.HasSuffix(filepath.ToSlash(h), lh) { + p.root = h[:len(h)-len(lh)] + } + out = append(out, p) + } + return out +} + +var piMu sync.Mutex + +// ReadPiExtensions lists every Pi here, with its extensions and packages. +func ReadPiExtensions() *PiExtensions { + v := &PiExtensions{Pis: []PiHere{}} + for _, p := range piPlaces() { + v.Pis = append(v.Pis, p.read()) + } + return v +} + +// piConf is what a Pi's settings.json says of its extensions and +// packages. +type piConf struct { + exts []string + pkgs []json.RawMessage +} + +func (p piPlace) settingsPath() string { return filepath.Join(p.dir, "settings.json") } + +// settings reads p's settings.json; one that isn't there is empty, one +// that can't be read or parsed is an error (unknown, never empty). +func (p piPlace) settings() (piConf, error) { + var s piConf + raw, err := edit.Read(p.settingsPath()) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return s, err + } + if len(strings.TrimSpace(string(raw))) == 0 { + return s, nil + } + var top map[string]json.RawMessage + if err := json.Unmarshal(jsonc.ToJSON(raw), &top); err != nil { + return s, fmt.Errorf("%s: %w", p.settingsPath(), err) + } + if r, ok := top["extensions"]; ok && string(r) != "null" { + if err := json.Unmarshal(r, &s.exts); err != nil { + return s, fmt.Errorf("%s: extensions isn't a list of paths: %w", p.settingsPath(), err) + } + } + if r, ok := top["packages"]; ok && string(r) != "null" { + if err := json.Unmarshal(r, &s.pkgs); err != nil { + return s, fmt.Errorf("%s: packages isn't a list: %w", p.settingsPath(), err) + } + } + return s, nil +} + +func (p piPlace) read() PiHere { + h := PiHere{ID: p.a.ID, Name: p.a.Name, Icon: p.a.Icon, WSL: p.a.WSL, Asleep: p.asleep, Dir: p.dir, Extensions: []PiExt{}, Packages: []PiPackage{}} + if p.asleep { + return h + } + if p.err != nil { + h.Err = p.err.Error() + return h + } + s, err := p.settings() + if err != nil { + h.Err = err.Error() + return h + } + h.Extensions = p.extensions(s) + h.Packages = p.packages(s) + return h +} + +// ---- extensions ------------------------------------------------------------- + +// extensions are p's own: those settings.json lists by path, then those +// in its extensions folder, each once. +func (p piPlace) extensions(s piConf) []PiExt { + var out []PiExt + seen := map[string]bool{} + for _, e := range s.exts { + if piIsPattern(e) || strings.HasPrefix(e, "builtin:") { + continue + } + at := p.resolve(e) + fi, err := os.Stat(p.open(at)) + if err != nil { + continue + } + var files []string + if fi.IsDir() { + files = p.under(at, piDirEntries) + } else { + files = []string{at} + } + if len(files) == 0 { + continue + } + x := PiExt{ID: e, Name: filepath.Base(at), Path: e, Listed: true, Folder: fi.IsDir(), files: files, src: at} + out = append(out, p.judge(x, s.exts, true)) + for _, f := range files { + seen[f] = true + } + } + dir := filepath.Join(p.dir, "extensions") + // a folder that is itself one extension (a package.json or an index + // there): its files, as one + if files := p.under(dir, piResolveEntries); files != nil { + x := PiExt{ID: "extensions", Name: "extensions", Path: p.shown(dir), Folder: true, files: files} + if !slices.ContainsFunc(files, func(f string) bool { return seen[f] }) { + out = append(out, p.judge(x, s.exts, false)) + } + return out + } + es, _ := os.ReadDir(dir) + for _, e := range es { + n := e.Name() + if strings.HasPrefix(n, ".") || n == "node_modules" { + continue + } + at := filepath.Join(dir, n) + fi, err := os.Stat(p.open(at)) + if err != nil { + continue + } + var files []string + switch { + case fi.Mode().IsRegular() && (strings.HasSuffix(n, ".ts") || strings.HasSuffix(n, ".js")): + files = []string{at} + case fi.IsDir(): + files = p.under(at, piResolveEntries) + } + if len(files) == 0 || slices.ContainsFunc(files, func(f string) bool { return seen[f] }) { + continue + } + x := PiExt{ID: "extensions/" + n, Name: n, Path: p.shown(at), Folder: fi.IsDir(), files: files, src: at} + out = append(out, p.judge(x, s.exts, false)) + } + return out +} + +// judge fills in x's keys and whether Pi loads it: on when any of its +// files is loaded. +func (p piPlace) judge(x PiExt, entries []string, listed bool) PiExt { + for _, f := range x.files { + x.keys = append(x.keys, p.key(f)) + } + for _, f := range x.files { + var on bool + if listed { + on = p.applied(f, entries) + } else { + on = p.enabled(f, entries) + } + if on { + x.On = true + } + } + return x +} + +// key is the pattern Pi's `pi config` writes for f: its path from the +// agent folder, with forward slashes. +func (p piPlace) key(f string) string { + rel, err := filepath.Rel(p.dir, f) + if err != nil { + return filepath.ToSlash(f) + } + return filepath.ToSlash(rel) +} + +// posixAbs is f as its own machine names it: in a WSL distro, the +// distro's path. +func (p piPlace) posixAbs(f string) string { + if p.root != "" && strings.HasPrefix(strings.ToLower(f), strings.ToLower(p.root)) { + return "/" + strings.TrimLeft(filepath.ToSlash(f[len(p.root):]), "/") + } + return filepath.ToSlash(f) +} + +// shown is f as the Pi's own machine names it, ~ for its home. +func (p piPlace) shown(f string) string { + a := p.posixAbs(f) + if h := p.posixAbs(p.home); h != "" && strings.HasPrefix(a, strings.TrimRight(h, "/")+"/") { + return "~" + a[len(strings.TrimRight(h, "/")):] + } + if p.root == "" { + return f + } + return a +} + +// resolve is a path settings.json names, where magpie opens it: from the +// agent folder, ~ the Pi's home (resolvePathFromBase). +func (p piPlace) resolve(e string) string { + e = strings.TrimSpace(e) + switch { + case e == "~": + return p.home + case strings.HasPrefix(e, "~/") || strings.HasPrefix(e, `~\`): + return filepath.Join(p.home, filepath.FromSlash(e[2:])) + case p.root != "" && strings.HasPrefix(e, "/"): + return filepath.Join(p.root, filepath.FromSlash(e)) + case filepath.IsAbs(e): + return e + } + return filepath.Join(p.dir, filepath.FromSlash(e)) +} + +// open is f where magpie can open it: in a WSL distro, below a link of +// the distro's, where the link leads (agent.WSLOpen). +func (p piPlace) open(f string) string { + if p.a == nil || p.a.WSL == "" { + return f + } + if o, err := agent.WSLOpen(p.a, f); err == nil { + return o + } + return f +} + +// under is find's files of the folder dir, named under dir as Pi names +// them (its path, not where a link there leads), though read where magpie +// opens it. +func (p piPlace) under(dir string, find func(string) []string) []string { + o := p.open(dir) + got := find(o) + if o == dir || got == nil { + return got + } + out := make([]string, 0, len(got)) + for _, f := range got { + if rel, err := filepath.Rel(o, f); err == nil { + f = filepath.Join(dir, rel) + } + out = append(out, f) + } + return out +} + +func piIsPattern(s string) bool { + return strings.HasPrefix(s, "!") || strings.HasPrefix(s, "+") || strings.HasPrefix(s, "-") || strings.ContainsAny(s, "*?") +} + +func piOverride(s string) bool { + return strings.HasPrefix(s, "!") || strings.HasPrefix(s, "+") || strings.HasPrefix(s, "-") +} + +// enabled is isEnabledByOverrides: a file Pi found in its extensions +// folder is loaded unless a "!" pattern matches it, then a "+" exact path +// brings it back and a "-" one takes it out. +func (p piPlace) enabled(f string, entries []string) bool { + on := true + for _, e := range entries { + if strings.HasPrefix(e, "!") && p.matches(f, e[1:]) { + on = false + } + } + for _, e := range entries { + if strings.HasPrefix(e, "+") && p.exact(f, e[1:]) { + on = true + } + } + for _, e := range entries { + if strings.HasPrefix(e, "-") && p.exact(f, e[1:]) { + on = false + } + } + return on +} + +// applied is applyPatterns for a file settings.json lists: its glob +// includes, when there are any, then "!", "+" and "-". +func (p piPlace) applied(f string, entries []string) bool { + var inc []string + for _, e := range entries { + if piIsPattern(e) && !piOverride(e) { + inc = append(inc, e) + } + } + on := len(inc) == 0 || slices.ContainsFunc(inc, func(g string) bool { return p.matches(f, g) }) + for _, e := range entries { + if strings.HasPrefix(e, "!") && p.matches(f, e[1:]) { + on = false + } + } + for _, e := range entries { + if strings.HasPrefix(e, "+") && p.exact(f, e[1:]) { + on = true + } + } + for _, e := range entries { + if strings.HasPrefix(e, "-") && p.exact(f, e[1:]) { + on = false + } + } + return on +} + +// exact is matchesAnyExactPattern: the pattern, without a leading ./, is +// f's path from the agent folder or its whole path. +func (p piPlace) exact(f, pat string) bool { + pat = strings.TrimPrefix(strings.TrimPrefix(pat, "./"), `.\`) + pat = posix.Clean(filepath.ToSlash(pat)) + return pat == p.key(f) || pat == p.posixAbs(f) +} + +// matches is matchesAnyPattern: a glob against f's path from the agent +// folder, its name, or its whole path. +func (p piPlace) matches(f, pat string) bool { + re := piGlob(filepath.ToSlash(pat)) + return re.MatchString(p.key(f)) || re.MatchString(filepath.Base(f)) || re.MatchString(p.posixAbs(f)) +} + +// piGlob is a minimatch pattern as a regexp: ** any path, * and ? within +// one part, [..] a class. +func piGlob(g string) *regexp.Regexp { + var b strings.Builder + b.WriteString("^") + for i := 0; i < len(g); i++ { + c := g[i] + switch { + case c == '*' && i+1 < len(g) && g[i+1] == '*': + i++ + if i+1 < len(g) && g[i+1] == '/' { + i++ + b.WriteString("(?:.*/)?") + } else { + b.WriteString(".*") + } + case c == '*': + b.WriteString("[^/]*") + case c == '?': + b.WriteString("[^/]") + case c == '[': + if j := strings.IndexByte(g[i:], ']'); j > 1 { + cls := g[i+1 : i+j] + if strings.HasPrefix(cls, "!") { + cls = "^" + cls[1:] + } + b.WriteString("[" + cls + "]") + i += j + } else { + b.WriteString(`\[`) + } + default: + b.WriteString(regexp.QuoteMeta(string(c))) + } + } + b.WriteString("$") + re, err := regexp.Compile(b.String()) + if err != nil { + return regexp.MustCompile(`^$.`) + } + return re +} + +// piResolveEntries is resolveExtensionEntries: the files a folder's +// package.json names under "pi.extensions" that are there, else its +// index.ts, else its index.js; nil for a folder that is no extension. +func piResolveEntries(dir string) []string { + if raw, err := os.ReadFile(filepath.Join(dir, "package.json")); err == nil { + var m struct { + Pi struct { + Extensions []string `json:"extensions"` + } `json:"pi"` + } + if json.Unmarshal(raw, &m) == nil && len(m.Pi.Extensions) > 0 { + var out []string + for _, e := range m.Pi.Extensions { + f := filepath.Join(dir, filepath.FromSlash(e)) + if _, err := os.Stat(f); err == nil { + out = append(out, f) + } + } + if len(out) > 0 { + return out + } + } + } + for _, n := range []string{"index.ts", "index.js"} { + if _, err := os.Stat(filepath.Join(dir, n)); err == nil { + return []string{filepath.Join(dir, n)} + } + } + return nil +} + +// piDirEntries is collectAutoExtensionEntries, for a folder settings.json +// lists: the folder as one extension, else each in it. +func piDirEntries(dir string) []string { + if out := piResolveEntries(dir); out != nil { + return out + } + var out []string + es, _ := os.ReadDir(dir) + for _, e := range es { + n := e.Name() + if strings.HasPrefix(n, ".") || n == "node_modules" { + continue + } + at := filepath.Join(dir, n) + fi, err := os.Stat(at) + if err != nil { + continue + } + if fi.Mode().IsRegular() && (strings.HasSuffix(n, ".ts") || strings.HasSuffix(n, ".js")) { + out = append(out, at) + } else if fi.IsDir() { + out = append(out, piResolveEntries(at)...) + } + } + return out +} + +// ---- packages --------------------------------------------------------------- + +func (p piPlace) packages(s piConf) []PiPackage { + var out []PiPackage + for _, r := range s.pkgs { + pk, ok := piPackageOf(r) + if !ok { + continue + } + pk.Installed, pk.Version = p.installed(pk) + out = append(out, pk) + } + return out +} + +// piFilterKeys are a package entry's filters (PackageSource in +// settings-manager.d.ts). +var piFilterKeys = []string{"extensions", "skills", "prompts", "themes"} + +// piPackageOf reads one "packages" entry: a source string, or an object +// with a source and filters. Off is every filter empty, which loads none +// of the package's resources; any other filter is the user's (or `pi +// config`'s), kept as it is. +func piPackageOf(r json.RawMessage) (PiPackage, bool) { + pk := PiPackage{raw: r, On: true} + var s string + if json.Unmarshal(r, &s) != nil { + var o map[string]json.RawMessage + if json.Unmarshal(r, &o) != nil || json.Unmarshal(o["source"], &s) != nil { + return pk, false + } + empty, set := 0, 0 + for _, k := range piFilterKeys { + v, ok := o[k] + if !ok || string(v) == "null" { + continue + } + set++ + var l []string + if json.Unmarshal(v, &l) == nil && len(l) == 0 { + empty++ + } + } + // with autoload false only what the filters name loads + noAuto := string(o["autoload"]) == "false" + off := set == len(piFilterKeys) && empty == set + pk.On = !off + pk.Filtered = noAuto || set > 0 && !off + } + s = strings.TrimSpace(s) + if s == "" { + return pk, false + } + pk.Source = s + pk.Name, pk.Pin = piPackageName(s) + pk.Kind = piKind(s) + return pk, true +} + +// piKind is parseSource's type: npm:…, a git source (git:…, a URL, an +// ssh address), or a local path. +func piKind(s string) string { + switch { + case strings.HasPrefix(s, "npm:"): + return "npm" + case strings.HasPrefix(s, "git:"), strings.HasPrefix(s, "git@"), + strings.HasPrefix(s, "https://"), strings.HasPrefix(s, "http://"), + strings.HasPrefix(s, "ssh://"), strings.HasPrefix(s, "git://"): + return "git" + } + return "local" +} + +// piGitPlace is a git source's host and path, the folder Pi clones it to +// under /git (getGitInstallPath), without its ref. +func piGitPlace(s string) (host, p string) { + s = strings.TrimPrefix(s, "git:") + cut := func(x string) string { + if i := strings.LastIndex(x, "@"); i > 0 && !strings.Contains(x[i:], "/") { + return x[:i] + } + return x + } + switch { + case strings.HasPrefix(s, "git@"): + hp := strings.TrimPrefix(s, "git@") + host, p, _ = strings.Cut(hp, ":") + p = cut(p) + case strings.Contains(s, "://"): + u, err := url.Parse(s) + if err != nil { + return "", "" + } + host, p = u.Hostname(), cut(strings.TrimPrefix(u.Path, "/")) + default: + host, p, _ = strings.Cut(s, "/") + p = cut(p) + } + return host, strings.TrimSuffix(strings.Trim(p, "/"), ".git") +} + +// piIdentity is getPackageIdentity: one package however its source pins +// it, so it isn't written twice. +func (p piPlace) piIdentity(s string) string { + switch piKind(s) { + case "npm": + n, _ := piPackageName(s) + return "npm:" + n + case "git": + h, gp := piGitPlace(s) + return "git:" + strings.ToLower(h) + "/" + gp + } + return "local:" + p.resolve(s) +} + +// installed says whether Pi has pk on disk, and its version there. +func (p piPlace) installed(pk PiPackage) (bool, string) { + var dirs []string + switch pk.Kind { + case "npm": + dirs = append(dirs, filepath.Join(p.dir, "npm", "node_modules", filepath.FromSlash(pk.Name))) + for _, r := range p.roots { + dirs = append(dirs, filepath.Join(r, filepath.FromSlash(pk.Name))) + } + case "git": + h, gp := piGitPlace(pk.Source) + if h == "" || gp == "" { + return false, "" + } + dirs = append(dirs, filepath.Join(p.dir, "git", h, filepath.FromSlash(gp))) + default: + dirs = append(dirs, p.resolve(pk.Source)) + } + for _, d := range dirs { + if _, err := os.Stat(d); err != nil { + continue + } + var m struct{ Version string } + if raw, err := os.ReadFile(filepath.Join(d, "package.json")); err == nil { + json.Unmarshal(raw, &m) + } + return true, m.Version + } + return false, "" +} + +// ---- changes ---------------------------------------------------------------- + +func piPlaceOf(id string) (piPlace, error) { + for _, p := range piPlaces() { + if p.a.ID != id { + continue + } + if p.asleep { + return p, fmt.Errorf("WSL %s isn't running, and magpie doesn't start it to change %s: start the distro (open its terminal), then try again", p.a.WSL, p.a.Name) + } + if p.err != nil { + return p, p.err + } + return p, nil + } + return piPlace{}, fmt.Errorf("%s isn't installed", id) +} + +// SetPiExtension switches one of a Pi's own extensions on or off, as `pi +// config` does: "-" in settings.json's extensions takes it out, and +// on takes that out again, adding "+" only when a "!" pattern there +// would still leave it out. +func SetPiExtension(pi, id string, on bool) (*PiExtensions, error) { + piMu.Lock() + defer piMu.Unlock() + p, err := piPlaceOf(pi) + if err != nil { + return nil, err + } + s, err := p.settings() + if err != nil { + return nil, err + } + var x *PiExt + for _, e := range p.extensions(s) { + if e.ID == id { + x = &e + break + } + } + if x == nil { + return nil, fmt.Errorf("%s has no extension %s", p.a.Name, id) + } + if x.On == on { + return ReadPiExtensions(), nil + } + keys := map[string]bool{} + for _, k := range x.keys { + keys[k] = true + } + var next []string + for _, e := range s.exts { + // an override of one of its files is replaced, as `pi config` + // replaces it; the user's paths and globs stay + if piOverride(e) && keys[posix.Clean(strings.TrimPrefix(filepath.ToSlash(e[1:]), "./"))] { + continue + } + next = append(next, e) + } + for _, k := range x.keys { + if !on { + next = append(next, "-"+k) + } + } + if on { + // still left out by a "!" pattern (or, for a listed one, a glob it + // doesn't match): brought back by "+" as `pi config` does + for i, f := range x.files { + loaded := p.enabled(f, next) + if x.Listed { + loaded = p.applied(f, next) + } + if !loaded { + next = append(next, "+"+x.keys[i]) + } + } + } + if next == nil { + next = []string{} + } + if err := newBackups().keep(p.a.ID, p.settingsPath()); err != nil { + return nil, err + } + if err := edit.SetJSON(p.settingsPath(), edit.KV{Path: "extensions", Value: next}); err != nil { + return nil, err + } + return ReadPiExtensions(), nil +} + +// SetPiPackage switches a whole package on or off: off is its entry with +// every filter empty, so Pi keeps it installed and loads none of it; on is +// its source alone again. One whose entry has other filters is changed in +// `pi config`, which can pick them one by one. +func SetPiPackage(pi, source string, on bool) (*PiExtensions, error) { + piMu.Lock() + defer piMu.Unlock() + p, err := piPlaceOf(pi) + if err != nil { + return nil, err + } + s, err := p.settings() + if err != nil { + return nil, err + } + at := -1 + var pk PiPackage + for i, r := range s.pkgs { + if x, ok := piPackageOf(r); ok && x.Source == source { + at, pk = i, x + break + } + } + if at < 0 { + return nil, fmt.Errorf("%s has no package %s", p.a.Name, source) + } + if pk.On == on { + return ReadPiExtensions(), nil + } + if pk.Filtered { + return nil, fmt.Errorf("%s picks some of %s's resources; change it with `pi config`", p.a.Name, pk.Name) + } + var o map[string]json.RawMessage + if json.Unmarshal(pk.raw, &o) != nil { + o = map[string]json.RawMessage{} + b, _ := json.Marshal(source) + o["source"] = b + } + for _, k := range piFilterKeys { + if on { + delete(o, k) + } else { + o[k] = json.RawMessage("[]") + } + } + var entry json.RawMessage + if len(o) == 1 { + entry, _ = json.Marshal(source) + } else { + entry, _ = json.Marshal(o) + } + next := slices.Clone(s.pkgs) + next[at] = entry + if err := newBackups().keep(p.a.ID, p.settingsPath()); err != nil { + return nil, err + } + if err := edit.SetJSON(p.settingsPath(), edit.KV{Path: "packages", Value: next}); err != nil { + return nil, err + } + return ReadPiExtensions(), nil +} + +// PiCopied is what a copy did, for the page to say. +type PiCopied struct { + *PiExtensions + // Install: the copied extension has dependencies of its own, which + // `npm install` in its folder on the other side fetches + Install string `json:"install,omitempty"` +} + +// CopyPi gives one of a Pi's extensions or packages to another Pi. A +// package is its settings.json entry, written into the other's packages; +// Pi there installs it when it next starts. An extension is its file or +// folder, copied into the other's extensions folder, without its +// node_modules (built for the machine it was on). +func CopyPi(from, to, ext, pkg string) (*PiCopied, error) { + piMu.Lock() + defer piMu.Unlock() + if from == to { + return nil, errors.New("pick another Pi to copy to") + } + src, err := piPlaceOf(from) + if err != nil { + return nil, err + } + dst, err := piPlaceOf(to) + if err != nil { + return nil, err + } + ss, err := src.settings() + if err != nil { + return nil, err + } + ds, err := dst.settings() + if err != nil { + return nil, err + } + if pkg != "" { + return piCopyPackage(src, dst, ss, ds, pkg) + } + var x *PiExt + for _, e := range src.extensions(ss) { + if e.ID == ext { + x = &e + break + } + } + if x == nil { + return nil, fmt.Errorf("%s has no extension %s", src.a.Name, ext) + } + if x.src == "" { + return nil, fmt.Errorf("%s's whole extensions folder is one extension; copy it by hand", src.a.Name) + } + name := filepath.Base(x.src) + at := filepath.Join(dst.dir, "extensions", name) + if _, err := os.Lstat(at); err == nil { + return nil, fmt.Errorf("%s has an extension named %s already", piLabel(dst), name) + } + if err := os.MkdirAll(filepath.Dir(at), 0o755); err != nil { + return nil, err + } + if err := piCopyTree(src.open(x.src), at); err != nil { + os.RemoveAll(at) + return nil, err + } + out := &PiCopied{PiExtensions: ReadPiExtensions()} + if x.Folder && piHasDeps(at) { + out.Install = dst.shown(at) + } + return out, nil +} + +func piCopyPackage(src, dst piPlace, ss, ds piConf, source string) (*PiCopied, error) { + var pk *PiPackage + for _, r := range ss.pkgs { + if x, ok := piPackageOf(r); ok && x.Source == source { + pk = &x + break + } + } + if pk == nil { + return nil, fmt.Errorf("%s has no package %s", src.a.Name, source) + } + if pk.Kind == "local" { + // a path on the first Pi's machine names nothing on the other's + return nil, fmt.Errorf("%s is a folder on %s's machine, which %s can't install from; copy the folder there and add it with `pi install`", pk.Name, piLabel(src), piLabel(dst)) + } + id := src.piIdentity(pk.Source) + for _, r := range ds.pkgs { + if x, ok := piPackageOf(r); ok && dst.piIdentity(x.Source) == id { + return nil, fmt.Errorf("%s has %s already", piLabel(dst), pk.Name) + } + } + next := append(slices.Clone(ds.pkgs), pk.raw) + if err := newBackups().keep(dst.a.ID, dst.settingsPath()); err != nil { + return nil, err + } + if err := os.MkdirAll(dst.dir, 0o755); err != nil { + return nil, err + } + if err := edit.SetJSON(dst.settingsPath(), edit.KV{Path: "packages", Value: next}); err != nil { + return nil, err + } + return &PiCopied{PiExtensions: ReadPiExtensions()}, nil +} + +func piLabel(p piPlace) string { return p.a.Name } + +// piHasDeps says whether a copied extension folder's package.json names +// dependencies, which its node_modules (left behind) held. +func piHasDeps(dir string) bool { + raw, err := os.ReadFile(filepath.Join(dir, "package.json")) + if err != nil { + return false + } + var m struct { + Dependencies map[string]any `json:"dependencies"` + } + return json.Unmarshal(raw, &m) == nil && len(m.Dependencies) > 0 +} + +// piCopyTree copies a file, or a folder without its node_modules and .git; +// a link inside it is left out, as where it leads on one machine is +// nothing on the other. The top itself is followed: an extension that is +// a link to the user's own checkout is copied from there. +func piCopyTree(from, to string) error { + fi, err := os.Stat(from) + if err != nil { + return err + } + if !fi.IsDir() { + return piCopyFile(from, to, fi.Mode().Perm()) + } + return filepath.WalkDir(from, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(from, p) + dst := filepath.Join(to, rel) + if p == from { + return os.MkdirAll(dst, 0o755) + } + if d.IsDir() { + if d.Name() == "node_modules" || d.Name() == ".git" { + return filepath.SkipDir + } + return os.MkdirAll(dst, 0o755) + } + if !d.Type().IsRegular() { + return nil + } + info, err := d.Info() + if err != nil { + return err + } + return piCopyFile(p, dst, info.Mode().Perm()) + }) +} + +func piCopyFile(from, to string, perm fs.FileMode) error { + in, err := os.Open(from) + if err != nil { + return err + } + defer in.Close() + out, err := os.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, perm|0o200) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + return err + } + return out.Close() +} diff --git a/internal/library/piext_test.go b/internal/library/piext_test.go new file mode 100644 index 000000000..35fb94571 --- /dev/null +++ b/internal/library/piext_test.go @@ -0,0 +1,362 @@ +package library + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/tidwall/jsonc" + + "github.com/yetone/magpie/internal/agent" +) + +// piTwo is the sandbox's own Pi, found as magpie finds it, and a second +// one standing for a Pi in a WSL distro (leokon3's), its home a folder of +// the test's. +func piTwo(t *testing.T) (here, wsl string) { + t.Helper() + h := sandbox(t) + here = filepath.Join(h, ".pi", "agent") + wh := filepath.Join(t.TempDir(), "home", "u") + wsl = filepath.Join(wh, ".pi", "agent") + if err := os.MkdirAll(wsl, 0o755); err != nil { + t.Fatal(err) + } + real := piPlaces + piPlaces = func() []piPlace { + out := real() + w := &agent.Agent{ID: "pi@wsl:Ubuntu", Name: "Pi", WSL: "Ubuntu"} + return append(out, piPlace{a: w, dir: wsl, home: wh}) + } + t.Cleanup(func() { piPlaces = real }) + return here, wsl +} + +func piOf(t *testing.T, v *PiExtensions, id string) PiHere { + t.Helper() + for _, p := range v.Pis { + if p.ID == id { + return p + } + } + t.Fatalf("no Pi %s in %+v", id, v.Pis) + return PiHere{} +} + +func piExtOf(t *testing.T, p PiHere, id string) PiExt { + t.Helper() + for _, e := range p.Extensions { + if e.ID == id { + return e + } + } + t.Fatalf("%s has no extension %s: %+v", p.ID, id, p.Extensions) + return PiExt{} +} + +func piExtensionsSetting(t *testing.T, dir string) []string { + t.Helper() + raw, err := os.ReadFile(filepath.Join(dir, "settings.json")) + if err != nil { + t.Fatal(err) + } + var s struct{ Extensions []string } + if err := json.Unmarshal(jsonc.ToJSON(raw), &s); err != nil { + t.Fatal(err) + } + return s.Extensions +} + +// The extensions Pi itself loads are listed, each switched on or off by +// Pi's own rules: a .ts or .js file in extensions/, a folder there with an +// index.ts or a package.json naming its entries, and a path settings.json +// lists; a dot file, node_modules and a folder with no entry are none. +func TestPiExtensionsListedAsPiLoadsThem(t *testing.T) { + here, _ := piTwo(t) + ext := filepath.Join(here, "extensions") + write(t, filepath.Join(ext, "a.ts"), "") + write(t, filepath.Join(ext, "b.ts"), "") + write(t, filepath.Join(ext, "c.js"), "") + write(t, filepath.Join(ext, ".hidden.ts"), "") + write(t, filepath.Join(ext, "notes.md"), "") + write(t, filepath.Join(ext, "node_modules", "x", "index.ts"), "") + write(t, filepath.Join(ext, "tool", "index.ts"), "") + write(t, filepath.Join(ext, "multi", "package.json"), `{"pi":{"extensions":["./src/one.ts","./src/missing.ts"]}}`) + write(t, filepath.Join(ext, "multi", "src", "one.ts"), "") + write(t, filepath.Join(ext, "empty", "readme.md"), "") + home, _ := os.UserHomeDir() + write(t, filepath.Join(home, "dev", "mine.ts"), "") + write(t, filepath.Join(here, "settings.json"), `{ + // the user's own comment + "extensions": ["~/dev/mine.ts", "-extensions/b.ts", "!*.js", "+extensions/c.js", "-builtin:llama.cpp"] +}`) + + p := piOf(t, ReadPiExtensions(), "pi") + var ids []string + for _, e := range p.Extensions { + ids = append(ids, e.ID) + } + want := []string{"~/dev/mine.ts", "extensions/a.ts", "extensions/b.ts", "extensions/c.js", "extensions/multi", "extensions/tool"} + if !slices.Equal(ids, want) { + t.Fatalf("extensions = %v, want %v", ids, want) + } + for id, on := range map[string]bool{"~/dev/mine.ts": true, "extensions/a.ts": true, "extensions/b.ts": false, "extensions/c.js": true, "extensions/tool": true, "extensions/multi": true} { + if e := piExtOf(t, p, id); e.On != on { + t.Errorf("%s on = %v, want %v", id, e.On, on) + } + } + if e := piExtOf(t, p, "extensions/multi"); !slices.Equal(e.keys, []string{"extensions/multi/src/one.ts"}) { + t.Errorf("multi's keys = %v, want the entry its package.json names that is there", e.keys) + } + if e := piExtOf(t, p, "~/dev/mine.ts"); !e.Listed { + t.Errorf("a path settings.json lists isn't marked listed: %+v", e) + } +} + +// Switched off and on as `pi config` does: "-" written, then taken +// out again, the user's comment and other entries kept; on writes "+" only +// when a "!" pattern would still leave it out. +func TestPiExtensionSwitch(t *testing.T) { + here, _ := piTwo(t) + ext := filepath.Join(here, "extensions") + write(t, filepath.Join(ext, "a.ts"), "") + write(t, filepath.Join(ext, "tool", "index.ts"), "") + write(t, filepath.Join(ext, "old.js"), "") + write(t, filepath.Join(here, "settings.json"), "{\n // mine\n \"extensions\": [\"!*.js\", \"-builtin:llama.cpp\"]\n}\n") + + v, err := SetPiExtension("pi", "extensions/a.ts", false) + if err != nil { + t.Fatal(err) + } + if e := piExtOf(t, piOf(t, v, "pi"), "extensions/a.ts"); e.On { + t.Error("a.ts still on after switching it off") + } + if got := piExtensionsSetting(t, here); !slices.Equal(got, []string{"!*.js", "-builtin:llama.cpp", "-extensions/a.ts"}) { + t.Errorf("extensions = %v", got) + } + if raw, _ := os.ReadFile(filepath.Join(here, "settings.json")); !strings.Contains(string(raw), "// mine") { + t.Errorf("the user's comment is gone:\n%s", raw) + } + if _, err := SetPiExtension("pi", "extensions/a.ts", true); err != nil { + t.Fatal(err) + } + if got := piExtensionsSetting(t, here); !slices.Equal(got, []string{"!*.js", "-builtin:llama.cpp"}) { + t.Errorf("on again: extensions = %v, want the -entry taken out and nothing added", got) + } + // a folder is switched by its entry file, as Pi names it + if _, err := SetPiExtension("pi", "extensions/tool", false); err != nil { + t.Fatal(err) + } + if got := piExtensionsSetting(t, here); !slices.Contains(got, "-extensions/tool/index.ts") { + t.Errorf("extensions = %v, want -extensions/tool/index.ts", got) + } + // left out by the user's "!*.js": on is "+" + v, err = SetPiExtension("pi", "extensions/old.js", true) + if err != nil { + t.Fatal(err) + } + if got := piExtensionsSetting(t, here); !slices.Contains(got, "+extensions/old.js") || !slices.Contains(got, "!*.js") { + t.Errorf("extensions = %v, want +extensions/old.js beside the user's !*.js", got) + } + if e := piExtOf(t, piOf(t, v, "pi"), "extensions/old.js"); !e.On { + t.Error("old.js still off") + } +} + +// A package is switched whole: off is every filter empty, which Pi reads +// as none of its resources; on is its source alone again. One with the +// user's own filters is left to `pi config`. +func TestPiPackageSwitch(t *testing.T) { + here, _ := piTwo(t) + write(t, filepath.Join(here, "npm", "node_modules", "@x", "pi-foo", "package.json"), `{"version":"1.2.3"}`) + write(t, filepath.Join(here, "settings.json"), `{"packages": ["npm:@x/pi-foo@1.2.3", {"source": "git:github.com/a/b@v1", "skills": []}, "git:github.com/a/c"]}`) + + p := piOf(t, ReadPiExtensions(), "pi") + if len(p.Packages) != 3 { + t.Fatalf("packages = %+v", p.Packages) + } + foo := p.Packages[0] + if foo.Name != "@x/pi-foo" || foo.Kind != "npm" || !foo.Installed || foo.Version != "1.2.3" || !foo.On { + t.Errorf("npm package = %+v", foo) + } + if b := p.Packages[1]; !b.Filtered || b.Kind != "git" || b.Installed { + t.Errorf("filtered git package = %+v", b) + } + if _, err := SetPiPackage("pi", "npm:@x/pi-foo@1.2.3", false); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(filepath.Join(here, "settings.json")) + var s struct{ Packages []any } + json.Unmarshal(raw, &s) + o, ok := s.Packages[0].(map[string]any) + if !ok || o["source"] != "npm:@x/pi-foo@1.2.3" || len(o) != 5 { + t.Fatalf("off: packages[0] = %#v", s.Packages[0]) + } + for _, k := range piFilterKeys { + if l, ok := o[k].([]any); !ok || len(l) != 0 { + t.Errorf("off: %s = %#v, want []", k, o[k]) + } + } + if p := piOf(t, ReadPiExtensions(), "pi"); p.Packages[0].On { + t.Error("still on after switching it off") + } + if _, err := SetPiPackage("pi", "npm:@x/pi-foo@1.2.3", true); err != nil { + t.Fatal(err) + } + raw, _ = os.ReadFile(filepath.Join(here, "settings.json")) + json.Unmarshal(raw, &s) + if s.Packages[0] != "npm:@x/pi-foo@1.2.3" { + t.Errorf("on: packages[0] = %#v, want its source alone", s.Packages[0]) + } + before, _ := os.ReadFile(filepath.Join(here, "settings.json")) + if _, err := SetPiPackage("pi", "git:github.com/a/b@v1", false); err == nil || !strings.Contains(err.Error(), "pi config") { + t.Errorf("a filtered package switched: %v", err) + } + if after, _ := os.ReadFile(filepath.Join(here, "settings.json")); string(after) != string(before) { + t.Error("a refused switch wrote settings.json") + } +} + +// A package goes to the other Pi as its settings.json entry, which Pi +// there installs when it starts; one it has already, however pinned, isn't +// written twice, and a local folder isn't sent at all. +func TestPiCopyPackage(t *testing.T) { + here, wsl := piTwo(t) + write(t, filepath.Join(here, "settings.json"), `{"packages": [{"source": "npm:pi-foo@2.0.0", "extensions": ["-a.ts"]}, "git:github.com/a/b@v1", "../mine"]}`) + write(t, filepath.Join(wsl, "settings.json"), "{\n \"packages\": [\"git:https://github.com/a/b\"]\n}\n") + + if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "npm:pi-foo@2.0.0"); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(filepath.Join(wsl, "settings.json")) + var s struct{ Packages []any } + if err := json.Unmarshal(raw, &s); err != nil { + t.Fatal(err) + } + if len(s.Packages) != 2 { + t.Fatalf("packages = %#v", s.Packages) + } + if o, _ := s.Packages[1].(map[string]any); o["source"] != "npm:pi-foo@2.0.0" || o["extensions"] == nil { + t.Errorf("copied entry = %#v, want it whole, filters kept", s.Packages[1]) + } + if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "git:github.com/a/b@v1"); err == nil || !strings.Contains(err.Error(), "already") { + t.Errorf("a package the other Pi has (another pin, another spelling) copied: %v", err) + } + if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "../mine"); err == nil { + t.Error("a local folder's path was written into the other Pi") + } + if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "npm:pi-foo@2.0.0"); err == nil { + t.Error("copied twice") + } + // the other way round, to a Pi with no settings.json yet + os.Remove(filepath.Join(here, "settings.json")) + if _, err := CopyPi("pi@wsl:Ubuntu", "pi", "", "git:https://github.com/a/b"); err != nil { + t.Fatal(err) + } + if p := piOf(t, ReadPiExtensions(), "pi"); len(p.Packages) != 1 || p.Packages[0].Source != "git:https://github.com/a/b" { + t.Errorf("packages = %+v", p.Packages) + } +} + +// An extension goes to the other Pi as its file or folder, without +// node_modules; one with dependencies says they need installing there, +// and one by a name the other Pi has isn't written over. +func TestPiCopyExtension(t *testing.T) { + here, wsl := piTwo(t) + write(t, filepath.Join(wsl, "extensions", "one.ts"), "export default 1\n") + write(t, filepath.Join(wsl, "extensions", "kit", "index.ts"), "x") + write(t, filepath.Join(wsl, "extensions", "kit", "package.json"), `{"dependencies":{"zod":"^3"}}`) + write(t, filepath.Join(wsl, "extensions", "kit", "lib", "u.ts"), "u") + write(t, filepath.Join(wsl, "extensions", "kit", "node_modules", "zod", "index.js"), "") + write(t, filepath.Join(here, "extensions", "taken.ts"), "mine") + write(t, filepath.Join(wsl, "extensions", "taken.ts"), "theirs") + + if _, err := CopyPi("pi@wsl:Ubuntu", "pi", "extensions/one.ts", ""); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(filepath.Join(here, "extensions", "one.ts")); string(b) != "export default 1\n" { + t.Errorf("one.ts = %q", b) + } + c, err := CopyPi("pi@wsl:Ubuntu", "pi", "extensions/kit", "") + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(here, "extensions", "kit", "lib", "u.ts")); err != nil { + t.Error("kit's lib wasn't copied") + } + if _, err := os.Stat(filepath.Join(here, "extensions", "kit", "node_modules")); err == nil { + t.Error("node_modules was copied") + } + if c.Install == "" { + t.Error("a folder with dependencies doesn't say to install them") + } + if e := piExtOf(t, piOf(t, c.PiExtensions, "pi"), "extensions/kit"); !e.On { + t.Error("the copy isn't listed on") + } + if _, err := CopyPi("pi@wsl:Ubuntu", "pi", "extensions/taken.ts", ""); err == nil { + t.Error("an extension of the same name was written over") + } + if b, _ := os.ReadFile(filepath.Join(here, "extensions", "taken.ts")); string(b) != "mine" { + t.Errorf("taken.ts = %q, want the Pi's own", b) + } +} + +// A settings.json that can't be read is unknown, not empty: nothing is +// listed for it and nothing written to it. +func TestPiUnreadSettingsNotWritten(t *testing.T) { + here, _ := piTwo(t) + write(t, filepath.Join(here, "extensions", "a.ts"), "") + bad := `{"extensions": ["-extensions/a.ts"],,, oops` + write(t, filepath.Join(here, "settings.json"), bad) + p := piOf(t, ReadPiExtensions(), "pi") + if p.Err == "" || len(p.Extensions) != 0 { + t.Errorf("unreadable settings read as %+v", p) + } + if _, err := SetPiExtension("pi", "extensions/a.ts", false); err == nil { + t.Error("switched with settings.json unread") + } + if b, _ := os.ReadFile(filepath.Join(here, "settings.json")); string(b) != bad { + t.Errorf("settings.json written: %q", b) + } +} + +// A Pi in a stopped distro is listed, with nothing read of it, and +// nothing is changed in it. +func TestPiAsleepNotRead(t *testing.T) { + piTwo(t) + real := piPlaces + piPlaces = func() []piPlace { + return append(real(), piPlace{a: &agent.Agent{ID: "pi@wsl:Debian", Name: "Pi", WSL: "Debian"}, asleep: true}) + } + t.Cleanup(func() { piPlaces = real }) + p := piOf(t, ReadPiExtensions(), "pi@wsl:Debian") + if !p.Asleep || len(p.Extensions) != 0 { + t.Errorf("asleep Pi = %+v", p) + } + if _, err := CopyPi("pi", "pi@wsl:Debian", "", "npm:x"); err == nil || !strings.Contains(err.Error(), "isn't running") { + t.Errorf("copy to a stopped distro: %v", err) + } +} + +func TestPiGlob(t *testing.T) { + for _, c := range []struct { + g, s string + ok bool + }{ + {"*.js", "c.js", true}, + {"*.js", "extensions/c.js", false}, + {"extensions/**", "extensions/a/b.ts", true}, + {"**/b.ts", "extensions/a/b.ts", true}, + {"**/b.ts", "b.ts", true}, + {"extensions/?.ts", "extensions/a.ts", true}, + {"extensions/[ab].ts", "extensions/c.ts", false}, + {"a.ts", "xa.ts", false}, + } { + if got := piGlob(c.g).MatchString(c.s); got != c.ok { + t.Errorf("%q ~ %q = %v, want %v", c.g, c.s, got, c.ok) + } + } +}