plugins: a runtime for built-in plugins, and Plugins › Built-in to switch them (P0)

Lxxyx on X (https://x.com/Lxxyx_/status/2109506752656150974): magpie has
too much in it. This is P0 of making magpie's parts plugins, as DeepSeek
Harness does: a runtime, plugins.yml, and the first five built-in plugins
the user can switch off.

- internal/pluginrt: a registry (Register from init), a manifest (API
  caret range, Requires/Provides, Essential, InUse, Apply, Parts,
  Defaults) and Reconcile: the plugins no longer wanted, with whatever
  needs a service they provided, are disposed newest first; the wanted
  ones are applied once their services are there. A plugin that fails or
  panics is failed and the rest run. TestPluginsImportOnlyCore keeps the
  boundary: nothing outside plugins/ imports one, none imports another.
- plugins.yml (appdir.Config()): default → preset (essentials | all) →
  the user's rows → in use. A new install is written Essentials, a magpie
  that ran here before (settings.RanBefore) All, so existing users keep
  everything. Writes are locked, whole and keep a .bak; a file that
  doesn't parse is an error, never empty, and is never written over.
- plugins/groups, library, otel, sessions, warmups. In P0 a plugin off
  is the window's alone: its page, sections and rows (data-feature) leave
  the window; the gateway, TUI and CLI serve the same, nothing is
  deleted. One in use stays on.
- The window: Plugins › Built-in, the first tab, a switch per plugin;
  GET/POST /api/plugins/builtin; boot.js says which are off before the
  first paint. CLI: magpie plugin builtin [on|off <id>], plugin preset,
  plugin dump [--json].
- docs/subsystems/plugin-runtime.md, gui-shell.md.

Run: go test ./internal/pluginrt/ ./internal/settings/ ./internal/gui/;
gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows
go vet ./.... GUI: builtins.test.cjs in Chromium and WebKit, 5 languages,
1100/800/420; list-sort, mobile-web, routing-keys-fold, routing-sessions
pass. By hand under a sandbox HOME: a new install gets essentials, an
existing one all, a broken plugins.yml is refused and kept, dump works.
Full suite results after the rebase are in the push notes.
This commit is contained in:
yetone
2026-10-13 16:19:13 +08:00
parent f2b0780fa2
commit 3ccbe6bc15
32 changed files with 2137 additions and 18 deletions
+1
View File
@@ -5,6 +5,7 @@ These pages describe current responsibilities, runtime paths, state, and contrac
| Subsystem | Reference |
| --- | --- |
| Built-in subscriptions moving to plugins | [Provider and plugin ownership](provider-plugins.md) |
| Built-in plugins: registry, lifecycle, plugins.yml, presets | [Plugin runtime](plugin-runtime.md) |
| Plugins that run on the gateway's requests and replies | [Gateway middleware](gateway-middleware.md) |
| Claude subscription turns across Claude Code runs | [Claude subscription bridge](claude-subscription-bridge.md) |
| How the gateway picks a provider, key or account, and falls back | [Gateway routing and fallback](gateway-routing.md) |
+1
View File
@@ -17,6 +17,7 @@ three.
| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) |
| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `routing.js`, `library.js`, `plugins.js`, `sessions.js` and `context.js` (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) |
| Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar), and the header a breadcrumb (`renderCrumb`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |
| Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in. They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` writes plugins.yml. A page marks what goes with a plugin `data-feature="<id>"`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) |
| No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) |
## Runtime path
+91
View File
@@ -0,0 +1,91 @@
# Plugin runtime
magpie's built-in plugins are the parts of magpie not everyone needs, each
one a package under `plugins/` that the user can switch off. The runtime in
`internal/pluginrt` keeps their registry, applies the ones that are on in the
order their services make, and disposes of what each registered when it is
turned off. `plugins.yml` says which are on. This page describes P0: the
runtime, the file and the window's switch. OpenCode plugins (npm packages in
the plugin host) are a different thing; see
[provider and plugin ownership](provider-plugins.md) and
[gateway middleware](gateway-middleware.md).
## Responsibilities and boundaries
| Part | What it does | Source |
| --- | --- | --- |
| Registry | A plugin calls `pluginrt.Register(Manifest)` from `init`. `Registered` lists them by id; two with one id panic. `plugins/all` imports every plugin, and only `main.go` imports `plugins/all`, so core code and its tests run without any. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go), [`plugins/all/all.go`](../../plugins/all/all.go) |
| Manifest | `ID`, `API` (a caret range of the host API, `"^1"`; `pluginrt.API` is `"1.0"`), `Requires` and `Provides` (services), `Essential`, `Name`/`Sub` (English; the window translates them), `One`/`Many` (what is in use, of 1 or `{n}`), `InUse`, `Apply`, `Parts` (`{Slot, Key}`: the window's parts it is) and `Defaults` (its config). | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) |
| Lifecycle | `Runtime.Reconcile(on, config)`. Off first: every plugin no longer wanted, and every one requiring a service one of those provided, is disposed newest first. Then on: each wanted plugin whose requirements are provided (by `Core`, `settings`, `providers`, `gateway`, `window`, or an active plugin) is applied, again and again until no more can be. States: `off`, `pending` (waiting for a service, logged), `active`, `failed` (Apply returned an error or panicked, or the API range doesn't match; what it registered before is undone), `disposed`. A failed plugin never stops the others. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) |
| Ctx | What `Apply` gets: `OnDispose(f)`, `Contribute(slot, key)`, `Provide(name, v)` (withdrawn when it goes), `Service(name)`, and its composed `Config`. Disposers run in reverse, each one's panic logged and the rest still run. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) |
| plugins.yml | `appdir.Config()/plugins.yml`: `preset` (`essentials` or `all`) and `plugins`, rows of `{id, enabled, config}` holding only what the user set. | [`config.go`](../../internal/pluginrt/config.go) |
| Built-in plugins in P0 | `groups`, `library`, `otel`, `sessions`, `warmups`. None is Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) |
The boundary is checked by `TestPluginsImportOnlyCore`: no package outside
`plugins/` imports one (but `main.go`, through `plugins/all`), a plugin never
imports another, and `plugins/all` imports every plugin folder. Plugins reach
each other only through services.
## Source of truth and composing
What a plugin runs with is composed field by field (`Compose`), each value
remembering its layer (`Source`):
1. `default`: every plugin on, its `Manifest.Defaults`;
2. `preset`: Essentials leaves every plugin not `Essential` off;
3. `user`: the rows of plugins.yml (`enabled`, and `config` merged into the
defaults key by key, maps deeply);
4. `in use`: a plugin whose `InUse` is above 0 is on whatever the rows say,
since off its things would go on working with nowhere to see them. An
`InUse` error counts as in use.
`Composed.Chosen` is plugins.yml's say before step 4. `magpie plugin dump`
(`--json`) prints the composed list with each plugin's state and why.
## Runtime paths
- **Start** (`internal/cli/main.go`, after `settings.Migrate`):
`pluginrt.Settle(!settings.RanBefore())` writes a first plugins.yml when
there is none: `essentials` on a new install, `all` on a magpie that ran
here before (one of `settings.ranBefore`'s files is there; one that can't
be looked at counts as there), so an existing user keeps everything. Then
`pluginrt.Refresh` makes the process's runtime and reconciles it. An error
is printed and magpie starts.
- **Every read**: `Refresh` loads plugins.yml again, composes it and
reconciles. The window's `/api/state`, `/api/plugins/builtin` and boot.js
each call it (`builtinsState`), so a change made by the CLI shows on the
next read.
- **Switch**: `Set(id, on)` (`POST /api/plugins/builtin`, `magpie plugin
builtin on|off <id>`) writes the user's row; `SetPreset` the preset
(`magpie plugin preset essentials|all`). Off is refused while the plugin
is in use.
- **The window**: see [GUI app shell](gui-shell.md), "Built-in plugins".
## Failure and compatibility
- A plugins.yml that can't be read or doesn't parse, or names another
preset, is an error, never an empty file. `Refresh` returns it and leaves
the runtime as it was; before the first good read every plugin is on, as
before plugins existed. `Set` and `SetPreset` refuse to write over it, the
window says it above the list and disables every switch, and the CLI exits
with it. The user fixes the file or removes it.
- Writes hold `filelock.Mutex` (`plugins.yml.lock`) against other magpies
and a mutex in the process, are written whole (temp file, sync, rename),
and keep the file they replace as `plugins.yml.bak`.
- A plugin written for another major API, or a newer minor, is `failed`
with the reason; the rest run.
- In P0 a plugin's off is the window's alone: its page, sections and rows
leave the window. The gateway, the TUI and the CLI serve the same either
way, and nothing the user made is deleted. Davsync doesn't carry
plugins.yml.
## Verification
- `go test ./internal/pluginrt/` (`TestReconcile`, `TestCompatible`,
`TestPluginsImportOnlyCore`, `TestCompose`, `TestSettleAndSet`,
`TestBrokenFileIsKept`), `go test ./internal/settings/ -run TestRanBefore`.
- `go test ./internal/gui/ -run 'TestBuiltin|TestBootSaysBuiltinsOff'`.
- `internal/gui/tests/builtins.test.cjs` in Chromium and WebKit, every
language, 1100, 800 and 420 points.
- By hand, under a sandbox HOME: `magpie plugin builtin`, `magpie plugin
builtin on groups`, `magpie plugin dump`, and a plugins.yml broken by hand.
+104
View File
@@ -0,0 +1,104 @@
package cli
import (
"encoding/json"
"errors"
"fmt"
"os"
"slices"
"gopkg.in/yaml.v3"
"github.com/yetone/magpie/internal/pluginrt"
)
// builtinCmd: `magpie plugin builtin [on|off <id>]` — magpie's built-in
// plugins (internal/pluginrt, plugins/), as Plugins › Built-in shows them.
// One in use is refused off, as the window refuses it.
func builtinCmd(rest []string) error {
if len(rest) == 0 || rest[0] == "list" {
cs, err := pluginrt.Refresh()
if err != nil {
return err
}
for _, m := range pluginrt.Registered() {
i := slices.IndexFunc(cs, func(c pluginrt.Composed) bool { return c.ID == m.ID })
c := cs[i]
mark, how := muted.Render("○"), "off"
if c.Enabled {
mark, how = green.Render("●"), "on"
}
if c.Source == pluginrt.FromInUse {
how = "on, in use"
}
fmt.Printf("%s %-10s %-12s %s\n", mark, m.ID, how, muted.Render(m.Name))
}
fmt.Println(muted.Render("in " + tildePath(pluginrt.Path())))
return nil
}
if len(rest) != 2 || (rest[0] != "on" && rest[0] != "off") {
return errors.New(pluginUsage)
}
on, id := rest[0] == "on", rest[1]
cs, err := pluginrt.Refresh()
if err != nil {
return err
}
i := slices.IndexFunc(cs, func(c pluginrt.Composed) bool { return c.ID == id })
if i < 0 {
return fmt.Errorf("no built-in plugin %q", id)
}
if !on && cs[i].InUse > 0 {
return fmt.Errorf("%s is in use and stays on", id)
}
if err := pluginrt.Set(id, on); err != nil {
return err
}
fmt.Println(green.Render("✓"), id, "is", rest[0])
return nil
}
// dumpPlugins: `magpie plugin dump` — what plugins.yml comes to after its
// layers: each built-in plugin, on or off and why, its config and the
// layer each value is from, and how it runs in this process.
func dumpPlugins(asJSON bool) error {
f, there, err := pluginrt.Load()
if err != nil {
return err
}
cs, err := pluginrt.Refresh()
if err != nil {
return err
}
type plug struct {
pluginrt.Composed `yaml:",inline"`
State pluginrt.State `json:"state" yaml:"state"`
Why string `json:"why,omitempty" yaml:"why,omitempty"`
}
st := map[string]pluginrt.Status{}
for _, s := range pluginrt.Running().Statuses() {
st[s.ID] = s
}
out := struct {
File string `json:"file" yaml:"file"`
There bool `json:"there" yaml:"there"`
Preset string `json:"preset" yaml:"preset"`
API string `json:"api" yaml:"api"`
Plugins []plug `json:"plugins" yaml:"plugins"`
}{File: pluginrt.Path(), There: there, Preset: f.Preset, API: pluginrt.API}
if out.Preset == "" {
out.Preset = pluginrt.PresetAll
}
for _, c := range cs {
out.Plugins = append(out.Plugins, plug{Composed: c, State: st[c.ID].State, Why: st[c.ID].Why})
}
if asJSON {
b, _ := json.MarshalIndent(out, "", " ")
fmt.Println(string(b))
return nil
}
e := yaml.NewEncoder(os.Stdout)
e.SetIndent(2)
defer e.Close()
return e.Encode(out)
}
+10
View File
@@ -21,6 +21,7 @@ import (
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/imagemcp"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
@@ -221,6 +222,15 @@ func run(args []string) error {
update.AwaitPredecessor()
makeDirs()
settings.Migrate()
// a new install starts with the Essentials preset of built-in plugins
// (plugins.yml), one that ran before with all of them, told by no file
// of a magpie run before: so before anything below writes one
if _, err := pluginrt.Settle(!settings.RanBefore()); err != nil {
fmt.Fprintf(os.Stderr, "magpie: plugins.yml: %v\n", err)
}
if _, err := pluginrt.Refresh(); err != nil {
fmt.Fprintf(os.Stderr, "magpie: plugins.yml: %v\n", err)
}
// the providers and settings read once for every agent's fields, which
// the moves below look at (a write among them reads them again)
release := provider.Hold()
+18 -1
View File
@@ -11,6 +11,7 @@ import (
"github.com/yetone/magpie/internal/middleware"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/provider"
)
@@ -24,7 +25,10 @@ const pluginUsage = `usage: magpie plugin [list] [--json]
magpie plugin login <provider> [<method>] sign in to a provider a plugin adds
magpie plugin logout <provider> forget the sign-in
magpie plugin move|migrate <subscription> run a built-in subscription's accounts on its community plugin
magpie plugin move-back|unmigrate <subscription> go back to the built-in, with its accounts`
magpie plugin move-back|unmigrate <subscription> go back to the built-in, with its accounts
magpie plugin builtin [on|off <id>] list magpie's built-in plugins (Sessions, Library, routing groups…), or turn one on or off
magpie plugin preset essentials|all start the built-in plugins from the Essentials preset, or from all of them
magpie plugin dump [--json] what plugins.yml comes to: each built-in plugin, its config, and the layer each value is from`
// pluginCmd: `magpie plugin …` — OpenCode's provider plugins and pi's
// packages, which sign in to a subscription and carry its requests
@@ -157,6 +161,19 @@ func pluginCmd(args []string) error {
}
fmt.Println(green.Render("✓"), rest[0], "is built-in again")
return nil
case "builtin", "builtins", "built-in":
return builtinCmd(rest)
case "preset":
if len(rest) != 1 {
return errors.New(pluginUsage)
}
if err := pluginrt.SetPreset(rest[0]); err != nil {
return err
}
fmt.Println(green.Render("✓"), "built-in plugins start from", rest[0])
return builtinCmd(nil)
case "dump":
return dumpPlugins(len(rest) > 0 && rest[0] == "--json")
case "help", "-h", "--help":
fmt.Println(pluginUsage)
return nil
+8
View File
@@ -342,6 +342,9 @@ type settingsJSON struct {
Version string `json:"version"`
Dir string `json:"dir"` // where magpie keeps its files, as shown
Gateway string `json:"gateway"` // the local endpoint
// Builtins are the built-in plugins: each one's switch, whether it
// runs and what of it is in use (builtins.go)
Builtins []builtinJSON `json:"builtins"`
// PublicURL is MAGPIE_PUBLIC_URL while other machines are let in
// (shared, or MAGPIE_ADDR on the network): where they reach the
// gateway, shown beside the local address agents here are pointed at
@@ -557,6 +560,7 @@ type searchFailedJSON struct {
func settingsState() settingsJSON {
s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()}
s.AddrEnv = os.Getenv("MAGPIE_ADDR")
s.Builtins = builtinsState()
s.OnNetwork = gateway.OnNetwork()
if list, env := gateway.AllowIPs(); env {
s.AllowIPsEnv, s.AllowIPsFromEnv = os.Getenv(gateway.AllowIPsEnv), list
@@ -778,6 +782,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
if on, _ := gatewayMode(isWeb(w)); on {
boot["gateway"] = true
}
// and the built-in plugins it leaves out (builtins.go), gone
// before the first paint rather than after the settings come
boot["featuresOff"] = builtinsOff(builtinsState())
// on Omarchy the page takes its theme's look before it paints
if th, ok := omarchyTheme(); ok {
boot["omarchy"] = th
@@ -1083,6 +1090,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
cliBehindRoutes(mux)
gatewayFixRoutes(mux)
gatewayModeRoutes(mux)
builtinRoutes(mux)
mux.HandleFunc("GET /api/settings", func(rw http.ResponseWriter, r *http.Request) {
access.MigrateLegacyLANKeyBestEffort()
writeJSON(rw, settingsState())
+5
View File
@@ -2974,6 +2974,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.set-searching .set-page::before { content: attr(data-part); display: block; margin: 4px 2px 6px; font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; color: var(--muted); }
.set-none { margin: 18px 2px; font-size: 13px; color: var(--muted); text-align: center; }
.set-page > .list:not(:last-child) { margin-bottom: 8px; }
/* Plugins › Built-in: what the list is over its rows, and a row in use
saying what uses it under its switch, which can't be turned off */
.feat-say { margin: 2px 4px 10px; font-size: 12px; line-height: 1.45; color: var(--muted); }
.set-searching .feat-say { display: none; }
.row.pref .sub.feat-why { color: var(--muted); font-size: 11px; }
.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); }
+100 -3
View File
@@ -18,6 +18,28 @@ const web = !!window.bootPrefs?.web;
// General turns it off, and they are back.
let gatewayMode = web && !!window.bootPrefs?.gateway;
const GATEWAY_HIDES = ["agents", "library"];
// Plugins › Built-in (builtins.go; Lxxyx on X: too much to look through):
// the optional parts of the window switched off, by id. Whatever is marked
// data-feature="<id>" leaves the page while its feature is off — by a
// style, so what a page draws later goes too — a page's tab leaves the nav
// (navHides), a link to the page opens Agents (show), and Settings and its
// search pass over its rows. boot.js says which before the first paint,
// each read of the settings after (applyFeatures). The gateway is the
// same either way.
let featuresOff = new Set(window.bootPrefs?.featuresOff || []);
const featureSel = () => [...featuresOff].map((id) => `[data-feature~="${id}"]`).join(",");
const featureHides = (n) => { const sel = featureSel(); return !!sel && !!n?.closest(sel); };
function featureStyle() {
let st = document.getElementById("featureStyle");
if (!st) {
st = document.createElement("style");
st.id = "featureStyle";
document.head.append(st);
}
const sel = featureSel();
st.textContent = sel ? sel + "{display:none!important}" : "";
}
featureStyle();
// The window is dragged by its header, and only where the header says so
// (--wails-draggable), so the tabs and buttons in it stay plain clicks.
// Outside the app — a browser on the gateway's page, or on `magpie web` —
@@ -1556,6 +1578,7 @@ function guideCard(g) {
const three = guideStep(3, g.routing, t("Set up routing (optional)"),
g.routing ? g.own.map((x) => x.name || x.id).join(", ") : t("A routing group sends each request to the right model, and to the next one when a model fails"));
three.li.dataset.step = "routing";
three.li.dataset.feature = "groups";
three.li.classList.add("optional");
if (!g.routing && g.source) {
guideLoadGroups();
@@ -11317,6 +11340,8 @@ function renderModels(p) {
const [tk, cb] = tick(t("Only through routing groups"), !!draft.unlisted);
cb.onchange = () => { draft.unlisted = cb.checked; draw(); };
tk.title = t("Its models leave the list agents pick from; the routing groups they are in still use them");
// with routing groups switched off, only while it is ticked: then it is in use
if (!draft.unlisted) tk.dataset.feature = "groups";
if (!decideOnly(p)) box.append(tk);
const lost = el("div", "hint model-hint warn");
box.append(why, lost);
@@ -16844,6 +16869,7 @@ function checkinRow(q, first, subs) {
const r = q.checkin;
const today = wbToday();
const row = el("div", "wb-checkin");
row.dataset.feature = "warmups";
let kind = "", text;
const last = r && r.day !== today && (r.outcome === "claimed" || r.outcome === "done") ? t("last checked in {day}", { day: r.day }) : "";
if (r && r.day === today) {
@@ -20388,6 +20414,7 @@ function sessionItem(s) {
r.append(go);
const open = (e) => {
if (window.getSelection()?.toString()) return;
if (featuresOff.has("sessions")) return; // Sessions is switched off: there is no page to open it on
window.openSessionOnPage?.(s, e);
};
r.onclick = open;
@@ -20689,6 +20716,7 @@ async function loadSettings() {
if (!prefsSettled(since) && prefs) return; // the save draws the page when it's in
// the state's copy too, which the other pages draw from (#1433)
prefs = state.settings = s;
applyFeatures(s.builtins);
// the WebDAV setup can have been changed from outside the window (magpie
// webdav at the terminal): the page's copy of it is dropped, so the page
// is drawn from a fresh read. Coming back to the window is safe with a
@@ -20785,7 +20813,7 @@ const partShows = (page) => {
const rows = [...page.querySelectorAll(".row")];
return !rows.length || rows.some((r) => {
for (let n = r; n && n !== page; n = n.parentElement) if (n.hidden && !n.matches('[role="tabpanel"]')) return false;
return true;
return !featureHides(r);
});
};
function setSetTab(tab, remember) {
@@ -20793,7 +20821,7 @@ function setSetTab(tab, remember) {
setTab = tab;
try { localStorage.setItem("magpie.settingsTab", tab); } catch {}
}
for (const id of SET_TABS) $("#setTab-" + id).hidden = !partShows($("#setPage-" + id));
for (const id of SET_TABS) $("#setTab-" + id).hidden = featureHides($("#setTab-" + id)) || !partShows($("#setPage-" + id));
if (!SET_TABS.includes(tab) || $("#setTab-" + tab).hidden) tab = SET_TABS.find((id) => !$("#setTab-" + id).hidden) || "general";
for (const id of SET_TABS) {
const b = $("#setTab-" + id), on = id === tab;
@@ -20858,6 +20886,7 @@ function findSettings() {
let shows = hit;
for (let a = n; shows && a && a !== page; a = a.parentElement) if (a.hidden && a !== pane) shows = false;
if (shows && pane && $('[aria-controls="' + pane.id + '"]').hidden) shows = false;
if (shows && featureHides(n)) shows = false; // a built-in plugin switched off
if (!shows) continue;
hits++;
lit.add(n.closest(".list") || n.parentElement);
@@ -24041,6 +24070,8 @@ for (const v of document.querySelectorAll(".view")) {
async function show(v) {
// a page gateway mode leaves out (a link to it, an address kept) opens Providers
if (gatewayMode && GATEWAY_HIDES.includes(v)) v = "providers";
// and one a built-in plugin switched off has, Agents
if (featureHides($(`#nav button[data-view="${v}"]`))) v = gatewayMode ? "providers" : "agents";
if (v !== view) {
if (view === "providers" && (editing !== null || importing || importingApps)) {
if (!await cancelEdit(true)) return false;
@@ -24114,11 +24145,76 @@ function setGatewayMode(on) {
gatewayMode = on;
document.body.classList.toggle("gateway-mode", on);
if (mode !== "window") return;
for (const v of GATEWAY_HIDES) $(`#nav button[data-view="${v}"]`).hidden = on;
navHides();
if (on && GATEWAY_HIDES.includes(view)) show("providers");
else if (!sideNav()) slide($("#nav"), "nav");
navSubs();
}
// navHides leaves out the tabs of the pages gateway mode or a built-in
// plugin switched off leaves out
function navHides() {
if (mode !== "window") return;
for (const b of $("#nav").querySelectorAll("button[data-view]")) b.hidden = (gatewayMode && GATEWAY_HIDES.includes(b.dataset.view)) || featureHides(b);
}
// applyFeatures takes the built-in plugins' state from a read of the
// settings, or a switch on Plugins › Built-in:
// what is off leaves the window, and the page open, if it went, gives way
// to Agents (Providers in gateway mode)
function applyFeatures(list) {
if (!Array.isArray(list)) return;
const off = new Set(list.filter((f) => !f.on).map((f) => f.id));
if (off.size === featuresOff.size && [...off].every((id) => featuresOff.has(id))) return;
featuresOff = off;
featureStyle();
if (mode !== "window") return;
navHides();
if (featureHides($(`#nav button[data-view="${view}"]`))) show(gatewayMode ? "providers" : "agents");
else if (!sideNav()) slide($("#nav"), "nav");
setSetTab(setTab);
navSubs();
}
// Plugins › Built-in: a row each, its name, what it is and a switch, kept
// in plugins.yml (builtins.go). One in use can't be switched off, and says
// what uses it; a plugins.yml that doesn't parse says so, and none can be
// switched until it is fixed. done gets the list after a switch.
function renderBuiltins(box, list, done) {
const broken = list.find((f) => f.broken)?.broken;
const rows = list.map((f) => {
const r = el("div", "row pref feat-row");
r.dataset.id = f.id;
const who = el("div", "who");
who.append(el("div", "name", t(f.name)), el("div", "sub", t(f.sub)));
if (f.inUse > 0) who.append(el("div", "sub feat-why", t(f.use, { n: f.inUse })));
const b = el("button", "lib-switch use-credits" + (f.on ? " on" : ""));
b.type = "button";
b.setAttribute("role", "switch");
b.setAttribute("aria-checked", String(f.on));
b.setAttribute("aria-label", t(f.name));
b.append(el("i"));
b.disabled = f.inUse > 0 || !!broken;
if (f.inUse > 0) b.title = t("In use, so it stays on");
b.onclick = async () => {
if (b.disabled) return;
b.disabled = true;
try {
const next = await api("plugins/builtin", { id: f.id, on: !f.on });
if (state.settings) state.settings.builtins = next;
applyFeatures(next);
done(next);
status(t("Saved"), "ok", 1500);
} catch (err) {
b.disabled = false;
status(t(err.message), "err");
}
};
r.append(who, b);
return r;
});
const out = [];
if (broken) out.push(el("p", "feat-say warn", t("plugins.yml can't be read, so every built-in plugin stays as it was: {error}", { error: broken })));
box.replaceChildren(...out, ...rows);
}
window.renderBuiltins = renderBuiltins;
// openSettings: the Settings page, in the window (the panel opens it there)
function openSettings() {
if (mode !== "window") { api("window/main?view=settings", {}); return; }
@@ -25125,6 +25221,7 @@ if (mode === "window" && params.get("view") === "usage") {
for (const k of ["tab", "provider", "agent", "computer", "card", "purpose", "via"]) u.searchParams.delete(k);
history.replaceState(null, "", u);
}
navHides(); // the pages built-in plugins switched off have, from boot.js
// The window opens on the page the reader last left, as a Mac app comes back
// as it was (molvqingtai, lc on Discord): a page asked for (?view=, a link
// from the tray or a reload) first, then the one kept; a page gateway mode
+68
View File
@@ -768,6 +768,23 @@ const I18N = {
"Looks in running WSL distros for agents to set up, their sessions and Claude Code; off, WSL is never asked anything and the agents found there are no longer shown": "在运行中的 WSL 发行版里查找可接入的 Agent、它们的会话和 Claude Code;关闭后不再向 WSL 询问任何内容,之前在那里找到的 Agent 也不再显示",
"Screen on too": "屏幕也常亮",
"Gateway mode": "网关模式",
"Built-in": "内置",
"plugins.yml can't be read, so every built-in plugin stays as it was: {error}": "plugins.yml 读不了,所以每个内置插件都保持原样:{error}",
"Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "不是人人都需要的部分。关掉后,它会从侧边栏、各页面和设置中隐去;magpie 的工作方式不变。",
"Your agents' past conversations: read, search, resume and export them": "Agent 的历史对话:查看、搜索、继续和导出",
"Recording gateway conversations": "正在记录网关对话",
"Instructions, MCP servers, skills and hooks, kept once and given to every agent": "指令、MCP 服务器、技能和 Hooks,统一管理,分发给每个 Agent",
"1 item given to agents": "1 项已分发给 Agent",
"{n} items given to agents": "{n} 项已分发给 Agent",
"Several models agents pick as one: each request goes to the right one, and to the next when one fails": "把几个模型当作一个给 Agent 选:每个请求发给合适的模型,一个失败时换下一个",
"1 group in use": "1 个路由组在用",
"{n} groups in use": "{n} 个路由组在用",
"Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits": "在你选的时间开启订阅的用量窗口,并领取厂商的每日签到额度",
"1 warm-up or check-in on": "1 项预热或签到已开启",
"{n} warm-ups and check-ins on": "{n} 项预热和签到已开启",
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每个请求的追踪和指标发送到 OpenTelemetry 收集器,比如 Langfuse",
"Sending to a collector": "正在发送到收集器",
"In use, so it stays on": "正在使用,因此保持开启",
"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",
@@ -5414,6 +5431,23 @@ const I18N = {
"Looks in running WSL distros for agents to set up, their sessions and Claude Code; off, WSL is never asked anything and the agents found there are no longer shown": "在執行中的 WSL 發行版裡尋找可接入的 Agent、它們的工作階段和 Claude Code;關閉後不再向 WSL 詢問任何內容,之前在那裡找到的 Agent 也不再顯示",
"Screen on too": "螢幕也常亮",
"Gateway mode": "閘道模式",
"Built-in": "內建",
"plugins.yml can't be read, so every built-in plugin stays as it was: {error}": "plugins.yml 讀不了,所以每個內建外掛都保持原樣:{error}",
"Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "不是人人都需要的部分。關掉後,它會從側邊欄、各頁面和設定中隱去;magpie 的運作方式不變。",
"Your agents' past conversations: read, search, resume and export them": "Agent 的歷史對話:檢視、搜尋、繼續和匯出",
"Recording gateway conversations": "正在記錄閘道對話",
"Instructions, MCP servers, skills and hooks, kept once and given to every agent": "指令、MCP 伺服器、技能和 Hooks,統一管理,分發給每個 Agent",
"1 item given to agents": "1 項已分發給 Agent",
"{n} items given to agents": "{n} 項已分發給 Agent",
"Several models agents pick as one: each request goes to the right one, and to the next when one fails": "把幾個模型當作一個給 Agent 選:每個請求發給合適的模型,一個失敗時換下一個",
"1 group in use": "1 個路由組在用",
"{n} groups in use": "{n} 個路由組在用",
"Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits": "在你選的時間開啟訂閱的用量時段,並領取廠商的每日簽到額度",
"1 warm-up or check-in on": "1 項預熱或簽到已開啟",
"{n} warm-ups and check-ins on": "{n} 項預熱和簽到已開啟",
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每個請求的追蹤和指標傳送到 OpenTelemetry 收集器,例如 Langfuse",
"Sending to a collector": "正在傳送到收集器",
"In use, so it stays on": "正在使用,因此保持開啟",
"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",
@@ -10027,6 +10061,23 @@ const I18N = {
"Looks in running WSL distros for agents to set up, their sessions and Claude Code; off, WSL is never asked anything and the agents found there are no longer shown": "実行中の WSL ディストリビューションで、設定できるエージェント、そのセッション、Claude Code を探します。オフにすると WSL には一切問い合わせず、そこで見つかったエージェントも表示しません",
"Screen on too": "画面もオン",
"Gateway mode": "ゲートウェイモード",
"Built-in": "内蔵",
"plugins.yml can't be read, so every built-in plugin stays as it was: {error}": "plugins.yml を読めないため、内蔵プラグインはすべてそのままです:{error}",
"Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "誰もが使うわけではない部分です。オフにすると、サイドバー、各ページ、設定から消えます。magpie の動作は変わりません。",
"Your agents' past conversations: read, search, resume and export them": "エージェントの過去の会話:閲覧、検索、再開、書き出し",
"Recording gateway conversations": "ゲートウェイの会話を記録中",
"Instructions, MCP servers, skills and hooks, kept once and given to every agent": "指示、MCP サーバー、スキル、フックを一か所で管理し、すべてのエージェントに渡します",
"1 item given to agents": "1 件をエージェントに渡しています",
"{n} items given to agents": "{n} 件をエージェントに渡しています",
"Several models agents pick as one: each request goes to the right one, and to the next when one fails": "複数のモデルをエージェントが 1 つとして選べます。各リクエストは適したモデルへ、失敗したら次へ送られます",
"1 group in use": "1 つのグループを使用中",
"{n} groups in use": "{n} 個のグループを使用中",
"Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits": "サブスクリプションの利用枠を選んだ時刻に始め、ベンダーの毎日のチェックイン特典を受け取ります",
"1 warm-up or check-in on": "1 件のウォームアップまたはチェックインがオン",
"{n} warm-ups and check-ins on": "{n} 件のウォームアップとチェックインがオン",
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "各リクエストのトレースとメトリクスを Langfuse などの OpenTelemetry コレクターに送ります",
"Sending to a collector": "コレクターに送信中",
"In use, so it stays on": "使用中のためオンのままです",
"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": "現在オン:このコンピューターにエージェントがありません",
@@ -14657,6 +14708,23 @@ const I18N = {
"Looks in running WSL distros for agents to set up, their sessions and Claude Code; off, WSL is never asked anything and the agents found there are no longer shown": "Sucht in laufenden WSL-Distributionen nach einrichtbaren Agenten, ihren Sitzungen und Claude Code; aus, wird WSL nie etwas gefragt, und die dort gefundenen Agenten werden nicht mehr angezeigt",
"Screen on too": "Bildschirm auch an",
"Gateway mode": "Gateway-Modus",
"Built-in": "Eingebaut",
"plugins.yml can't be read, so every built-in plugin stays as it was: {error}": "plugins.yml lässt sich nicht lesen, daher bleibt jedes eingebaute Plugin, wie es war: {error}",
"Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "Teile von magpie, die nicht jeder braucht. Ausgeschaltet verschwindet ein Teil aus der Seitenleiste, seinen Seiten und den Einstellungen; magpie arbeitet weiter wie bisher.",
"Your agents' past conversations: read, search, resume and export them": "Die bisherigen Unterhaltungen deiner Agenten: lesen, suchen, fortsetzen und exportieren",
"Recording gateway conversations": "Gateway-Unterhaltungen werden aufgezeichnet",
"Instructions, MCP servers, skills and hooks, kept once and given to every agent": "Anweisungen, MCP-Server, Skills und Hooks, einmal gepflegt und an jeden Agenten gegeben",
"1 item given to agents": "1 Eintrag an Agenten gegeben",
"{n} items given to agents": "{n} Einträge an Agenten gegeben",
"Several models agents pick as one: each request goes to the right one, and to the next when one fails": "Mehrere Modelle, die Agenten als eines wählen: Jede Anfrage geht an das passende und beim Ausfall an das nächste",
"1 group in use": "1 Gruppe in Gebrauch",
"{n} groups in use": "{n} Gruppen in Gebrauch",
"Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits": "Das Nutzungsfenster eines Abos zu einer gewählten Zeit starten und die täglichen Check-in-Guthaben der Anbieter abholen",
"1 warm-up or check-in on": "1 Vorwärmen oder Check-in an",
"{n} warm-ups and check-ins on": "{n} Vorwärmen und Check-ins an",
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "Traces und Metriken jeder Anfrage an einen OpenTelemetry-Collector senden, etwa Langfuse",
"Sending to a collector": "Sendet an einen Collector",
"In use, so it stays on": "In Gebrauch, daher bleibt es an",
"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",
+9 -9
View File
@@ -47,8 +47,8 @@
<nav class="seg" id="nav" aria-label="Main navigation" data-ta style="--wails-draggable:no-drag">
<span class="nav-gl" data-t>Work</span>
<button data-view="agents" class="on" aria-current="page"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6l4 4-4 4M10 14h6"/></g></svg><span data-t>Agents</span></button>
<button data-view="sessions"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5h12v8H9l-4 3v-3H4z"/></g></svg><span data-t>Sessions</span></button>
<button data-view="library"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3.5h9v13H5a1.5 1.5 0 0 1 0-3h9"/></g></svg><span data-t>Library</span></button>
<button data-view="sessions" data-feature="sessions"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5h12v8H9l-4 3v-3H4z"/></g></svg><span data-t>Sessions</span></button>
<button data-view="library" data-feature="library"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3.5h9v13H5a1.5 1.5 0 0 1 0-3h9"/></g></svg><span data-t>Library</span></button>
<span class="nav-gl" data-t>Models</span>
<button data-view="providers"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="10" r="3"/><path d="M10 10h7M14 10v3M16.5 10v2"/></g></svg><span data-t>Providers</span></button>
<button data-view="routing"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10h5l4-5h5M8 10l4 5h5M14.5 3l2.5 2-2.5 2M14.5 13l2.5 2-2.5 2"/></g></svg><span data-t>Routing</span></button>
@@ -140,7 +140,7 @@
<main class="view" id="view-routing" hidden>
<div class="row-head"><span class="label" data-t>Routing</span><span class="rt-livedot" aria-hidden="true"></span><span class="note" data-t>live, as the gateway decides</span><span class="grow"></span>
<button class="text rt-newgroup" id="rtNewGroup" type="button" data-tt="Make a routing group of any models you like — agents pick it as one model"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M8 3.5v9M3.5 8h9"/></svg><span data-t>New group</span></button>
<button class="text rt-newgroup" id="rtNewGroup" type="button" data-feature="groups" data-tt="Make a routing group of any models you like — agents pick it as one model"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M8 3.5v9M3.5 8h9"/></svg><span data-t>New group</span></button>
<button class="text rt-mask" id="rtMask" aria-pressed="false" data-tt="Mask the accounts on this page — email addresses and account names — for a screenshot to share"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.9 4.2A10.4 10.4 0 0 1 12 4c6.5 0 10 8 10 8a17.6 17.6 0 0 1-2.2 3.2M6.6 6.6C3.9 8.4 2 12 2 12s3.5 8 10 8a9.7 9.7 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2M2 2l20 20"/></svg><span data-t>Hide accounts</span></button></div>
<section class="rt" id="rt"></section>
<div class="rt-more" id="rtMore"></div>
@@ -250,7 +250,7 @@
<div class="row-head" id="sessListHead" hidden>
<span class="label" data-t>Latest sessions</span>
<span class="grow"></span>
<button class="text sess-all" id="sessAll" type="button" data-t>All sessions</button>
<button class="text sess-all" id="sessAll" type="button" data-feature="sessions" data-t>All sessions</button>
<input class="sess-filter" id="sessQ" type="search" spellcheck="false" autocomplete="off" placeholder="Search sessions" data-tp>
</div>
<div class="list sess-list" id="sessList"></div>
@@ -271,7 +271,7 @@
<button type="button" role="tab" id="setTab-network" data-set="network" aria-controls="setPage-network" data-t>Network and sharing</button>
<button type="button" role="tab" id="setTab-models" data-set="models" aria-controls="setPage-models" data-t>Models</button>
<button type="button" role="tab" id="setTab-privacy" data-set="privacy" aria-controls="setPage-privacy" data-t>Privacy</button>
<button type="button" role="tab" id="setTab-otel" data-set="otel" aria-controls="setPage-otel" data-t>Observability</button>
<button type="button" role="tab" id="setTab-otel" data-set="otel" aria-controls="setPage-otel" data-feature="otel" data-t>Observability</button>
<button type="button" role="tab" id="setTab-sync" data-set="sync" aria-controls="setPage-sync" data-t>Sync and backup</button>
<button type="button" role="tab" id="setTab-about" data-set="about" aria-controls="setPage-about" data-t>About</button>
</div><input class="sess-filter set-q" id="setQ" type="search" spellcheck="false" autocomplete="off" placeholder="Find a setting" aria-label="Find a setting" data-tp></div>
@@ -366,7 +366,7 @@
<div class="who"><div class="name" data-t>Detect agents in WSL</div><div class="sub" data-t>Looks in running WSL distros for agents to set up, their sessions and Claude Code; off, WSL is never asked anything and the agents found there are no longer shown</div></div>
<div id="wslAgentsSegs"></div>
</div>
<div class="row pref" id="sessionTerminalRow" hidden>
<div class="row pref" id="sessionTerminalRow" data-feature="sessions" hidden>
<div class="who"><div class="name" data-t>Session terminal</div><div class="sub" data-t>The terminal a session opens in</div></div>
<button type="button" id="sessionTerminalSelect" class="sess-pick session-terminal-select" aria-label="Session terminal" aria-haspopup="menu" aria-expanded="false" data-ta></button>
</div>
@@ -423,7 +423,7 @@
<div id="turnDoneSegs"></div>
</div>
</div>
<div class="row-head warm-head"><div class="warm-tabs" id="warmTabs" role="tablist">
<div class="row-head warm-head" data-feature="warmups"><div class="warm-tabs" id="warmTabs" role="tablist">
<button type="button" role="tab" id="warmTab-codex" data-warm="codex" aria-controls="codexWarmList">Codex</button>
<button type="button" role="tab" id="warmTab-claude" data-warm="claude" aria-controls="claudeWarmList">Claude Code</button>
<button type="button" role="tab" id="warmTab-wb" data-warm="wb" aria-controls="wbList" hidden>WorkBuddy</button>
@@ -432,7 +432,7 @@
<button type="button" role="tab" id="warmTab-qoder" data-warm="qoder" aria-controls="qoderList" hidden>Qoder</button>
<button type="button" role="tab" id="warmTab-plugins" data-warm="plugins" aria-controls="pluginCheckinList" data-t hidden>Plugins</button>
</div></div>
<div class="warm-panes">
<div class="warm-panes" data-feature="warmups">
<div class="list prefs" id="codexWarmList" role="tabpanel" aria-labelledby="warmTab-codex">
<div class="row pref">
<div class="who"><div class="name" data-t>Warm up on reset</div><div class="sub" id="warmSub"></div></div>
@@ -512,7 +512,7 @@
<div class="row-head"><span class="label" data-t>Agents' sign-ins</span></div>
<div class="list prefs" id="discoveryList"></div>
</section>
<section class="set-page" id="setPage-otel" role="tabpanel" aria-labelledby="setTab-otel">
<section class="set-page" id="setPage-otel" role="tabpanel" aria-labelledby="setTab-otel" data-feature="otel">
<div id="otelList"></div>
</section>
<section class="set-page" id="setPage-sync" role="tabpanel" aria-labelledby="setTab-sync">
+37 -3
View File
@@ -206,6 +206,7 @@
loadMine().then(() => { draw(); window.renderPluginDot?.(); }),
loadListings().then(draw),
loadTagged().then(drawBody),
loadBuiltins(),
providers ? null : loadProviders().then(drawBody, () => {}),
];
await Promise.all(parts);
@@ -655,16 +656,19 @@
function head() {
const n = mine?.plugins?.length || 0;
const tabs = segs([["discover", t("Discover")], ["installed", t("Installed") + (n ? " · " + n : "")]], tab, (id) => {
const tabs = segs([["builtin", t("Built-in")], ["discover", t("Discover")], ["installed", t("Installed") + (n ? " · " + n : "")]], tab, (id) => {
tab = id;
try { localStorage.setItem("magpie.pluginTab", id); } catch {}
searchShown();
drawBody();
});
tabs.classList.add("lib-tabs");
q.placeholder = t("Search plugins and npm…");
if (q.value !== query) q.value = query;
q.setAttribute("aria-label", t("Search plugins"));
replaceKeeping(headBox, [tabs, el("span", "grow"), mirrorSwitch(), find]);
mirror = mirrorSwitch();
replaceKeeping(headBox, [tabs, el("span", "grow"), mirror, find]);
searchShown();
headBox.classList.toggle("stuck", page.scrollTop > 0);
return headBox;
}
@@ -673,6 +677,13 @@
// mirrors in China first (npmmirror, jsDelivr); none before what's
// installed has come, which says how it is set
let mirrorSaving = false;
// the built-in plugins are a short list of switches: nothing to search
// or fetch through a mirror
let mirror = null;
function searchShown() {
find.hidden = tab === "builtin";
if (mirror) mirror.hidden = !mine || tab === "builtin";
}
function mirrorSwitch() {
const on = !!mine?.mirror;
const b = el("button", "pm-mirror" + (on ? " on" : ""));
@@ -734,8 +745,9 @@
shown = key;
// the search field keeps its focus: only the body is redrawn while
// typing, and the GitHub section's field is kept in it
if (tab === "installed" || !listings) body.replaceChildren();
if (tab === "installed" || tab === "builtin" || !listings) body.replaceChildren();
if (tab === "installed") return drawInstalled();
if (tab === "builtin") return drawBuiltin();
if (failedList && !listings) {
body.append(el("p", "pm-empty", t("Couldn't load the plugins: {error}", { error: failedList })));
return;
@@ -864,6 +876,28 @@
return b;
}
// Built-in: magpie's own plugins (Sessions, Library, routing groups…),
// each with a switch (renderBuiltins in app.js), read afresh each time
// the tab is drawn
let builtins = null, builtinsFailed = "";
async function loadBuiltins() {
try {
builtins = await api("plugins/builtin");
builtinsFailed = "";
} catch (e) {
builtinsFailed = e.message;
}
if (tab === "builtin") drawBody();
}
function drawBuiltin() {
const say = el("p", "feat-say", t("Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way."));
const list = el("div", "list prefs");
list.id = "builtinList";
body.append(say, list);
if (builtinsFailed && !builtins) list.append(el("p", "pm-empty", t(builtinsFailed)));
else if (builtins) window.renderBuiltins(list, builtins, (next) => { builtins = next; drawBody(); });
}
function drawInstalled() {
if (failed && !mine) {
body.append(el("p", "pm-empty", t("Couldn't load the plugins: {error}", { error: failed })));
+2
View File
@@ -3164,6 +3164,8 @@
// for the providers' models), so it sits over the groups rather than in
// one group's editor (PAMI on Discord)
const gNames = el("div", "rt-gnames");
// the groups go with the routing groups built-in plugin; the pools stay
for (const n of [gHead, gFound, gNames, gList]) n.dataset.feature = "groups";
gsec.append(gHead, gFound, gNames, gList, pHead, pList);
// after the requests: a request picked in the list plays on the stage,
// so the list sits right under it
+130
View File
@@ -0,0 +1,130 @@
package gui
import (
"encoding/json"
"fmt"
"net/http"
"github.com/yetone/magpie/internal/pluginrt"
)
// Plugins › Built-in (Lxxyx on X: "功能太多了"): magpie's built-in plugins
// (internal/pluginrt, plugins/), each with a switch kept in plugins.yml.
// Off, a plugin's parts leave the window: its page leaves the sidebar and
// the header's tabs, its sections leave the pages they are on, its rows
// leave Settings and Settings' search, and a link to it opens nothing. The
// page hides whatever is marked data-feature="<id>" while the plugin isn't
// active.
//
// One in use stays on: its switch can't be turned off, and its row says
// what uses it. A new install starts with the Essentials preset; one that
// ran before has them all on until the user says otherwise.
// TestBuiltinsTranslated asks each string of every plugin of every
// language.
// builtinJSON is a built-in plugin as the page is told it: whether it
// shows (On: active, which plugins.yml or its use makes it), the user's
// own choice, and what of it is in use.
type builtinJSON struct {
ID string `json:"id"`
Name string `json:"name"`
Sub string `json:"sub"`
On bool `json:"on"`
Chosen bool `json:"chosen"`
Source pluginrt.Source `json:"source"`
State pluginrt.State `json:"state"`
// Why is the reason it isn't running, when it is on and isn't
Why string `json:"why,omitempty"`
InUse int `json:"inUse"`
Use string `json:"use,omitempty"` // One or Many, by InUse
Parts []pluginrt.Part `json:"parts,omitempty"`
// Broken is plugins.yml's error when it can't be read: every
// plugin runs as it did, and no switch can be changed
Broken string `json:"broken,omitempty"`
}
// builtinsState composes plugins.yml again, brings the runtime to it, and
// says every built-in plugin, in their order.
func builtinsState() []builtinJSON {
cs, err := pluginrt.Refresh()
byID := map[string]pluginrt.Composed{}
for _, c := range cs {
byID[c.ID] = c
}
st := map[string]pluginrt.Status{}
if rt := pluginrt.Running(); rt != nil {
for _, s := range rt.Statuses() {
st[s.ID] = s
}
}
out := []builtinJSON{}
for _, m := range pluginrt.Registered() {
c, s := byID[m.ID], st[m.ID]
j := builtinJSON{ID: m.ID, Name: m.Name, Sub: m.Sub, On: s.State == pluginrt.Active, Chosen: c.Chosen, Source: c.Source, State: s.State, Why: s.Why, InUse: c.InUse, Parts: s.Parts}
if err != nil {
j.Broken, j.Chosen = err.Error(), j.On
}
switch {
case j.InUse == 1:
j.Use = m.One
case j.InUse > 1:
j.Use = m.Many
}
out = append(out, j)
}
return out
}
// builtinsOff are the ids of the plugins the window leaves out now, for
// boot.js to hide them before the page paints.
func builtinsOff(list []builtinJSON) []string {
out := []string{}
for _, b := range list {
if !b.On {
out = append(out, b.ID)
}
}
return out
}
// builtinRoutes: GET /api/plugins/builtin is every built-in plugin; POST
// {"id", "on"} switches one, kept in plugins.yml as the user's own choice.
// One in use is refused off.
func builtinRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/plugins/builtin", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, builtinsState())
})
mux.HandleFunc("POST /api/plugins/builtin", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
ID string `json:"id"`
On bool `json:"on"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
var b *builtinJSON
for _, x := range builtinsState() {
if x.ID == in.ID {
b = &x
break
}
}
switch {
case b == nil:
fail(rw, fmt.Errorf("no built-in plugin %q", in.ID))
return
case b.Broken != "":
fail(rw, fmt.Errorf("%s", b.Broken))
return
case !in.On && b.InUse > 0:
fail(rw, fmt.Errorf("%s is in use and stays on", b.Name))
return
}
if err := pluginrt.Set(in.ID, in.On); err != nil {
fail(rw, err)
return
}
writeJSON(rw, builtinsState())
})
}
+149
View File
@@ -0,0 +1,149 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/settings"
_ "github.com/yetone/magpie/plugins/all"
)
func builtinHome(t *testing.T) http.Handler {
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"))
return Handler(nil, nil)
}
func postBuiltin(h http.Handler, body string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/api/plugins/builtin", strings.NewReader(body)))
return rec
}
// A switch is kept in plugins.yml as the user's own choice and the
// runtime follows it; one in use is refused off and stays on; an unknown
// one is refused.
func TestBuiltinSwitch(t *testing.T) {
h := builtinHome(t)
if _, err := pluginrt.Settle(true); err != nil {
t.Fatal(err)
}
if rec := postBuiltin(h, `{"id":"library","on":true}`); rec.Code != http.StatusOK {
t.Fatalf("library on: %d %s", rec.Code, rec.Body)
} else {
var out []builtinJSON
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 5 {
t.Fatalf("the built-ins: %+v", out)
}
for _, b := range out {
if b.On != (b.ID == "library") || b.On != (b.State == pluginrt.Active) {
t.Fatalf("after library on: %+v", out)
}
}
}
if !pluginrt.Running().Active("library") || pluginrt.Running().Active("sessions") {
t.Fatalf("the runtime: %+v", pluginrt.Running().Statuses())
}
if rec := postBuiltin(h, `{"id":"nope","on":true}`); rec.Code != http.StatusBadRequest {
t.Fatalf("an unknown plugin: %d", rec.Code)
}
// Observability in use: sending to a collector
s := settings.Load()
s.OTel.Enabled = true
s.OTel.Endpoint = "http://127.0.0.1:4318"
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if rec := postBuiltin(h, `{"id":"otel","on":false}`); rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "in use") {
t.Fatalf("otel off while in use: %d %s", rec.Code, rec.Body)
}
for _, b := range builtinsState() {
if b.ID == "otel" && (!b.On || b.Chosen || b.InUse != 1 || b.Use != "Sending to a collector" || b.Source != pluginrt.FromInUse) {
t.Fatalf("otel in use: %+v", b)
}
}
}
// A plugins.yml that doesn't parse leaves every plugin on, says so, and
// no switch writes over it.
func TestBuiltinBrokenFile(t *testing.T) {
h := builtinHome(t)
if err := os.MkdirAll(filepath.Dir(pluginrt.Path()), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(pluginrt.Path(), []byte("plugins: [\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, b := range builtinsState() {
if b.Broken == "" {
t.Fatalf("not told broken: %+v", b)
}
}
if rec := postBuiltin(h, `{"id":"library","on":false}`); rec.Code != http.StatusBadRequest {
t.Fatalf("switched over a broken file: %d", rec.Code)
}
if b, _ := os.ReadFile(pluginrt.Path()); string(b) != "plugins: [\n" {
t.Fatalf("written over: %q", b)
}
}
// boot.js says what is off before the page paints: everything for a new
// install, nothing for one that ran before.
func TestBootSaysBuiltinsOff(t *testing.T) {
h := builtinHome(t)
boot := func() string {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/boot.js", nil))
return rec.Body.String()
}
if _, err := pluginrt.Settle(false); err != nil {
t.Fatal(err)
}
if b := boot(); !strings.Contains(b, `"featuresOff":[]`) {
t.Fatalf("an existing user: %s", b)
}
if err := pluginrt.SetPreset(pluginrt.PresetEssentials); err != nil {
t.Fatal(err)
}
if err := pluginrt.Set("library", true); err != nil {
t.Fatal(err)
}
if b := boot(); !strings.Contains(b, `"featuresOff":["groups","otel","sessions","warmups"]`) {
t.Fatalf("a new install: %s", b)
}
}
// Every string of every built-in plugin is said in every language.
func TestBuiltinsTranslated(t *testing.T) {
src, err := os.ReadFile("assets/i18n.js")
if err != nil {
t.Fatal(err)
}
for _, lang := range []string{"zh: {", `"zh-TW": {`, "ja: {", "de: {"} {
_, block, ok := strings.Cut(string(src), "\n "+lang+"\n")
if !ok {
t.Fatalf("no %s block", lang)
}
block, _, _ = strings.Cut(block, "\n },")
for _, m := range pluginrt.Registered() {
for _, s := range []string{m.Name, m.Sub, m.One, m.Many} {
k, _ := json.Marshal(s)
if !strings.Contains(block, "\n "+string(k)+": ") {
t.Errorf("%s doesn't say %s", lang, k)
}
}
}
}
}
+192
View File
@@ -0,0 +1,192 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Plugins › Built-in (Lxxyx on X: too much to look through): magpie's
// built-in plugins (internal/pluginrt, plugins/), each with a switch kept in
// plugins.yml. Off, a plugin's parts leave the window: its page leaves the
// nav — the sidebar's and the header's — and an address kept for it opens
// Agents, its Settings tab goes. One in use can't be switched off: its
// switch is on and disabled and its row says what uses it, in the page's
// language. Switched on, a page's tab is back at once. A plugins.yml that
// doesn't parse says so and no switch moves. The tab is first on the
// Plugins page, with no search field. Every language, both layouts and a
// narrow window; no backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
// as plugins/*'s manifests say them, in pluginrt.Registered's order (by id)
const PLUGINS = [
{ id: "groups", name: "Routing groups", sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails", one: "1 group in use", many: "{n} groups in use" },
{ id: "library", name: "Library", sub: "Instructions, MCP servers, skills and hooks, kept once and given to every agent", one: "1 item given to agents", many: "{n} items given to agents" },
{ id: "otel", name: "Observability", sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse", one: "Sending to a collector", many: "Sending to a collector" },
{ id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" },
{ id: "warmups", name: "Warm-up and check-in", sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits", one: "1 warm-up or check-in on", many: "{n} warm-ups and check-ins on" },
];
// a new install's (the Essentials preset): all off, but two routing groups
// the user made
const START = { groups: [false, 2], library: [false, 0], otel: [false, 0], sessions: [false, 0], warmups: [false, 0] };
function builtins(st, broken) {
return PLUGINS.map((p) => {
const [chosen, inUse] = st[p.id];
const on = chosen || inUse > 0;
return { id: p.id, name: p.name, sub: p.sub, on, chosen, source: inUse > 0 && !chosen ? "in use" : "preset", state: on ? "active" : "off", inUse, use: inUse === 1 ? p.one : inUse > 1 ? p.many : undefined, broken };
});
}
function server(lang, posts, broken) {
const st = structuredClone(START);
const list = () => builtins(st, broken);
const cur = () => ({
theme: "light", lang, tray: "panel", currency: "usd", textSize: 100, redactWords: [],
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "",
version: "0.1.400", dir: "/config/home/.config/magpie", gateway: "http://127.0.0.1:3425",
proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
builtins: list(),
});
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") {
const off = list().filter((f) => !f.on).map((f) => f.id);
return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",featuresOff:${JSON.stringify(off)}};` });
}
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: cur(), fx: cur().fx });
if (url.pathname === "/api/plugins/builtin") {
if (req.method() !== "POST") return json(list());
const { id, on } = req.postDataJSON();
posts.push([id, on]);
if (broken || (!on && st[id][1] > 0)) return route.fulfill({ status: 400, json: { error: "in use" } });
st[id][0] = on;
return json(list());
}
if (url.pathname === "/api/settings") return json(cur());
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
if (url.pathname === "/api/plugins") return json({ bun: true, bunVersion: "1.4.2", plugins: [], picker: false, movable: [] });
if (url.pathname === "/api/plugins/listings") return json({ listings: [] });
if (url.pathname === "/api/plugins/github") return json({ repos: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
if (url.pathname.startsWith("/api/")) return json({});
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: "" }); }
};
}
// the pages' tabs shown, the page shown
const tabs = (page) => page.evaluate(() => [...document.querySelectorAll("#nav button[data-view]")].filter((b) => !b.hidden && b.offsetParent && getComputedStyle(b).display !== "none").map((b) => b.dataset.view));
const viewShown = (page) => page.evaluate(() => [...document.querySelectorAll("main.view")].filter((v) => !v.hidden).map((v) => v.id));
const KEPT = ["agents", "providers", "routing", "gateway", "usage", "plugins"];
const rowsOf = (page) => page.evaluate(() => [...document.querySelectorAll("#builtinList .feat-row")].map((r) => {
const b = r.querySelector('[role="switch"]');
return { id: r.dataset.id, name: r.querySelector(".name").textContent, on: b.getAttribute("aria-checked"), disabled: b.disabled, why: r.querySelector(".feat-why")?.textContent || "" };
}));
// the Plugins page's tabs: the sidebar's, from 1024 points, or the page's
// own strip
const pluginTabs = (page, side) => page.locator(side ? ".nav-sub:not(.leaving) .nav-s" : "#view-plugins .lib-tabs .opt");
async function builtinTab(page, side) {
await pluginTabs(page, side).first().click();
await page.waitForSelector("#builtinList .feat-row");
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: Plugins › Built-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"]) {
// the sidebar from 1024 points, the header's tabs under it, and narrow
for (const width of [1100, 800, 420]) {
const where = `${engine} ${lang} ${width}`;
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts));
await page.goto("http://magpie.test/?view=sessions");
await page.waitForSelector("#nav button.on");
const side = await page.evaluate(() => document.body.classList.contains("side-nav"));
assert.equal(side, width >= 1024, `${where}: the layout`);
if (width >= 800) assert.deepEqual(await tabs(page), KEPT, `${where}: Sessions' and Library's tabs gone`);
// an address kept for a page switched off opens Agents
assert.deepEqual(await viewShown(page), ["view-agents"], `${where}: ?view=sessions`);
// Settings has no Features tab of its own, and Observability's is off
assert.equal(await page.locator("#setTab-features").count(), 0, `${where}: no Settings › Features`);
assert.ok(await page.locator("#setTab-otel").isHidden(), `${where}: Observability's tab, off`);
await page.goto("http://magpie.test/?view=plugins");
await pluginTabs(page, side).first().waitFor();
// Built-in first, in the page's language
const first = (await pluginTabs(page, side).first().textContent()).trim();
assert.equal(first, await page.evaluate(() => t("Built-in")), where);
if (lang !== "en") assert.notEqual(first, "Built-in", `${where}: Built-in translated`);
await builtinTab(page, side);
assert.ok(await page.locator("#view-plugins .pm-find").isHidden(), `${where}: no search on Built-in`);
const rows = await rowsOf(page);
const want = await page.evaluate((ps) => ps.map((p) => ({ id: p.id, name: t(p.name) })), PLUGINS);
assert.deepEqual(rows.map((r) => ({ id: r.id, name: r.name })), want, `${where}: a row each, by the table`);
// the groups in use: on, can't be switched off, saying why
const g = rows.find((r) => r.id === "groups");
assert.deepEqual([g.on, g.disabled], ["true", true], `${where}: in use, locked`);
assert.equal(g.why, await page.evaluate(() => t("{n} groups in use", { n: 2 })), where);
if (lang !== "en") assert.notEqual(g.why, "2 groups in use", `${where}: why translated`);
for (const r of rows.filter((r) => r.id !== "groups")) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true });
await page.waitForTimeout(100);
assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`);
// nothing wider than the window
assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-plugins"); return v.scrollWidth <= v.clientWidth + 1; }), `${where}: fits`);
// Library switched on: its tab is back at once, the page stays
await page.locator('#builtinList [data-id="library"] [role="switch"]').click();
await page.waitForSelector('#builtinList [data-id="library"] [aria-checked="true"]');
assert.deepEqual(posts, [["library", true]], where);
if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1)], `${where}: Library back`);
assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`);
// and Observability: its Settings tab is back
await page.locator('#builtinList [data-id="otel"] [role="switch"]').click();
await page.waitForSelector('#builtinList [data-id="otel"] [aria-checked="true"]');
assert.ok(await page.locator("#setTab-otel").evaluate((b) => getComputedStyle(b).display !== "none"), `${where}: Observability back`);
// Discover brings the search back
await pluginTabs(page, side).nth(1).click();
assert.ok(await page.locator("#view-plugins .pm-find").isVisible(), `${where}: search on Discover`);
assert.deepEqual(errors, [], where);
await context.close();
}
}
});
test(`${engine}: Plugins › Built-in, plugins.yml broken`, 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"]) {
const where = `${engine} ${lang}`;
const context = await browser.newContext({ viewport: { width: 420, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts, "/config/plugins.yml doesn't parse: yaml: line 2"));
await page.goto("http://magpie.test/?view=plugins");
await builtinTab(page, false);
const say = await page.locator("#builtinList .feat-say.warn").textContent();
assert.ok(say.includes("yaml: line 2"), `${where}: says the error`);
if (lang !== "en") assert.ok(!say.startsWith("plugins.yml can't be read"), `${where}: translated`);
for (const r of await rowsOf(page)) assert.equal(r.disabled, true, `${where}: ${r.id} can't be switched`);
await page.locator('#builtinList [data-id="library"] [role="switch"]').click({ force: true });
await page.waitForTimeout(100);
assert.deepEqual(posts, [], `${where}: no switch posts`);
assert.deepEqual(errors, [], where);
await context.close();
}
});
}
+1 -1
View File
@@ -134,7 +134,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const pluginNames = () => names("#view-plugins .pm-list .pm-row > .who > .name > span:first-child");
const openPlugins = async () => {
await page.goto("http://magpie.test/?view=plugins");
await page.locator(":is(#view-plugins .lib-tabs .opt, .nav-s):visible").nth(1).click();
await page.locator(":is(#view-plugins .lib-tabs .opt, .nav-s):visible").nth(2).click(); // Built-in, Discover, Installed
await page.locator("#view-plugins .pm-row").first().waitFor();
};
await openPlugins();
+8
View File
@@ -331,6 +331,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
}, addedFooter.height);
addedFooter = await current.locator("#agentsManage").boundingBox();
}
// Plugins' Built-in tab is new: until BASE_REF has it, the
// page is compared with that tab taken out of its strip (the
// sidebar's list follows the strip); builtins.test.cjs covers
// the tab and its list.
if (view === "plugins" && !baselineFile("plugins.js").includes("function drawBuiltin")) {
await current.locator("#view-plugins .lib-tabs .opt").first().evaluate((b) => b.remove());
await current.waitForTimeout(350);
}
const before = PNG.sync.read(await still(original));
const after = PNG.sync.read(await still(current));
const sameSize = before.width === after.width && before.height === after.height;
+18
View File
@@ -248,3 +248,21 @@ func Restore(s *Setup) (*Result, error) {
}
return res, err
}
// InUse counts what the library gives agents: each server, skill, hook
// and project folder it keeps, and the shared instructions while an agent
// gets them. The library built-in plugin stays on while it is
// more than 0. A library.json that can't be read is an error, never 0.
func InUse() (int, error) {
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return 0, err
}
n := len(l.MCP) + len(l.Skills) + len(l.Hooks) + len(l.Projects)
if len(l.Instructions.Agents) > 0 {
n++
}
return n, nil
}
+302
View File
@@ -0,0 +1,302 @@
package pluginrt
import (
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"sync"
"gopkg.in/yaml.v3"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/filelock"
)
// plugins.yml says which built-in plugins are on, and each one's config:
//
// preset: essentials # or all
// plugins:
// - id: groups
// enabled: true
// config: {}
//
// What a plugin runs with is composed, field by field, from three layers:
// the built-in default (every plugin on, its Manifest.Defaults), the
// preset (Essentials leaves the plugins not Essential off), then the
// user's own rows. A plugin in use (Manifest.InUse) is on whatever they
// say. `magpie plugin dump` shows the result and where each value came
// from.
//
// A new install is written the Essentials preset, a magpie that ran here
// before All (Settle), so an existing user keeps everything they had.
// Presets a plugins.yml can name.
const (
PresetEssentials = "essentials"
PresetAll = "all"
)
// File is plugins.yml as written.
type File struct {
Preset string `yaml:"preset,omitempty"`
Plugins []Row `yaml:"plugins,omitempty"`
}
// Row is the user's own say about one plugin: only what they set.
type Row struct {
ID string `yaml:"id"`
Enabled *bool `yaml:"enabled,omitempty"`
Config map[string]any `yaml:"config,omitempty"`
}
// Path is plugins.yml, in magpie's folder.
func Path() string { return filepath.Join(appdir.Config(), "plugins.yml") }
var (
inProcess sync.Mutex // filelock.Mutex holds other magpies off; this, this one's goroutines
fileLock = filelock.Mutex{Path: func() string { return Path() + ".lock" }}
)
// Load reads plugins.yml. A file not there is (File{}, false, nil): the
// default layers alone. One that can't be read or doesn't parse is an
// error, never an empty file.
func Load() (File, bool, error) {
b, err := os.ReadFile(Path())
if errors.Is(err, os.ErrNotExist) {
return File{}, false, nil
}
if err != nil {
return File{}, true, err
}
var f File
if err := yaml.Unmarshal(b, &f); err != nil {
return File{}, true, fmt.Errorf("%s doesn't parse: %w", Path(), err)
}
switch f.Preset {
case "", PresetAll, PresetEssentials:
default:
return File{}, true, fmt.Errorf("%s: no preset %q (essentials or all)", Path(), f.Preset)
}
return f, true, nil
}
// Source says which layer a composed value came from.
type Source string
const (
FromDefault Source = "default"
FromPreset Source = "preset"
FromUser Source = "user"
FromInUse Source = "in use"
)
// Composed is one plugin as plugins.yml and its use make it.
type Composed struct {
ID string `json:"id" yaml:"id"`
Enabled bool `json:"enabled" yaml:"enabled"`
Source Source `json:"source" yaml:"source"`
Chosen bool `json:"chosen" yaml:"chosen"` // plugins.yml's say, before what is in use
InUse int `json:"inUse" yaml:"inUse,omitempty"`
Config map[string]any `json:"config,omitempty" yaml:"config,omitempty"`
Sources map[string]Source `json:"configSources,omitempty" yaml:"configSources,omitempty"`
}
// Compose layers f over the defaults for each manifest, in ms' order.
func Compose(ms []Manifest, f File) []Composed {
rows := map[string]Row{}
for _, r := range f.Plugins {
rows[r.ID] = r
}
out := make([]Composed, 0, len(ms))
for _, m := range ms {
c := Composed{ID: m.ID, Enabled: true, Source: FromDefault, Config: map[string]any{}, Sources: map[string]Source{}}
for k, v := range m.Defaults {
c.Config[k], c.Sources[k] = v, FromDefault
}
if f.Preset == PresetEssentials && !m.Essential {
c.Enabled, c.Source = false, FromPreset
}
if r, ok := rows[m.ID]; ok {
if r.Enabled != nil {
c.Enabled, c.Source = *r.Enabled, FromUser
}
for k, v := range r.Config {
c.Config[k], c.Sources[k] = merge(c.Config[k], v), FromUser
}
}
c.Chosen = c.Enabled
if m.InUse != nil {
n, err := m.InUse()
if err != nil {
n = 1 // can't be told: unknown is never unused
}
c.InUse = n
if n > 0 && !c.Enabled {
c.Enabled, c.Source = true, FromInUse
}
}
if len(c.Config) == 0 {
c.Config, c.Sources = nil, nil
}
out = append(out, c)
}
return out
}
// merge lays the user's value over the one under it: a map key by key,
// anything else whole.
func merge(under, over any) any {
u, ok1 := under.(map[string]any)
o, ok2 := over.(map[string]any)
if !ok1 || !ok2 {
return over
}
out := maps.Clone(u)
for k, v := range o {
out[k] = merge(out[k], v)
}
return out
}
// Settle writes a first plugins.yml when there is none: the Essentials
// preset on a new install, All on a magpie that ran here before. It says
// whether it wrote one. A plugins.yml there, or one that can't be looked
// at, is left as it is.
func Settle(newInstall bool) (bool, error) {
inProcess.Lock()
defer inProcess.Unlock()
fileLock.Lock()
defer fileLock.Unlock()
if _, err := os.Lstat(Path()); !errors.Is(err, os.ErrNotExist) {
return false, nil
}
f := File{Preset: PresetAll}
if newInstall {
f.Preset = PresetEssentials
}
return true, write(f)
}
// Set turns plugin id on or off as the user's own choice, keeping the rest
// of plugins.yml as it was. A plugins.yml that doesn't parse is not
// written over: the user fixes it, or removes it.
func Set(id string, on bool) error {
return update(func(f *File) {
i := slices.IndexFunc(f.Plugins, func(r Row) bool { return r.ID == id })
if i < 0 {
f.Plugins = append(f.Plugins, Row{ID: id})
i = len(f.Plugins) - 1
}
f.Plugins[i].Enabled = &on
})
}
// SetPreset changes the preset, keeping the user's own rows.
func SetPreset(preset string) error {
if preset != PresetAll && preset != PresetEssentials {
return fmt.Errorf("no preset %q (essentials or all)", preset)
}
return update(func(f *File) { f.Preset = preset })
}
func update(change func(*File)) error {
inProcess.Lock()
defer inProcess.Unlock()
fileLock.Lock()
defer fileLock.Unlock()
f, _, err := Load()
if err != nil {
return err
}
change(&f)
return write(f)
}
const header = "# magpie's built-in plugins: which are on, and each one's config.\n" +
"# `magpie plugin dump` shows what they come to, and where each value is from.\n"
// write puts f in plugins.yml whole or not at all, the file it replaces
// kept as plugins.yml.bak. Called with the locks held.
func write(f File) error {
b, err := yaml.Marshal(f)
if err != nil {
return err
}
b = append([]byte(header), b...)
path := Path()
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
if old, err := os.ReadFile(path); err == nil {
if err := os.WriteFile(path+".bak", old, 0o600); err != nil {
return fmt.Errorf("keeping %s before writing it: %w", path, err)
}
}
tmp, err := os.CreateTemp(filepath.Dir(path), ".plugins.yml-*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(b); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
var (
defMu sync.Mutex
def *Runtime
)
// Refresh composes plugins.yml with the registered plugins and brings the
// process's runtime to it, made on the first call. A plugins.yml that
// can't be read leaves the runtime as it was (every plugin on, before the
// first good read) and is returned.
func Refresh() ([]Composed, error) {
defMu.Lock()
defer defMu.Unlock()
ms := Registered()
if def == nil {
def = New(ms)
}
f, _, err := Load()
if err != nil {
if !def.reconciled {
def.Reconcile(allOn(ms), nil)
}
return nil, err
}
cs := Compose(ms, f)
on, config := map[string]bool{}, map[string]map[string]any{}
for _, c := range cs {
on[c.ID], config[c.ID] = c.Enabled, c.Config
}
def.Reconcile(on, config)
return cs, nil
}
func allOn(ms []Manifest) map[string]bool {
on := map[string]bool{}
for _, m := range ms {
on[m.ID] = true
}
return on
}
// Running is the process's runtime, nil before the first Refresh.
func Running() *Runtime {
defMu.Lock()
defer defMu.Unlock()
return def
}
+127
View File
@@ -0,0 +1,127 @@
package pluginrt
import (
"os"
"reflect"
"strings"
"testing"
)
func home(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("MAGPIE_PORTABLE", "")
}
var three = []Manifest{
{ID: "core", Essential: true, Defaults: map[string]any{"n": 1, "deep": map[string]any{"a": 1, "b": 2}}},
{ID: "extra"},
{ID: "used", InUse: func() (int, error) { return 2, nil }},
}
func byID(cs []Composed) map[string]Composed {
m := map[string]Composed{}
for _, c := range cs {
m[c.ID] = c
}
return m
}
// The layers, field by field: the default, the preset, the user's rows,
// and in use over them all; each value says where it came from.
func TestCompose(t *testing.T) {
no := false
cs := byID(Compose(three, File{Preset: PresetEssentials, Plugins: []Row{
{ID: "core", Config: map[string]any{"deep": map[string]any{"b": 3}}},
{ID: "used", Enabled: &no},
}}))
if c := cs["core"]; !c.Enabled || c.Source != FromDefault {
t.Errorf("core: %+v", c)
}
if c := cs["core"]; !reflect.DeepEqual(c.Config, map[string]any{"n": 1, "deep": map[string]any{"a": 1, "b": 3}}) || c.Sources["deep"] != FromUser || c.Sources["n"] != FromDefault {
t.Errorf("core's config: %+v %+v", c.Config, c.Sources)
}
if c := cs["extra"]; c.Enabled || c.Source != FromPreset {
t.Errorf("extra under Essentials: %+v", c)
}
if c := cs["used"]; !c.Enabled || c.Chosen || c.Source != FromInUse || c.InUse != 2 {
t.Errorf("used, turned off: %+v", c)
}
// All, or no file at all: every one on
for _, f := range []File{{Preset: PresetAll}, {}} {
for _, c := range Compose(three, f) {
if !c.Enabled {
t.Errorf("%q: %s off", f.Preset, c.ID)
}
}
}
}
// A new install is written Essentials, one that ran before All; the file
// there is never written over by Settle; Set keeps the other rows and the
// preset, and the file it replaces is kept beside it.
func TestSettleAndSet(t *testing.T) {
home(t)
if wrote, err := Settle(true); err != nil || !wrote {
t.Fatalf("settle: %v %v", wrote, err)
}
if f, there, err := Load(); err != nil || !there || f.Preset != PresetEssentials {
t.Fatalf("after settle: %+v %v %v", f, there, err)
}
if wrote, _ := Settle(false); wrote {
t.Fatal("settled over a plugins.yml there")
}
if err := Set("extra", true); err != nil {
t.Fatal(err)
}
if err := Set("used", false); err != nil {
t.Fatal(err)
}
if err := Set("extra", false); err != nil {
t.Fatal(err)
}
f, _, err := Load()
if err != nil || f.Preset != PresetEssentials || len(f.Plugins) != 2 || *f.Plugins[0].Enabled || f.Plugins[0].ID != "extra" {
t.Fatalf("after sets: %+v %v", f, err)
}
if _, err := os.Stat(Path() + ".bak"); err != nil {
t.Fatalf("no .bak: %v", err)
}
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if wrote, _ := Settle(false); !wrote {
t.Fatal("not settled")
}
if f, _, _ := Load(); f.Preset != PresetAll {
t.Fatalf("an existing user: %+v", f)
}
}
// A plugins.yml that doesn't parse is an error, never an empty file, and
// is never written over.
func TestBrokenFileIsKept(t *testing.T) {
home(t)
if err := os.MkdirAll(strings.TrimSuffix(Path(), "/plugins.yml"), 0o700); err != nil {
t.Fatal(err)
}
broken := []byte("plugins: [ {id: x\n")
if err := os.WriteFile(Path(), broken, 0o600); err != nil {
t.Fatal(err)
}
if _, _, err := Load(); err == nil {
t.Fatal("a broken file read")
}
if err := Set("x", true); err == nil {
t.Fatal("a broken file written")
}
if wrote, _ := Settle(true); wrote {
t.Fatal("a broken file settled over")
}
if b, _ := os.ReadFile(Path()); string(b) != string(broken) {
t.Fatalf("the broken file changed: %q", b)
}
if err := os.WriteFile(Path(), []byte("preset: slim\n"), 0o600); err != nil {
t.Fatal(err)
}
if _, _, err := Load(); err == nil || !strings.Contains(err.Error(), "slim") {
t.Fatalf("an unknown preset: %v", err)
}
}
+388
View File
@@ -0,0 +1,388 @@
// Package pluginrt runs magpie's built-in plugins: the parts of magpie not
// everyone needs (Lxxyx on X: "功能太多了"), each one a package under
// plugins/ that registers a Manifest. The runtime applies the ones the user
// has on (plugins.yml, see config.go) in the order their Requires and
// Provides make, and disposes of what each registered, in reverse, when it
// is turned off. One that fails or panics is FAILED and the rest run on.
//
// The runtime is core: it never imports a plugin, and a plugin never
// imports another (TestPluginsImportOnlyCore). Plugins reach each other
// only through the services they Provide.
package pluginrt
import (
"fmt"
"log"
"slices"
"sort"
"strconv"
"strings"
"sync"
)
// API is the host API plugins are written against. A plugin's
// Manifest.API is a caret range ("^1", "^1.2"): the same major, and a
// minor no newer than this one's. One that doesn't match isn't applied.
const API = "1.0"
// Core are the services magpie itself provides, which a plugin may
// Require without another plugin providing them.
var Core = []string{"settings", "providers", "gateway", "window"}
// Manifest is a built-in plugin: what it is, what it needs and gives, and
// Apply, which registers its parts through the Ctx.
type Manifest struct {
ID string
API string // the host API range it is written for, "^1"
// Requires are services it can't run without; Provides those it gives
// others ("router.strategy/groups")
Requires, Provides []string
// Essential plugins are on in the Essentials preset a new install
// starts with; every built-in is on for a magpie that ran before
Essential bool
// Name and Sub say what it is, in English; the window translates them
Name, Sub string
// One and Many say what of it is in use, of 1 or of {n}
One, Many string
// InUse counts what the user has made with it (groups, warm-ups, items
// given to agents). One in use stays on whatever plugins.yml says: off,
// its things would go on working with nowhere to see or change them.
// An error counts as in use: unknown is never unused.
InUse func() (int, error)
// Apply registers the plugin's parts; nil is a plugin of parts only
// (Contribute) that does nothing else
Apply func(*Ctx) error
// Parts are the window's parts it is, by slot: "nav.page" sessions,
// "settings.section" otel, "part" groups (whatever the page marks
// data-feature="<id>"). The runtime contributes them before Apply.
Parts []Part
// Defaults is its config before plugins.yml's preset and rows
Defaults map[string]any
}
// Part is one thing a plugin puts in the window: a Slot and a Key in it.
type Part struct{ Slot, Key string }
// State is where a plugin is in its life.
type State string
const (
Off State = "off" // turned off in plugins.yml
Pending State = "pending" // on, waiting for a service no active plugin provides
Active State = "active" // applied
Failed State = "failed" // Apply returned an error or panicked
Disposed State = "disposed" // turned off at run time, its parts gone
)
// Ctx is what a plugin's Apply is handed. Everything registered through it
// is undone when the plugin is turned off, in reverse.
type Ctx struct {
ID string
Config map[string]any // the composed config, read only
rt *Runtime
disposes []func()
parts []Part
provided []string
}
// OnDispose runs f when the plugin is turned off or magpie stops.
func (c *Ctx) OnDispose(f func()) { c.disposes = append(c.disposes, f) }
// Contribute puts a part in the window while the plugin is active.
func (c *Ctx) Contribute(slot, key string) {
c.parts = append(c.parts, Part{slot, key})
}
// Provide gives a service other plugins may Require. It is withdrawn when
// the plugin is turned off.
func (c *Ctx) Provide(name string, v any) {
c.rt.services[name] = v
c.provided = append(c.provided, name)
c.OnDispose(func() { delete(c.rt.services, name) })
}
// Service is a service a plugin Provides, or nil.
func (c *Ctx) Service(name string) any { return c.rt.services[name] }
var (
regMu sync.Mutex
registry = map[string]Manifest{}
)
// Register adds a built-in plugin; plugins call it from init. Two with one
// id is a programming error.
func Register(m Manifest) {
regMu.Lock()
defer regMu.Unlock()
if m.ID == "" {
panic("pluginrt: a plugin with no id")
}
if _, dup := registry[m.ID]; dup {
panic("pluginrt: two plugins " + m.ID)
}
registry[m.ID] = m
}
// Registered are the built-in plugins, by id.
func Registered() []Manifest {
regMu.Lock()
defer regMu.Unlock()
out := make([]Manifest, 0, len(registry))
for _, m := range registry {
out = append(out, m)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// Status is one plugin as it runs now.
type Status struct {
ID string `json:"id"`
State State `json:"state"`
// Why says what kept it from Active: the service it waits for, the
// error it failed with, the API it wants
Why string `json:"why,omitempty"`
Parts []Part `json:"parts,omitempty"`
}
type running struct {
m Manifest
state State
why string
ctx *Ctx
wanted bool
}
// Runtime applies the plugins that are on and keeps what each registered.
type Runtime struct {
mu sync.Mutex
plugins map[string]*running
order []string // applied order, for disposing in reverse
services map[string]any
// reconciled is set once Reconcile has run
reconciled bool
}
// New is a runtime of the registered plugins, none applied yet.
func New(ms []Manifest) *Runtime {
rt := &Runtime{plugins: map[string]*running{}, services: map[string]any{}}
for _, s := range Core {
rt.services[s] = struct{}{}
}
for _, m := range ms {
rt.plugins[m.ID] = &running{m: m, state: Off}
}
return rt
}
// Reconcile brings the runtime to on: each plugin wanted and not active is
// applied, once what it requires is provided; each active one no longer
// wanted is disposed, with whatever requires a service it provided. on
// says, by id, whether a plugin is wanted; config is each one's composed
// config.
func (rt *Runtime) Reconcile(on map[string]bool, config map[string]map[string]any) {
rt.mu.Lock()
defer rt.mu.Unlock()
rt.reconciled = true
for id, p := range rt.plugins {
p.wanted = on[id]
}
// off first: each one no longer wanted, and each that requires a
// service one of those provided, newest first, so a service is
// withdrawn after its users
going := map[string]bool{}
for {
more := false
for _, id := range rt.order {
p := rt.plugins[id]
if going[id] {
continue
}
if !p.wanted || rt.needsGoing(p, going) {
going[id], more = true, true
}
}
if !more {
break
}
}
for i := len(rt.order) - 1; i >= 0; i-- {
if id := rt.order[i]; going[id] {
rt.dispose(rt.plugins[id])
}
}
// then on, as long as one more can be applied
ids := make([]string, 0, len(rt.plugins))
for id := range rt.plugins {
ids = append(ids, id)
}
sort.Strings(ids)
for {
applied := false
for _, id := range ids {
p := rt.plugins[id]
if !p.wanted || p.state == Active || p.state == Failed {
continue
}
if !Compatible(p.m.API) {
p.state, p.why = Failed, fmt.Sprintf("written for host API %s, this is %s", p.m.API, API)
continue
}
if !rt.satisfied(p.m) {
p.state, p.why = Pending, "waiting for "+strings.Join(rt.missing(p.m), ", ")
continue
}
rt.apply(p, config[id])
applied = applied || p.state == Active
}
if !applied {
break
}
}
for _, p := range rt.plugins {
if !p.wanted && p.state != Disposed {
p.state, p.why = Off, ""
}
if p.state == Pending {
log.Printf("plugins: %s is on but %s", p.m.ID, p.why)
}
}
}
// needsGoing is whether p requires a service a plugin in going provides.
func (rt *Runtime) needsGoing(p *running, going map[string]bool) bool {
for id := range going {
if q := rt.plugins[id]; q.ctx != nil {
for _, s := range q.ctx.provided {
if slices.Contains(p.m.Requires, s) {
return true
}
}
}
}
return false
}
func (rt *Runtime) missing(m Manifest) []string {
var out []string
for _, s := range m.Requires {
if _, ok := rt.services[s]; !ok {
out = append(out, s)
}
}
return out
}
func (rt *Runtime) satisfied(m Manifest) bool { return len(rt.missing(m)) == 0 }
// apply runs a plugin's Apply, called with rt.mu held. A panic is a
// failure of that plugin alone; what it registered before it is undone.
func (rt *Runtime) apply(p *running, config map[string]any) {
ctx := &Ctx{ID: p.m.ID, Config: config, rt: rt}
ctx.parts = append(ctx.parts, p.m.Parts...)
err := func() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
if p.m.Apply != nil {
return p.m.Apply(ctx)
}
return nil
}()
if err != nil {
undo(ctx)
p.state, p.why, p.ctx = Failed, err.Error(), nil
log.Printf("plugins: %s failed: %v", p.m.ID, err)
return
}
p.state, p.why, p.ctx = Active, "", ctx
rt.order = append(rt.order, p.m.ID)
}
// dispose undoes what a plugin registered, newest first, called with
// rt.mu held.
func (rt *Runtime) dispose(p *running) {
if p.ctx != nil {
undo(p.ctx)
}
p.ctx, p.state, p.why = nil, Disposed, ""
rt.order = slices.DeleteFunc(rt.order, func(id string) bool { return id == p.m.ID })
}
func undo(ctx *Ctx) {
for i := len(ctx.disposes) - 1; i >= 0; i-- {
func() {
defer func() {
if r := recover(); r != nil {
log.Printf("plugins: %s: disposing panicked: %v", ctx.ID, r)
}
}()
ctx.disposes[i]()
}()
}
ctx.disposes = nil
}
// Stop disposes of every active plugin, newest first.
func (rt *Runtime) Stop() {
rt.mu.Lock()
defer rt.mu.Unlock()
for len(rt.order) > 0 {
rt.dispose(rt.plugins[rt.order[len(rt.order)-1]])
}
}
// Statuses are the plugins as they run now, by id.
func (rt *Runtime) Statuses() []Status {
rt.mu.Lock()
defer rt.mu.Unlock()
out := make([]Status, 0, len(rt.plugins))
for id, p := range rt.plugins {
s := Status{ID: id, State: p.state, Why: p.why}
if p.ctx != nil {
s.Parts = slices.Clone(p.ctx.parts)
}
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// Active is whether the plugin id is applied now.
func (rt *Runtime) Active(id string) bool {
rt.mu.Lock()
defer rt.mu.Unlock()
p := rt.plugins[id]
return p != nil && p.state == Active
}
// Compatible is whether a plugin written for the caret range want runs on
// this host's API. An empty range is "^1".
func Compatible(want string) bool {
if want == "" {
want = "^1"
}
want, ok := strings.CutPrefix(want, "^")
if !ok {
return false
}
wMaj, wMin, ok1 := version(want)
hMaj, hMin, ok2 := version(API)
return ok1 && ok2 && wMaj == hMaj && wMin <= hMin
}
func version(v string) (int, int, bool) {
maj, min, _ := strings.Cut(v, ".")
a, err := strconv.Atoi(maj)
if err != nil {
return 0, 0, false
}
if min == "" {
return a, 0, true
}
min, _, _ = strings.Cut(min, ".")
b, err := strconv.Atoi(min)
return a, b, err == nil
}
+149
View File
@@ -0,0 +1,149 @@
package pluginrt
import (
"errors"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
)
// A plugin is applied once what it requires is provided, whatever the
// order; one that fails or panics is FAILED, what it registered undone,
// and the rest run on; turned off, what it registered is undone newest
// first, with the plugins that require what it provided.
func TestReconcile(t *testing.T) {
var log []string
note := func(s string) func() { return func() { log = append(log, s) } }
ms := []Manifest{
{ID: "a", Requires: []string{"svc.b"}, Apply: func(c *Ctx) error {
if c.Service("svc.b") != "b" {
t.Errorf("a got %v", c.Service("svc.b"))
}
c.OnDispose(note("a.1"))
c.OnDispose(note("a.2"))
return nil
}},
{ID: "b", Provides: []string{"svc.b"}, Apply: func(c *Ctx) error {
c.Provide("svc.b", "b")
c.OnDispose(note("b"))
return nil
}},
{ID: "bad", Apply: func(c *Ctx) error { c.OnDispose(note("bad")); return errors.New("no") }},
{ID: "boom", Apply: func(c *Ctx) error { c.OnDispose(note("boom")); panic("boom") }},
{ID: "old", API: "^2"},
{ID: "wait", Requires: []string{"svc.none"}},
{ID: "ui", Parts: []Part{{"nav.page", "ui"}}},
}
rt := New(ms)
all := map[string]bool{"a": true, "b": true, "bad": true, "boom": true, "old": true, "wait": true, "ui": true}
rt.Reconcile(all, nil)
want := map[string]State{"a": Active, "b": Active, "bad": Failed, "boom": Failed, "old": Failed, "wait": Pending, "ui": Active}
for _, s := range rt.Statuses() {
if s.State != want[s.ID] {
t.Errorf("%s is %s (%s), want %s", s.ID, s.State, s.Why, want[s.ID])
}
if s.ID == "ui" && !slices.Equal(s.Parts, []Part{{"nav.page", "ui"}}) {
t.Errorf("ui's parts: %v", s.Parts)
}
if s.ID == "wait" && !strings.Contains(s.Why, "svc.none") {
t.Errorf("wait says %q", s.Why)
}
}
if !slices.Equal(log, []string{"bad", "boom"}) {
t.Fatalf("the failed ones' parts undone: %v", log)
}
log = nil
// b off: a, which requires it, goes first, its parts newest first
off := map[string]bool{"a": true, "ui": true}
rt.Reconcile(off, nil)
if !slices.Equal(log, []string{"a.2", "a.1", "b"}) {
t.Fatalf("disposed: %v", log)
}
if rt.Active("a") || rt.Active("b") || !rt.Active("ui") {
t.Fatalf("after b off: %+v", rt.Statuses())
}
// and back on, a with it
rt.Reconcile(all, nil)
if !rt.Active("a") || !rt.Active("b") {
t.Fatalf("after b on: %+v", rt.Statuses())
}
log = nil
rt.Stop()
if !slices.Equal(log, []string{"a.2", "a.1", "b"}) {
t.Fatalf("stopped: %v", log)
}
}
func TestCompatible(t *testing.T) {
for want, ok := range map[string]bool{"": true, "^1": true, "^1.0": true, "^1.1": false, "^2": false, "1": false, "^x": false} {
if Compatible(want) != ok {
t.Errorf("Compatible(%q) = %v", want, !ok)
}
}
}
// Core never imports a plugin, and a plugin never imports another: they
// reach each other through services. main.go and plugins/all alone gather
// them; a test may too.
func TestPluginsImportOnlyCore(t *testing.T) {
root := filepath.Join("..", "..")
const mod = "github.com/yetone/magpie/plugins/"
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(root, path)
if d.IsDir() {
if rel == "site" || rel == "build" || strings.HasPrefix(d.Name(), ".") && rel != "." {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
for _, im := range f.Imports {
p, _ := strconv.Unquote(im.Path.Value)
if !strings.HasPrefix(p, mod) {
continue
}
switch {
case rel == "main.go" && p == mod+"all":
case strings.HasPrefix(rel, "plugins/all/"):
case strings.HasPrefix(rel, "plugins/"):
t.Errorf("%s imports %s: a plugin never imports another", rel, p)
default:
t.Errorf("%s imports %s: core never imports a plugin", rel, p)
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
// and every plugin is gathered
dirs, err := os.ReadDir(filepath.Join(root, "plugins"))
if err != nil {
t.Fatal(err)
}
all, err := os.ReadFile(filepath.Join(root, "plugins", "all", "all.go"))
if err != nil {
t.Fatal(err)
}
for _, d := range dirs {
if d.IsDir() && d.Name() != "all" && !strings.Contains(string(all), `"`+mod+d.Name()+`"`) {
t.Errorf("plugins/all doesn't import plugins/%s", d.Name())
}
}
}
+29
View File
@@ -0,0 +1,29 @@
package settings
import (
"os"
"path/filepath"
)
// ranBefore are files a magpie (or the dial before it, copied over by
// Migrate) leaves in Dir once it has run: its settings, a provider, an
// account, the version it last ran as, the library, a profile, a plugin,
// an agent's stashed config, a request served, the id stats send.
var ranBefore = []string{
"settings.json", "providers.json", "logins.json", "last-version",
"library.json", "profiles.json", "plugins.json", "stash.json",
"usage.jsonl", "migrations.json", "install-id",
}
// RanBefore is whether a magpie has run here before: one of ranBefore's
// files is in Dir. It is asked at start, after Migrate and before anything
// writes into Dir. A file that can't be looked at counts as there:
// unknown is never new.
func RanBefore() bool {
for _, name := range ranBefore {
if _, err := os.Lstat(filepath.Join(Dir(), name)); !os.IsNotExist(err) {
return true
}
}
return false
}
+30
View File
@@ -0,0 +1,30 @@
package settings
import (
"os"
"path/filepath"
"testing"
)
// An empty folder is a new install; any one of ranBefore's files says a
// magpie ran here before.
func TestRanBefore(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if RanBefore() {
t.Fatal("an empty folder ran before")
}
for _, name := range ranBefore {
t.Run(name, func(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := os.MkdirAll(Dir(), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(Dir(), name), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
if !RanBefore() {
t.Fatalf("%s there, and not ran before", name)
}
})
}
}
+5 -1
View File
@@ -2,7 +2,11 @@
// internal/cli; this is only where the binary starts.
package main
import "github.com/yetone/magpie/internal/cli"
import (
"github.com/yetone/magpie/internal/cli"
// the built-in plugins, registered with the runtime (internal/pluginrt)
_ "github.com/yetone/magpie/plugins/all"
)
// version is set at build time: -ldflags "-X main.version=…" (Makefile,
// Dockerfile, magpie-releases), so it stays in package main.
+11
View File
@@ -0,0 +1,11 @@
// Package all registers every built-in plugin. Only magpie's main imports
// it: core never imports a plugin, and a plugin never imports another.
package all
import (
_ "github.com/yetone/magpie/plugins/groups"
_ "github.com/yetone/magpie/plugins/library"
_ "github.com/yetone/magpie/plugins/otel"
_ "github.com/yetone/magpie/plugins/sessions"
_ "github.com/yetone/magpie/plugins/warmups"
)
+27
View File
@@ -0,0 +1,27 @@
// Package groups is routing groups' part of the window: several models
// agents pick as one, each request sent to the right one and on to the
// next when one fails. While the user has a group, it stays on.
package groups
import (
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/provider"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "groups", API: "^1", Requires: []string{"window", "providers"},
Name: "Routing groups", Sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails",
One: "1 group in use", Many: "{n} groups in use",
InUse: func() (int, error) {
n := 0
for _, g := range provider.Groups() {
if !g.Auto && !g.Hidden {
n++
}
}
return n, nil
},
Parts: []pluginrt.Part{{Slot: "part", Key: "groups"}},
})
}
+19
View File
@@ -0,0 +1,19 @@
// Package library is the Library page: instructions, MCP servers, skills
// and hooks, kept once and given to every agent. While it gives agents
// anything, it stays on.
package library
import (
lib "github.com/yetone/magpie/internal/library"
"github.com/yetone/magpie/internal/pluginrt"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "library", API: "^1", Requires: []string{"window"},
Name: "Library", Sub: "Instructions, MCP servers, skills and hooks, kept once and given to every agent",
One: "1 item given to agents", Many: "{n} items given to agents",
InUse: lib.InUse,
Parts: []pluginrt.Part{{Slot: "nav.page", Key: "library"}},
})
}
+28
View File
@@ -0,0 +1,28 @@
// Package otel is Settings' Observability: each request's traces and
// metrics sent to an OpenTelemetry collector, such as Langfuse. While it
// sends, it stays on.
package otel
import (
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/settings"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "otel", API: "^1", Requires: []string{"window", "settings"},
Name: "Observability", Sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse",
One: "Sending to a collector", Many: "Sending to a collector",
InUse: func() (int, error) {
s, err := settings.LoadChecked()
if err != nil {
return 0, err
}
if s.OTel.Enabled {
return 1, nil
}
return 0, nil
},
Parts: []pluginrt.Part{{Slot: "settings.section", Key: "otel"}},
})
}
+29
View File
@@ -0,0 +1,29 @@
// Package sessions is the Sessions page: the agents' past conversations,
// to read, search, resume and export. Off, the page leaves the window;
// the gateway still records conversations while Settings asks it to, and
// that keeps the plugin on.
package sessions
import (
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/settings"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "sessions", API: "^1", Requires: []string{"window"},
Name: "Sessions", Sub: "Your agents' past conversations: read, search, resume and export them",
One: "Recording gateway conversations", Many: "Recording gateway conversations",
InUse: func() (int, error) {
s, err := settings.LoadChecked()
if err != nil {
return 0, err
}
if s.GatewayConversations {
return 1, nil
}
return 0, nil
},
Parts: []pluginrt.Part{{Slot: "nav.page", Key: "sessions"}},
})
}
+41
View File
@@ -0,0 +1,41 @@
// Package warmups is warm-up and check-in: start a subscription's usage
// window at a time the user picks, and claim vendors' daily check-in
// credits. While one is set, it stays on.
package warmups
import (
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/settings"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "warmups", API: "^1", Requires: []string{"window", "settings"},
Name: "Warm-up and check-in", Sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits",
One: "1 warm-up or check-in on", Many: "{n} warm-ups and check-ins on",
InUse: func() (int, error) {
s, err := settings.LoadChecked()
if err != nil {
return 0, err
}
n := count(s.CodexWarmup != "", s.ClaudeWarmup != "", s.CodexWarmAt != "" || len(s.CodexWarmAts) > 0,
s.ClaudeWarmAt != "" || len(s.ClaudeWarmAts) > 0, s.WorkBuddyCheckin, s.TraeCheckin, s.MiniMaxCheckin, s.QoderCheckin)
n += len(s.CodexWarmAtOf)
for _, on := range s.PluginCheckins {
n += count(on)
}
return n, nil
},
Parts: []pluginrt.Part{{Slot: "part", Key: "warmups"}},
})
}
func count(on ...bool) int {
n := 0
for _, b := range on {
if b {
n++
}
}
return n
}