library: list the skills, MCP servers and hooks of plugins installed natively in Codex and Pi (#7244)

The Library now reads Codex's plugin cache (plugins/cache/<marketplace>/<plugin>/<version>,
manifests under .codex-plugin, .claude-plugin or .cursor-plugin; config.toml's
enabled flag) and Pi's packages (settings.json packages, package.json pi.skills,
user and project scope) and lists what they bring on the skills, MCP and hooks
tabs under "Installed in the agents themselves", with origin and scope.
Read-only: nothing is copied, linked or registered; the agent keeps loading it,
load status stays unknown. Paths stay inside the plugin; an unreadable file
means unknown. New GET /api/library/native (lazy, not on the polled
/api/library) and `magpie library native`. Docs row in library.md.

Run (mica, sandbox HOME, nothing of the live ~/.codex or ~/.pi touched):
- go vet darwin; internal/library native tests (6) and the new GUI test
  library-native.test.cjs in chromium and webkit, 5 languages, 980 and 380 px.
- Built binary against a sandbox copy of the real Codex cache manifests (74 files).
- Not tried: Claude native plugins, subagents, Pi MCP and hooks, a live Codex
  or Pi, Windows and WSL Pi. The whole GUI suite and the full Go suite run after the push.
- Not mine: every package using testenv is red on origin/main 9ec023a46 from the
  stale docs index (docs/routing-groups.html and its ja/zh copies; its author is
  regenerating it), so go test of internal/library and internal/gui fails there
  before and after this change. TestEveryRouteHasACommandOrIsNamed named the new
  route; settings_parity_test.go now maps it to `magpie library native`.
This commit is contained in:
yetone
2026-11-20 02:34:58 +08:00
parent 9ec023a46b
commit 6d153bffca
11 changed files with 1084 additions and 9 deletions
+1
View File
@@ -51,6 +51,7 @@ Pi's extensions and packages.
| billion-context.json | The tab's Settings (@Luxzinw on X) change bili's own config, found by bili's `src/paths.ts`: `BILI_CONFIG_FILE`, else `$XDG_CONFIG_HOME` (or `~/.config`, `%USERPROFILE%\.config` on Windows) then `billion-context/billion-context.json` (`BiliConfigFile`). `ReadBiliSettings` reads it as JSONC; `SetBiliSettings` changes five of its `compress` keys and nothing else, through `edit.PatchJSON` (comments, BOM and every other key kept) and a temporary file renamed in: `nudgeGrowthTokens` (1000 to 10,000,000; empty takes it out, bili's 50000), `requireNudge` (off takes it out), `externalSummary` (`enabled` with `targets`, the picked one first, at most 16) and `prompts.compressPhilosophy` with `acknowledgePromptsRisk`, which bili needs before it reads a prompt override (under Advanced). `visibilityMarkers` (@JamesYu32 on X, under Advanced): bili's 📦/❌ lines after a compress, decompress or search_context call, on by default; off writes `false`, on takes the key out, and a provider's or model's own `compress.visibilityMarkers` is left as it is. bili turns off the whole compress section on one bad value, so magpie writes only values bili accepts and refuses a summary with no target. A model of magpie's is a recipe `providers.magpie` (`api: openai`, the gateway's `/v1`, `credentialRef: magpie`), its key the gateway's for the agent `billion-context` saved in bili's own credential store `<config>.summary-credentials.json` the way bili writes it (0600, an `O_EXCL` `.lock`, a temporary file renamed in); a user's own `providers.magpie` is never taken over. A file bili can't read is said so and left alone. After a change every running bili (`biliOrigins`, loopback only) is asked `POST /__bili/config/reload`; bili reloads routes and compress there, and the page says when none did. The file is carried in the library part (see [sync and backup](sync-backup.md)), the credential store never. `TestBiliConfigFileWhereBiliLooks`, `TestBiliSettingsChanged`, `TestBiliSettingsRefused`, `TestBiliMarkersSwitch`, `TestBiliKeyStoreKeptPrivate`, `TestBiliSettingsRoute`; the page is `biliSettings` (library-bili-settings.test.cjs). | [`bili_config.go`](../../internal/library/bili_config.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 `<agentDir>/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 `<agentDir>/npm`, git into `<agentDir>/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) |
| Pi market | `MarketPiPackages` lists npm's packages with the keyword `pi-package`, the way pi.dev's gallery finds them: the 500 most downloaded (two pages of npm's search, sorted by last month's downloads), cached 6h in memory and on disk, else the bundled `market_pi.json`; a search of two or more characters adds npm's own `keywords:pi-package <q>` search, and a search npm doesn't answer keeps the popular matches with a `SearchError` (the page says so). Every name is held to npm's rules (`piNameRe`), and a repository link is https only. `InstallPiPackage` runs `pi install npm:<name>` with `PI_CODING_AGENT_DIR` set to that Pi's folder (`piRun`), then checks settings.json lists it; `RemovePiPackage` runs `pi remove <source>`, which drops every entry of the same identity and uninstalls it. A Pi with no `pi` here (a WSL distro's, or this computer's with no CLI on PATH) gets the settings.json entry written, or taken out, instead, and Pi installs it when it next starts (`pending`). Both refuse an unreadable settings.json, install refuses a package the Pi has by Pi's identity, and each write is backed up first. `GET /api/library/market/pi`, `POST /api/library/pi/install`, `POST /api/library/pi/remove`; Discover under the Pi packages tab (`piCard`, `installPi`, `confirmRemovePi` in plugins/library/client.js; library-pi-market.test.cjs) marks a package every running Pi has Installed, and Install asks which Pi when several lack it (nineruiing on X). | [`pimarket.go`](../../internal/library/pimarket.go) |
| Native inventory | `ReadNative` (`GET /api/library/native`, `magpie library native`; #7244, jinpwng) lists what the plugins Codex installed itself and the packages Pi installed itself declare, so the skills, MCP servers and hooks they bring are in the Library's tabs once, with their origin and scope. Read only: nothing is copied, linked or registered, the agent keeps loading them, and `Loaded` is always `unknown` because only a session shows it. Codex (`codexNative`, codex-rs `core-plugins` loader.rs): `plugins/cache/<marketplace>/<plugin>/<version>/.codex-plugin/plugin.json` (`.claude-plugin` and `.cursor-plugin` too); the version folder stands for the plugin, a `latest` copy only when alone; skills are the manifest's `skills` folders, else `skills/`; servers its `mcpServers` (a file or inline), else `.mcp.json`; hooks its `hooks` (files or inline objects, as chrome's), else `hooks/hooks.json`; every path stays inside the plugin (`inside`); `[plugins."p@m"] enabled` in config.toml is `Enabled`, unset is nil. Pi (`piNativePlugins`): each package in a Pi's settings.json that is on disk (`packageDir`, shared with `installed`), its skills from package.json `pi.skills` (with `!` drops matched against each skill's path) or `skills/` when it has no `pi` object, and the `.pi/settings.json` packages of the library's projects with scope `project` and `Enabled` unknown (Pi loads them only once it trusts the project). Neither agent has subagents in a plugin, and a Pi package declares no servers or hooks here, so only skills, servers and hooks are listed. Asked for when a tab is drawn, not part of the polled `/api/library`. | [`native.go`](../../internal/library/native.go) |
## Runtime path
+3
View File
@@ -54,6 +54,7 @@ const libraryUsage = `magpie library what the library gives
magpie library skill use-library <name> <agent> an agent's own skill by that name is in the way: set it aside, link the library's
magpie library skill keep-own <name> <agent> …or keep the agent's, and take the agent off the library's
magpie library project … a project folder's own skills (Library › Projects): magpie library project help
magpie library native what plugins Codex and packages Pi installed themselves declare (read only; the agent loads them)
magpie library rtk which agents run their shell commands through RTK (rtk-ai.app), to save tokens
magpie library rtk on|off <agent> switch it (on with RTK's own installer; off works with RTK gone)
magpie library rtk install install RTK (Homebrew, winget, or RTK's own script)
@@ -279,6 +280,8 @@ func libraryCmd(args []string) error {
default:
return fmt.Errorf("usage:\n %s", libraryUsage)
}
case "native":
return libraryNativeCmd(rest)
case "rtk":
return rtkCmd(rest)
case "project", "projects":
+41
View File
@@ -0,0 +1,41 @@
package cli
import (
"fmt"
"github.com/yetone/magpie/internal/library"
)
// libraryNativeCmd is magpie library native: what the plugins Codex and
// the packages Pi installed themselves declare. It reads and writes
// nothing; the agent loads them, and whether one is loaded in a session
// isn't known from its files.
func libraryNativeCmd(rest []string) error {
if len(rest) != 0 {
return fmt.Errorf("usage:\n %s", libraryUsage)
}
v := library.ReadNative()
if len(v) == 0 {
fmt.Println(muted.Render("no plugins or packages installed through Codex or Pi"))
return nil
}
for _, p := range v {
where := p.Scope
if p.Project != "" {
where += " " + p.Project
}
state := "state unknown"
if p.Enabled != nil {
state = map[bool]string{true: "on", false: "off"}[*p.Enabled] + " in its settings"
}
fmt.Printf("%s %s %s (%s, %s)\n", p.AgentName, p.Name, p.Version, where, state)
for _, x := range p.Parts {
fmt.Printf(" %-5s %s", x.Kind, x.Name)
if x.Detail != "" && x.Kind != "skill" {
fmt.Printf(" %s", x.Detail)
}
fmt.Println()
}
}
return nil
}
+1
View File
@@ -212,6 +212,7 @@ var cliForRoute = map[string]string{
"POST /api/settings/mtls/issue": "magpie mtls issue",
"POST /api/settings/mtls/revoke": "magpie mtls revoke",
"GET /api/library": "magpie library",
"GET /api/library/native": "magpie library native",
"POST /api/library/{what}/{action}": "magpie library",
"GET /api/plugins": "magpie plugin",
"POST /api/plugins/{op}": "magpie plugin",
@@ -991,6 +991,8 @@ magpie.plugin("library", (ctx) => {
if (id === "bili" && bili) loadBili();
// Pi's extensions too: one installed or changed outside magpie since
if (id === "pi" && piView) loadPi();
// and the plugins and packages the agents installed themselves
if (["skills", "mcp", "hooks"].includes(id) && nativeView) loadNative();
// memory too: agents save to it while the page is open
if (id === "memory" && mem) loadMemory();
if (!lib) return page.querySelector(":scope > .lib-skel")?.replaceWith(skeleton(id));
@@ -2201,6 +2203,59 @@ magpie.plugin("library", (ctx) => {
piLoading = false;
if (tab === "pi" && piView) render();
}
// What plugins Codex and packages Pi installed themselves declare (#7244,
// jinpwng): listed once beside the library's own, with where each came
// from. Read only: the agent loads them, magpie copies, links and
// registers nothing, and whether a session loads one isn't known from
// its files. Asked for when a tab that lists them is drawn, not part of
// /api/library, which is polled.
let nativeView = null; // /api/library/native
let nativeLoading = false;
async function loadNative() {
if (nativeLoading) return;
nativeLoading = true;
try {
nativeView = await api("library/native");
} catch {
// a list that can't be read is not drawn, never a wrong one
}
nativeLoading = false;
if (nativeView && ["skills", "mcp", "hooks"].includes(tab)) render();
}
function nativeSection(kind) {
if (agentless()) return [];
if (!nativeView) { if (!nativeLoading) loadNative(); return []; }
const rows = [];
for (const p of nativeView) {
for (const x of p.parts || []) {
if (x.kind !== kind || isHidden({ id: p.agent })) continue;
const row = el("div", "row lib-row lib-native");
row.dataset.native = p.agent + " " + p.name + " " + x.name;
const who = el("div", "who");
who.append(el("div", "name mono", x.name));
if (x.detail) who.append(el("div", kind === "hook" ? "sub mono" : "sub", x.detail));
const origin = el("div", "lib-src");
const bits = [p.agentName, p.name + (p.version ? " " + p.version : ""), p.scope === "project" ? t("project scope") : t("user scope")];
origin.append(el("span", "", bits.join(" · ")));
if (p.project) origin.append(pathLink(p.project));
origin.title = p.source || "";
who.append(origin);
row.append(glyph(GLYPH[kind === "mcp" ? "web" : kind === "hook" ? "cmd" : "skill"]), who);
if (p.enabled === false) row.append(tag(t("Off in {agent}", { agent: p.agentName }), "warn", t("{agent}'s own settings turn this plugin off", { agent: p.agentName })));
rows.push(row);
}
}
if (!rows.length) return [];
const box = el("section", "lib-nativebox");
const rh = el("div", "row-head");
rh.append(el("span", "label", t("Installed in the agents themselves")), el("span", "grow"));
box.append(rh, intro(t("Listed as the agents' plugins and packages declare them. The agent loads them: magpie copies and changes nothing, and a session shows what is loaded.")));
const list = el("div", "list lib-list");
list.append(...rows);
box.append(list);
return [box];
}
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) {
@@ -2976,6 +3031,7 @@ magpie.plugin("library", (ctx) => {
body.append(el("p", "lib-aside lib-wb-trust", t("{agent} connects a server only once you trust it: switch it on in {agent}'s MCP settings, and again after its command or address changes.", { agent: wb.name })));
}
}
body.append(...nativeSection("mcp"));
body.append(discover("mcp"));
}
@@ -4761,6 +4817,7 @@ magpie.plugin("library", (ctx) => {
// ones whose hooks files magpie knows
const skip = all.filter((a) => hookAgentOf(a.id).no);
if (skip.length) body.append(el("p", "lib-aside lib-hooks-no", t("magpie can't give hooks to {agents} yet: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") })));
body.append(...nativeSection("hook"));
}
function hookRow(h, all) {
@@ -5925,6 +5982,7 @@ magpie.plugin("library", (ctx) => {
if (shownAgents().some((a) => a.id === "claude-desktop" && a.skills)) {
body.append(el("p", "lib-aside", t("Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.", { keys: /^Mac/.test(navigator.platform) ? "⌘R" : "Ctrl+R" })));
}
body.append(...nativeSection("skill"));
body.append(discover("skills"));
}
@@ -2,6 +2,12 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"project scope": "项目范围",
"user scope": "用户范围",
"Off in {agent}": "在 {agent} 中已关闭",
"{agent}'s own settings turn this plugin off": "{agent} 自己的设置把这个插件关掉了",
"Installed in the agents themselves": "Agent 自己安装的内容",
"Listed as the agents' plugins and packages declare them. The agent loads them: magpie copies and changes nothing, and a session shows what is loaded.": "按 Agent 的插件和包所声明的内容列出。由 Agent 自己加载:magpie 不复制也不改动,会话中才能看到实际加载了什么。",
"In {plugin}": "属于 {plugin}",
"Comes with the Claude plugin {plugin}. Changing the plugin's agents, or turning it off and on, gives this to the plugin's agents again.": "随 Claude 插件 {plugin} 安装。改动插件的 Agent,或把插件关掉再打开,会把它重新给到插件的 Agent。",
"Put back in {agents}": "放回 {agents}",
@@ -1140,6 +1146,12 @@ magpie.strings({
"{agents} reads no project instructions file magpie knows of.": "{agents} 没有 magpie 已知的项目指令文件。",
},
"zh-TW": {
"project scope": "專案範圍",
"user scope": "使用者範圍",
"Off in {agent}": "在 {agent} 中已關閉",
"{agent}'s own settings turn this plugin off": "{agent} 自己的設定把這個外掛關掉了",
"Installed in the agents themselves": "Agent 自己安裝的內容",
"Listed as the agents' plugins and packages declare them. The agent loads them: magpie copies and changes nothing, and a session shows what is loaded.": "依 Agent 的外掛與套件所宣告的內容列出。由 Agent 自己載入:magpie 不複製也不改動,工作階段中才看得到實際載入了什麼。",
"In {plugin}": "屬於 {plugin}",
"Comes with the Claude plugin {plugin}. Changing the plugin's agents, or turning it off and on, gives this to the plugin's agents again.": "隨 Claude 外掛 {plugin} 安裝。變更外掛的 Agent,或把外掛關閉再開啟,會把它重新給到外掛的 Agent。",
"Put back in {agents}": "放回 {agents}",
@@ -2278,6 +2290,12 @@ magpie.strings({
"{agents} reads no project instructions file magpie knows of.": "{agents} 沒有 magpie 已知的專案指令檔案。",
},
ja: {
"project scope": "プロジェクトの範囲",
"user scope": "ユーザーの範囲",
"Off in {agent}": "{agent} ではオフ",
"{agent}'s own settings turn this plugin off": "{agent} 自身の設定でこのプラグインはオフです",
"Installed in the agents themselves": "エージェント自身がインストールしたもの",
"Listed as the agents' plugins and packages declare them. The agent loads them: magpie copies and changes nothing, and a session shows what is loaded.": "エージェントのプラグインとパッケージが宣言する内容を一覧にしています。読み込むのはエージェント自身で、magpie はコピーも変更もしません。実際に読み込まれたものはセッションで分かります。",
"In {plugin}": "{plugin} の一部",
"Comes with the Claude plugin {plugin}. Changing the plugin's agents, or turning it off and on, gives this to the plugin's agents again.": "Claude プラグイン {plugin} と一緒に入りました。プラグインのエージェントを変えるか、オフにしてオンに戻すと、プラグインのエージェントに改めて渡されます。",
"Put back in {agents}": "{agents} に戻す",
@@ -3416,6 +3434,12 @@ magpie.strings({
"{agents} reads no project instructions file magpie knows of.": "{agents} は magpie が把握しているプロジェクトの指示ファイルを読みません。",
},
de: {
"project scope": "Projektbereich",
"user scope": "Benutzerbereich",
"Off in {agent}": "In {agent} aus",
"{agent}'s own settings turn this plugin off": "Die eigenen Einstellungen von {agent} schalten dieses Plugin aus",
"Installed in the agents themselves": "Von den Agents selbst installiert",
"Listed as the agents' plugins and packages declare them. The agent loads them: magpie copies and changes nothing, and a session shows what is loaded.": "So aufgelistet, wie die Plugins und Pakete der Agents sie angeben. Der Agent lädt sie selbst: magpie kopiert und ändert nichts, und eine Sitzung zeigt, was geladen ist.",
"In {plugin}": "Teil von {plugin}",
"Comes with the Claude plugin {plugin}. Changing the plugin's agents, or turning it off and on, gives this to the plugin's agents again.": "Kommt mit dem Claude-Plugin {plugin}. Werden die Agenten des Plugins geändert oder wird es aus- und wieder eingeschaltet, geht dies erneut an die Agenten des Plugins.",
"Put back in {agents}": "Zurück zu {agents}",
+6
View File
@@ -344,6 +344,12 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/library/pi", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, library.ReadPiExtensions())
})
// What the agents' own plugins (Codex's marketplaces) and packages (Pi's)
// declare, read and never written (#7244). Asked for when the Library
// is opened, not part of the polled /api/library.
mux.HandleFunc("GET /api/library/native", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, library.ReadNative())
})
mux.HandleFunc("POST /api/library/pi", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
Pi, Ext, Pkg string
+119
View File
@@ -0,0 +1,119 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// jinpwng (#7244): a plugin Codex installed from a marketplace and a package
// Pi installed list their skills, MCP servers and hooks in the Library's own
// tabs, once, with where they came from. Read only: nothing there to switch,
// copy or remove, and no row twice. In every language, both engines, at a
// phone's width too. No backend: the API is faked here, with the shapes
// the Go reader returns for Codex's real cache layout (chrome's inline
// hooks, codex-app-tools' .mcp.json) and a Pi package.
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/me";
const lib = () => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [{ id: "codex", name: "Codex", icon: "", skills: `${HOME}/.codex/skills`, mcp: true, hooks: true }],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [], hooks: [],
});
const native = [
{
agent: "codex", agentName: "Codex", name: "chrome", version: "26.1029.61003", source: "openai-bundled", scope: "user", dir: `${HOME}/.codex/plugins/cache/openai-bundled/chrome/26.1029.61003`, enabled: false, loaded: "unknown",
parts: [
{ kind: "skill", name: "chrome", detail: "Drive Chrome" },
{ kind: "hook", name: "Stop", detail: "mcp_tool node_repl/turn_ended" },
],
},
{
agent: "codex", agentName: "Codex", name: "codex-app-tools", version: "26.1029.61003", source: "openai-bundled", scope: "user", dir: `${HOME}/.codex/plugins/cache/openai-bundled/codex-app-tools/26.1029.61003`, loaded: "unknown",
parts: [{ kind: "mcp", name: "codex_app", detail: "stdio" }],
},
{
agent: "pi", agentName: "Pi", name: "proj-kit", version: "2.0.0", source: "npm:proj-kit", scope: "project", project: `${HOME}/work/app`, dir: `${HOME}/work/app/.pi/npm/node_modules/proj-kit`, loaded: "unknown",
parts: [{ kind: "skill", name: "review", detail: "Review code" }],
},
];
function server(lang, tab, calls) {
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};try{localStorage.setItem("magpie.libTab","${tab}")}catch{}` });
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/native") { calls.push(req.method()); return route.fulfill({ json: native }); }
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: { head: "Installed in the agents themselves", off: "Off in Codex", project: "project scope", user: "user scope" },
zh: { head: "Agent 自己安装的内容", off: "在 Codex 中已关闭", project: "项目范围", user: "用户范围" },
"zh-TW": { head: "Agent 自己安裝的內容", off: "在 Codex 中已關閉", project: "專案範圍", user: "使用者範圍" },
ja: { head: "エージェント自身がインストールしたもの", off: "Codex ではオフ", project: "プロジェクトの範囲", user: "ユーザーの範囲" },
de: { head: "Von den Agents selbst installiert", off: "In Codex aus", project: "Projektbereich", user: "Benutzerbereich" },
};
// the tab, and the rows of its kind the fake lists
const tabs = {
skills: ["chrome", "review"],
mcp: ["codex_app"],
hooks: ["Stop"],
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": what Codex plugins and Pi packages declare is listed once, read only", 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]) for (const tab of Object.keys(tabs)) {
await t.test(`${tab} ${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, tab, calls));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const v = page.locator("#view-library");
const rows = v.locator(".lib-nativebox .lib-native");
await rows.first().waitFor();
assert.deepEqual(await rows.locator(".name").allTextContents(), tabs[tab]);
assert.equal(await v.locator(".lib-nativebox .label").textContent(), w.head);
// each row says where it came from, once, with its scope
const first = (await rows.first().textContent());
assert(first.includes("Codex · " + (tab === "mcp" ? "codex-app-tools" : "chrome") + " 26.1029.61003"), first);
if (tab === "skills") {
assert(first.includes(w.user), first);
assert((await rows.nth(1).textContent()).includes(w.project), await rows.nth(1).textContent());
assert((await rows.nth(1).textContent()).includes("proj-kit 2.0.0"));
// chrome's own settings turn it off
assert.equal(await rows.first().locator(".lib-tag").textContent(), w.off);
}
// read only: nothing to switch, copy or remove
assert.equal(await rows.getByRole("switch").count(), 0);
assert.equal(await rows.locator("button.danger, .lib-icon").count(), 0);
assert.deepEqual(calls, ["GET"]);
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, []);
});
}
+545
View File
@@ -0,0 +1,545 @@
package library
import (
"encoding/json"
"io/fs"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/pelletier/go-toml/v2"
)
// What the agents' own plugins and packages declare (jinpwng, #7244). A
// plugin installed in Codex (its marketplaces) or a package installed in
// Pi (`pi install`) is the agent's to load. magpie only reads what it
// declares, to list the skills, MCP servers and hooks in the Library's own
// tabs once, with where it came from and its scope, and writes, links and
// registers nothing: the agent keeps loading it, so nothing is listed a
// second time as a copy of the library's. Whether a session loads it is
// not known from its files, so it is listed as unknown (Loaded) until one
// shows it.
//
// Codex (codex-rs/core-plugins loader.rs), under CODEX_HOME:
//
// plugins/cache/<marketplace>/<plugin>/<version>/.codex-plugin/plugin.json
// (.claude-plugin/plugin.json and .cursor-plugin/plugin.json too)
// config.toml [plugins."<plugin>@<marketplace>"] enabled, [marketplaces.<m>] source
//
// skills are the plugin.json "skills" folders, else skills/; MCP servers
// its "mcpServers" (a file, or the servers inline), else .mcp.json; hooks
// its "hooks" (files, or inline), else hooks/hooks.json. Codex has no
// subagents in a plugin.
//
// Pi (settings-manager and package-manager.js, @earendil-works/pi-coding-agent
// 1.4): each entry of settings.json "packages" (the Pi's own, and a
// registered project's .pi/settings.json) whose folder is on disk. A
// package declares skills in package.json pi.skills, else skills/ when it
// has no "pi" object; Pi has no MCP servers, hooks or subagents of a
// package's. A project's packages load only once Pi trusts the project, so
// they are listed with Enabled unknown.
// NativePart is one thing a native plugin or package declares.
type NativePart struct {
// Kind is skill, mcp or hook
Kind string `json:"kind"`
Name string `json:"name"`
// Detail is a skill's description, a server's transport, a hook's
// command
Detail string `json:"detail,omitempty"`
dir string // a skill's folder, what a Pi package's filters match
}
// NativePlugin is a plugin or package an agent installed itself.
type NativePlugin struct {
Agent string `json:"agent"`
AgentName string `json:"agentName"`
Name string `json:"name"`
Version string `json:"version,omitempty"`
// Source is the marketplace it came from (Codex), or the entry in
// settings.json (Pi)
Source string `json:"source,omitempty"`
// Scope is user, or project for one a project's own settings name
Scope string `json:"scope"`
Project string `json:"project,omitempty"`
Dir string `json:"dir"`
// Enabled is what the agent's own settings say; nil when they don't
Enabled *bool `json:"enabled,omitempty"`
// Loaded is always "unknown": only a session shows what was loaded
Loaded string `json:"loaded"`
Parts []NativePart `json:"parts"`
}
const nativePartsMax = 500
// ReadNative lists what the agents' own plugins and packages declare. It
// writes nothing and starts nothing.
func ReadNative() []NativePlugin {
out := codexNative()
out = append(out, piNativePlugins()...)
if out == nil {
out = []NativePlugin{}
}
return out
}
// ---- Codex ------------------------------------------------------------------
type codexConf struct {
Plugins map[string]struct{ Enabled *bool } `toml:"plugins"`
Marketplaces map[string]struct{ Source string } `toml:"marketplaces"`
}
var codexManifests = []string{".codex-plugin", ".claude-plugin", ".cursor-plugin"}
func codexNative() []NativePlugin {
home := codexDir()
var conf codexConf
if raw, err := os.ReadFile(filepath.Join(home, "config.toml")); err == nil {
// one that doesn't parse says nothing of enabled or sources
if toml.Unmarshal(raw, &conf) != nil {
conf = codexConf{}
}
}
cache := filepath.Join(home, "plugins", "cache")
var out []NativePlugin
markets, _ := os.ReadDir(cache)
for _, m := range markets {
if !m.IsDir() || strings.HasPrefix(m.Name(), ".") {
continue
}
plugins, _ := os.ReadDir(filepath.Join(cache, m.Name()))
for _, pl := range plugins {
if !pl.IsDir() || strings.HasPrefix(pl.Name(), ".") {
continue
}
root, man := codexVersion(filepath.Join(cache, m.Name(), pl.Name()))
if root == "" {
continue
}
p := NativePlugin{Agent: "codex", AgentName: "Codex", Name: plStr(man["name"]), Version: plStr(man["version"]),
Scope: "user", Dir: root, Loaded: "unknown", Source: m.Name()}
if p.Name == "" {
p.Name = pl.Name()
}
if p.Version == "" {
p.Version = filepath.Base(root)
}
if s := conf.Marketplaces[m.Name()].Source; s != "" {
p.Source = m.Name() + " (" + s + ")"
}
p.Enabled = conf.Plugins[pl.Name()+"@"+m.Name()].Enabled
p.Parts = codexParts(root, man)
out = append(out, p)
}
}
return out
}
// codexVersion is the version folder of a cached plugin that is current:
// the newest one with a manifest (a "latest" beside the version it copies
// is the same plugin once), and that manifest.
func codexVersion(dir string) (string, map[string]any) {
vs, _ := os.ReadDir(dir)
var best string
var bestMan map[string]any
var bestTime int64
for _, v := range vs {
d := filepath.Join(dir, v.Name())
if !isDir(d) {
continue
}
var man map[string]any
for _, mf := range codexManifests {
if m, err := readJSONFile(filepath.Join(d, mf, "plugin.json")); err == nil {
man = m
break
}
}
if man == nil {
continue
}
fi, err := os.Stat(d)
if err != nil {
continue
}
// "latest" is a copy of a version beside it: that one stands for
// the plugin, "latest" only when it is alone
t := fi.ModTime().UnixNano()
if v.Name() == "latest" {
t = 0
}
if best == "" || t > bestTime {
best, bestMan, bestTime = d, man, t
}
}
return best, bestMan
}
func codexParts(root string, man map[string]any) []NativePart {
var parts []NativePart
// skills
roots := pathsOf(man["skills"])
if len(roots) == 0 {
roots = []string{"skills"}
}
for _, r := range roots {
if d, ok := inside(root, r); ok && isDir(d) {
parts = append(parts, nativeSkills(d, 0)...)
}
}
// MCP servers: a file or the servers inline, else .mcp.json
var docs []map[string]any
switch v := man["mcpServers"].(type) {
case string:
docs = nativeJSONFiles(root, []string{v})
case map[string]any:
docs = []map[string]any{v}
default:
docs = nativeJSONFiles(root, []string{".mcp.json"})
}
for _, d := range docs {
parts = append(parts, nativeServers(d)...)
}
// hooks: files or inline objects, else hooks/hooks.json
switch v := man["hooks"].(type) {
case string:
docs = nativeJSONFiles(root, []string{v})
case map[string]any:
docs = []map[string]any{v}
case []any:
docs = nil
var files []string
for _, e := range v {
switch x := e.(type) {
case string:
files = append(files, x)
case map[string]any:
docs = append(docs, x)
}
}
docs = append(docs, nativeJSONFiles(root, files)...)
default:
docs = nativeJSONFiles(root, []string{"hooks/hooks.json"})
}
for _, d := range docs {
parts = append(parts, nativeHooks(d)...)
}
return nativeUnique(parts)
}
// nativeJSONFiles reads the files a manifest names inside the plugin's
// folder: one that leaves it, or can't be read as an object, is skipped.
func nativeJSONFiles(root string, names []string) []map[string]any {
var out []map[string]any
for _, n := range names {
p, ok := inside(root, n)
if !ok {
continue
}
if m, err := readJSONFile(p); err == nil {
out = append(out, m)
}
}
return out
}
func nativeServers(doc map[string]any) []NativePart {
m, _ := doc["mcpServers"].(map[string]any)
if m == nil {
m = doc
}
var out []NativePart
for _, k := range slices.Sorted(mapKeys(m)) {
e, ok := m[k].(map[string]any)
if !ok {
continue
}
tr := "stdio"
switch typ := plStr(e["type"]); {
case typ == "sse":
tr = "sse"
case typ == "http" || typ == "streamable-http" || typ == "" && plStr(e["url"]) != "":
tr = "http"
}
out = append(out, NativePart{Kind: "mcp", Name: k, Detail: tr})
}
return out
}
func mapKeys(m map[string]any) func(func(string) bool) {
return func(yield func(string) bool) {
for k := range m {
if !yield(k) {
return
}
}
}
}
// nativeHooks lists a hooks file's handlers, one for each event and
// matcher: {"hooks": {"Stop": [{"matcher", "hooks": [{"type", "command"}]}]}}.
func nativeHooks(doc map[string]any) []NativePart {
m, _ := doc["hooks"].(map[string]any)
if m == nil {
m = doc
}
var out []NativePart
for _, ev := range slices.Sorted(mapKeys(m)) {
groups, _ := m[ev].([]any)
for _, g := range groups {
gm, _ := g.(map[string]any)
hs, _ := gm["hooks"].([]any)
for _, h := range hs {
hm, _ := h.(map[string]any)
if hm == nil {
continue
}
name := ev
if mt := plStr(gm["matcher"]); mt != "" {
name += " · " + mt
}
detail := plStr(hm["command"])
if detail == "" {
detail = plStr(hm["type"])
if s, t := plStr(hm["server"]), plStr(hm["tool"]); s != "" {
detail += " " + s + "/" + t
}
}
out = append(out, NativePart{Kind: "hook", Name: name, Detail: detail})
}
}
}
return out
}
// nativeSkills are the skills below dir: a folder with a SKILL.md is one,
// not looked into further.
func nativeSkills(dir string, depth int) []NativePart {
if m, ok := readMeta(dir); ok {
name := m.Name
if name == "" {
name = filepath.Base(dir)
}
return []NativePart{{Kind: "skill", Name: name, Detail: m.Description, dir: dir}}
}
if depth > 6 {
return nil
}
var out []NativePart
es, _ := os.ReadDir(dir)
for _, e := range es {
if strings.HasPrefix(e.Name(), ".") || e.Name() == "node_modules" {
continue
}
d := filepath.Join(dir, e.Name())
if e.IsDir() || e.Type()&fs.ModeSymlink != 0 && isDir(d) {
out = append(out, nativeSkills(d, depth+1)...)
}
if len(out) >= nativePartsMax {
break
}
}
return out
}
// nativeUnique drops a part listed twice, and keeps the list bounded.
func nativeUnique(parts []NativePart) []NativePart {
seen := map[NativePart]bool{}
out := []NativePart{}
for _, p := range parts {
if seen[p] || len(out) >= nativePartsMax {
continue
}
seen[p] = true
out = append(out, p)
}
kinds := map[string]int{"skill": 0, "mcp": 1, "hook": 2}
sort.SliceStable(out, func(i, j int) bool { return kinds[out[i].Kind] < kinds[out[j].Kind] })
return out
}
// ---- Pi ---------------------------------------------------------------------
func piNativePlugins() []NativePlugin {
var out []NativePlugin
var local *piPlace
for _, p := range piPlaces() {
if p.asleep || p.err != nil {
continue
}
if p.a.WSL == "" && local == nil {
c := p
local = &c
}
out = append(out, piNativeIn(p, p, "user", "")...)
}
if local != nil {
for _, dir := range nativeProjects() {
pp := *local
pp.dir = filepath.Join(dir, ".pi")
// a project's packages load once Pi trusts the project
out = append(out, piNativeIn(*local, pp, "project", dir)...)
}
}
return out
}
// nativeProjects are the library's projects, read without changing it.
func nativeProjects() []string {
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return nil
}
var out []string
for _, p := range l.Projects {
out = append(out, p.Dir)
}
return out
}
// piNativeIn lists the packages in the settings.json of where, for the Pi
// pi. One that isn't on disk yet is not listed: Pi installs it when it
// next starts, and nothing is known of what it declares.
func piNativeIn(pi, where piPlace, scope, project string) []NativePlugin {
s, err := where.settings()
if err != nil {
return nil
}
var out []NativePlugin
seen := map[string]bool{}
for _, r := range s.pkgs {
pk, ok := piPackageOf(r)
if !ok {
continue
}
id := where.piIdentity(pk.Source)
if seen[id] {
continue
}
seen[id] = true
dir := where.packageDir(pk)
if dir == "" {
continue
}
var man struct {
Name, Version string
}
if raw, err := os.ReadFile(filepath.Join(dir, "package.json")); err == nil {
json.Unmarshal(stripBOM(raw), &man)
}
p := NativePlugin{Agent: pi.a.ID, AgentName: pi.a.Name, Name: pk.Name, Version: man.Version, Source: pk.Source,
Scope: scope, Project: project, Dir: dir, Loaded: "unknown", Parts: piSkills(dir)}
if man.Name != "" {
p.Name = man.Name
}
if scope == "user" {
on := pk.On
p.Enabled = &on
}
out = append(out, p)
}
return out
}
// piSkills are the skills a package declares: package.json pi.skills when
// it has a "pi" object, else its skills folder.
func piSkills(root string) []NativePart {
var pkg struct {
Pi map[string]json.RawMessage `json:"pi"`
}
if raw, err := os.ReadFile(filepath.Join(root, "package.json")); err == nil {
json.Unmarshal(stripBOM(raw), &pkg)
}
if pkg.Pi == nil {
return nativeUnique(nativeSkills(filepath.Join(root, "skills"), 0))
}
var entries []string
if json.Unmarshal(pkg.Pi["skills"], &entries) != nil {
return []NativePart{}
}
var dirs, drops []string
for _, e := range entries {
switch {
case strings.HasPrefix(e, "!") || strings.HasPrefix(e, "-"):
drops = append(drops, e[1:])
case strings.HasPrefix(e, "+"):
case piIsPattern(e):
dirs = append(dirs, piExpand(root, e)...)
default:
if d, ok := inside(root, e); ok {
dirs = append(dirs, d)
}
}
}
var parts []NativePart
dropped := func(p string) bool {
rel, err := filepath.Rel(root, p)
if err != nil {
return true
}
rel = filepath.ToSlash(rel)
for _, x := range drops {
x = strings.TrimPrefix(filepath.ToSlash(x), "./")
re := piGlob(x)
if rel == x || re.MatchString(rel) || re.MatchString(rel+"/SKILL.md") || re.MatchString(filepath.Base(p)) {
return true
}
}
return false
}
for _, d := range dirs {
if dropped(d) {
continue
}
if isDir(d) {
for _, sk := range nativeSkills(d, 0) {
if !dropped(sk.dir) {
parts = append(parts, sk)
}
}
} else if strings.HasSuffix(d, ".md") {
if b, err := os.ReadFile(d); err == nil {
m := parseMeta(b)
name := m.Name
if name == "" {
name = strings.TrimSuffix(filepath.Base(d), ".md")
}
parts = append(parts, NativePart{Kind: "skill", Name: name, Detail: m.Description, dir: d})
}
}
}
return nativeUnique(parts)
}
// piExpand is the folders and files below root that a glob of a package's
// manifest matches.
func piExpand(root, glob string) []string {
re := piGlob(strings.TrimPrefix(filepath.ToSlash(glob), "./"))
var out []string
filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() && (d.Name() == "node_modules" || d.Name() == ".git") {
return filepath.SkipDir
}
rel, err := filepath.Rel(root, p)
if err != nil || rel == "." {
return nil
}
if re.MatchString(filepath.ToSlash(rel)) {
out = append(out, p)
}
if len(out) >= nativePartsMax {
return filepath.SkipAll
}
return nil
})
return out
}
+269
View File
@@ -0,0 +1,269 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
)
// chromeManifest is the shape of the real chrome plugin in Codex's cache
// (openai-bundled/chrome/26.1029.61003): the hooks are inline in
// plugin.json, as {"hooks": {event: [{"hooks": [..]}]}}, and the skills
// are a folder.
const chromeManifest = `{
"name": "chrome",
"hooks": {"hooks": {
"Stop": [{"hooks": [{"type": "mcp_tool", "server": "node_repl", "tool": "turn_ended", "input": {"turn_id": "${turn_id}"}}]}],
"Interrupt": [{"hooks": [{"type": "mcp_tool", "server": "node_repl", "tool": "turn_ended"}]}]
}},
"version": "26.1029.61003",
"description": "Chrome automation",
"skills": "./skills/"
}`
// appToolsManifest and its .mcp.json are codex-app-tools' (the servers
// are in a file the manifest names).
const appToolsManifest = `{"version": "26.1029.61003", "name": "codex-app-tools", "mcpServers": "./.mcp.json", "description": "Exposes Codex desktop app tools."}`
const appToolsMCP = `{"mcpServers": {"codex_app": {"command": "/x/launch_codex_app_tools_mcp", "args": ["./server.mjs"], "enabled": false, "env": {"A": "1"}}}}`
const skillMD = "---\nname: visualize\ndescription: \"Create visualizations\n in conversation.\"\n---\n\n# Visualize\n"
func nativeCodexHome(t *testing.T) (home, cache string) {
t.Helper()
home = sandbox(t)
cache = filepath.Join(home, ".codex", "plugins", "cache")
write(t, filepath.Join(home, ".codex", "config.toml"), `[marketplaces.openai-bundled]
source = "/x/bundled-marketplaces/openai-bundled"
[plugins."chrome@openai-bundled"]
enabled = false
[plugins."codex-app-tools@openai-bundled"]
enabled = true
`)
c := filepath.Join(cache, "openai-bundled")
write(t, filepath.Join(c, "chrome", "26.1029.61003", ".codex-plugin", "plugin.json"), chromeManifest)
write(t, filepath.Join(c, "chrome", "26.1029.61003", "skills", "chrome", "SKILL.md"), "---\nname: chrome\ndescription: Drive Chrome\n---\n")
// "latest" is a copy of the version beside it
write(t, filepath.Join(c, "chrome", "latest", ".codex-plugin", "plugin.json"), chromeManifest)
write(t, filepath.Join(c, "chrome", "latest", "skills", "chrome", "SKILL.md"), "---\nname: chrome\ndescription: Drive Chrome\n---\n")
write(t, filepath.Join(c, "codex-app-tools", "26.1029.61003", ".codex-plugin", "plugin.json"), appToolsManifest)
write(t, filepath.Join(c, "codex-app-tools", "26.1029.61003", ".mcp.json"), appToolsMCP)
write(t, filepath.Join(c, "visualize", "1.0.74", ".codex-plugin", "plugin.json"), `{"name": "visualize", "version": "1.0.74", "skills": "./skills/"}`)
write(t, filepath.Join(c, "visualize", "1.0.74", "skills", "visualize", "SKILL.md"), skillMD)
return home, cache
}
func nativeOf(t *testing.T, v []NativePlugin, agent, name string) NativePlugin {
t.Helper()
var got []NativePlugin
for _, p := range v {
if p.Agent == agent && p.Name == name {
got = append(got, p)
}
}
if len(got) != 1 {
t.Fatalf("want one %s %s, got %d in %+v", agent, name, len(got), v)
}
return got[0]
}
func partsOf(p NativePlugin, kind string) []NativePart {
var out []NativePart
for _, x := range p.Parts {
if x.Kind == kind {
out = append(out, x)
}
}
return out
}
// A plugin Codex installed from a marketplace is listed once, with its
// skills, MCP servers and hooks, read from where Codex reads them, and
// nothing is written.
func TestNativeCodexPlugins(t *testing.T) {
home, _ := nativeCodexHome(t)
before := dirDump(t, filepath.Join(home, ".codex"))
v := ReadNative()
chrome := nativeOf(t, v, "codex", "chrome")
if chrome.Version != "26.1029.61003" || chrome.Scope != "user" || chrome.Loaded != "unknown" {
t.Errorf("chrome: %+v", chrome)
}
if chrome.Enabled == nil || *chrome.Enabled {
t.Errorf("config.toml turns chrome off: %v", chrome.Enabled)
}
if !strings.HasPrefix(chrome.Source, "openai-bundled") {
t.Errorf("source %q", chrome.Source)
}
if s := partsOf(chrome, "skill"); len(s) != 1 || s[0].Name != "chrome" || s[0].Detail != "Drive Chrome" {
t.Errorf("chrome skills: %+v", s)
}
h := partsOf(chrome, "hook")
if len(h) != 2 || h[0].Name != "Interrupt" || h[1].Name != "Stop" || h[1].Detail != "mcp_tool node_repl/turn_ended" {
t.Errorf("chrome hooks (inline in plugin.json): %+v", h)
}
app := nativeOf(t, v, "codex", "codex-app-tools")
if m := partsOf(app, "mcp"); len(m) != 1 || m[0].Name != "codex_app" || m[0].Detail != "stdio" {
t.Errorf("app tools' servers (a file plugin.json names): %+v", m)
}
if app.Enabled == nil || !*app.Enabled {
t.Errorf("enabled: %v", app.Enabled)
}
viz := nativeOf(t, v, "codex", "visualize")
if s := partsOf(viz, "skill"); len(s) != 1 || s[0].Name != "visualize" || s[0].Detail != "Create visualizations in conversation." {
t.Errorf("visualize: %+v", s)
}
if viz.Enabled != nil {
t.Errorf("config.toml says nothing of visualize: %v", *viz.Enabled)
}
if after := dirDump(t, filepath.Join(home, ".codex")); after != before {
t.Errorf("reading changed Codex's folder:\n%s\n--\n%s", before, after)
}
}
// What a manifest names stays inside the plugin: a path that leaves it
// reads nothing, a broken file is skipped, and the default files are read
// when the manifest names none.
func TestNativeCodexStaysInsidePlugin(t *testing.T) {
home, cache := nativeCodexHome(t)
secret := filepath.Join(home, "secret.json")
write(t, secret, `{"mcpServers": {"stolen": {"command": "x"}}}`)
root := filepath.Join(cache, "m", "evil", "1")
write(t, filepath.Join(root, ".codex-plugin", "plugin.json"), `{"name": "evil", "mcpServers": "../../../../../secret.json", "hooks": "../../../../../secret.json", "skills": "../../../../../"}`)
d := filepath.Join(cache, "m", "defaults", "1")
write(t, filepath.Join(d, ".codex-plugin", "plugin.json"), `{"name": "defaults"}`)
write(t, filepath.Join(d, ".mcp.json"), `{"web": {"url": "https://x.example/mcp"}}`)
write(t, filepath.Join(d, "hooks", "hooks.json"), `{"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "echo hi"}]}]}}`)
write(t, filepath.Join(d, "skills", "s", "SKILL.md"), "---\nname: s\n---\n")
write(t, filepath.Join(cache, "m", "broken", "1", ".codex-plugin", "plugin.json"), `{"name": "broken", "mcpServers": "./nope.json"`)
v := ReadNative()
if e := nativeOf(t, v, "codex", "evil"); len(e.Parts) != 0 {
t.Errorf("a path leaving the plugin was read: %+v", e.Parts)
}
def := nativeOf(t, v, "codex", "defaults")
if m := partsOf(def, "mcp"); len(m) != 1 || m[0].Name != "web" || m[0].Detail != "http" {
t.Errorf("default .mcp.json: %+v", m)
}
if h := partsOf(def, "hook"); len(h) != 1 || h[0].Name != "PreToolUse · Bash" || h[0].Detail != "echo hi" {
t.Errorf("default hooks/hooks.json: %+v", h)
}
if s := partsOf(def, "skill"); len(s) != 1 || s[0].Name != "s" {
t.Errorf("default skills/: %+v", s)
}
for _, p := range v {
if p.Name == "broken" {
t.Errorf("a plugin whose manifest doesn't parse is listed: %+v", p)
}
}
}
// The same plugin, as a version and its "latest" copy, is listed once.
func TestNativeCodexListedOnce(t *testing.T) {
nativeCodexHome(t)
n := 0
for _, p := range ReadNative() {
if p.Name == "chrome" {
n++
if filepath.Base(p.Dir) == "latest" {
t.Errorf("the copy stands for the plugin: %s", p.Dir)
}
}
}
if n != 1 {
t.Errorf("chrome listed %d times", n)
}
}
func dirDump(t *testing.T, root string) string {
t.Helper()
var b strings.Builder
filepath.Walk(root, func(p string, fi os.FileInfo, err error) error {
if err == nil && !fi.IsDir() {
raw, _ := os.ReadFile(p)
b.WriteString(p + " " + string(raw) + "\n")
}
return nil
})
return b.String()
}
// A Pi package is listed with the skills its package.json "pi" manifest
// names (and those a "!" entry drops), one with no manifest by its
// skills/ folder; a package Pi hasn't installed yet is not listed.
func TestNativePiPackages(t *testing.T) {
here, _ := piTwo(t)
nm := filepath.Join(here, "npm", "node_modules")
write(t, filepath.Join(here, "settings.json"), `{"packages": ["npm:@acme/pi-kit", "npm:plain-skills", "npm:not-installed", {"source": "npm:off-pkg", "extensions": [], "skills": [], "prompts": [], "themes": []}]}`)
write(t, filepath.Join(nm, "@acme", "pi-kit", "package.json"), `{"name": "@acme/pi-kit", "version": "1.2.0", "keywords": ["pi-package"], "pi": {"extensions": ["./ext"], "skills": ["./skills", "!**/draft"]}}`)
write(t, filepath.Join(nm, "@acme", "pi-kit", "skills", "review", "SKILL.md"), "---\nname: review\ndescription: Review code\n---\n")
write(t, filepath.Join(nm, "@acme", "pi-kit", "skills", "draft", "SKILL.md"), "---\nname: draft\n---\n")
write(t, filepath.Join(nm, "@acme", "pi-kit", "ext", "index.ts"), "export default () => {}\n")
write(t, filepath.Join(nm, "plain-skills", "package.json"), `{"name": "plain-skills", "version": "0.3.1"}`)
write(t, filepath.Join(nm, "plain-skills", "skills", "tidy", "SKILL.md"), "---\nname: tidy\n---\n")
write(t, filepath.Join(nm, "off-pkg", "package.json"), `{"name": "off-pkg"}`)
v := ReadNative()
var pis []NativePlugin
for _, p := range v {
if strings.HasPrefix(p.Agent, "pi") {
pis = append(pis, p)
}
}
if len(pis) != 3 {
t.Fatalf("want the three installed packages, got %+v", pis)
}
kit := nativeOf(t, v, pis[0].Agent, "@acme/pi-kit")
if kit.Version != "1.2.0" || kit.Scope != "user" || kit.Loaded != "unknown" || kit.Source != "npm:@acme/pi-kit" {
t.Errorf("kit: %+v", kit)
}
if s := partsOf(kit, "skill"); len(s) != 1 || s[0].Name != "review" || s[0].Detail != "Review code" {
t.Errorf("kit skills (the \"pi\" manifest, \"!**/draft\" drops one): %+v", s)
}
if s := partsOf(nativeOf(t, v, pis[0].Agent, "plain-skills"), "skill"); len(s) != 1 || s[0].Name != "tidy" {
t.Errorf("a package with no manifest keeps its skills/: %+v", s)
}
if off := nativeOf(t, v, pis[0].Agent, "off-pkg"); off.Enabled == nil || *off.Enabled {
t.Errorf("a package with every filter empty is off: %+v", off.Enabled)
}
}
// A project's own .pi/settings.json packages are listed under it, as
// project scope.
func TestNativePiProjectPackages(t *testing.T) {
here, _ := piTwo(t)
_ = here
proj := t.TempDir()
if _, err := AddProject(proj); err != nil {
t.Fatal(err)
}
write(t, filepath.Join(proj, ".pi", "settings.json"), `{"packages": ["npm:proj-kit"]}`)
write(t, filepath.Join(proj, ".pi", "npm", "node_modules", "proj-kit", "package.json"), `{"name": "proj-kit", "version": "2.0.0"}`)
write(t, filepath.Join(proj, ".pi", "npm", "node_modules", "proj-kit", "skills", "p", "SKILL.md"), "---\nname: p\n---\n")
var got *NativePlugin
for _, p := range ReadNative() {
if p.Name == "proj-kit" {
p := p
got = &p
}
}
if got == nil {
t.Fatalf("project package not listed")
}
if got.Scope != "project" || got.Project != proj || got.Enabled != nil || len(partsOf(*got, "skill")) != 1 {
t.Errorf("%+v", *got)
}
}
// An unreadable settings.json lists nothing for that Pi, and a machine
// with no Codex and no Pi lists an empty list, not null.
func TestNativeNothingIsEmptyList(t *testing.T) {
sandbox(t)
if v := ReadNative(); v == nil || len(v) != 0 {
t.Errorf("%#v", v)
}
}
+17 -9
View File
@@ -690,6 +690,19 @@ func piSourceID(s string) string {
// installed says whether Pi has pk on disk, and its version there.
func (p piPlace) installed(pk PiPackage) (bool, string) {
d := p.packageDir(pk)
if d == "" {
return false, ""
}
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
}
// packageDir is where Pi has pk on disk, "" when it hasn't.
func (p piPlace) packageDir(pk PiPackage) string {
var dirs []string
switch pk.Kind {
case "npm":
@@ -700,23 +713,18 @@ func (p piPlace) installed(pk PiPackage) (bool, string) {
case "git":
h, gp := piGitPlace(pk.Source)
if h == "" || gp == "" {
return false, ""
return ""
}
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
if _, err := os.Stat(d); err == nil {
return d
}
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, ""
return ""
}
// ---- changes ----------------------------------------------------------------