plugins: a community plugin's own page in magpie's window, shut in a sandboxed frame (P4)

A plugin's package.json may declare magpie.page {title, file, icon} and
magpie.permissions.reads. While the plugin is on, its page gets a tab in a
"Plugins" group after the built-in pages, drawn in an iframe sandboxed to
allow-scripts only (an opaque origin: no cookie, no storage, no parent).
Its files come from /_magpie/plugin/<token>/ (HMAC of the spec with a
per-process secret) under a CSP with connect-src 'none' and
frame-ancestors 'self'; a path that leaves the page's folder, a symlink
out, or an off plugin's token is refused. The window's postMessage bridge
answers only that frame (event.source checked) with theme and language,
the plugin's own options.get/set (throttled), and the reads it declared;
any other read is refused in the window and again by the server, and no
read carries a secret. /api refuses Origin: null and frame/iframe
fetch-dest requests (noFramedAPI), so the frame never reaches the GUI's
API even with the cookie. A page that throws or never says hello shows
the kernel's broken-page state with Try again. The Plugins page shows the
page and what it reads before the plugin is turned on.

Docs: gui-shell.md, plugin-runtime.md (P4 section), site docs en/zh/ja
with an example plugin; i18n zh, zh-TW, ja, de; fixture in
internal/gui/testdata/page-plugin.

Run (worktree at base 4df1ba0c6, -p 2, one package at a time):
- go test -count=1 -timeout 45m: internal/gui ok, internal/plugin ok,
  internal/pluginrt ok, plugins/... (budget groups middleware otel redact
  rotation search) ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
- Playwright (chromium + webkit, 5 languages, narrow widths): plugin-page 4/4,
  plugin-kernel 4/4, builtins 4/4, i18n-keys, gui-de, gui-ja, gui-zh-tw 3/3,
  plugin-middleware 24/24, plugin-own-icon 22/22, plugin-options 22/22,
  plugin-local 8/8, plugin-agent 22/22, click-scroll 22/22.

Broken by hand, each went red: CSP without connect-src; apiFramed always
false; the server's read check removed; the noFramedAPI wrap removed from
api.go (red through the real Handler); inside() letting every path
through; CORP same-origin re-added; in JS the client read check removed,
the ev.source check removed, and allow-same-origin added to the sandbox.
Without the Array.isArray guard on /api/plugin-pages, plugin-kernel,
builtins and plugin-middleware/own-icon/options went red (their mocks
answer a non-list) - that was found by the run, then fixed.

Real use: built magpie, `magpie web` on 127.0.0.1:3472 (gateway 3471) in a
sandbox HOME with the example plugin added. curl: the page file loads
with the CSP and no cookie, traversal and a bad token are 404, /api with
Origin: null or Sec-Fetch-Dest: iframe is 403 even with the cookie, an
undeclared read 403, a declared one 200. Chromium and WebKit at 1100 and
420: the page draws its declared read, the probe's fetch/absolute
fetch/top access/undeclared read are all refused, an <img> of /api is
refused, no page errors. Real use found that a
Cross-Origin-Resource-Policy: same-origin header blocked the frame's own
files (its origin is opaque); it is gone and a test guards it.

Not tried: the desktop (Wails) window. Market cards of plugins not yet
installed don't show a page's reads. The Playwright suite mirrors the
CSP in a mock route rather than the Go server (the Go tests and real use
cover the server).
This commit is contained in:
yetone
2026-10-15 22:36:59 +08:00
parent 6ac7032b4b
commit 64b0f3a201
28 changed files with 1744 additions and 15 deletions
+17
View File
@@ -307,6 +307,23 @@ posted and doesn't make the editor dirty.
[`plugin-options.test.cjs`](../../internal/gui/tests/plugin-options.test.cjs)
covers it.
### A plugin's own page
A community plugin that declares `magpie.page` gets a tab in a Plugins
group at the sidebar's foot (`pluginpages.js`, loaded after `plugins.js`),
listed from `GET /api/plugin-pages` and again whenever Plugins reloads its
list (`window.loadPluginPages`). The tab's title is the plugin's own and is
not translated; `renderCrumb` and the sub-nav's label read its plain
`<span>` where a built-in tab has `span[data-t]`. The frame is made the
first time the page opens and fills the view (`.view.plugin-page`,
`.plugin-frame`). The theme and language reach it on every change of
`data-theme`, `lang`, `class` or `style` on `:root`. A page gone off or
away loses its tab, and the window goes to Plugins if it was on it. The
security model, the bridge and the reads are in
[plugin-runtime.md](plugin-runtime.md#p4-community-plugins-at-every-point).
[`plugin-page.test.cjs`](../../internal/gui/tests/plugin-page.test.cjs)
covers it in both engines, every language and a narrow window.
### Shared UI rules
- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`.
+5 -3
View File
@@ -247,13 +247,15 @@ asks it.
## P4: community plugins at every point
P4 opens each gateway extension point to community plugins (OpenCode
plugins, npm packages in the plugin host), each behind the built-in plugin
that serves the point, so off still means off.
P4 opens each extension point, the gateway's and the window's, to
community plugins (OpenCode plugins, npm packages in the plugin host). A
gateway point stays behind the built-in plugin that serves it, so off
still means off; a page is its own plugin's to turn on and off.
| Point | What a community plugin gives | Served by | Reference |
| --- | --- | --- | --- |
| Tool | Its OpenCode `tool` hook's tools, offered to every agent by magpie's MCP server at `/mcp/magpie/tools`, each named `<plugin>_<tool>`, each call held to the calling key's limit and run in the host within 55s. Off, no tool is listed and a call says the plugin is off. | `plugins/tools` ("Plugin tools", Essential; `InUse` counts the plugins on that give tools, from `plugin-tools.json`), `gwtool.PluginTools` | [Plugin tools](plugin-tools.md) |
| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin/<token>/` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) |
## Source of truth and composing
+14 -1
View File
@@ -789,6 +789,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
mux := http.NewServeMux()
mux.Handle("/", devPage(revalidated(http.FileServer(http.FS(staticFS())))))
devRoutes(mux)
pluginPageRoutes(mux)
// boot.js hands the page the saved language and theme before it paints:
// they came only with the settings, so the tabs showed English first
mux.HandleFunc("GET /boot.js", func(rw http.ResponseWriter, r *http.Request) {
@@ -2183,7 +2184,19 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
})
agentModelsAPI(mux)
devListen(mux)
return held(mux)
return noFramedAPI(held(mux))
}
// noFramedAPI turns away a request for /api that no page of the window's
// own makes (apiFramed): a plugin's page in its frame among them.
func noFramedAPI(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if apiFramed(r) {
http.Error(rw, "magpie's API answers magpie's own window only", http.StatusForbidden)
return
}
h.ServeHTTP(rw, r)
})
}
// held has a page's reads share one build of the catalog, which every row
+5
View File
@@ -3083,6 +3083,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
/* a plugin's page that broke (kernel.js): what broke, and Try again */
.slot-error .row { gap: 14px; padding: 12px 14px; }
.slot-error .sub { margin-top: 2px; color: var(--fg-2); overflow-wrap: anywhere; }
/* a community plugin's page (pluginpages.js): its frame fills the page */
.view.plugin-page { padding: 0; }
.plugin-frame { flex: 1; display: block; width: 100%; min-height: 240px; border: 0; background: transparent; }
.view.plugin-page > .slot-error { margin: 0 12px; }
img.nav-ic { border-radius: 3px; object-fit: contain; }
.row.pref { min-height: 50px; padding: 8px 12px 8px 14px; gap: 14px; }
.row.pref .who { flex: 1 1 auto; }
.row.pref .sub { margin-top: 2px; color: var(--fg-2); }
+3 -2
View File
@@ -22264,7 +22264,7 @@ function navSubs() {
};
at.after(box);
}
box.setAttribute("aria-label", at.querySelector("span[data-t]")?.textContent || "");
box.setAttribute("aria-label", (at.querySelector("span[data-t]") || at.querySelector("span"))?.textContent || "");
for (const s of box.querySelectorAll(".nav-s")) s.remove();
items.forEach((b, i) => {
const [name, n] = b.textContent.trim().split(" · ");
@@ -22363,7 +22363,8 @@ function renderCrumb(items) {
let gl = b?.previousElementSibling;
while (gl && !gl.matches(".nav-gl")) gl = gl.previousElementSibling;
if (gl) parts.push(gl.textContent);
if (b) parts.push(b.querySelector("span[data-t]").textContent);
// a plugin's page's tab has its own title, not one translated here
if (b) parts.push((b.querySelector("span[data-t]") || b.querySelector("span"))?.textContent || "");
}
const on = items.find((b) => b.classList.contains("on"));
if (on) parts.push(on.textContent.trim().split(" · ")[0]);
+44
View File
@@ -792,6 +792,17 @@ const I18N = {
"Recent calls at a time": "每次显示的最近调用",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "页面显示多少条网关最近的调用,以及每次“显示其余”再多显示多少条",
"This page stopped working": "此页面已停止工作",
"Page": "页面",
"Adds a page of its own to the sidebar. It runs shut off from the rest of magpie and can read only what its row lists": "为侧边栏添加一个自己的页面。它与 magpie 的其余部分隔离运行,只能读取这一行列出的内容",
"your usage totals, by model": "你的用量合计(按模型)",
"your providers' names": "你的服务商名称",
"Adds a page to the sidebar, which can read {reads}": "为侧边栏添加一个页面,可读取{reads}",
"Adds a page to the sidebar, which reads nothing of magpie's": "为侧边栏添加一个页面,不读取 magpie 的任何内容",
"{name}'s page didn't answer": "{name} 的页面没有响应",
"A page's options are an object": "页面的选项须是一个对象",
"{name} doesn't ask to read {what}": "{name} 没有声明读取 {what}",
"No such call: {what}": "没有这个调用:{what}",
"The page hit an error": "页面出错了",
"Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "只显示给其他电脑当网关所需的内容:不显示 Agent 和资源库,也不显示本机 Agent 的设置",
"Now on: magpie web was started with --gateway": "当前开启:magpie web 以 --gateway 启动",
"Now on: no agents on this computer": "当前开启:本机没有 Agent",
@@ -4382,6 +4393,17 @@ const I18N = {
"Recent calls at a time": "每次顯示的最近呼叫",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "頁面顯示多少筆閘道最近的呼叫,以及每次「顯示其餘」再多顯示多少筆",
"This page stopped working": "此頁面已停止運作",
"Page": "頁面",
"Adds a page of its own to the sidebar. It runs shut off from the rest of magpie and can read only what its row lists": "為側邊欄加入一個自己的頁面。它與 magpie 的其餘部分隔離執行,只能讀取這一列列出的內容",
"your usage totals, by model": "你的用量合計(依模型)",
"your providers' names": "你的供應商名稱",
"Adds a page to the sidebar, which can read {reads}": "為側邊欄加入一個頁面,可讀取{reads}",
"Adds a page to the sidebar, which reads nothing of magpie's": "為側邊欄加入一個頁面,不讀取 magpie 的任何內容",
"{name}'s page didn't answer": "{name} 的頁面沒有回應",
"A page's options are an object": "頁面的選項須是一個物件",
"{name} doesn't ask to read {what}": "{name} 沒有宣告讀取 {what}",
"No such call: {what}": "沒有這個呼叫:{what}",
"The page hit an error": "頁面出錯了",
"Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "只顯示給其他電腦當閘道所需的內容:不顯示 Agent 和資源庫,也不顯示本機 Agent 的設定",
"Now on: magpie web was started with --gateway": "目前開啟:magpie web 以 --gateway 啟動",
"Now on: no agents on this computer": "目前開啟:本機沒有 Agent",
@@ -7944,6 +7966,17 @@ const I18N = {
"Recent calls at a time": "一度に表示する最近の呼び出し",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "ページに表示するゲートウェイの最近の呼び出しの数と、「さらに表示」ごとに追加する数",
"This page stopped working": "このページは動作を停止しました",
"Page": "ページ",
"Adds a page of its own to the sidebar. It runs shut off from the rest of magpie and can read only what its row lists": "サイドバーに独自のページを追加します。magpie のほかの部分から切り離されて動き、この行に示されたものだけを読み取れます",
"your usage totals, by model": "使用量の合計(モデル別)",
"your providers' names": "プロバイダの名前",
"Adds a page to the sidebar, which can read {reads}": "サイドバーにページを追加します。読み取れるもの:{reads}",
"Adds a page to the sidebar, which reads nothing of magpie's": "サイドバーにページを追加します。magpie のものは何も読み取りません",
"{name}'s page didn't answer": "{name} のページが応答しませんでした",
"A page's options are an object": "ページのオプションはオブジェクトです",
"{name} doesn't ask to read {what}": "{name} は {what} の読み取りを宣言していません",
"No such call: {what}": "そのような呼び出しはありません:{what}",
"The page hit an error": "ページでエラーが起きました",
"Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "他のコンピューターのゲートウェイに必要なものだけ:エージェント、ライブラリ、このコンピューターのエージェントの設定は表示しません",
"Now on: magpie web was started with --gateway": "現在オン:magpie web が --gateway で起動されています",
"Now on: no agents on this computer": "現在オン:このコンピューターにエージェントがありません",
@@ -11520,6 +11553,17 @@ const I18N = {
"Recent calls at a time": "Letzte Aufrufe auf einmal",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "Wie viele der letzten Aufrufe des Gateways die Seite zeigt und wie viele jedes „weitere anzeigen“ hinzufügt",
"This page stopped working": "Diese Seite funktioniert nicht mehr",
"Page": "Seite",
"Adds a page of its own to the sidebar. It runs shut off from the rest of magpie and can read only what its row lists": "Fügt der Seitenleiste eine eigene Seite hinzu. Sie läuft abgeschottet vom Rest von magpie und kann nur lesen, was diese Zeile nennt",
"your usage totals, by model": "deine Nutzungssummen, nach Modell",
"your providers' names": "die Namen deiner Anbieter",
"Adds a page to the sidebar, which can read {reads}": "Fügt der Seitenleiste eine Seite hinzu, die {reads} lesen kann",
"Adds a page to the sidebar, which reads nothing of magpie's": "Fügt der Seitenleiste eine Seite hinzu, die nichts von magpie liest",
"{name}'s page didn't answer": "Die Seite von {name} hat nicht geantwortet",
"A page's options are an object": "Die Optionen einer Seite sind ein Objekt",
"{name} doesn't ask to read {what}": "{name} fragt nicht danach, {what} zu lesen",
"No such call: {what}": "Kein solcher Aufruf: {what}",
"The page hit an error": "Die Seite hat einen Fehler",
"Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "Nur, was ein Gateway für andere Computer braucht: keine Agenten oder Bibliothek, keine Einstellungen der Agenten auf diesem Computer",
"Now on: magpie web was started with --gateway": "Jetzt an: magpie web wurde mit --gateway gestartet",
"Now on: no agents on this computer": "Jetzt an: keine Agenten auf diesem Computer",
+1
View File
@@ -455,6 +455,7 @@
<script src="purposes.js"></script>
<script src="app.js"></script>
<script src="plugins.js"></script>
<script src="pluginpages.js"></script>
<script src="context.js"></script>
<script src="plugins/usage/page.js"></script>
<script src="start.js"></script>
+7
View File
@@ -25,6 +25,13 @@
// ctx.config has it
onConfig(fn) { p.onConfig.push(fn); },
onDispose(fn) { p.disposers.push(fn); },
// a page of the plugin's that broke after its hook returned (a
// frame's own error, one that never answered): it shows what broke,
// with a Try again, as a hook that throws does
broke(key, err) {
const page = pages.get(key);
if (page && page.plugin === p && !page.broken) fail(page, "open", [], err);
},
slots: { add: (slot, part) => add(p, slot, part) },
ui,
};
+200
View File
@@ -0,0 +1,200 @@
// A community plugin's own page in the window (docs/subsystems/
// plugin-runtime.md, P4): package.json's magpie.page, in a tab of the
// sidebar's Plugins group, after the built-in pages. The page runs in a
// frame sandboxed to scripts alone, in an origin of its own: it has no
// way to the window, to magpie's API (apiFramed) or to the network (its
// policy, pluginpage.go). What it asks of the window comes by message,
// from that frame only, and the window answers only what the page may:
// the theme, its own options, and the reads its package declared
// (magpie.permissions), which /api/plugin-pages/read checks again.
// A page that throws, or never says hello, shows the kernel's "This
// page stopped working" with its Try again.
(() => {
if (mode !== "window") return;
// how long a page has to say hello before it is taken as broken
const HELLO_MS = 10e3;
const pages = new Map(); // key → { entry, frame, hello, timer }
let ctx = null;
magpie.plugin("plugin-pages", (c) => { ctx = c; });
const TOKENS = ["bg", "card", "fg", "fg-2", "muted", "faint", "line", "accent", "accent-soft", "accent-fg", "green", "red", "amber", "font", "code"];
function theme() {
const css = getComputedStyle(document.documentElement);
const tokens = {};
for (const k of TOKENS) tokens[k] = css.getPropertyValue("--" + k).trim();
const dark = document.documentElement.dataset.theme === "dark"
|| (document.documentElement.dataset.theme !== "light" && matchMedia("(prefers-color-scheme: dark)").matches);
return { dark, lang: locale, tokens };
}
function post(win, msg) { win?.postMessage({ magpie: 1, ...msg }, "*"); }
// the theme or the language changed: every page open is told
function pushTheme() {
const data = theme();
for (const p of pages.values()) if (p.hello) post(p.frame?.contentWindow, { event: "theme", data });
}
new MutationObserver(pushTheme).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "lang", "class", "style"] });
matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", pushTheme);
function broke(key, why) { ctx?.broke(key, new Error(why)); }
// the page's frame, made the first time the page is opened (and again
// after Try again): a plugin's page costs nothing until it is looked at
function open(key) {
const p = pages.get(key);
if (!p) return undefined;
if (p.frame?.isConnected) return p.ready;
const main = $("#view-" + key);
const f = document.createElement("iframe");
f.className = "plugin-frame";
// scripts, and nothing else: no same origin (no cookie, no storage of
// the window's, no reach into it), no forms, popups or top navigation
f.setAttribute("sandbox", "allow-scripts");
f.setAttribute("referrerpolicy", "no-referrer");
f.setAttribute("allow", "");
f.title = p.entry.title;
f.src = p.entry.url;
p.frame = f;
p.hello = false;
p.ready = new Promise((resolve, reject) => {
p.said = resolve;
clearTimeout(p.timer);
p.timer = setTimeout(() => { if (!p.hello) reject(new Error(t("{name}'s page didn't answer", { name: p.entry.title }))); }, HELLO_MS);
});
main.replaceChildren(f);
return p.ready;
}
async function answer(p, m) {
const e = p.entry;
switch (m.method) {
case "hello":
p.hello = true;
clearTimeout(p.timer);
p.said?.();
return theme();
case "theme":
return theme();
case "options.get":
return api("plugin-pages/options", { spec: e.spec });
case "options.set": {
const o = m.params?.options;
if (!o || typeof o !== "object" || Array.isArray(o)) throw new Error(t("A page's options are an object"));
return api("plugin-pages/options", { spec: e.spec, options: o });
}
case "read": {
const name = String(m.params?.name || "");
// what its package didn't declare is refused here, and again by
// the server
if (!e.reads.includes(name)) throw new Error(t("{name} doesn't ask to read {what}", { name: e.title, what: name }));
return api("plugin-pages/read", { spec: e.spec, read: name, params: m.params?.params || {} });
}
}
throw new Error(t("No such call: {what}", { what: String(m.method) }));
}
addEventListener("message", async (ev) => {
// only a page's own frame is listened to: another window's message,
// or one that names a page, is nothing
let key = "", p = null;
for (const [k, x] of pages) if (x.frame && ev.source === x.frame.contentWindow) { key = k; p = x; break; }
if (!p) return;
const m = ev.data;
if (!m || typeof m !== "object" || m.magpie !== 1 || typeof m.method !== "string") return;
if (m.method === "error") {
broke(key, String(m.params?.message || t("The page hit an error")));
return;
}
const src = ev.source;
try {
post(src, { id: m.id, result: await answer(p, m) });
} catch (err) {
post(src, { id: m.id, error: String(err?.message || err) });
}
});
// the sidebar's tab for each page, in a Plugins group of its own after
// the built-in pages
function tab(e) {
const b = document.createElement("button");
b.dataset.view = e.key;
b.dataset.pluginPage = "";
if (e.icon) {
const img = document.createElement("img");
img.className = "nav-ic";
img.src = e.icon;
img.alt = "";
img.width = img.height = 16;
b.append(img);
} else {
const s = svg(PUZZLE, 16, 1.5);
s.classList.add("nav-ic");
s.setAttribute("aria-hidden", "true");
b.append(s);
}
b.append(el("span", "", e.title));
b.onclick = () => { show(e.key); b.blur(); };
return b;
}
async function load() {
let list;
try { list = await api("plugin-pages"); } catch { return; }
// an answer that isn't a list is not known: the tabs drawn stay
if (!Array.isArray(list)) return;
const nav = $("#nav");
const keys = new Set(list.map((e) => e.key));
// a page whose plugin went off, or away: its tab goes, and the window
// leaves it if it was open
for (const b of nav.querySelectorAll("button[data-plugin-page]")) if (!keys.has(b.dataset.view)) b.remove();
for (const [k, p] of pages) {
if (keys.has(k)) continue;
p.frame?.remove();
p.frame = null;
p.gone = true;
if (view === k) show("plugins");
}
let head = nav.querySelector(".nav-gl[data-plugin-pages]");
if (!list.length) { head?.remove(); return; }
if (!head) {
head = el("span", "nav-gl", t("Plugins"));
head.dataset.pluginPages = "";
head.dataset.en = "Plugins";
head.setAttribute("data-t", "");
nav.append(head);
}
let at = head;
for (const e of list) {
let p = pages.get(e.key);
if (!p) {
p = { entry: e };
pages.set(e.key, p);
ctx.slots.add("page", { key: e.key, title: e.title, html: "", mount(main) { main.classList.add("plugin-page"); p.frame = null; }, open: () => open(e.key) });
} else if (p.entry.url !== e.url || p.gone) {
p.frame?.remove();
p.frame = null;
}
p.gone = false;
p.entry = e;
const part = magpie.page(e.key);
if (part) part.title = e.title;
let b = nav.querySelector(`button[data-plugin-page][data-view="${e.key}"]`);
if (!b) b = tab(e);
b.classList.toggle("on", view === e.key);
at.after(b);
at = b;
}
// a reload of a plugin's page, or the one the window was left on,
// comes back to it once its tab is there
if (view === "agents" && !opened) {
opened = true;
let want = params.get("view") || "";
if (!want) { try { want = localStorage.getItem("magpie.lastView") || ""; } catch { /* none kept */ } }
if (pages.has(want)) show(want);
}
}
let opened = false;
window.loadPluginPages = load;
load();
})();
+25 -5
View File
@@ -39,6 +39,7 @@
const PLUG = "M6 2v3 M10 2v3 M4.5 5h7v2.5a3.5 3.5 0 0 1-7 0z M8 11v3";
const PIPE = "M1.5 8h3 M11.5 8h3 M4.5 4.5h7v7h-7z";
const TERM = "M2 3.5h12v9H2z M4.5 6.5l2 1.5-2 1.5 M8 9.5h3";
const PAGE = "M2 3.5h12v9H2z M2 6h12 M4 4.75h.01";
const FOLDER = "M14.7 12.7a1.3 1.3 0 0 1-1.3 1.3H2.6a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.6 2h3.3l1.3 2h6.2a1.3 1.3 0 0 1 1.3 1.3z";
// a folder's path is its name whole, as plugin.Name: C:\Users\me@corp\…
@@ -112,11 +113,13 @@
// subscription and serves its models; middleware ("mw") runs in the
// gateway on every agent's requests and replies, whatever serves them;
// an agent ("ag") is one magpie has no wiring of its own for, which it
// then connects as it does its own
// then connects as it does its own; a page ("pg") is a page of its own
// in the window's sidebar (pluginpages.js)
const KINDS = {
pv: [PLUG, "Provider", "Signs in to a subscription and serves its models"],
mw: [PIPE, "Middleware", "Runs in magpie's gateway on the requests your agents send and on the replies"],
ag: [TERM, "Agent", "Adds an agent magpie has no setup of its own for: pick its model on the Agents page and it goes through magpie"],
pg: [PAGE, "Page", "Adds a page of its own to the sidebar. It runs shut off from the rest of magpie and can read only what its row lists"],
};
const kindOf = (l) => l.kind === "middleware" ? "mw" : l.kind === "agent" ? "ag" : "pv";
function kindChip(kind) {
@@ -129,7 +132,7 @@
function logo(ic, big, kind) {
const box = el("span", "pm-logo" + (big ? " big" : ""));
if (ic) box.append(icon(ic));
else box.append(glyph(kind === "mw" ? PIPE : kind === "ag" ? TERM : PUZZLE, big ? 22 : 17, 1.4));
else box.append(glyph(kind === "mw" ? PIPE : kind === "ag" ? TERM : kind === "pg" ? PAGE : PUZZLE, big ? 22 : 17, 1.4));
return box;
}
@@ -145,6 +148,8 @@
try {
mine = await api("plugins");
failed = "";
// a plugin turned on or off brings its page's tab, or takes it
window.loadPluginPages?.();
} catch (e) {
failed = e.message;
}
@@ -1017,6 +1022,7 @@
if (ag || e.isAgent) nm.append(kindChip("ag"));
// a plugin of tools alone signs in to nothing: no Provider chip
const toolsOnly = !!e.tools?.length && !e.providers?.length;
if (e.page) nm.append(kindChip("pg"));
if (e.providers?.length || !(e.middlewareOnly || e.inMagpieOnly || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv"));
who.append(nm);
const subs = subsOf(pkg);
@@ -1048,8 +1054,8 @@
else if (!x.signedIn && subs.some((y) => y.signedIn)) s.title = t("{name} is a subscription of its own; {other} works without it", { name: x.name, other: subs.find((y) => y.signedIn).name });
sub.append(s);
}
} else if ((mw || ag || toolsOnly) && !e.providers.length) {
// only middleware, an agent or tools: its own line says what it does
} else if ((mw || ag || toolsOnly || e.page && e.inMagpieOnly) && !e.providers.length) {
// only middleware, an agent, tools or a page: its own line says what it does
} else if (clashes.length && !e.providers.length) {
// its own line below says whose it is
} else if (e.providers.length) sub.textContent = t("Signs in to {names}", { names: e.providers.join(t(", ")) });
@@ -1063,10 +1069,12 @@
if (mw && !e.off && !ask) who.append(mwLine(mw));
if (ag && !e.off && !ask) who.append(agentLine(ag));
if (e.tools?.length && !e.off && !ask) who.append(toolsLine(e.tools));
// off too: what its page may read is said before it is turned on
if (e.page && !ask) who.append(pageLine(e.page));
if (mw && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e));
// the plugin's own picture (package.json's magpie.icon) before its
// first provider's, which a plugin of several gives each its own (#1775)
r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : ""), who);
r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : e.inMagpieOnly && e.page && !e.isAgent && !e.isMiddleware ? "pg" : ""), who);
const val = el("div", "val");
const b = busy.get(pkg) || busy.get(e.spec);
// npm's newer version, or a git one's repository at a newer commit
@@ -1241,6 +1249,18 @@
return d;
}
// what a plugin's page may read of magpie's: what its package.json's
// magpie.permissions declares, each a read with no secret in it
const READS = { "usage:summary": "your usage totals, by model", "providers:list": "your providers' names" };
function pageLine(p) {
const d = el("div", "sub pm-mw pm-page");
const reads = (p.reads || []).map((r) => t(READS[r] || r));
d.textContent = d.title = reads.length
? t("Adds a page to the sidebar, which can read {reads}", { reads: reads.join(t(", ")) })
: t("Adds a page to the sidebar, which reads nothing of magpie's");
return d;
}
function mwLine(m) {
const d = el("div", "sub pm-mw");
if (m.error) {
+71
View File
@@ -0,0 +1,71 @@
// The page's side of a plugin page's messages to magpie's window
// (docs/subsystems/plugin-runtime.md, P4). A plugin's page loads it with
// <script src="_magpie/bridge.js"></script>; it is served beside every
// page's own files.
//
// await magpie.ready the window's theme, once it has answered
// magpie.theme { dark, lang, tokens: { bg, fg, … } }
// magpie.onTheme(fn) fn(theme) on each change of it
// await magpie.options.get() the plugin's own options (plugins.json)
// await magpie.options.set(o) sets them, and answers with them
// await magpie.read(name, p) a read its package.json's
// magpie.permissions declares
//
// The page can't reach the network or magpie's API itself: everything goes
// through the window, which answers only what the package declared. An
// error the page doesn't catch shows the window's "This page stopped
// working" in its place.
(() => {
const waiting = new Map();
let next = 0;
const themed = [];
function call(method, params) {
const id = ++next;
return new Promise((resolve, reject) => {
waiting.set(id, { resolve, reject });
parent.postMessage({ magpie: 1, id, method, params }, "*");
});
}
function paint(theme) {
const root = document.documentElement;
root.dataset.theme = theme.dark ? "dark" : "light";
// the frame's canvas matches the window's, not a white sheet in dark
root.style.colorScheme = theme.dark ? "dark" : "light";
root.lang = theme.lang || "en";
for (const [k, v] of Object.entries(theme.tokens || {})) root.style.setProperty("--magpie-" + k, v);
}
addEventListener("message", (e) => {
if (e.source !== parent) return;
const m = e.data;
if (!m || m.magpie !== 1) return;
if (m.event === "theme") {
api.theme = m.data;
paint(m.data);
for (const fn of themed) { try { fn(m.data); } catch (err) { report(err); } }
return;
}
const w = waiting.get(m.id);
if (!w) return;
waiting.delete(m.id);
if (m.error) w.reject(new Error(m.error)); else w.resolve(m.result);
});
function report(err) {
parent.postMessage({ magpie: 1, method: "error", params: { message: String(err?.message || err) } }, "*");
}
// a script's error reaches a sandboxed page only as "Script error." (its
// files are another origin's to it); the window then says "The page hit
// an error" in the reader's language, and the console has the rest
addEventListener("error", (e) => report(e.error || (e.message === "Script error." ? "" : e.message)));
addEventListener("unhandledrejection", (e) => report(e.reason));
const api = {
theme: null,
onTheme(fn) { themed.push(fn); },
options: {
get: () => call("options.get"),
set: (options) => call("options.set", { options }),
},
read: (name, params) => call("read", { name, params }),
};
api.ready = call("hello").then((theme) => { api.theme = theme; paint(theme); return theme; });
window.magpie = api;
})();
+391
View File
@@ -0,0 +1,391 @@
package gui
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// A community plugin's own page in magpie's window (P4 of
// docs/subsystems/plugin-runtime.md): package.json's magpie.page, shown in
// a sandboxed frame (pluginpages.js). Its files are served under
// pluginPagePrefix and a token only this run of magpie hands out, with a
// policy that lets the page load nothing but its own files and reach
// nothing over the network; it has no way to magpie's /api (apiFramed),
// and what it may read of magpie's it asks the window for, which asks
// /api/plugin-pages/read for the reads its package declared.
// pluginPagePrefix is where a plugin's page's files are served:
// pluginPagePrefix + token + "/" + the file's path in the page's folder.
const pluginPagePrefix = "/_magpie/plugin/"
// pluginBridgePath is the window's side of the page's messages, served
// beside every page's files: a page loads it as
// <script src="_magpie/bridge.js">.
const pluginBridgePath = "_magpie/bridge.js"
//go:embed pagebridge.js
var pageBridgeJS []byte
// pageSecret keys this run's tokens: a token from an earlier run, or one
// made up, serves nothing.
var pageSecret = func() []byte {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return b
}()
func pageToken(spec string) string {
m := hmac.New(sha256.New, pageSecret)
m.Write([]byte(spec))
return hex.EncodeToString(m.Sum(nil)[:16])
}
// pluginPage is a plugin's page, of a plugin that is on.
type pluginPage struct {
Spec string `json:"spec"`
Name string `json:"name"` // its package's
Key string `json:"key"` // the window's page key
Title string `json:"title"` // the page's, or the package's short name
URL string `json:"url"` // the page, under pluginPagePrefix
Icon string `json:"icon,omitempty"`
Reads []string `json:"reads"` // what it may read, of plugin.PageReads
token string
spec *plugin.PageSpec
}
// pageKeyChars are what a window page's key can't have
var pageKeyChars = strings.NewReplacer("@", "", "/", "-", ".", "-", "_", "-", " ", "-")
// pluginPages are the pages of the plugins that are on, in plugins.json's
// order. A plugin switched off has none: its files aren't served.
func pluginPages() []pluginPage {
var out []pluginPage
seen := map[string]bool{}
for _, e := range plugin.Load().Plugins {
if e.Off {
continue
}
spec, _ := plugin.WindowPage(plugin.Target(e.Spec))
if spec == nil {
continue
}
name := plugin.PackageName(e.Spec)
key := "plugin-" + strings.Trim(pageKeyChars.Replace(strings.ToLower(plugin.ShortName(name))), "-")
key = strings.Map(func(r rune) rune {
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' {
return r
}
return -1
}, key)
for k, n := key, 2; seen[key]; n++ {
key = fmt.Sprintf("%s-%d", k, n)
}
seen[key] = true
tok := pageToken(e.Spec)
rel, _ := filepath.Rel(spec.Dir, spec.File)
p := pluginPage{Spec: e.Spec, Name: name, Key: key, Title: spec.Title, Reads: spec.Reads, token: tok, spec: spec,
URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel)}
if p.Title == "" {
p.Title = plugin.ShortName(name)
}
if p.Reads == nil {
p.Reads = []string{}
}
if spec.Icon != "" {
p.Icon = pluginPagePrefix + tok + "/" + spec.Icon
}
out = append(out, p)
}
return out
}
func pageOf(spec string) (pluginPage, bool) {
for _, p := range pluginPages() {
if p.Spec == spec {
return p, true
}
}
return pluginPage{}, false
}
// pagePolicy is what a plugin's page may load and reach: its own files,
// inline styles, data: pictures, and nothing over the network. sandbox
// keeps a page opened by itself (not in the window's frame) as shut in as
// the frame keeps it.
func pagePolicy(r *http.Request, tok string) string {
own := "'self'"
if r.Host != "" {
// the page's own folder: not the window's files, nor /api
own = r.Host + pluginPagePrefix + tok + "/"
}
return strings.Join([]string{
"sandbox allow-scripts",
"default-src 'none'",
"script-src " + own,
"style-src " + own + " 'unsafe-inline'",
"img-src " + own + " data:",
"font-src " + own,
"media-src " + own,
"connect-src 'none'",
"frame-src 'none'",
"worker-src 'none'",
"object-src 'none'",
"form-action 'none'",
"base-uri 'none'",
"frame-ancestors 'self'",
}, "; ")
}
// servePluginPage serves a file of a plugin's page, by its token.
func servePluginPage(rw http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
return
}
rest := strings.TrimPrefix(r.URL.Path, pluginPagePrefix)
tok, rel, ok := strings.Cut(rest, "/")
if !ok || len(tok) != 32 {
http.NotFound(rw, r)
return
}
var page *pluginPage
for _, p := range pluginPages() {
if hmac.Equal([]byte(p.token), []byte(tok)) {
page = &p
break
}
}
if page == nil {
http.NotFound(rw, r)
return
}
h := rw.Header()
h.Set("Content-Security-Policy", pagePolicy(r, tok))
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
// no Cross-Origin-Resource-Policy: to the page's sandboxed frame, an
// origin of its own, its own files are another origin's, and
// same-origin (or same-site) would block every one of them
h.Set("Cache-Control", "no-cache")
if rel == pluginBridgePath {
h.Set("Content-Type", "text/javascript; charset=utf-8")
http.ServeContent(rw, r, "bridge.js", time.Time{}, strings.NewReader(string(pageBridgeJS)))
return
}
file, ok := page.spec.PageFile(rel)
if !ok {
http.NotFound(rw, r)
return
}
// ServeContent, not ServeFile: ServeFile sends .../index.html to ./,
// which a page's own links needn't follow.
f, err := os.Open(file)
if err != nil {
http.NotFound(rw, r)
return
}
defer f.Close()
st, err := f.Stat()
if err != nil || st.IsDir() {
http.NotFound(rw, r)
return
}
http.ServeContent(rw, r, filepath.Base(file), st.ModTime(), f)
}
// apiFramed is whether r is a request for /api that no page of the window's
// own makes: one from a sandboxed frame (Origin: null, which a plugin's
// page's fetch would send were its policy not to stop it), one that loads
// /api into a frame, or one another site's page sends. The desktop
// window's /api has no key, so this is what keeps a plugin's page out.
func apiFramed(r *http.Request) bool {
if !strings.HasPrefix(r.URL.Path, "/api/") {
return false
}
if r.Header.Get("Origin") == "null" {
return true
}
switch r.Header.Get("Sec-Fetch-Dest") {
case "iframe", "frame", "embed", "object":
return true
}
return r.Header.Get("Sec-Fetch-Site") == "cross-site" && r.Header.Get("Sec-Fetch-Dest") != "document"
}
func pluginPageRoutes(mux *http.ServeMux) {
mux.HandleFunc(pluginPagePrefix, servePluginPage)
mux.HandleFunc("GET /api/plugin-pages", func(rw http.ResponseWriter, r *http.Request) {
out := pluginPages()
if out == nil {
out = []pluginPage{}
}
writeJSON(rw, out)
})
// what a page asked the window to read: only what its package
// declared, and never a secret
mux.HandleFunc("POST /api/plugin-pages/read", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
Spec string `json:"spec"`
Read string `json:"read"`
Params map[string]any `json:"params"`
}
if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 64<<10)).Decode(&in); err != nil {
fail(rw, err)
return
}
p, ok := pageOf(in.Spec)
if !ok {
fail(rw, errors.New("no plugin page "+in.Spec))
return
}
if !slices.Contains(p.Reads, in.Read) {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusForbidden)
_ = json.NewEncoder(rw).Encode(map[string]string{"error": fmt.Sprintf("%s's package doesn't ask to read %q", p.Name, in.Read)})
return
}
v, err := pageRead(in.Read, in.Params)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, v)
})
// a page's own options, as plugins.json keeps them: no other plugin's
mux.HandleFunc("POST /api/plugin-pages/options", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
Spec string `json:"spec"`
Options json.RawMessage `json:"options"`
}
if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 64<<10)).Decode(&in); err != nil {
fail(rw, err)
return
}
if _, ok := pageOf(in.Spec); !ok {
fail(rw, errors.New("no plugin page "+in.Spec))
return
}
if len(in.Options) > 0 && string(in.Options) != "null" {
var opts map[string]any
if err := json.Unmarshal(in.Options, &opts); err != nil {
fail(rw, errors.New("a page's options are an object"))
return
}
// a page that sets them over and over would start the
// host, every plugin's, again each time
if !pageSetAllowed(in.Spec, time.Now()) {
http.Error(rw, "a page sets its options once a second at most", http.StatusTooManyRequests)
return
}
if err := plugin.SetPageOptions(in.Spec, opts); err != nil {
fail(rw, err)
return
}
}
for _, e := range plugin.Load().Plugins {
if e.Spec == in.Spec {
opts := e.Options
if opts == nil {
opts = map[string]any{}
}
writeJSON(rw, opts)
return
}
}
writeJSON(rw, map[string]any{})
})
}
var pageSets = struct {
sync.Mutex
at map[string]time.Time
}{at: map[string]time.Time{}}
// pageSetAllowed is whether spec's page may set its options now: a second
// after it last did.
func pageSetAllowed(spec string, now time.Time) bool {
pageSets.Lock()
defer pageSets.Unlock()
if last, ok := pageSets.at[spec]; ok && now.Sub(last) < time.Second {
return false
}
pageSets.at[spec] = now
return true
}
// pageRead is one of plugin.PageReads.
func pageRead(read string, params map[string]any) (any, error) {
switch read {
case "providers:list":
// a name and an id each: no key, no account, no address
type prov struct {
ID string `json:"id"`
Name string `json:"name"`
}
out := []prov{}
for _, p := range provider.All() {
out = append(out, prov{ID: p.ID, Name: p.Name})
}
return out, nil
case "usage:summary":
period := usage.Today
if s, _ := params["period"].(string); s != "" {
period = usage.Period(s)
}
if !slices.Contains([]usage.Period{usage.Today, usage.Week, usage.Month}, period) {
return nil, fmt.Errorf("no period %q: today, 7d or 30d", period)
}
s := usage.Summarize(period)
type model struct {
Model string `json:"model"`
Calls int `json:"calls"`
Input int `json:"input"`
Output int `json:"output"`
Cost float64 `json:"cost"`
}
// the totals and each model's, never a key's, an account's or a
// session's
out := struct {
Period string `json:"period"`
Since time.Time `json:"since"`
Calls int `json:"calls"`
Errors int `json:"errors"`
Input int `json:"input"`
Output int `json:"output"`
Cache int `json:"cacheRead"`
Cost float64 `json:"cost"`
Models []model `json:"models"`
}{Period: string(period), Since: s.Since, Calls: s.Calls, Errors: s.Errors, Input: s.Input, Output: s.Output, Cache: s.CacheRead, Cost: s.Cost, Models: []model{}}
for i, g := range s.Models {
if i == 20 {
break
}
m := g.Model
if m == "" {
m = g.ID
}
out.Models = append(out.Models, model{Model: m, Calls: g.Calls, Input: g.Input, Output: g.Output, Cost: g.Cost})
}
return out, nil
}
return nil, fmt.Errorf("no read %q", read)
}
+253
View File
@@ -0,0 +1,253 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// pagePlugins writes plugins.json with the example page plugin
// (testdata/page-plugin), on, and a copy of it switched off; it answers
// their specs.
func pagePlugins(t *testing.T) (on, off string) {
t.Helper()
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))
t.Setenv("MAGPIE_BUN", "")
t.Setenv("PATH", "")
copyDir := func(to string) {
t.Helper()
err := filepath.WalkDir("testdata/page-plugin", func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel("testdata/page-plugin", p)
if d.IsDir() {
return os.MkdirAll(filepath.Join(to, rel), 0o755)
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(to, rel), b, 0o644)
})
if err != nil {
t.Fatal(err)
}
}
on, off = filepath.Join(h, "src", "glance"), filepath.Join(h, "src", "glance-off")
copyDir(on)
copyDir(off)
// a file of the plugin's own, but out of its page's folder, and one out
// of the plugin, which a link in the page's folder points to
if err := os.WriteFile(filepath.Join(h, "secret.txt"), []byte("SECRET"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(h, "secret.txt"), filepath.Join(on, "page", "link.txt")); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(settings.Dir(), 0o755); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(map[string]any{"plugins": []map[string]any{{"spec": on}, {"spec": off, "off": true}}})
if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644); err != nil {
t.Fatal(err)
}
return on, off
}
func pageMux() http.Handler {
mux := http.NewServeMux()
pluginPageRoutes(mux)
mux.HandleFunc("GET /api/state", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, map[string]string{"secret": "the window's"})
})
return noFramedAPI(mux)
}
func do(h http.Handler, r *http.Request) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// A plugin's page's files are served by a token of this run, with a policy
// that keeps it to its own folder and off the network; nothing outside its
// page's folder is served, nor anything of a plugin switched off, nor
// anything by a token made up.
func TestPluginPageServedShutIn(t *testing.T) {
on, off := pagePlugins(t)
h := pageMux()
var pages []pluginPage
w := do(h, httptest.NewRequest("GET", "/api/plugin-pages", nil))
if err := json.Unmarshal(w.Body.Bytes(), &pages); err != nil || len(pages) != 1 {
t.Fatalf("pages: %s %v", w.Body, err)
}
p := pages[0]
if p.Spec != on || p.Key != "plugin-magpie-usage-glance" || p.Title != "Usage glance" || len(p.Reads) != 1 || p.Reads[0] != "usage:summary" {
t.Fatalf("page %+v", p)
}
tok := strings.Split(strings.TrimPrefix(p.URL, pluginPagePrefix), "/")[0]
r := httptest.NewRequest("GET", p.URL, nil)
r.Host = "127.0.0.1:3437"
w = do(h, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Usage glance") {
t.Fatalf("the page: %d %s", w.Code, w.Body)
}
csp := w.Header().Get("Content-Security-Policy")
for _, want := range []string{"sandbox allow-scripts", "default-src 'none'", "connect-src 'none'", "script-src 127.0.0.1:3437" + pluginPagePrefix + tok + "/;", "form-action 'none'", "frame-src 'none'"} {
if !strings.Contains(csp, want) {
t.Errorf("policy %q has no %q", csp, want)
}
}
if strings.Contains(csp, "allow-same-origin") || strings.Contains(csp, "'unsafe-eval'") {
t.Errorf("policy %q lets the page out", csp)
}
// the sandboxed frame is an origin of its own: a resource policy of
// same-origin or same-site blocks the page's own scripts and styles
if c := w.Header().Get("Cross-Origin-Resource-Policy"); c != "" && c != "cross-origin" {
t.Errorf("Cross-Origin-Resource-Policy %q keeps the page from its own files", c)
}
if w.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Error("no nosniff")
}
if w := do(h, httptest.NewRequest("GET", pluginPagePrefix+tok+"/"+pluginBridgePath, nil)); w.Code != 200 || !strings.Contains(w.Body.String(), "postMessage") {
t.Errorf("the bridge: %d", w.Code)
}
// out of the page's folder, through a link, by another token
for _, path := range []string{
pluginPagePrefix + tok + "/../package.json",
pluginPagePrefix + tok + "/link.txt",
pluginPagePrefix + pageToken(off) + "/index.html",
pluginPagePrefix + strings.Repeat("0", 32) + "/index.html",
pluginPagePrefix + tok,
} {
r := httptest.NewRequest("GET", "/", nil)
r.URL.Path = path
w := httptest.NewRecorder()
servePluginPage(w, r)
if w.Code == 200 || strings.Contains(w.Body.String(), "SECRET") || strings.Contains(w.Body.String(), `"name"`) {
t.Errorf("%s: %d %s", path, w.Code, w.Body)
}
}
}
// What a page didn't declare it reads is refused by the server too, not
// only by the window; a page sets its own options and no other plugin's.
func TestPluginPageReadsWhatItDeclared(t *testing.T) {
on, off := pagePlugins(t)
h := pageMux()
post := func(path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
return do(h, r)
}
spec, _ := json.Marshal(on)
if w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"providers:list"}`); w.Code != http.StatusForbidden {
t.Errorf("an undeclared read: %d %s", w.Code, w.Body)
}
w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"usage:summary","params":{"period":"today"}}`)
var sum map[string]any
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &sum) != nil || sum["period"] != "today" {
t.Errorf("a declared read: %d %s", w.Code, w.Body)
}
for _, k := range []string{"callerKeys", "accounts", "sessions", "providerKeys"} {
if _, ok := sum[k]; ok {
t.Errorf("usage:summary gave the page %s", k)
}
}
offSpec, _ := json.Marshal(off)
if w := post("/api/plugin-pages/read", `{"spec":`+string(offSpec)+`,"read":"usage:summary"}`); w.Code == 200 {
t.Errorf("a plugin switched off read: %d", w.Code)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`,"options":{"hideCost":true}}`); w.Code != 200 || !strings.Contains(w.Body.String(), `"hideCost":true`) {
t.Fatalf("options set: %d %s", w.Code, w.Body)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`,"options":{"hideCost":false}}`); w.Code != http.StatusTooManyRequests {
t.Errorf("a second set within the second: %d", w.Code)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`}`); !strings.Contains(w.Body.String(), `"hideCost":true`) {
t.Errorf("options get: %s", w.Body)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(offSpec)+`,"options":{"x":1}}`); w.Code == 200 {
t.Errorf("another plugin's options set: %d", w.Code)
}
if !pageSetAllowed("x", time.Now()) || pageSetAllowed("x", time.Now()) || !pageSetAllowed("x", time.Now().Add(2*time.Second)) {
t.Error("pageSetAllowed")
}
}
// The desktop window's /api has no key: what keeps a plugin's page off it
// is that every way a sandboxed frame can ask is turned away, a fetch
// (Origin: null), a frame of /api, another site's page; the window's own
// requests, and a link opened from elsewhere, go on.
func TestPluginPageNoAPI(t *testing.T) {
pagePlugins(t)
h := pageMux()
ask := func(set map[string]string) int {
r := httptest.NewRequest("GET", "/api/state", nil)
for k, v := range set {
r.Header.Set(k, v)
}
return do(h, r).Code
}
for _, c := range []map[string]string{
{"Origin": "null"},
{"Origin": "null", "Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Dest": "empty"},
{"Sec-Fetch-Dest": "iframe", "Sec-Fetch-Site": "same-origin"},
{"Sec-Fetch-Dest": "image", "Sec-Fetch-Site": "cross-site"},
{"Sec-Fetch-Dest": "script", "Sec-Fetch-Site": "cross-site"},
} {
if code := ask(c); code != http.StatusForbidden {
t.Errorf("%v: %d", c, code)
}
}
// the window's own handler, not only this test's
r := httptest.NewRequest("GET", "/api/plugin-pages", nil)
r.Header.Set("Origin", "null")
if w := do(Handler(nil, nil), r); w.Code != http.StatusForbidden {
t.Errorf("the window's /api to a sandboxed frame: %d", w.Code)
}
for _, c := range []map[string]string{
{},
{"Sec-Fetch-Site": "same-origin", "Sec-Fetch-Dest": "empty", "Origin": "http://127.0.0.1:3437"},
{"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Dest": "document"},
} {
if code := ask(c); code != 200 {
t.Errorf("%v: %d", c, code)
}
}
}
// magpie web's guard lets a page's files through without the cookie a
// sandboxed frame never sends, and only those: a made-up token is served
// nothing, and the rest of the page still wants the key.
func TestPluginPageWebGuard(t *testing.T) {
pagePlugins(t)
g := webGuard("magpie_web_1", "key", 0, pageMux())
var pages []pluginPage
_ = json.Unmarshal(do(pageMux(), httptest.NewRequest("GET", "/api/plugin-pages", nil)).Body.Bytes(), &pages)
if len(pages) != 1 {
t.Fatal("no page")
}
if w := do(g, httptest.NewRequest("GET", pages[0].URL, nil)); w.Code != 200 {
t.Errorf("the page's file without the cookie: %d", w.Code)
}
if w := do(g, httptest.NewRequest("GET", pluginPagePrefix+strings.Repeat("a", 32)+"/index.html", nil)); w.Code != 404 {
t.Errorf("a made-up token: %d", w.Code)
}
if w := do(g, httptest.NewRequest("GET", "/api/plugin-pages", nil)); w.Code != http.StatusUnauthorized {
t.Errorf("/api without the cookie: %d", w.Code)
}
}
+17
View File
@@ -134,6 +134,10 @@ type pluginEntryJSON struct {
Agent *pluginAgentJSON `json:"agent,omitempty"`
IsAgent bool `json:"isAgent,omitempty"`
InMagpieOnly bool `json:"inMagpieOnly,omitempty"`
// Page is the page it adds to the window (magpie.page), said of one
// switched off too: what the row shows before it is turned on, with
// what the page may read of magpie's
Page *pluginPageInfoJSON `json:"page,omitempty"`
// Clashes are the providers it signs in to that another plugin signs
// in to as well (a plugin of the user's own beside a third party's):
// the host runs one plugin for each, and the row says which, with a
@@ -152,6 +156,12 @@ type pluginToolJSON struct {
MCP string `json:"mcp"` // its name on the MCP server
}
// pluginPageInfoJSON is a plugin's page as its row says it.
type pluginPageInfoJSON struct {
Title string `json:"title,omitempty"`
Reads []string `json:"reads"`
}
// pluginClashJSON is a provider two plugins sign in to, as a row says it.
type pluginClashJSON struct {
plugin.Clash
@@ -266,6 +276,13 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON {
j.Agent = pluginAgentOf(e.Spec, agentErrs)
}
}
if pg, _ := plugin.WindowPage(plugin.Target(e.Spec)); pg != nil {
j.Page = &pluginPageInfoJSON{Title: pg.Title, Reads: pg.Reads}
if j.Page.Reads == nil {
j.Page.Reads = []string{}
}
j.InMagpieOnly = plugin.InMagpieOnly(plugin.Target(e.Spec))
}
for _, c := range clashes[e.Spec] {
n := idName[c.ID]
if n == "" {
+9
View File
@@ -0,0 +1,9 @@
{
"name": "magpie-usage-glance",
"version": "0.1.0",
"description": "An example of a plugin's own page in magpie's window: today's usage at a glance",
"magpie": {
"page": { "title": "Usage glance", "file": "page/index.html", "icon": "page/icon.svg" },
"permissions": ["usage:summary"]
}
}
+16
View File
@@ -0,0 +1,16 @@
// What magpie's window gives a page: the theme, its own options, and the
// reads package.json's magpie.permissions declares.
(async () => {
await magpie.ready;
const opts = await magpie.options.get();
const s = await magpie.read("usage:summary", { period: "today" });
document.getElementById("calls").textContent = `${s.calls} calls, ${s.input + s.output} tokens`;
const cost = document.getElementById("cost");
const paint = (hide) => { cost.textContent = hide ? "" : `$${s.cost.toFixed(2)}`; };
paint(opts.hideCost);
document.getElementById("hide").onclick = async () => {
const next = await magpie.options.set({ ...opts, hideCost: !opts.hideCost });
Object.assign(opts, next);
paint(opts.hideCost);
};
})();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M3 13V8M7 13V4M11 13V9" fill="none" stroke="#4f46e5" stroke-width="1.6" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 172 B

+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Usage glance</title>
<link rel="stylesheet" href="style.css">
<script src="_magpie/bridge.js"></script>
<script src="app.js" defer></script>
</head>
<body>
<h1>Today</h1>
<p id="calls">…</p>
<p id="cost"></p>
<button type="button" id="hide">Hide cost</button>
</body>
</html>
+4
View File
@@ -0,0 +1,4 @@
body { margin: 0; padding: 16px; font: 13px/1.5 var(--magpie-font, system-ui); color: var(--magpie-fg); background: var(--magpie-bg); }
h1 { font-size: 15px; font-weight: 600; margin: 0 0 8px; }
p { margin: 0 0 4px; }
button { font: inherit; color: var(--magpie-accent); background: none; border: 0; padding: 0; cursor: pointer; }
+264
View File
@@ -0,0 +1,264 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A community plugin's own page in the window (pluginpages.js, P4): the
// example plugin (testdata/page-plugin) gets a tab in the sidebar's
// Plugins group and draws in a frame sandboxed to scripts, with the
// window's theme, its own options and the read it declared. The frame
// can't reach magpie's API: its policy stops the fetch, and with the
// policy gone the request it would send carries Origin: null, which
// apiFramed turns away (TestPluginPageNoAPI). A read it didn't declare is
// refused, and a message from another frame is nothing. A page that
// throws shows "This page stopped working" with Try again. The Plugins
// page says what a page may read before it is on. Every language, both
// engines, a narrow window. The API is faked here; the server's side is
// pluginpage_test.go.
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 example = path.resolve(__dirname, "../testdata/page-plugin/page");
const bridge = path.resolve(__dirname, "../pagebridge.js");
const GLANCE = "a".repeat(32), PROBE = "b".repeat(32), OPEN = "c".repeat(32), BROKEN = "d".repeat(32);
const entry = (tok, name, title, reads, file = "index.html") => ({
spec: "/x/" + name, name, key: "plugin-" + name, title, reads,
url: `/_magpie/plugin/${tok}/${file}`, icon: name === "glance" ? `/_magpie/plugin/${tok}/icon.svg` : "",
});
const pages = [
entry(GLANCE, "glance", "Usage glance", ["usage:summary"]),
entry(PROBE, "probe", "Probe", []),
entry(OPEN, "open", "Probe without a policy", []),
entry(BROKEN, "broken", "Broken", []),
];
// what pluginpage.go's pagePolicy sends, for this host
const policy = (tok) => {
const own = `magpie.test/_magpie/plugin/${tok}/`;
return [
"sandbox allow-scripts", "default-src 'none'", `script-src ${own}`, `style-src ${own} 'unsafe-inline'`,
`img-src ${own} data:`, `font-src ${own}`, `media-src ${own}`, "connect-src 'none'", "frame-src 'none'",
"worker-src 'none'", "object-src 'none'", "form-action 'none'", "base-uri 'none'", "frame-ancestors 'self'",
].join("; ");
};
// a page that tries every way out it has, and tells the window what came
// of each (its message has no magpie:1, so the window's bridge ignores it)
const PROBE_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="probe.js"></script><p id="p">probe</p>`;
const PROBE_JS = `(async () => {
const out = {};
await magpie.ready;
try { const r = await fetch("/api/state?probe=1"); out.fetch = "status " + r.status; } catch (e) { out.fetch = "refused"; }
try { out.storage = typeof localStorage.length; } catch (e) { out.storage = "refused"; }
try { out.cookie = document.cookie; } catch (e) { out.cookie = "refused"; }
try { out.top = String(parent.document.title); } catch (e) { out.top = "refused"; }
try { await magpie.read("usage:summary"); out.read = "given"; } catch (e) { out.read = e.message; }
try { await magpie.read("providers:list"); out.read2 = "given"; } catch (e) { out.read2 = e.message; }
parent.postMessage({ probe: out }, "*");
})();`;
const BROKEN_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="app.js"></script><p id="ok">drawn</p>`;
function server(lang, seen, plugins) {
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.searchParams.get("probe")) {
seen.api.push(await req.allHeaders());
return route.fulfill({ status: 403, body: "" });
}
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/plugin-pages") return json(pages);
if (url.pathname === "/api/plugin-pages/read") {
const b = req.postDataJSON();
seen.reads.push(b);
return json({ period: "today", calls: 12, errors: 0, input: 1000, output: 234, cost: 0.5, models: [] });
}
if (url.pathname === "/api/plugin-pages/options") {
const b = req.postDataJSON();
if (b.options) { seen.options.push(b); seen.saved = b.options; }
return json(seen.saved || {});
}
if (url.pathname === "/api/plugins") return json(plugins);
if (url.pathname === "/api/plugins/market") return json({ listings: [], state: plugins });
if (url.pathname === "/api/plugins/listings") return json({ listings: [] });
if (url.pathname.startsWith("/api/")) return json({});
const m = url.pathname.match(/^\/_magpie\/plugin\/([0-9a-f]{32})\/(.+)$/);
if (m) {
const [, tok, rel] = m;
const headers = { "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-cache" };
if (tok !== OPEN) headers["Content-Security-Policy"] = policy(tok);
const type = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml" }[path.extname(rel)];
let body;
if (rel === "_magpie/bridge.js") body = await fs.readFile(bridge);
else if (tok === GLANCE) body = await fs.readFile(path.join(example, rel)).catch(() => null);
else if ((tok === PROBE || tok === OPEN) && rel === "index.html") body = PROBE_HTML;
else if ((tok === PROBE || tok === OPEN) && rel === "probe.js") body = PROBE_JS;
else if (tok === BROKEN && rel === "index.html") body = BROKEN_HTML;
else if (tok === BROKEN && rel === "app.js") body = seen.broken ? "throw new Error('fixture: the page broke')" : "1";
if (body == null) return route.fulfill({ status: 404, body: "" });
return route.fulfill({ status: 200, headers: { ...headers, "Content-Type": type }, body });
}
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const plugins = { bun: true, bunVersion: "1.3.0", plugins: [
{ spec: "/x/magpie-usage-glance", providers: [], moved: [], inMagpieOnly: true, page: { title: "Usage glance", reads: ["usage:summary", "providers:list"] } },
{ spec: "/x/quiet-page", off: true, providers: [], moved: [], inMagpieOnly: true, page: { title: "Quiet", reads: [] } },
] };
const frameOf = (page, tok) => page.frames().find((f) => f.url().includes(tok));
async function frameReady(page, tok) {
await page.waitForFunction((tok) => [...document.querySelectorAll("iframe.plugin-frame")].some((f) => f.src.includes(tok)), tok);
for (let i = 0; i < 100 && !frameOf(page, tok); i++) await page.waitForTimeout(50);
return frameOf(page, tok);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a plugin's page draws in its frame, shut in`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
const where = `${engine} ${lang} ${width}`;
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(8000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const seen = { api: [], reads: [], options: [] };
await page.route("**/*", server(lang, seen, plugins));
await page.goto("http://magpie.test/");
// the sidebar's Plugins group, after the built-in pages
const head = page.locator("#nav .nav-gl[data-plugin-pages]");
await head.waitFor({ state: "attached" });
assert.equal(await head.textContent(), await page.evaluate(() => t("Plugins")), where);
const tabs = page.locator("#nav button[data-plugin-page]");
assert.equal(await tabs.count(), 4, where);
assert.equal(await page.evaluate(() => { const h = document.querySelector("#nav .nav-gl[data-plugin-pages]"); return [...h.parentElement.children].indexOf(h) > [...h.parentElement.querySelectorAll("button[data-view='plugins']")].map((b) => [...b.parentElement.children].indexOf(b))[0]; }), true, `${where}: after the built-in pages`);
assert.equal(await tabs.first().locator("img.nav-ic").getAttribute("src"), `/_magpie/plugin/${GLANCE}/icon.svg`, where);
// no frame until the page is looked at
assert.equal(await page.locator("iframe.plugin-frame").count(), 0, `${where}: nothing loaded unseen`);
// the example: its declared read, the theme, its options
await page.evaluate(() => show("plugin-glance"));
const glance = await frameReady(page, GLANCE);
assert.equal(await page.locator("#view-plugin-glance iframe").getAttribute("sandbox"), "allow-scripts", where);
await glance.waitForFunction(() => document.getElementById("cost").textContent === "$0.50");
assert.equal(await glance.locator("#calls").textContent(), "12 calls, 1234 tokens", where);
assert.deepEqual(seen.reads.map((r) => [r.spec, r.read]), [["/x/glance", "usage:summary"]], where);
assert.equal(await glance.evaluate(() => document.documentElement.lang), lang, `${where}: the window's language`);
assert.equal(await glance.evaluate(() => document.documentElement.dataset.theme), "light", where);
await page.evaluate(() => { document.documentElement.dataset.theme = "dark"; });
await glance.waitForFunction(() => document.documentElement.dataset.theme === "dark");
assert.ok((await glance.evaluate(() => document.documentElement.style.getPropertyValue("--magpie-bg"))).length > 0, `${where}: the tokens`);
await glance.locator("#hide").click();
await glance.waitForFunction(() => document.getElementById("cost").textContent === "");
assert.deepEqual(seen.options.map((o) => [o.spec, o.options.hideCost]), [["/x/glance", true]], `${where}: its own options`);
// the frame fits the window
assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-plugin-glance"); const f = v.querySelector("iframe"); return f.getBoundingClientRect().width <= v.clientWidth + 1 && v.scrollWidth <= v.clientWidth + 1 && f.getBoundingClientRect().height > 200; }), `${where}: fits`);
if (lang === "en" && width === 1100) {
// every way out of the frame is shut; a read it didn't declare
// is refused before it reaches the server
const got = page.evaluate(() => new Promise((res) => addEventListener("message", (e) => { if (e.data?.probe) res(e.data.probe); })));
await page.evaluate(() => show("plugin-probe"));
const probe = await got;
assert.equal(probe.fetch, "refused", `${where}: the policy stops a fetch of /api`);
assert.equal(probe.storage, "refused", `${where}: no storage`);
assert.equal(probe.cookie, "refused", `${where}: no cookie`);
assert.equal(probe.top, "refused", `${where}: no reach into the window`);
assert.equal(probe.read, "Probe doesn't ask to read usage:summary", where);
assert.equal(probe.read2, "Probe doesn't ask to read providers:list", where);
assert.equal(seen.api.length, 0, `${where}: nothing reached /api`);
assert.equal(seen.reads.length, 1, `${where}: an undeclared read never reached the server`);
// with the policy gone, what the frame's fetch would send is what
// apiFramed turns away
const got2 = page.evaluate(() => new Promise((res) => addEventListener("message", (e) => { if (e.data?.probe) res(e.data.probe); })));
await page.evaluate(() => show("plugin-open"));
const open = await got2;
assert.equal(open.fetch.startsWith("status") || open.fetch === "refused", true, where);
assert.equal(seen.api.length, 1, `${where}: the fetch went out`);
assert.equal(seen.api[0].origin, "null", `${where}: as Origin: null`);
assert.ok(!seen.api[0].cookie, `${where}: without a cookie`);
// a message from another frame naming a page is nothing
const before = seen.reads.length;
await page.evaluate(() => {
const f = document.createElement("iframe");
f.srcdoc = `<script>parent.postMessage({magpie:1,id:1,method:"read",params:{name:"usage:summary"}},"*")<\/script>`;
document.body.append(f);
});
await page.waitForTimeout(300);
assert.equal(seen.reads.length, before, `${where}: another frame's read is not answered`);
// a page that throws shows the kernel's broken state, and Try again
// draws it once its code works
seen.broken = true;
await page.evaluate(() => show("plugin-broken"));
const card = page.locator("#view-plugin-broken .slot-error");
await card.waitFor();
assert.equal(await card.locator(".name").textContent(), "This page stopped working", where);
// the frame's own script's error is muted to it ("Script error."):
// the window says the page hit one
assert.equal(await card.locator(".sub").textContent(), "The page hit an error", where);
seen.broken = false;
await card.locator(".slot-again").click();
const fixed = await frameReady(page, BROKEN);
await fixed.locator("#ok").waitFor();
assert.equal(await card.count(), 0, `${where}: the card gone`);
}
// the broken page's own throw, in its frame, is the only error
assert.deepEqual(errors.filter((e) => e !== "fixture: the page broke"), [], where);
await context.close();
}
}
});
test(`${engine}: Plugins says what a page may read before it is on`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [980, 420]) {
const where = `${engine} ${lang} ${width}`;
const page = await (await browser.newContext({ viewport: { width, height: 820 } })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, { api: [], reads: [], options: [] }, plugins));
await page.goto("http://magpie.test/?view=plugins");
const view = page.locator("#view-plugins");
const installed = await page.evaluate(() => t("Installed"));
await page.locator(":is(.lib-tabs .opt, .nav-s):visible", { hasText: installed }).first().click();
const row = (name) => view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: name }) });
const glance = row("magpie-usage-glance");
await glance.waitFor();
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
assert.deepEqual((await glance.locator(".pm-chip.kind").allInnerTexts()).map((x) => x.trim()), [await tr("Page")], where);
const reads = [await tr("your usage totals, by model"), await tr("your providers' names")].join(await tr(", "));
assert.equal((await glance.locator(".pm-page").innerText()).trim(), await tr("Adds a page to the sidebar, which can read {reads}", { reads }), where);
if (lang !== "en") assert.ok(!(await glance.locator(".pm-page").innerText()).includes("Adds a page"), `${where}: translated`);
// one switched off still says it
const quiet = row("quiet-page");
assert.equal((await quiet.locator(".pm-page").innerText()).trim(), await tr("Adds a page to the sidebar, which reads nothing of magpie's"), where);
assert.ok(await view.evaluate((v) => v.scrollWidth <= v.clientWidth + 1), `${where}: fits`);
// nothing drawn with a coloured left border
const borders = await view.locator(".pm-row *").evaluateAll((els) => els.filter((e) => { const s = getComputedStyle(e); return parseFloat(s.borderLeftWidth) > 0 && s.borderLeftStyle !== "none" && parseFloat(s.borderRightWidth) === 0; }).length);
assert.equal(borders, 0, where);
assert.deepEqual(errors, [], where);
await page.context().close();
}
}
});
}
+7
View File
@@ -208,6 +208,13 @@ func webGuard(cookie, key string, keep time.Duration, next http.Handler) http.Ha
http.Redirect(rw, r, back, http.StatusSeeOther)
}
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// a plugin's page's files: a sandboxed frame's requests carry no
// cookie, and its token, which only a signed-in /api hands out,
// is the key (servePluginPage serves nothing without a good one)
if strings.HasPrefix(r.URL.Path, pluginPagePrefix) {
next.ServeHTTP(rw, r)
return
}
if q := r.URL.Query(); q.Has("k") {
if !same(q.Get("k")) {
http.Error(rw, "this link's key is not this magpie web's: use the link it printed when it started", http.StatusUnauthorized)
+5 -4
View File
@@ -42,13 +42,14 @@ func Agent(target string) (file string, only bool) {
}
// InMagpieOnly is whether everything a plugin at target has runs in
// magpie's own process, its gateway middleware and its agent, so the
// host has nothing of it to load.
// magpie's own process, its gateway middleware, its agent and its page,
// so the host has nothing of it to load.
func InMagpieOnly(target string) bool {
mw, mwOnly := Middleware(target)
ag, agOnly := Agent(target)
if mw == "" && ag == "" {
pg, pgOnly := WindowPage(target)
if mw == "" && ag == "" && pg == nil {
return false
}
return (mw == "" || mwOnly) && (ag == "" || agOnly)
return (mw == "" || mwOnly) && (ag == "" || agOnly) && (pg == nil || pgOnly)
}
+141
View File
@@ -0,0 +1,141 @@
package plugin
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
)
// PageSpec is the page a plugin adds to magpie's window: package.json's
// magpie.page, and the reads magpie.permissions asks for.
type PageSpec struct {
Title string // "" when it names none
Icon string // a file in the page's folder, relative to it, or ""
File string // the page's HTML, inside the plugin's folder
Dir string // the folder the page's files are served from: File's
// Reads are the reads the page asked for that magpie has (PageReads),
// in the order asked.
Reads []string
}
// PageReads are the reads a plugin's page can be granted, each in
// magpie.permissions. None of them carries a secret.
var PageReads = []string{"usage:summary", "providers:list"}
// WindowPage is the page a plugin at target adds to magpie's window, or nil:
// package.json's magpie.page {title, file, icon}. A file outside the
// plugin's folder is no page. only is whether it is nothing else: no
// OpenCode plugin for the host to load (no main, no exports).
func WindowPage(target string) (p *PageSpec, only bool) {
st, err := os.Stat(target)
if err != nil || !st.IsDir() {
return nil, false
}
b, err := os.ReadFile(filepath.Join(target, "package.json"))
if err != nil {
return nil, false
}
var pkg struct {
Main string `json:"main"`
Exports json.RawMessage `json:"exports"`
Magpie struct {
Page *struct {
Title string `json:"title"`
File string `json:"file"`
Icon string `json:"icon"`
} `json:"page"`
Permissions []string `json:"permissions"`
} `json:"magpie"`
}
if json.Unmarshal(b, &pkg) != nil || pkg.Magpie.Page == nil {
return nil, false
}
pg := pkg.Magpie.Page
file, ok := inside(target, pg.File)
if !ok || !strings.HasSuffix(strings.ToLower(file), ".html") {
return nil, false
}
p = &PageSpec{Title: strings.TrimSpace(pg.Title), File: file, Dir: filepath.Dir(file)}
// the icon is served with the page, so it sits in the page's folder
if icon, ok := inside(target, pg.Icon); ok {
if rel, err := filepath.Rel(p.Dir, icon); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
p.Icon = filepath.ToSlash(rel)
}
}
for _, r := range pkg.Magpie.Permissions {
if slices.Contains(PageReads, r) && !slices.Contains(p.Reads, r) {
p.Reads = append(p.Reads, r)
}
}
return p, pkg.Main == "" && len(pkg.Exports) == 0
}
// inside is rel joined to dir, if that stays inside dir: no "..", no
// absolute path, and no symbolic link out of it.
func inside(dir, rel string) (string, bool) {
rel = strings.TrimSpace(rel)
if rel == "" || filepath.IsAbs(rel) || strings.HasPrefix(rel, "/") || strings.Contains(rel, `\`) {
return "", false
}
clean := filepath.Clean(filepath.FromSlash(rel))
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
return "", false
}
full := filepath.Join(dir, clean)
realDir, err := filepath.EvalSymlinks(dir)
if err != nil {
return "", false
}
real, err := filepath.EvalSymlinks(full)
if err != nil {
return "", false
}
if r, err := filepath.Rel(realDir, real); err != nil || r == ".." || strings.HasPrefix(r, ".."+string(filepath.Separator)) {
return "", false
}
return full, true
}
// PageFile is the file at rel among a page's files, if it is one: inside
// the page's folder, and a file.
func (p *PageSpec) PageFile(rel string) (string, bool) {
f, ok := inside(p.Dir, rel)
if !ok {
return "", false
}
if st, err := os.Stat(f); err != nil || st.IsDir() {
return "", false
}
return f, true
}
// SetPageOptions sets the options of a plugin from its page. One whose
// page is all it has is never loaded by the host, so the host goes on as
// it was; any other is SetOptions, which starts the host again for it.
func SetPageOptions(spec string, opts map[string]any) error {
t := Target(spec)
if mw, _ := Middleware(t); mw != "" {
return SetOptions(spec, opts)
}
if ag, _ := Agent(t); ag != "" {
return SetOptions(spec, opts)
}
if p, only := WindowPage(t); p == nil || !only {
return SetOptions(spec, opts)
}
listMu.Lock()
defer listMu.Unlock()
l := Load()
i := indexOf(l, spec)
if i < 0 {
return fmt.Errorf("no plugin %q", spec)
}
if len(opts) == 0 {
opts = nil
}
l.Plugins[i].Options = opts
return save(l)
}
+71
View File
@@ -0,0 +1,71 @@
package plugin
import (
"os"
"path/filepath"
"slices"
"testing"
)
// A plugin's page (magpie.page) is a file inside the plugin's folder: one
// that names a path out of it, by "..", an absolute path or a symbolic
// link, is no page. Its reads are those magpie has, and a plugin that is
// only a page is nothing for the host to load, nor "not a plugin".
func TestWindowPageStaysInside(t *testing.T) {
root := t.TempDir()
outside := filepath.Join(root, "secret.html")
if err := os.WriteFile(outside, []byte("<p>secret</p>"), 0o644); err != nil {
t.Fatal(err)
}
mk := func(name, pkg string) string {
t.Helper()
d := filepath.Join(root, name)
if err := os.MkdirAll(filepath.Join(d, "page"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(d, "page", "index.html"), []byte("<p>hi</p>"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(d, "package.json"), []byte(pkg), 0o644); err != nil {
t.Fatal(err)
}
return d
}
good := mk("good", `{"name":"good","magpie":{"page":{"title":"Good","file":"page/index.html","icon":"page/index.html"},"permissions":["usage:summary","secrets:all","usage:summary"]}}`)
p, only := WindowPage(good)
if p == nil || !only || p.Title != "Good" || p.Icon != "index.html" {
t.Fatalf("good: %+v only=%v", p, only)
}
if !slices.Equal(p.Reads, []string{"usage:summary"}) {
t.Errorf("reads %v, want only the one magpie has, once", p.Reads)
}
if !InMagpieOnly(good) || notPlugin(good) != nil {
t.Errorf("a page-only plugin: InMagpieOnly %v, notPlugin %v", InMagpieOnly(good), notPlugin(good))
}
if _, only := WindowPage(mk("main", `{"name":"m","main":"index.js","magpie":{"page":{"file":"page/index.html"}}}`)); only {
t.Error("a plugin with a main is more than its page")
}
link := mk("link", `{"name":"l","magpie":{"page":{"file":"page/out.html"}}}`)
if err := os.Symlink(outside, filepath.Join(link, "page", "out.html")); err != nil {
t.Fatal(err)
}
for name, pkg := range map[string]string{
"dotdot": `{"name":"d","magpie":{"page":{"file":"../secret.html"}}}`,
"abs": `{"name":"a","magpie":{"page":{"file":"` + filepath.ToSlash(outside) + `"}}}`,
"notml": `{"name":"n","magpie":{"page":{"file":"package.json"}}}`,
"none": `{"name":"x","magpie":{"page":{"file":"page/missing.html"}}}`,
} {
if p, _ := WindowPage(mk(name, pkg)); p != nil {
t.Errorf("%s: %+v is a page", name, p)
}
}
if p, _ := WindowPage(link); p != nil {
t.Errorf("a symbolic link out of the folder: %+v is a page", p)
}
if f, ok := p.PageFile("../package.json"); ok {
t.Errorf("PageFile served %s", f)
}
if f, ok := p.PageFile("index.html"); !ok || filepath.Base(f) != "index.html" {
t.Errorf("PageFile(index.html) = %s %v", f, ok)
}
}
+3
View File
@@ -469,6 +469,9 @@ func notPlugin(target string) error {
if f, _ := Agent(target); f != "" {
return nil
}
if p, _ := WindowPage(target); p != nil {
return nil
}
var pkg struct {
Name string `json:"name"`
Main string `json:"main"`
+51
View File
@@ -86,6 +86,7 @@
<a href="#middleware">ゲートウェイミドルウェア</a>
<a href="#tools">すべてのエージェントのツール</a>
<a href="#agents">エージェントプラグイン</a>
<a href="#pages">ウィンドウのページ</a>
<a href="#pi">pi パッケージ</a>
<a href="#protocol">ホストプロトコル</a>
<a href="#faq">よくある質問</a>
@@ -755,6 +756,56 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
<li><b>宣言。</b><code>package.json</code> の <code>"magpie": { "agent": "./agent.js" }</code>、または <code>*.agent.js</code>(または <code>.mjs</code>)という単一ファイル。1 つのパッケージがプロバイダー、ミドルウェア、エージェントを兼ねられます。プラグインマーケットではエージェントのエントリーに <code>"kind": "agent"</code> を付け、<span class="ui">エージェント</span>の下に並びます。コミュニティのものは <code>@magpie-community/agent-&lt;name&gt;</code> と名付けます。</li>
</ul>
<h2 id="pages"><a class="anchor" href="#pages">ウィンドウのページ</a></h2>
<p>プラグインは magpie のウィンドウに自分のページを追加できます。オンにすると、サイドバーの<span class="ui">プラグイン</span>グループの、magpie 自身のページの後ろにタブが出ます。ページはプラグインのフォルダにある HTML、CSS、JavaScript だけで、Bun もビルドも要りません。下の例は今日の使用量を表示します。</p>
<div class="code">
<span class="lang">package.json</span>
<button class="copy" data-copy="pg-pkg">コピー</button>
<pre id="pg-pkg">{
<span class="s">"name"</span>: <span class="s">"magpie-usage-glance"</span>,
<span class="s">"version"</span>: <span class="s">"0.1.0"</span>,
<span class="s">"magpie"</span>: {
<span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span> },
<span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]
}
}</pre>
</div>
<div class="code">
<span class="lang">page/index.html</span>
<button class="copy" data-copy="pg-html">コピー</button>
<pre id="pg-html">&lt;!doctype html&gt;
&lt;link rel="stylesheet" href="style.css"&gt;
&lt;script src="_magpie/bridge.js"&gt;&lt;/script&gt; <span class="c">&lt;!-- served beside every page --&gt;</span>
&lt;script src="app.js" defer&gt;&lt;/script&gt;
&lt;p id="calls"&gt;…&lt;/p&gt;</pre>
</div>
<div class="code">
<span class="lang">page/app.js</span>
<button class="copy" data-copy="pg-js">コピー</button>
<pre id="pg-js"><span class="k">await</span> magpie.ready <span class="c">// the window's theme, painted</span>
<span class="k">const</span> s = <span class="k">await</span> magpie.read(<span class="s">"usage:summary"</span>, { period: <span class="s">"today"</span> })
document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls} calls`
<span class="k">const</span> opts = <span class="k">await</span> magpie.options.get() <span class="c">// this plugin's own options</span>
<span class="k">await</span> magpie.options.set({ ...opts, hideCost: <span class="k">true</span> })</pre>
</div>
<p>プラグインページの行には、オンにする前からページと読めるものが表示されます。<code>page.file</code> と <code>page.icon</code> はプラグイン内のパスです。ページのファイルは <code>file</code> のフォルダにあるものだけで、外を指すパスやリンクは配信されません。1 つのパッケージがページとプロバイダ、ミドルウェア、エージェントを兼ねることもできます。ページだけのプラグインはプラグインホストを起動しません。</p>
<h3>ページが頼めること</h3>
<div class="table-wrap"><table>
<tr><th>フィールド / 呼び出し</th><th>返すもの</th></tr>
<tr><td><code>magpie.ready</code></td><td>ウィンドウが応答すると、ウィンドウのテーマが得られます。それまでページは magpie と何も話していません。10 秒以内に話さないページは応答なしと表示されます。</td></tr>
<tr><td><code>magpie.theme, magpie.onTheme(fn)</code></td><td><code>{ dark, lang, tokens }</code>。bridge は <code>&lt;html&gt;</code> に <code>data-theme</code>、<code>lang</code>、<code>color-scheme</code> と <code>--magpie-bg</code>、<code>--magpie-fg</code>、<code>--magpie-accent</code> なども設定し、変わるたびに設定し直します。</td></tr>
<tr><td><code>magpie.options.get(), .set(o)</code></td><td>plugins.json にあるそのプラグイン自身のオプションです。ほかのプラグインのものは扱えません。<code>set</code> はオブジェクトを受け取り、保存されたオプションを返します。呼べるのは 1 秒に 1 回までです。</td></tr>
<tr><td><code>magpie.read(name, params)</code></td><td><code>magpie.permissions</code> で宣言した読み取りです。それ以外はウィンドウが拒否し、magpie ももう一度拒否します。<code>usage:summary</code>(<code>period</code>:<code>today</code>、<code>7d</code>、<code>30d</code>)は呼び出し数、エラー数、トークン、費用と上位 20 モデルを、<code>providers:list</code> は各プロバイダの id と名前を返します。キー、アカウント、サインイン、リクエスト本文を返す読み取りはありません。</td></tr>
</table></div>
<h3>ページにできないこと</h3>
<ul>
<li>ページはスクリプトだけを許したサンドボックスのフレーム(<code>sandbox="allow-scripts"</code>、<code>Content-Security-Policy</code> でも同じ)で、独自のオリジンで動きます。ウィンドウにも、magpie の cookie にも、ウィンドウのストレージにも届きません。</li>
<li>ポリシーで読み込めるのは自分のファイルだけです。<code>connect-src 'none'</code> なので <code>fetch</code>、WebSocket、beacon は使えず、フォームやフレームもありません。スクリプトはファイル(<code>&lt;script src&gt;</code>)にする必要があり、インラインは使えません。インラインのスタイルと <code>data:</code> の画像は使えます。</li>
<li>このようなフレームが送れるリクエスト(<code>Origin: null</code>、フレームからのリクエスト、ほかのサイトのリクエスト)は magpie の API がすべて拒否するので、ポリシーがなくてもページは API に入れません。ファイルは <code>/_magpie/plugin/&lt;token&gt;/</code> から配信され、token は magpie を起動するたびに変わります。</li>
<li>それでもページは自分をほかのサイトへ移動できます。そのサイトがフレームを持つことになるので、読み取りは秘密でないものだけを返します。ページが読めるものは公開されたものとして扱ってください。</li>
<li>ページが捕まえなかったエラーは、その場所に<span class="ui">このページは動作を停止しました</span>と<span class="ui">再試行</span>を表示します。ページ自身のスクリプトのエラーはページには「Script error.」としか届かないので、詳しくはウィンドウのコンソールを見てください。</li>
</ul>
<h2 id="pi"><a class="anchor" href="#pi">pi パッケージ</a></h2>
<p>magpie は <a href="https://github.com/earendil-works/pi">pi</a> のパッケージも動かします。<code>pi.registerProvider</code> でプロバイダを登録する pi 拡張は、何も変えずに pi と同じように magpie で動き、ほかのプラグインと同じ方法で追加できます(<code>magpie plugin add pi-antigravity</code>)。</p>
<ul>
+51
View File
@@ -86,6 +86,7 @@
<a href="#middleware">Gateway middleware</a>
<a href="#tools">Tools for every agent</a>
<a href="#agents">Agent plugins</a>
<a href="#pages">Pages in the window</a>
<a href="#pi">pi packages</a>
<a href="#protocol">The host protocol</a>
<a href="#faq">FAQ</a>
@@ -755,6 +756,56 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
<li><b>Declaring it.</b> <code>"magpie": { "agent": "./agent.js" }</code> in <code>package.json</code>, or a single file named <code>*.agent.js</code> (or <code>.mjs</code>). A package can be a provider, middleware and an agent at once. In the plugin market an agent’s entry has <code>"kind": "agent"</code> and is listed under <span class="ui">Agents</span>; a community one is named <code>@magpie-community/agent-&lt;name&gt;</code>.</li>
</ul>
<h2 id="pages"><a class="anchor" href="#pages">Pages in the window</a></h2>
<p>A plugin can add a page of its own to magpie’s window. Once it is on, the page has a tab in the sidebar’s <span class="ui">Plugins</span> group, after magpie’s own pages. The page is plain HTML, CSS and JavaScript in the plugin’s folder, and needs no Bun and no build step. The example below shows today’s usage.</p>
<div class="code">
<span class="lang">package.json</span>
<button class="copy" data-copy="pg-pkg">Copy</button>
<pre id="pg-pkg">{
<span class="s">"name"</span>: <span class="s">"magpie-usage-glance"</span>,
<span class="s">"version"</span>: <span class="s">"0.1.0"</span>,
<span class="s">"magpie"</span>: {
<span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span> },
<span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]
}
}</pre>
</div>
<div class="code">
<span class="lang">page/index.html</span>
<button class="copy" data-copy="pg-html">Copy</button>
<pre id="pg-html">&lt;!doctype html&gt;
&lt;link rel="stylesheet" href="style.css"&gt;
&lt;script src="_magpie/bridge.js"&gt;&lt;/script&gt; <span class="c">&lt;!-- served beside every page --&gt;</span>
&lt;script src="app.js" defer&gt;&lt;/script&gt;
&lt;p id="calls"&gt;…&lt;/p&gt;</pre>
</div>
<div class="code">
<span class="lang">page/app.js</span>
<button class="copy" data-copy="pg-js">Copy</button>
<pre id="pg-js"><span class="k">await</span> magpie.ready <span class="c">// the window's theme, painted</span>
<span class="k">const</span> s = <span class="k">await</span> magpie.read(<span class="s">"usage:summary"</span>, { period: <span class="s">"today"</span> })
document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls} calls`
<span class="k">const</span> opts = <span class="k">await</span> magpie.options.get() <span class="c">// this plugin's own options</span>
<span class="k">await</span> magpie.options.set({ ...opts, hideCost: <span class="k">true</span> })</pre>
</div>
<p>The Plugins page shows the page, and what it may read, on the plugin’s row before it is turned on. <code>page.file</code> and <code>page.icon</code> are paths inside the plugin. The page’s files are what sits in <code>file</code>’s folder; a path out of it, or a link that leads out, isn’t served. A package can be a page and a provider, middleware or an agent too. A plugin that is only a page doesn’t start the plugin host.</p>
<h3>What the page can ask</h3>
<div class="table-wrap"><table>
<tr><th>Field / call</th><th>What it gives</th></tr>
<tr><td><code>magpie.ready</code></td><td>A promise of the window’s theme. It resolves once the window has answered. Until then the page has said nothing to magpie, and a page that doesn’t say it in 10 seconds is shown as not answering.</td></tr>
<tr><td><code>magpie.theme, magpie.onTheme(fn)</code></td><td><code>{ dark, lang, tokens }</code>. The bridge also sets <code>data-theme</code>, <code>lang</code>, <code>color-scheme</code> and <code>--magpie-bg</code>, <code>--magpie-fg</code>, <code>--magpie-accent</code> and so on on <code>&lt;html&gt;</code>, and again on each change.</td></tr>
<tr><td><code>magpie.options.get(), .set(o)</code></td><td>The plugin’s own options in plugins.json, never another plugin’s. <code>set</code> takes an object and answers with the options saved. It can be called at most once a second.</td></tr>
<tr><td><code>magpie.read(name, params)</code></td><td>A read that <code>magpie.permissions</code> declares. Anything else is refused, by the window and again by magpie. <code>usage:summary</code> (<code>period</code>: <code>today</code>, <code>7d</code> or <code>30d</code>) gives calls, errors, tokens and cost, with the top 20 models. <code>providers:list</code> gives each provider’s id and name. No read gives keys, accounts, sign-ins or request bodies.</td></tr>
</table></div>
<h3>What the page can’t do</h3>
<ul>
<li>The page runs in a frame sandboxed to scripts alone (<code>sandbox="allow-scripts"</code>, and the same in its <code>Content-Security-Policy</code>), in an origin of its own. It can’t reach the window, magpie’s cookie or the window’s storage.</li>
<li>Its policy allows its own files and nothing else: <code>connect-src 'none'</code>, so no <code>fetch</code>, WebSocket or beacon, and no forms or frames. Scripts must be files (<code>&lt;script src&gt;</code>), not inline. Inline styles and <code>data:</code> pictures are fine.</li>
<li>magpie’s API refuses any request a frame like this one can make (<code>Origin: null</code>, a frame or another site’s request), so it is closed to the page even without the policy. Its files are served at <code>/_magpie/plugin/&lt;token&gt;/</code>, a token that changes each time magpie starts.</li>
<li>A page can still send itself to another site, which then holds its frame. That is why reads give nothing secret. Treat what a page can read as public.</li>
<li>An error the page doesn’t catch shows <span class="ui">This page stopped working</span> in its place, with <span class="ui">Try again</span>. Its own scripts’ errors reach it as “Script error.”, so look in the window’s console for the rest.</li>
</ul>
<h2 id="pi"><a class="anchor" href="#pi">pi packages</a></h2>
<p>magpie also runs <a href="https://github.com/earendil-works/pi">pi</a>’s packages. A pi extension that registers a provider with <code>pi.registerProvider</code> works in magpie as it does in pi, with nothing to change, and is added like any plugin (<code>magpie plugin add pi-antigravity</code>).</p>
<ul>
+51
View File
@@ -86,6 +86,7 @@
<a href="#middleware">网关中间件</a>
<a href="#tools">给每个智能体的工具</a>
<a href="#agents">Agent 插件</a>
<a href="#pages">窗口里的页面</a>
<a href="#pi">pi 扩展包</a>
<a href="#protocol">宿主协议</a>
<a href="#faq">答疑</a>
@@ -755,6 +756,56 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
<li><b>声明方式。</b><code>package.json</code> 里写 <code>"magpie": { "agent": "./agent.js" }</code>,或者一个名为 <code>*.agent.js</code>(或 <code>.mjs</code>)的单文件。一个包可以同时是供应商、中间件和 Agent。插件市场里 Agent 条目写 <code>"kind": "agent"</code>,列在 <span class="ui">Agent</span> 下;社区包命名为 <code>@magpie-community/agent-&lt;name&gt;</code>。</li>
</ul>
<h2 id="pages"><a class="anchor" href="#pages">窗口里的页面</a></h2>
<p>插件可以在 magpie 的窗口里加一个自己的页面。插件打开后,侧边栏的<span class="ui">插件</span>分组里会出现它的标签,排在 magpie 自带页面的后面。页面就是插件文件夹里的 HTML、CSS 和 JavaScript,不需要 Bun,也不用构建。下面的例子显示今天的用量。</p>
<div class="code">
<span class="lang">package.json</span>
<button class="copy" data-copy="pg-pkg">复制</button>
<pre id="pg-pkg">{
<span class="s">"name"</span>: <span class="s">"magpie-usage-glance"</span>,
<span class="s">"version"</span>: <span class="s">"0.1.0"</span>,
<span class="s">"magpie"</span>: {
<span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span> },
<span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]
}
}</pre>
</div>
<div class="code">
<span class="lang">page/index.html</span>
<button class="copy" data-copy="pg-html">复制</button>
<pre id="pg-html">&lt;!doctype html&gt;
&lt;link rel="stylesheet" href="style.css"&gt;
&lt;script src="_magpie/bridge.js"&gt;&lt;/script&gt; <span class="c">&lt;!-- served beside every page --&gt;</span>
&lt;script src="app.js" defer&gt;&lt;/script&gt;
&lt;p id="calls"&gt;…&lt;/p&gt;</pre>
</div>
<div class="code">
<span class="lang">page/app.js</span>
<button class="copy" data-copy="pg-js">复制</button>
<pre id="pg-js"><span class="k">await</span> magpie.ready <span class="c">// the window's theme, painted</span>
<span class="k">const</span> s = <span class="k">await</span> magpie.read(<span class="s">"usage:summary"</span>, { period: <span class="s">"today"</span> })
document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls} calls`
<span class="k">const</span> opts = <span class="k">await</span> magpie.options.get() <span class="c">// this plugin's own options</span>
<span class="k">await</span> magpie.options.set({ ...opts, hideCost: <span class="k">true</span> })</pre>
</div>
<p>插件打开之前,插件页面就会在它的那一行显示这个页面和它能读什么。<code>page.file</code> 和 <code>page.icon</code> 是插件里面的路径;页面的文件就是 <code>file</code> 所在文件夹里的文件,指向外面的路径或链接不会被提供。一个包可以同时是页面、供应商、中间件或 agent。只有页面的插件不会启动插件宿主。</p>
<h3>页面能请求什么</h3>
<div class="table-wrap"><table>
<tr><th>字段 / 调用</th><th>给出什么</th></tr>
<tr><td><code>magpie.ready</code></td><td>窗口回应后得到窗口的主题。在那之前页面还没和 magpie 说过话;10 秒内没说的页面会显示为没有回应。</td></tr>
<tr><td><code>magpie.theme, magpie.onTheme(fn)</code></td><td><code>{ dark, lang, tokens }</code>。bridge 也会在 <code>&lt;html&gt;</code> 上设置 <code>data-theme</code>、<code>lang</code>、<code>color-scheme</code> 以及 <code>--magpie-bg</code>、<code>--magpie-fg</code>、<code>--magpie-accent</code> 等,每次变化都会再设一次。</td></tr>
<tr><td><code>magpie.options.get(), .set(o)</code></td><td>插件自己在 plugins.json 里的选项,不能是别的插件的。<code>set</code> 接受一个对象,返回保存后的选项,每秒最多一次。</td></tr>
<tr><td><code>magpie.read(name, params)</code></td><td><code>magpie.permissions</code> 声明过的读取。其他的一律拒绝,窗口拒绝一次,magpie 再拒绝一次。<code>usage:summary</code>(<code>period</code>:<code>today</code>、<code>7d</code> 或 <code>30d</code>)给出调用数、错误数、token 和费用,以及前 20 个模型;<code>providers:list</code> 给出每个供应商的 id 和名字。没有任何读取会给出密钥、账号、登录信息或请求内容。</td></tr>
</table></div>
<h3>页面不能做什么</h3>
<ul>
<li>页面运行在只允许脚本的沙盒框架里(<code>sandbox="allow-scripts"</code>,它的 <code>Content-Security-Policy</code> 里也一样),有自己独立的 origin。它碰不到窗口、magpie 的 cookie 和窗口的存储。</li>
<li>它的策略只允许加载自己的文件:<code>connect-src 'none'</code>,所以没有 <code>fetch</code>、WebSocket 或 beacon,也没有表单和框架。脚本必须是文件(<code>&lt;script src&gt;</code>),不能内联;内联样式和 <code>data:</code> 图片可以。</li>
<li>这种框架能发出的请求(<code>Origin: null</code>、框架请求、别的网站的请求),magpie 的 API 都会拒绝,所以就算没有策略,页面也进不了 API。它的文件从 <code>/_magpie/plugin/&lt;token&gt;/</code> 提供,token 每次 magpie 启动都会变。</li>
<li>页面仍然可以把自己跳转到别的网站,那个网站就接管了它的框架。所以读取只给不机密的东西:把页面能读到的都当作公开的。</li>
<li>页面没接住的错误会在它的位置显示<span class="ui">此页面已停止工作</span>和<span class="ui">重试</span>。它自己脚本的错误在页面里只显示为“Script error.”,详细内容看窗口的控制台。</li>
</ul>
<h2 id="pi"><a class="anchor" href="#pi">pi 扩展包</a></h2>
<p>magpie 也运行 <a href="https://github.com/earendil-works/pi">pi</a> 的扩展包。用 <code>pi.registerProvider</code> 注册了供应商的 pi 扩展,在 magpie 里和在 pi 里一样工作,不用改任何东西,添加方式和其他插件相同(<code>magpie plugin add pi-antigravity</code>)。</p>
<ul>