plugins: the window gets a plugin kernel, and the Gateway page is the first page a plugin draws (P1)

P1 of docs/subsystems/plugin-runtime.md. P0 (3ccbe6bc1) gave built-in
plugins a manifest, plugins.yml and a switch; their pages were still
app.js's own code. Now the window has a kernel a plugin draws its page
through, and the Gateway page moved into plugins/gateway to prove it.

What changed:
- internal/gui/assets/kernel.js (new): window.magpie. A plugin
  registers with magpie.plugin(id, setup); ctx.slots.add("page", part)
  puts its markup where index.html's <template data-slot="page"> is.
  The shell calls its hooks through magpie.call, behind an error
  boundary: a hook that throws, or whose promise fails, is logged and
  its page shows "This page stopped working", what broke and Try
  again, while every other page goes on. ctx.ui is the kit (button,
  switch, the app menu, a settings row) and ui.form draws a plugin's
  settings from their schema. ctx.config / onConfig carry the settings,
  from boot.js before the first paint and from Plugins › Built-in after.
- internal/pluginrt/schema.go (new): a plugin's settings are a Go
  struct (Manifest.Settings); SchemaOf makes the JSON Schema the form
  is drawn from, and Validate is what SetConfig (config.go) takes into
  plugins.yml. Compose drops a hand-edited value the schema refuses.
- plugins/gateway: the Gateway page as a plugin, Essential and in use
  while a gateway key is there. One setting, callsPage (10/20/50/100,
  20 by default). Its client is plugins/gateway/{keys.js,client.js},
  moved out of app.js (and caller-keys.js) unchanged in behaviour.
- internal/gui: builtins.go takes POST {id, config} beside {id, on}
  and lists each plugin's schema and config; boot.js carries
  pluginConfig; /plugins/<id>/… files are served. Plugins › Built-in
  draws a plugin's settings rows under its switch.
- Docs: plugin-runtime.md has "The window's kernel (P1)"; gui-shell.md,
  subsystems/README.md and tests/README.md updated.

What was run:
- go test ./... (sandbox HOME, pinned caches): all packages ok;
  gofmt -l clean; go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- New tests: TestSchemaOf, TestValidate, TestSetConfig,
  TestBuiltinConfig, TestBuiltinClientsLoaded;
  plugin-kernel.test.cjs (a page that throws breaks only itself and
  Try again draws it, at 1100 and 420 in en, zh, zh-TW, ja, de;
  callsPage from boot.js and from Plugins › Built-in), both engines.
- Broken by hand, each turned its test red: the boundary's catch
  removed; Try again not putting the page's markup back; the Gateway
  page's onConfig not re-reading callsPage; boot.js's pluginConfig
  ignored; SetConfig skipping Validate.
- The full GUI suite in Chromium and WebKit (node --test *.test.cjs).
  One red was this change's own. providers-fetching-retry lifts
  providersWhileFetching out of app.js, which now asks providersPage,
  and the lift lacked it. The test now lifts that too, and gains "a poll
  under the Gateway page, a plugin's page that reads with Providers,
  reads". That case goes red with providersPage dropped from the poll's
  guard.
- The reds that were on origin/main a75de4c21 too are fixed in their
  own commits after this one. Two of them came from P0's Built-in tab:
  nav-sub-unroll and plugin-check-github-limit.
This commit is contained in:
yetone
2026-10-13 20:39:39 +08:00
parent a75de4c21a
commit 2dcc51417e
25 changed files with 1895 additions and 718 deletions
+1 -1
View File
@@ -5,7 +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) |
| Built-in plugins: registry, lifecycle, plugins.yml, presets, settings schemas, the window's kernel (slots, error boundary, kit) | [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 -1
View File
@@ -17,7 +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) |
| 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, and the Gateway page (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". 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}` (or `{id, config}`) 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`) and their settings (`pluginConfig`) 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
+64 -8
View File
@@ -4,8 +4,10 @@ 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
turned off. `plugins.yml` says which are on. This page describes P0 (the
runtime, the file and the window's switch) and P1 (the window's kernel: a
plugin's page, its error boundary, the kit it draws with and its settings
form, with the Gateway page as the first plugin to draw its own page). 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).
@@ -15,17 +17,64 @@ the plugin host) are a different thing; see
| 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) |
| 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), `Defaults` (its config), `Settings` (a struct of its settings, made into `Defaults` and a schema at `Register`) and `Client` (its scripts in the window, under `internal/gui/assets/plugins/<id>/`). | [`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) |
| Settings schema | `SchemaOf(Settings)` makes a JSON Schema object of the struct, in its fields' order (`x-order`): each exported field with a json name is a setting, of `bool`, an int, `float64` or `string`, with tags `title` (English; the window translates it), `description`, `enum` (comma separated) and `min`/`max`. Its values are the defaults. A field a form can't draw, or a tag that doesn't parse, panics at `Register`. `Schema.Validate` takes a value only as the schema allows it (a JSON float64 or a YAML int for an integer); `SetConfig(id, config)` writes the user's row through it, and `Compose` leaves out a value edited into plugins.yml by hand that it doesn't allow, so the default stands. | [`schema.go`](../../internal/pluginrt/schema.go), [`config.go`](../../internal/pluginrt/config.go) |
| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), and `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`). Its one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't 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.
## The window's kernel (P1)
`internal/gui/assets/kernel.js` loads after `i18n.js` and before the
plugins' scripts and `app.js`, all classic scripts sharing one scope. It is
`window.magpie`:
- `magpie.plugin(id, setup)`: a plugin's script registers, and `setup` gets
a context: `config` (from boot.js's `pluginConfig`, then Plugins ›
Built-in), `onConfig(fn)`, `onDispose(fn)`, `slots.add(slot, part)` and
`ui`.
- **Slots.** The one slot is `page`: a part `{key, html, loads, mount,
…hooks}` becomes `<main class="view" id="view-<key>"
data-feature="<plugin>">` where index.html's `<template data-slot="page">`
is, at once, so app.js finds the page as it finds its own. app.js calls
`magpie.start()` when it is set up, which mounts every page, and then each
hook through `magpie.call(key, hook, …)`: `loading`, `draft` and `render`
around `/api/providers` for a page that `loads: "providers"`, `open` when
`show` opens it. `magpie.pages()` adds the plugins' pages to the views
`show` and `?view=` know.
- **Error boundary.** A hook that throws, or whose promise fails, is caught
in `run`: logged with `[magpie] <plugin>: <key>.<hook>`, and the page is
replaced by a card saying "This page stopped working", the error's message
and Try again. Further hooks of a broken page do nothing, so nothing half
drawn comes back, and the other pages go on. Try again puts the page's
markup back, translates it, mounts it and runs the hook that broke with
what it was given. A plugin whose `setup` throws is logged and has no page.
- **Kit** (`magpie.ui`): `el`, `button`, `toggle` (the switch Plugins uses,
`role="switch"`), `menu` (the app's menu through `openProtoMenu`, never a
native `<select>`), `row` (a settings row) and `form(schema, values,
onChange)`: a switch for a boolean, a menu for an enum (numbers in the
window's locale), a field for a number (kept to its range, `aria-invalid`
when not) or text.
- **Settings.** Plugins › Built-in draws the rows of each plugin on, with a
schema, from `ui.form` under its row (`.feat-set`), and a change posts
`{id, config}`; `applyFeatures` hands each plugin's config to
`magpie.configure`, which calls its `onConfig` only when it changed.
The Gateway page is `plugins/gateway` with `Client: keys.js, client.js`
(`internal/gui/assets/plugins/gateway/`): `keys.js` is the gateway-key
manager that was `caller-keys.js`, and `client.js` is the page's code that
was in app.js, ending in its `magpie.plugin("gateway", …)`. Still in
app.js and app.css: its styles, its sidebar and header buttons
(`data-feature="gateway"` in index.html), and `decideEntry`, which the model
info card shares. `TestBuiltinClientsLoaded` holds index.html to load every
plugin's `Client` file between kernel.js and app.js, each with its `?v=`.
## Source of truth and composing
What a plugin runs with is composed field by field (`Compose`), each value
@@ -74,7 +123,9 @@ remembering its layer (`Source`):
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
- A plugin's page whose code throws breaks only that page (the boundary
above); a POST of a config the schema refuses is a 400 and writes nothing.
- 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.
@@ -84,8 +135,13 @@ remembering its layer (`Source`):
- `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.
- `go test ./internal/pluginrt/ -run 'TestSchemaOf|TestValidate|TestSetConfig'`.
- `go test ./internal/gui/ -run 'TestBuiltin|TestBootSaysBuiltinsOff'`
(`TestBuiltinConfig`, `TestBuiltinClientsLoaded`).
- `internal/gui/tests/builtins.test.cjs` (the settings form) and
`plugin-kernel.test.cjs` (the boundary, Try again, `callsPage` from
boot.js and from a change) in Chromium and WebKit, every language, 1100,
800 and 420 points; the Gateway page's own tests (`gateway-*`,
`recent-calls-*`) unchanged.
- By hand, under a sandbox HOME: `magpie plugin builtin`, `magpie plugin
builtin on groups`, `magpie plugin dump`, and a plugins.yml broken by hand.
+7 -3
View File
@@ -747,8 +747,9 @@ func revalidated(next http.Handler) http.Handler {
})
}
// pageFile is a script or stylesheet of the page's own, named in it.
var pageFile = regexp.MustCompile(`(src|href)="([A-Za-z0-9_.-]+\.(?:js|css))"`)
// pageFile is a script or stylesheet of the page's own, named in it: one
// of the page's, or of a built-in plugin's under plugins/<id>/.
var pageFile = regexp.MustCompile(`(src|href)="([A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*\.(?:js|css))"`)
// versionedPage is the page with each of its own scripts and stylesheets
// named with its content's hash; one not among the page's files (boot.js,
@@ -795,7 +796,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
// 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())
list := builtinsState()
boot["featuresOff"] = builtinsOff(list)
// and the settings of those the page draws (kernel.js)
boot["pluginConfig"] = builtinConfig(list)
// on Omarchy the page takes its theme's look before it paints
if th, ok := omarchyTheme(); ok {
boot["omarchy"] = th
+9
View File
@@ -2980,6 +2980,15 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.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; }
/* a plugin's settings, under its row (kernel.js ui.form) */
.row.pref.feat-set { min-height: 44px; padding-left: 30px; }
.row.pref.feat-set .name { font-size: 12.5px; }
.row.pref .set-field { flex: none; width: 120px; height: 24px; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); }
.row.pref .set-field[type=number] { width: 72px; text-align: right; }
.row.pref .set-field[aria-invalid=true] { border-color: var(--red); }
/* a plugin's page that broke (kernel.js): what broke, and Try again */
.slot-error .row { gap: 14px; padding: 12px 14px; }
.slot-error .sub { margin-top: 2px; color: var(--fg-2); overflow-wrap: anywhere; }
.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); }
+44 -665
View File
@@ -40,6 +40,10 @@ function featureStyle() {
st.textContent = sel ? sel + "{display:none!important}" : "";
}
featureStyle();
// a page a plugin adds (kernel.js) that draws from /api/providers, as the
// Gateway page does: read with Providers and Routing, and drawn through its
// hooks
const providersPage = (v) => magpie.page(v)?.loads === "providers";
// 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` —
@@ -73,18 +77,6 @@ let providerDiscovery = []; // only opaque fingerprints and app names, never cre
let discoveryAt = 0, discoveryRun = 0, discoveryPending = false;
let discoveryIgnored = new Set();
try { discoveryIgnored = new Set(JSON.parse(localStorage.getItem("magpie.discoveryIgnored") || "[]")); } catch {}
// the gateway tab's choices, kept per machine
let flavor = params.get("flavor") || localStorage.getItem("magpie.flavor") || "openai"; // which API the snippets speak
let lang = params.get("lang") || localStorage.getItem("magpie.lang") || "shell"; // which snippet
let snipOS = localStorage.getItem("magpie.snipOS") || ""; // the shell the Shell and curl snippets are for (#1514)
let exampleModel = localStorage.getItem("magpie.model") || ""; // the model in the snippets
let decideModel = localStorage.getItem("magpie.decideModel") || ""; // the System One snippets' decision model
let connectFolded = false; // Connect folded away under its heading
try { connectFolded = localStorage.getItem("magpie.gwConnectFolded") === "1"; } catch {}
const expandedCalls = new Set(); // recent-call ids whose wire bodies are open
const callBodies = new Map(); // callRow → its bodies, read when it is opened (#1521)
const CALLS_PAGE = 20;
let callsShown = CALLS_PAGE; // recent calls drawn a page at a time
// a streamed reply's body is read as its reply, its events or as it came;
// the pick is one for every call and kept, the events drawn per call
let sseView = "events";
@@ -3794,7 +3786,7 @@ async function load(again) {
// the gateway page too waits for the state first: its skeleton, not a
// blank page, until then (#123)
if (view === "providers" && !providers) renderProvidersLoading();
if (view === "gateway" && !providers) renderGatewayLoading();
if (providersPage(view) && !providers) magpie.call(view, "loading");
try {
const since = prefsWrites, hid = hiddenIds().join(), visibilitySince = agentsVisibilityRevision;
const asked = api("state");
@@ -3852,7 +3844,7 @@ async function load(again) {
if (mode === "panel") { renderPanelQuota(); panelTab === "usage" && !document.hidden && (again || document.hasFocus()) ? quotasOpened() : loadQuotas(); }
// an open provider editor is someone typing: coming back to the window
// must not rebuild it under them
if ((view === "providers" || view === "gateway") && !(editing || adding)) await loadProviders();
if ((view === "providers" || providersPage(view)) && !(editing || adding)) await loadProviders();
// the window back on the Usage page reads the tab shown as its own timer
// does: drawn again only on a change, with no skeleton between; on the
// Overview, where the allowances are, that is opening them (#1588)
@@ -5384,10 +5376,10 @@ saveCurrent.onclick = () => {
async function loadProviders() {
// the skeletons only while there is nothing yet: a reload keeps what is
// drawn, and where the reader is in it, until the new one is in
if (!providers) { if (view === "gateway") renderGatewayLoading(); else renderProvidersLoading(); }
// the gateway page opened from another that had the list: drawn from it
// at once, not left as empty cards until the new one is in (#123)
else if (view === "gateway" && !$("#gateway").childElementCount) renderGatewayView();
if (!providers) { if (providersPage(view)) magpie.call(view, "loading"); else renderProvidersLoading(); }
// a plugin's page opened from another that had the list: drawn from it
// at once (#123)
else if (providersPage(view)) magpie.call(view, "draft");
const was = providers;
providers = await api("providers");
renderSideGw(providers.gateway);
@@ -5395,16 +5387,9 @@ async function loadProviders() {
if (typeof editing === "string" && !providers.providers.some((p) => p.id === editing)) editing = null;
// a providers.json that can't be read is not a first use: no Add sheet
if (!providers.providers.length && editing === null && !providers.fileError) adding = true;
if (view === "gateway") {
// the gateway page is looked at and left open: coming back to the window
// redraws it only when something on it changed, and when only the calls
// did, only them (an account's last sign-in check isn't on it)
const json = (a) => JSON.stringify(a, (k, v) => (k === "seen" ? undefined : v));
const same = (a, b) => json(a) === json(b);
if (was && !$("#view-gateway").classList.contains("loading") && same({ ...was, gateway: { ...was.gateway, calls: 0 } }, { ...providers, gateway: { ...providers.gateway, calls: 0 } })) {
if (!same(was.gateway.calls, providers.gateway.calls)) renderActivity();
} else renderGatewayView();
backToReader($("#view-gateway"));
if (providersPage(view)) {
magpie.call(view, "render", was);
backToReader($("#view-" + view));
} else renderProviders();
renderArchive();
providersWhileFetching();
@@ -5421,7 +5406,7 @@ function providersWhileFetching() {
clearTimeout(providersWhileFetching.timer);
if (!providers?.fetching) return;
providersWhileFetching.timer = setTimeout(async () => {
if (!["providers", "gateway", "routing"].includes(view) || editing !== null || adding || document.hidden) return;
if (!(["providers", "routing"].includes(view) || providersPage(view)) || editing !== null || adding || document.hidden) return;
let next;
try { next = await api("providers"); } catch { providersWhileFetching(); return; }
const json = (p) => JSON.stringify({ ...p, fetching: false, gateway: { ...p.gateway, calls: 0 } });
@@ -6159,344 +6144,9 @@ function copyBtn(text, what, message) {
return b;
}
function renderGatewayLoading() {
const page = $("#view-gateway");
page.classList.add("loading");
page.setAttribute("aria-busy", "true");
$("#connectNote").textContent = "";
$("#callsNote").textContent = "";
$("#copyModels").hidden = true;
const gateway = $("#gateway");
gateway.replaceChildren();
const mark = el("span", "skeleton gw-sk-dot");
const who = el("div", "who gw-sk-who");
who.append(el("span", "skeleton gw-sk-title"), el("span", "skeleton gw-sk-sub"));
gateway.append(mark, who, el("span", "skeleton gw-sk-url"));
const connect = $("#connect");
connect.replaceChildren();
connect.hidden = connectFolded;
for (let i = 0; i < 4; i++) {
connect.append(el("span", "skeleton gw-sk-label"));
const value = el("div", "gw-sk-field");
value.append(el("span", "skeleton"), el("span", "skeleton short"));
connect.append(value);
}
const models = $("#gwModels");
models.replaceChildren();
for (let i = 0; i < 4; i++) {
const row = el("div", "row model gw-sk-row");
row.append(el("span", "skeleton gw-sk-model"), el("span", "grow"), el("span", "skeleton gw-sk-provider"));
models.append(row);
}
const activity = $("#activity");
activity.replaceChildren();
for (let i = 0; i < 4; i++) {
const row = el("div", "call gw-sk-call");
row.append(el("span", "skeleton time"), el("span", "skeleton agent"), el("span", "skeleton model"), el("span", "grow"), el("span", "skeleton result"));
activity.append(row);
}
}
function renderGatewayView() {
const page = $("#view-gateway");
page.classList.remove("loading");
page.removeAttribute("aria-busy");
renderGateway();
$("#gatewayKeysBlock").hidden = !providers.gateway.lan;
// not shared, the keys are left out; this line says where they come from,
// as a tunnel to loopback is refused until sharing is on (DD on Discord)
$("#gatewayKeysOff").hidden = !!providers.gateway.lan;
if (!providers.gateway.lan) gatewayKeyDraft = null;
if (gatewayKeyDraft === null && gatewayLimit === null && !$("#gatewayKeys .rename-in")) renderGatewayKeys();
renderConnect();
renderGatewayModels();
renderActivity();
}
// The status card's button (leslie_luo on Discord: told to quit the older
// magpie serving the gateway, with no way to tell which one it was): with
// an older magpie on the port it quits that one, checked to be magpie by
// its process, and this one serves the gateway at once; otherwise it
// restarts the gateway this one serves, or starts it. A magpie of this
// version or newer serving it gets none: that one is not to be quit here.
// What stood in the way stays under it until the gateway's state changes.
let gatewayFix = { busy: false, err: "", when: "" };
const gatewayFixWhen = (g) => [g.running, g.mine, g.version || ""].join("|");
function gatewayFixButton(g, older) {
if (g.running && !g.mine && !older) return null;
// bordered: a plain text button read as words on the card in dark mode
const b = el("button", "text action gw-fix");
b.textContent = gatewayFix.busy
? (older ? t("Quitting magpie {v}…", { v: g.version }) : t(g.running ? "Restarting the gateway…" : "Starting the gateway…"))
: (older ? t("Quit magpie {v} and take over", { v: g.version }) : t(g.running ? "Restart gateway" : "Start gateway"));
b.disabled = gatewayFix.busy;
b.onclick = async () => {
const when = gatewayFixWhen(g);
gatewayFix = { busy: true, err: "", when };
renderGateway();
let out;
try { out = await api(older ? "gateway/take-over" : "gateway/restart", {}); } catch (e) { out = { reason: "error", error: e.message }; }
gatewayFix = { busy: false, err: out?.ok ? "" : gatewayFixSays(out || {}), when };
try { await loadProviders(); } catch {}
renderGateway();
};
return b;
}
// gatewayFixSays is why a take-over or a restart didn't go, in the page's
// language, naming the process it was
function gatewayFixSays(o) {
const p = { port: o.port || "", pid: o.pid || "", path: o.path || "", v: o.version || "", error: o.error || "" };
switch (o.reason) {
case "not-magpie": return t("Port {port} is held by {path} (pid {pid}), which isn't magpie, so magpie leaves it alone. Quit it yourself, or move the gateway to another port in Settings.", p);
// leslie_luo on Discord: an old magpie in OrbStack, its helper named
// as the program to quit
case "container": return t("Port {port} is forwarded by {path} (pid {pid}) to a container or a VM: the magpie {v} answering there runs inside it, out of this magpie's reach. Stop that container (docker ps lists it, docker stop <name> stops it, or stop it in OrbStack or Docker Desktop), or move this magpie's gateway to another port in Settings.", p);
case "unseen": return t("magpie can't see which process holds port {port}: it runs as another user or as administrator. Quit it there.", p);
case "denied": return t("magpie {v} (pid {pid}, {path}) runs as another user or as administrator, so this magpie can't quit it. Quit it there.", p);
case "stuck": return t("magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).", p);
case "respawned": return t("Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.", p);
case "taken": return p.pid
? t("Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.", p)
: t("Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.", p);
case "other": return t("magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.", p);
}
return t("The gateway couldn't be served here: {error}", p);
}
// The status card: dot, state, the URL.
function renderGateway() {
const g = providers.gateway;
const box = $("#gateway");
box.replaceChildren();
// an older magpie keeping the port sends every agent's request its own
// way, without this version's fixes (#506): said in place of the counts
const older = g.running && !g.mine && g.older;
const dot = el("span", "dot " + (older ? "old" : g.running ? "on" : ""));
const who = el("div", "who");
const name = el("div", "name", t("Gateway"));
name.append(el("span", "state", older
? t("running · served by magpie {v}, older than this one", { v: g.version })
: t(g.running ? (g.mine ? "running" : "running · served by another magpie") : "not running")));
const routed = new Set();
for (const p of providers.providers) for (const a of p.agents) if (a.current) routed.add(a.id);
const n = routed.size;
if (older) {
who.append(name, el("div", "sub old", t("Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.", { v: g.version })));
} else who.append(name, el("div", "sub", g.running
? [t(g.models === 1 ? "{n} model" : "{n} models", { n: g.models }), n ? t(n === 1 ? "{n} agent routed through it" : "{n} agents routed through it", { n }) : t("no agent routed through it yet"), t("five APIs, one URL")].join(" · ")
: t("start it with magpie serve, or open magpie at login")));
const fix = gatewayFixButton(g, older);
if (fix) who.append(fix);
if (gatewayFix.err && gatewayFix.when === gatewayFixWhen(g)) who.append(el("div", "sub old err", gatewayFix.err));
// served to other machines' browsers (magpie web), the address shown is
// the one they reach, MAGPIE_PUBLIC_URL's, not this computer's loopback
// (#1551)
const shown = web && g.publicURL || g.url;
const url = el("button", "url");
url.append(el("code", "", shown));
url.title = t("Copy the gateway URL");
url.onclick = () => copy(shown, t("Gateway URL"));
box.append(dot, who, url);
}
// One entry per API the gateway serves: where each SDK's base URL points,
// the env vars the usual tools read, and a request in four dialects.
const FLAVORS = {
openai: {
name: "OpenAI", base: (u) => u + "/v1", baseEnv: "OPENAI_BASE_URL", keyEnv: "OPENAI_API_KEY",
note: "Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.",
curl: (b, m, k = "magpie") => ({ url: `${b}/chat/completions`, headers: [`Authorization: Bearer ${k}`],
body: `{"model": "${m}",\n "messages": [{"role": "user", "content": "hi"}]}` }),
python: (b, m, k = "magpie") => `from openai import OpenAI
client = OpenAI(base_url="${b}", api_key="${k}")
r = client.chat.completions.create(
model="${m}",
messages=[{"role": "user", "content": "hi"}],
)
print(r.choices[0].message.content)`,
node: (b, m, k = "magpie") => `import OpenAI from "openai";
const client = new OpenAI({ baseURL: "${b}", apiKey: "${k}" });
const r = await client.chat.completions.create({
model: "${m}",
messages: [{ role: "user", content: "hi" }],
});
console.log(r.choices[0].message.content);`,
},
responses: {
name: "Responses", base: (u) => u + "/v1", baseEnv: "OPENAI_BASE_URL", keyEnv: "OPENAI_API_KEY",
note: "OpenAI's newer API: reasoning, built-in tool items, encrypted reasoning. Codex speaks this.",
curl: (b, m, k = "magpie") => ({ url: `${b}/responses`, headers: [`Authorization: Bearer ${k}`],
body: `{"model": "${m}", "input": "hi"}` }),
python: (b, m, k = "magpie") => `from openai import OpenAI
client = OpenAI(base_url="${b}", api_key="${k}")
r = client.responses.create(model="${m}", input="hi")
print(r.output_text)`,
node: (b, m, k = "magpie") => `import OpenAI from "openai";
const client = new OpenAI({ baseURL: "${b}", apiKey: "${k}" });
const r = await client.responses.create({ model: "${m}", input: "hi" });
console.log(r.output_text);`,
},
anthropic: {
name: "Anthropic", base: (u) => u, baseEnv: "ANTHROPIC_BASE_URL", keyEnv: "ANTHROPIC_API_KEY",
note: "Messages API. Claude Code reads ANTHROPIC_AUTH_TOKEN instead of the key; the Agents tab sets that for you.",
curl: (b, m, k = "magpie") => ({ url: `${b}/v1/messages`, headers: [`x-api-key: ${k}`, "anthropic-version: 2023-06-01"],
body: `{"model": "${m}", "max_tokens": 1024,\n "messages": [{"role": "user", "content": "hi"}]}` }),
python: (b, m, k = "magpie") => `import anthropic
client = anthropic.Anthropic(
base_url="${b}", api_key="${k}",
)
m = client.messages.create(
model="${m}",
max_tokens=1024,
messages=[{"role": "user", "content": "hi"}],
)
print(m.content[0].text)`,
node: (b, m, k = "magpie") => `import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ baseURL: "${b}", apiKey: "${k}" });
const m = await client.messages.create({
model: "${m}",
max_tokens: 1024,
messages: [{ role: "user", content: "hi" }],
});
console.log(m.content[0].text);`,
},
gemini: {
name: "Gemini", base: (u) => u, baseEnv: "GOOGLE_GEMINI_BASE_URL", keyEnv: "GEMINI_API_KEY",
note: "Google's generateContent API, v1beta. Gemini CLI and the google-genai SDKs speak this.",
curl: (b, m, k = "magpie") => ({ url: `${b}/v1beta/models/${m}:generateContent`, headers: [`x-goog-api-key: ${k}`],
body: `{"contents": [{"parts": [{"text": "hi"}]}]}` }),
python: (b, m, k = "magpie") => `from google import genai
client = genai.Client(api_key="${k}", http_options={"base_url": "${b}"})
r = client.models.generate_content(model="${m}", contents="hi")
print(r.text)`,
node: (b, m, k = "magpie") => `import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: "${k}",
httpOptions: { baseUrl: "${b}" },
});
const r = await ai.models.generateContent({ model: "${m}", contents: "hi" });
console.log(r.text);`,
},
// magpie's own System One API (ARNO on Discord: gateway添加system one
// api 有想法吗): a decision model — Jev, Clef, Bailian's — answers typed
// questions about a state; no SDK speaks it, so no shell variables
systemone: {
name: "System One", base: (u) => u + "/v1", decide: true,
note: "TypeSafe's decision API: a Jev or Clef model answers typed questions (choice, noul, score) about a state, with how sure it is. Clef also reads images: add \"images\": [\"data:image/png;base64,…\"].",
curl: (b, m, k = "magpie") => ({ url: `${b}/systemone`, headers: [`Authorization: Bearer ${k}`],
body: `{"model": "${m}",\n "state": {"message": "My order never arrived, refund it"},\n "questions": {"team": {"type": "choice",\n "instructions": "Which team should answer the message?",\n "criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"}}}}` }),
python: (b, m, k = "magpie") => `import requests
r = requests.post("${b}/systemone",
headers={"Authorization": "Bearer ${k}"},
json={
"model": "${m}",
"state": {"message": "My order never arrived, refund it"},
"questions": {"team": {
"type": "choice",
"instructions": "Which team should answer the message?",
"criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"},
}},
})
a = r.json()["answers"]["team"]
print(a["choice"], a["confidence"])`,
node: (b, m, k = "magpie") => `const r = await fetch("${b}/systemone", {
method: "POST",
headers: { Authorization: "Bearer ${k}", "Content-Type": "application/json" },
body: JSON.stringify({
model: "${m}",
state: { message: "My order never arrived, refund it" },
questions: { team: {
type: "choice",
instructions: "Which team should answer the message?",
criteria: { billing: "Payments and refunds", shipping: "Deliveries", other: "Anything else" },
} },
}),
});
const a = (await r.json()).answers.team;
console.log(a.choice, a.confidence);`,
},
};
// The Shell and curl snippets are written for one shell: PowerShell on
// Windows ($env: in place of export, and the curl.exe that ships with it,
// as plain curl there is Invoke-WebRequest; the body goes in on stdin,
// since Windows PowerShell drops the quotes inside an argument), or a POSIX
// shell (bash, zsh) on macOS and Linux. They start as the shell of the
// machine magpie runs on, and can be switched to the other: a Windows
// desktop's user often runs them on a Linux server over ssh (FourLeafTec,
// #1514). The choice is kept with the snippet language.
const WIN = /^Win/.test(navigator.platform);
const SNIP_OSES = [["windows", "Windows"], ["unix", "macOS · Linux"]];
const snipWin = () => (SNIP_OSES.some(([id]) => id === snipOS) ? snipOS : WIN ? "windows" : "unix") === "windows";
const langs4 = () => [["shell", snipWin() ? "PowerShell" : "Shell"], ["curl", "curl"], ["python", "Python"], ["node", "Node"]];
// A word each shell takes as it is, quoted only where it has to be: a key
// of the user's own can hold any ASCII symbol (", $, `, ', !), and a model
// id brackets ([1m]) that zsh would glob; a comma would make PowerShell
// pass a list.
const plainWord = /^[\w%+=:./-]+$/;
const shQuote = (s) => (plainWord.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`);
// in "…" for a header's spaces, unless it holds what bash expands there
const shHeader = (s) => (/[$`"\\!]/.test(s) ? `'${s.replaceAll("'", `'\\''`)}'` : `"${s}"`);
const psQuote = (s) => (plainWord.test(s) ? s : `'${s.replace(/['‘’‚‛]/g, "$&$&")}'`);
// "…" as the C runtime splits a command line: \" for a quote, and the
// backslashes before one doubled
const winArg = (s) => (plainWord.test(s) ? s : `"${s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`);
const psHeader = (s) => (/[$`"“”„]/.test(s) ? `'${s.replace(/['‘’‚‛]/g, "$&$&")}'` : `"${s}"`);
function curlSnippet({ url, headers, body }) {
headers = [...headers, "Content-Type: application/json"];
// curl reads [ ] { } in a URL as a range unless told not to
const g = /[[\]{}]/.test(url) ? " -g" : "";
// A " inside an argument reaches curl.exe differently from Windows
// PowerShell 5.1 and from PowerShell 7, and whole from neither as
// written; after --% the line goes to curl.exe as it stands, on one line,
// quoted as the C runtime reads a command line. (A %NAME% of a variable
// the shell has is still put in there; a key would have to hold both.)
if (snipWin() && headers.some((h) => h.includes('"'))) return `@'\n${body}\n'@ | curl.exe --%${g} ${winArg(url)} ${headers.map((h) => `-H ${winArg(h)}`).join(" ")} --data-binary "@-"`;
if (snipWin()) return `@'\n${body}\n'@ | curl.exe${g} ${psQuote(url)} \`\n${headers.map((h) => ` -H ${psHeader(h)} \``).join("\n")}\n --data-binary "@-"`;
return `curl${g} ${shQuote(url)} \\\n${headers.map((h) => ` -H ${shHeader(h)} \\`).join("\n")}\n -d '${body.replaceAll("'", `'\\''`).replaceAll("\n", "\n ")}'`;
}
function envSnippet(vars) {
return vars.map(([k, v]) => (snipWin() ? `$env:${k}=${psHeader(v)}` : `export ${k}=${shQuote(v)}`)).join("\n");
}
// a decision model on the list: one only System One asks, never an agent
const decideEntry = (m) => !m.group && !!m.provider?.id && decidesModel(m.provider, m.id.slice(m.provider.id.length + 1));
// every exposed model, as the ids agents use
function gatewayModels() {
// the routing groups first, as the agents' pickers list them
// a group's lists may come as null (#1585): one such group mustn't take
// every model off the list
const out = (providers.gateway.groups || []).filter((g) => g && typeof g.id === "string").map((g) => ({ id: g.id, name: g.name || g.id, icons: g.icons || [], group: true,
provider: { name: [t("routing group"), (g.providers || []).join(", ")].filter(Boolean).join(" · ") },
efforts: g.efforts || [], images: !!g.images, context: g.context, output: g.output, members: g.members || [] }));
// a provider switched off is skipped: the gateway refuses its models, so
// they are not ids an agent can use, and listing them here would show a
// model the picker's own list, the Gateway count and the Connect example
// all say works but a request to it turns away (the same off gate the
// backend's providerEntries and the fallback picker already honour).
// the levels agents are offered: those kept, else all it has; one whose
// levels aren't known (given) offers only those it was given
const offered = (m) => m.kept?.length || m.given ? m.kept || [] : m.efforts || [];
for (const p of providers.providers) { if (p.off) continue; for (const m of p.models) if (m.on) out.push({ id: `${p.id}/${m.id}`, name: m.name, provider: p, context: m.context, output: m.output, efforts: offered(m), images: !!m.images }); }
return out;
}
let segsMade = 0;
function segs(items, current, onPick) {
const box = el("div", "segs");
@@ -6600,134 +6250,6 @@ function sortBy(list, items, onPick) {
// a comparer of names for a pick: A→Z, or Z→A
const byName = (pick, nameOf = (x) => x.name) => (a, b) => (pick === "za" ? -1 : 1) * nameOf(a).localeCompare(nameOf(b));
// Connect is set up once and seldom looked at again, so it folds away under
// its heading, the base URL left beside it; the fold is remembered
// (connectFolded, with the tab's other choices at the top).
$("#foldConnect").prepend(svg(CHEV_R, 11, 1.6));
$("#foldConnect").onclick = () => {
connectFolded = !connectFolded;
try { localStorage.setItem("magpie.gwConnectFolded", connectFolded ? "1" : "0"); } catch {}
renderConnect();
backToReader($("#view-gateway"));
};
function renderConnect() {
const g = providers.gateway;
const box = $("#connect");
box.replaceChildren();
const f = FLAVORS[flavor] || FLAVORS.openai;
// System One's snippets take a decision model, the others any other
const models = gatewayModels().filter((m) => decideEntry(m) === !!f.decide);
let model;
if (f.decide) {
if (!models.some((m) => m.id === decideModel)) decideModel = models[0]?.id || "";
model = decideModel || "provider/jev-latest";
} else {
if (!models.some((m) => m.id === exampleModel)) exampleModel = models[0]?.id || "";
model = exampleModel || "provider/model";
}
// no SDK speaks System One, so it has no shell variables to set
const langs = f.baseEnv ? langs4() : langs4().filter(([id]) => id !== "shell");
const snipLang = langs.some(([id]) => id === lang) ? lang : "curl";
const urls = [g.url, ...(g.lanURLs || [])];
// the address picked is kept (coeo91): an address not offered right now
// (the network not up yet after a start) shows this computer's, and the
// pick comes back with it. With none picked, MAGPIE_PUBLIC_URL is where
// it starts: it says the address other machines use (#1551)
const first = g.publicURL && urls.includes(g.publicURL) ? g.publicURL : g.url;
connectURL = urls.includes(connectWant) ? connectWant : first;
// a gateway MAGPIE_ADDR puts on the network (a Docker image's, whose
// host is another machine to it) is shown with a gateway key everywhere
const remote = connectURL !== g.url || !!g.onNetwork;
const keys = g.lan ? (gatewayKeys || []).filter((k) => !k.off) : [];
if (!keys.some((k) => k.id === connectKeyID)) {
connectKeyID = "";
connectSecret = null;
}
if (!connectKeyID && connectKeyWant && keys.some((k) => k.id === connectKeyWant)) {
queueMicrotask(() => selectConnectKey(connectKeyWant));
} else if (remote && !connectKeyID && keys.length) {
queueMicrotask(() => selectConnectKey(keys[0].id));
}
const key = keys.find((k) => k.id === connectKeyID);
const secret = key ? (connectSecret?.id === key.id ? connectSecret.secret : "") : remote ? "" : "magpie";
const base = f.base(connectURL);
const fold = $("#foldConnect");
fold.setAttribute("aria-expanded", String(!connectFolded));
fold.title = t(connectFolded ? "Show how to connect" : "Fold Connect away");
box.hidden = connectFolded;
// folded, the head keeps the one thing reached for: the address, to copy
const note = $("#connectNote");
note.replaceChildren();
note.classList.toggle("brief", connectFolded);
if (connectFolded) note.append(el("code", "", base), copyBtn(base, "Base URL"));
else note.textContent = t(remote ? "Local network · an enabled gateway key is required" : g.lan && gatewayKeys?.length ? "Use a gateway key to track usage" : "Loopback only · the key can be anything");
box.append(...field("API", segs(Object.entries(FLAVORS).map(([k, v]) => [k, v.name]), flavor, (id) => { flavor = id; localStorage.setItem("magpie.flavor", id); renderConnect(); }), t(f.note)));
const b = el("div", "val");
if (urls.length > 1) b.append(connectPick("connectAddress", "Address", base,
urls.map((u) => ({ v: u, name: f.base(u), note: t(u === g.url ? "This computer" : u === g.publicURL ? "Public address" : "Local network") })), connectURL,
(u) => { connectWant = u; keepPick("magpie.connectAddress", u); renderConnect(); }));
else b.append(el("code", "", base));
b.append(copyBtn(base, "Base URL"));
box.append(...field("Base URL", b, f.baseEnv ? t("What {env} takes.", { env: f.baseEnv }) : t("Requests go to POST {url}.", { url: base + "/systemone" })));
const k = el("div", "val");
const options = keys.map((k) => ({ v: k.id, name: k.name, literalName: true, note: k.masked }));
if (!remote) options.unshift({ v: "", name: "This computer", note: t("Any key · no key attribution") });
const keyLabel = remote || key ? "Gateway key" : "API key";
if (!g.lan) k.append(el("code", "", "magpie"));
else if (options.length) k.append(connectPick("connectKey", keyLabel, key ? key.name : remote ? t("Choose a gateway key") : t("This computer"),
options, connectKeyID, (id) => { connectKeyWant = id; keepPick("magpie.connectKey", id); selectConnectKey(id); }));
else k.append(el("code", "", t("Create a gateway key above to connect")));
if (key) k.append(copyCallerKeyBtn(key));
else if (!remote) k.append(copyBtn("magpie", t("Key")));
box.append(...field(t(keyLabel), k, !f.keyEnv ? t(g.lan && (remote || gatewayKeys?.length)
? "Choose a gateway key to send as Authorization: Bearer; usage is tracked by key."
: "Sent as Authorization: Bearer. The gateway trusts everything on loopback, so any value works.") : t(g.lan && (remote || gatewayKeys?.length)
? "Choose a gateway key to use as {env}; usage is tracked by key."
: "{env}=magpie. The gateway trusts everything on loopback, so any value works.", { env: f.keyEnv })));
const m = el("div", "val");
m.append(el("code", "", model), copyBtn(model, t("Model id")));
box.append(...field(t("Model"), m, f.decide
? t(models.length ? "A decision model (Jev, Clef), as listed below. Click one there to put it in the snippets." : "No decision models yet. Add a System One, Jev or Workers AI provider.")
: t(models.length ? "provider/model, as listed below. Click a model there to put it in the snippets." : "No models yet. Add a provider, or sign in to Codex or Copilot.")));
const ex = el("div", "stack");
const tabs = el("div", "snip-tabs");
tabs.append(segs(langs, snipLang, (id) => { lang = id; localStorage.setItem("magpie.lang", id); renderConnect(); }));
// the shell the Shell and curl snippets are for; Python and Node read the same everywhere
if (snipLang === "shell" || snipLang === "curl") {
const os = segs(SNIP_OSES.map(([id, name]) => [id, t(name)]), snipWin() ? "windows" : "unix", (id) => {
snipOS = id;
try { localStorage.setItem("magpie.snipOS", id); } catch {}
renderConnect();
});
os.classList.add("snip-os");
os.setAttribute("role", "group");
os.setAttribute("aria-label", t("Where the snippet runs"));
os.title = t("Where the snippet runs");
tabs.append(os);
}
ex.append(tabs);
const code = !secret ? t(key ? "Loading gateway key…" : "Create a gateway key above to connect")
: snipLang === "shell" ? envSnippet([[f.baseEnv, base], [f.keyEnv, secret]])
: snipLang === "curl" ? curlSnippet(f.curl(base, model, secret))
: f[snipLang](base, model, secret);
const pre = el("pre", "snip");
const c = el("code");
c.append(highlight(code, snipLang));
pre.append(c);
// the button sits outside the scrolling box, so a long line doesn't carry it off
const wrap = el("div", "snip-wrap");
wrap.append(pre);
if (secret) wrap.append(copyBtn(code, t("Snippet")));
ex.append(wrap);
box.append(...field(t("Example"), ex, snipLang === "shell" ? t("Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.") : ""));
}
// A small highlighter for the four snippet dialects: strings, comments,
// keywords, numbers, calls, and the env vars and flags shells care about.
const KEYWORDS = {
@@ -6771,81 +6293,6 @@ function highlight(code, lang) {
return out;
}
let modelQuery = "";
// The model list can be folded away, so Recent calls sits under Connect;
// the fold is remembered.
let modelsFolded = false;
try { modelsFolded = localStorage.getItem("magpie.gwModelsFolded") === "1"; } catch {}
$("#foldModels").prepend(svg(CHEV_R, 11, 1.6));
$("#foldModels").onclick = () => {
modelsFolded = !modelsFolded;
try { localStorage.setItem("magpie.gwModelsFolded", modelsFolded ? "1" : "0"); } catch {}
renderGatewayModels();
backToReader($("#view-gateway"));
};
function renderGatewayModels() {
const list = $("#gwModels");
list.replaceChildren();
const all = gatewayModels();
const fold = $("#foldModels");
fold.setAttribute("aria-expanded", String(!modelsFolded));
fold.title = t(modelsFolded ? "Show the models" : "Fold the models away");
$("#modelsCount").textContent = all.length ? String(all.length) : "";
list.hidden = modelsFolded && all.length > 0;
// the search sits in the section head, beside Copy all ids; typing
// redraws only the list, so it keeps its focus
let q = $("#findModel");
if (!q) {
q = input(modelQuery, t("Find a model…"));
q.id = "findModel";
q.className = "find";
q.oninput = () => { modelQuery = q.value; renderGatewayModels(); };
q.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape" && q.value) { q.value = modelQuery = ""; renderGatewayModels(); } };
$("#copyModels").before(q);
}
q.hidden = all.length < 5 || list.hidden;
q.title = t("Words match a model's id, name, provider or a group's models");
const words = modelQuery.trim().toLowerCase().split(/\s+/).filter(Boolean);
const models = q.hidden ? all : all.filter((m) => {
const hay = `${m.id} ${m.name || ""} ${m.provider.name} ${(m.members || []).join(" ")}`.toLowerCase();
return words.every((w) => hay.includes(w));
});
$("#copyModels").hidden = !models.length || list.hidden;
$("#copyModels").onclick = () => copy(models.map((m) => m.id).join("\n"), t("Model ids"));
if (!all.length) {
const empty = el("div", "empty-state", "");
empty.append(el("b", "", t("No models exposed yet")), t("Add a provider, or sign in to Codex or Copilot; their models show up here for every agent."));
list.append(empty);
return;
}
if (!models.length) {
list.append(el("div", "none", t("No models match “{q}”", { q: modelQuery.trim() })));
return;
}
for (const m of models) {
const row = el("div", "row model" + (m.id === (FLAVORS[flavor]?.decide ? decideModel : exampleModel) ? " selected" : ""));
const who = el("div", "who");
const name = el("div", "name", m.id);
if (namedFree(m.id, m.name)) name.append(freeBadge(false));
who.append(name, el("div", "sub", m.name && m.name !== m.id.split("/")[1] ? `${m.name} · ${m.provider.name}` : m.provider.name));
row.append(m.group ? stackIcon(m.icons) : icon(m.provider.icon || "generic"), who, modelInfo(m), copyBtn(m.id, t("Model id")));
row.title = t("Use this model in the snippets");
// a decision model is put in System One's snippets, any other in the
// other APIs'; the API follows the model clicked
row.onclick = () => {
const selection = window.getSelection();
if (selection && !selection.isCollapsed && row.contains(selection.anchorNode)) return;
const so = decideEntry(m);
if (so) { decideModel = m.id; localStorage.setItem("magpie.decideModel", m.id); }
else { exampleModel = m.id; localStorage.setItem("magpie.model", m.id); }
if (so !== !!FLAVORS[flavor]?.decide) { flavor = so ? "systemone" : "openai"; localStorage.setItem("magpie.flavor", flavor); }
renderConnect(); renderGatewayModels();
};
list.append(row);
}
}
// What agents are told of a model on the Gateway list (ARNO on Discord:
// 支持显示模型或者模型组更多的信息): its reasoning levels, whether it takes
// images and the context it holds, as small chips at the row's end, and in
@@ -7371,96 +6818,6 @@ function archivePanel(name, id, redraw) {
return box;
}
// A recent call's bodies, which /api/providers leaves out: forty calls'
// bodies made every refresh of it 20 MB (#1521).
function loadCallBodies(c, id) {
const pending = { busy: true };
callBodies.set(id, pending);
api(`gateway/call?id=${encodeURIComponent(c.id)}`)
.then((body) => { if (callBodies.get(id) === pending) callBodies.set(id, body); })
.catch((e) => { if (callBodies.get(id) === pending) callBodies.set(id, { error: t(e.message) }); })
.finally(() => { if (view === "gateway" && providers) renderActivity(); });
}
// a recent call's row: by the gateway's number for it, as two calls of
// one agent to one model can come in the same instant
const callRow = (c) => (c.id ? `#${c.id}` : `${c.time}|${c.agent}|${c.model}`);
function renderActivity() {
const g = providers.gateway;
// what calls left the ring keep, they let go of
const ids = new Set(g.calls.map(callRow));
for (const id of callBodies.keys()) if (!ids.has(id)) callBodies.delete(id);
for (const id of expandedCalls) if (!ids.has(id)) expandedCalls.delete(id);
const box = $("#activity");
// a body being read keeps its place as new calls come in
const kept = new Map();
for (const item of box.querySelectorAll(".call-item[data-id]")) kept.set(item.dataset.id, [...item.querySelectorAll("pre")].map((p) => p.scrollTop));
box.replaceChildren();
$("#callsNote").textContent = g.running && !g.mine ? t("shown by the magpie that serves the gateway") : "";
const calls = g.calls.slice(0, callsShown);
if (!calls.length) { box.append(el("div", "none", t("No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens."))); return; }
for (const c of calls) {
const id = callRow(c);
const open = expandedCalls.has(id);
const item = el("div", "call-item" + (open ? " open" : "") + (c.status >= 400 ? " bad" : ""));
const r = el("div", "call");
r.setAttribute("role", "button");
r.setAttribute("tabindex", "0");
r.setAttribute("aria-expanded", String(open));
const chev = el("span", "call-chev");
chev.append(svg(CHEV_R, 11, 1.6));
r.append(chev);
r.append(el("span", "when", new Date(c.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit" })));
r.append(el("span", "a", c.agent || "—"));
r.append(el("span", "m", c.model));
r.append(el("span", "p", c.from === c.to ? c.from : `${c.from} → ${c.to}`));
r.append(el("span", "grow"));
r.append(el("span", "st", c.error ? `${c.status} ${c.error}` : `${c.status} · ${ledTook(c.ms)}` + (c.ttft ? " · " + t("TTFT {ms}", { ms: ledTook(c.ttft) }) : "")));
r.title = open ? t("Hide request and response bodies") : t("Show request and response bodies");
const toggle = () => {
if (expandedCalls.has(id)) expandedCalls.delete(id); else expandedCalls.add(id);
renderActivity();
};
r.onclick = toggle;
r.onkeydown = (ev) => {
if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); toggle(); }
};
item.append(r);
if (open) {
if (!callBodies.has(id)) loadCallBodies(c, id);
const body = callBodies.get(id);
const details = el("div", body.busy || body.error ? "" : "call-details");
if (body.busy) details.append(el("div", "none", t("Fetching…")));
else if (body.error) {
details.append(el("div", "call-archive-err", body.error));
const retry = el("button", "text", t("Try again"));
retry.onclick = () => { loadCallBodies(c, id); renderActivity(); };
details.append(retry);
} else details.append(
callBodyPanel("Request Body", body.requestBody, body.requestTruncated, undefined, id + "|req"),
callBodyPanel("Response Body", body.responseBody, body.responseTruncated, id),
);
item.dataset.id = id;
item.append(details);
}
box.append(item);
}
if (g.calls.length > calls.length) {
const more = el("button", "text activity-more");
more.textContent = t("Show {n} more", { n: Math.min(CALLS_PAGE, g.calls.length - calls.length) });
more.onclick = () => {
callsShown = Math.min(g.calls.length, callsShown + CALLS_PAGE);
renderActivity();
};
box.append(more);
}
for (const item of box.querySelectorAll(".call-item[data-id]")) {
const tops = kept.get(item.dataset.id) || [];
item.querySelectorAll("pre").forEach((p, i) => { if (tops[i]) p.scrollTop = tops[i]; });
}
}
// An agent's model field, and whether any of its options come from provider p.
function modelField(a) {
const agent = state.agents.find((x) => x.id === a.id);
@@ -24381,15 +23738,15 @@ async function show(v) {
$("#prefs").classList.toggle("on", v === "settings");
if (v === "settings") $("#prefs").setAttribute("aria-current", "page"); else $("#prefs").removeAttribute("aria-current");
navSubs();
for (const id of ["agents", "providers", "gateway", "routing", "usage", "sessions", "library", "plugins", "settings"]) $("#view-" + id).hidden = v !== id;
for (const id of ["agents", "providers", "routing", "usage", "sessions", "library", "plugins", "settings", ...magpie.pages()]) $("#view-" + id).hidden = v !== id;
// back to where the reader was in it, and again once it has what it loads
const back = () => backToReader($("#view-" + v));
requestAnimationFrame(back);
closePicker();
closeAgentModels();
if (v !== "providers" && editing !== null) cancelEdit(true);
if (v === "gateway") loadGatewayKeys();
if (v === "providers" || v === "gateway" || v === "routing") loadProviders().then(back, (e) => status(e.message, "err"));
magpie.call(v, "open");
if (v === "providers" || v === "routing" || providersPage(v)) loadProviders().then(back, (e) => status(e.message, "err"));
// Routing's accounts show their windows as the Usage page read them
// (#1833): what is kept, read in an ordinary way, never an asked read
if (v === "routing" && (!quotas || Date.now() - quotasAt > 60e3)) loadQuotas();
@@ -24438,6 +23795,8 @@ function navHides() {
// to Agents (Providers in gateway mode)
function applyFeatures(list) {
if (!Array.isArray(list)) return;
// each plugin's settings to its code in the page (kernel.js)
for (const f of list) if (f.schema) magpie.configure(f.id, f.config);
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;
@@ -24452,10 +23811,12 @@ function applyFeatures(list) {
// 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.
// switched until it is fixed. done gets the list after a switch. One on
// with settings has them under it, a row each, drawn from their schema
// (kernel.js's ui.form) and saved as each is changed.
function renderBuiltins(box, list, done) {
const broken = list.find((f) => f.broken)?.broken;
const rows = list.map((f) => {
const rows = list.flatMap((f) => {
const r = el("div", "row pref feat-row");
r.dataset.id = f.id;
const who = el("div", "who");
@@ -24484,7 +23845,24 @@ function renderBuiltins(box, list, done) {
}
};
r.append(who, b);
return r;
if (!f.on || !f.schema || broken) return [r];
const form = magpie.ui.form(f.schema, f.config, async (change) => {
try {
const next = await api("plugins/builtin", { id: f.id, config: change });
if (state.settings) state.settings.builtins = next;
applyFeatures(next);
done(next);
status(t("Saved"), "ok", 1500);
} catch (err) {
status(t(err.message), "err");
done(list);
}
});
for (const s of form) {
s.classList.add("feat-set");
s.dataset.of = f.id;
}
return [r, ...form];
});
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 })));
@@ -24500,7 +23878,6 @@ function openSettings() {
show("settings");
}
$("#prefs").onclick = () => { openSettings(); $("#prefs").blur(); };
$("#openLanSettings").onclick = () => { openSettings(); setSetTab("network", true); };
// The header's refresh reads again what the page shown draws (#844): on
// Agents it looks for the agents on this computer again (one just installed
@@ -25511,13 +24888,15 @@ if (mode === "window" && params.get("view") === "usage") {
for (const k of ["tab", "provider", "agent", "computer", "card", "purpose", "via", "period"]) u.searchParams.delete(k);
history.replaceState(null, "", u);
}
// the plugins' pages wired up (kernel.js), before the first is shown
magpie.start();
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
// leaves out, or one there is no longer, gives way to the first page.
// the pages the window can open on besides the first (Agents)
const OPEN_VIEWS = ["providers", "gateway", "routing", "usage", "sessions", "library", "plugins", "settings"];
const OPEN_VIEWS = ["providers", "routing", "usage", "sessions", "library", "plugins", "settings", ...magpie.pages()];
function keptView() {
const asked = params.get("view");
if (asked === "agents" || OPEN_VIEWS.includes(asked)) return asked;
+28
View File
@@ -786,6 +786,13 @@ const I18N = {
"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": "正在使用,因此保持开启",
"Gateway page": "网关页面",
"The gateway's state and keys, how to connect a client, its models and recent calls": "网关的状态与密钥、客户端如何连接、它的模型和最近的调用",
"1 gateway key": "1 个网关密钥",
"{n} gateway keys": "{n} 个网关密钥",
"Recent calls at a time": "每次显示的最近调用",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "页面显示多少条网关最近的调用,以及每次“显示其余”再多显示多少条",
"This page stopped working": "此页面已停止工作",
"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",
@@ -5508,6 +5515,13 @@ const I18N = {
"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": "正在使用,因此保持開啟",
"Gateway page": "閘道頁面",
"The gateway's state and keys, how to connect a client, its models and recent calls": "閘道的狀態與金鑰、用戶端如何連線、它的模型和最近的呼叫",
"1 gateway key": "1 個閘道金鑰",
"{n} gateway keys": "{n} 個閘道金鑰",
"Recent calls at a time": "每次顯示的最近呼叫",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "頁面顯示多少筆閘道最近的呼叫,以及每次「顯示其餘」再多顯示多少筆",
"This page stopped working": "此頁面已停止運作",
"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",
@@ -10189,6 +10203,13 @@ const I18N = {
"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": "使用中のためオンのままです",
"Gateway page": "ゲートウェイページ",
"The gateway's state and keys, how to connect a client, its models and recent calls": "ゲートウェイの状態とキー、クライアントの接続方法、モデルと最近の呼び出し",
"1 gateway key": "ゲートウェイキー 1 個",
"{n} gateway keys": "ゲートウェイキー {n} 個",
"Recent calls at a time": "一度に表示する最近の呼び出し",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "ページに表示するゲートウェイの最近の呼び出しの数と、「さらに表示」ごとに追加する数",
"This page stopped working": "このページは動作を停止しました",
"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": "現在オン:このコンピューターにエージェントがありません",
@@ -14891,6 +14912,13 @@ const I18N = {
"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",
"Gateway page": "Gateway-Seite",
"The gateway's state and keys, how to connect a client, its models and recent calls": "Zustand und Schlüssel des Gateways, wie sich ein Client verbindet, seine Modelle und letzten Aufrufe",
"1 gateway key": "1 Gateway-Schlüssel",
"{n} gateway keys": "{n} Gateway-Schlüssel",
"Recent calls at a time": "Letzte Aufrufe auf einmal",
"How many of the gateway's recent calls the page shows, and how many more each Show more adds": "Wie viele der letzten Aufrufe des Gateways die Seite zeigt und wie viele jedes „weitere anzeigen“ hinzufügt",
"This page stopped working": "Diese Seite funktioniert nicht mehr",
"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",
+8 -20
View File
@@ -27,7 +27,7 @@
<div class="side-top" style="--wails-draggable:drag"></div>
<div class="side-scroll"></div>
<div class="side-foot">
<button type="button" class="side-gw" id="sideGw" hidden><i></i><span></span></button>
<button type="button" class="side-gw" id="sideGw" data-feature="gateway" hidden><i></i><span></span></button>
</div>
<!-- its edge, dragged to make it wider or narrower (app.js sideDrag) -->
<div class="side-edge" id="sideEdge" role="separator" aria-orientation="vertical" tabindex="0" style="--wails-draggable:no-drag"></div>
@@ -52,7 +52,7 @@
<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>
<button data-view="gateway"><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"><rect x="3" y="4" width="14" height="5" rx="1.5"/><rect x="3" y="11" width="14" height="5" rx="1.5"/><path d="M6 6.5h.01M6 13.5h.01"/></g></svg><span data-t>Gateway</span></button>
<button data-view="gateway" data-feature="gateway"><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"><rect x="3" y="4" width="14" height="5" rx="1.5"/><rect x="3" y="11" width="14" height="5" rx="1.5"/><path d="M6 6.5h.01M6 13.5h.01"/></g></svg><span data-t>Gateway</span></button>
<span class="nav-gl" data-t>Insights</span>
<button data-view="usage"><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 16V9M8 16V5M12 16v-5M16 16V7"/></g></svg><span data-t>Usage</span></button>
<span class="nav-gl" data-t>Extend</span>
@@ -121,23 +121,8 @@
<section class="sheet" id="addSheet" hidden></section>
</main>
<main class="view" id="view-gateway" hidden>
<div class="list gwcard">
<div class="row gw" id="gateway"></div>
</div>
<section id="gatewayKeysBlock" hidden>
<div class="row-head"><span class="label" data-t>Gateway keys</span><span class="grow"></span><button class="text" id="addGatewayKey" data-t>Add gateway key</button></div>
<p class="usage-note" data-t>Create a gateway key for each client. Usage is counted separately for each key.</p>
<section id="gatewayKeys"></section>
</section>
<p class="usage-note gw-keys-off" id="gatewayKeysOff" hidden><span data-t>Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.</span> <button class="text" id="openLanSettings" data-t>Network and sharing</button></p>
<div class="row-head"><button class="fold" id="foldConnect" aria-expanded="true" aria-controls="connect"><span class="label" data-t>Connect</span></button><span class="grow"></span><span class="note" id="connectNote"></span></div>
<section class="list connect" id="connect"></section>
<div class="row-head"><button class="fold" id="foldModels" aria-expanded="true" aria-controls="gwModels"><span class="label" data-t>Models</span><span class="note" id="modelsCount"></span></button><span class="grow"></span><button class="text" id="copyModels" data-t>Copy all ids</button></div>
<div class="list" id="gwModels"></div>
<div class="row-head"><span class="label" data-t>Recent calls</span><span class="grow"></span><span class="note" id="callsNote"></span></div>
<div class="list activity" id="activity"></div>
</main>
<!-- the pages plugins add (kernel.js) go here, in the order they register -->
<template data-slot="page"></template>
<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>
@@ -568,7 +553,10 @@
</div>
<script src="i18n.js"></script>
<script src="caller-keys.js"></script>
<script src="kernel.js"></script>
<!-- the built-in plugins' own scripts (pluginrt.Manifest.Client) -->
<script src="plugins/gateway/keys.js"></script>
<script src="plugins/gateway/client.js"></script>
<script src="purposes.js"></script>
<script src="app.js"></script>
<script src="routing.js"></script>
+252
View File
@@ -0,0 +1,252 @@
// The window's plugin kernel (docs/subsystems/plugin-runtime.md, P1). A
// plugin's page is a part it adds to the "page" slot: its markup, put in the
// page where index.html's <template data-slot="page"> is, and its hooks,
// which the shell calls through magpie.call. A hook that throws breaks only
// its own page: the page says so, with a Try again, and the other pages go
// on (the error boundary). ctx.ui is the kit a plugin draws with, and
// ui.form draws a plugin's settings from the schema the Go side made of
// them (pluginrt.SchemaOf).
//
// Loaded after i18n.js and before the plugins' scripts and app.js. A
// plugin's scripts register at once, so its page is in the page before
// app.js looks for it, but run nothing of app.js's then: mount runs at
// magpie.start, which app.js calls once it is set up.
(() => {
const plugins = new Map(); // id → { id, config, onConfig: [], disposers: [] }
const pages = new Map(); // key → { plugin, part, main, mounted, broken }
let started = false;
function context(p) {
return {
id: p.id,
get config() { return p.config; },
// a change of the plugin's settings (Plugins › Built-in), after
// ctx.config has it
onConfig(fn) { p.onConfig.push(fn); },
onDispose(fn) { p.disposers.push(fn); },
slots: { add: (slot, part) => add(p, slot, part) },
ui,
};
}
function add(p, slot, part) {
if (slot !== "page") throw new Error(`no slot ${slot}`);
if (!/^[a-z][a-z0-9-]*$/.test(part.key || "") || pages.has(part.key) || document.getElementById("view-" + part.key)) {
throw new Error(`page ${part.key} is taken`);
}
const main = document.createElement("main");
main.className = "view";
main.id = "view-" + part.key;
main.hidden = true;
main.dataset.feature = p.id;
main.innerHTML = part.html || "";
const anchor = document.querySelector('template[data-slot="page"]');
if (anchor) anchor.before(main);
else document.body.append(main);
const page = { plugin: p, part, main, mounted: false, broken: null };
pages.set(part.key, page);
if (started) run(page, "mount", [main]);
}
// The error boundary: a hook that throws (or whose promise fails) is
// caught here, and the page shows what broke instead of what it had.
function fail(page, hook, args, err) {
console.error(`[magpie] ${page.plugin.id}: ${page.part.key}.${hook}`, err);
page.broken = { hook, args };
const card = document.createElement("div");
card.className = "list slot-error";
card.setAttribute("role", "alert");
const row = document.createElement("div");
row.className = "row";
const who = document.createElement("div");
who.className = "who";
const name = document.createElement("div");
name.className = "name";
name.textContent = t("This page stopped working");
const sub = document.createElement("div");
sub.className = "sub";
sub.textContent = String(err?.message || err);
who.append(name, sub);
const again = document.createElement("button");
again.type = "button";
again.className = "text slot-again";
again.textContent = t("Try again");
again.onclick = () => retry(page);
row.append(who, again);
card.append(row);
page.main.classList.remove("loading");
page.main.removeAttribute("aria-busy");
page.main.replaceChildren(card);
}
// Try again: the page's markup as it came, mounted again, and the hook
// that broke run again with what it was given.
function retry(page) {
const { hook, args } = page.broken;
page.broken = null;
page.mounted = false;
page.main.innerHTML = page.part.html || "";
window.translateStatic?.();
if (hook !== "mount") run(page, "mount", [page.main]);
run(page, hook, args);
}
function run(page, hook, args) {
if (page.broken) return undefined;
if (hook === "mount") {
if (page.mounted) return undefined;
page.mounted = true;
} else if (!page.mounted && started) {
run(page, "mount", [page.main]);
if (page.broken) return undefined;
}
const fn = page.part[hook];
if (typeof fn !== "function") return undefined;
try {
const out = fn.apply(page.part, args);
if (out && typeof out.then === "function") {
return out.catch((err) => { if (!page.broken) fail(page, hook, args, err); });
}
return out;
} catch (err) {
fail(page, hook, args, err);
return undefined;
}
}
// ---------- the kit ----------
// What a plugin draws with, as the rest of the window draws: el, the app
// menu (never a native <select>), the switch, the settings row.
const ui = {
el: (tag, cls, text) => el(tag, cls, text),
button(label, onClick, cls = "text") {
const b = el("button", cls, label);
b.type = "button";
b.onclick = onClick;
return b;
},
toggle(on, label, onChange) {
const b = el("button", "lib-switch use-credits" + (on ? " on" : ""));
b.type = "button";
b.setAttribute("role", "switch");
b.setAttribute("aria-checked", String(on));
b.setAttribute("aria-label", label);
b.append(el("i"));
b.onclick = () => {
on = !on;
b.classList.toggle("on", on);
b.setAttribute("aria-checked", String(on));
onChange(on);
};
return b;
},
// a pick of one of opts ([{ v, name }]), in the app's menu
menu(opts, value, head, onPick) {
const b = el("button", "proto pick");
b.type = "button";
const paint = () => {
const o = opts.find((x) => x.v === value);
b.replaceChildren(el("span", "", o ? o.name : String(value)), svg(CHEV, 11, 1.6));
};
paint();
b.onclick = (ev) => {
ev.stopPropagation();
openProtoMenu(b, opts.map((o) => ({ ...o, literalName: true, note: "" })), value, (v) => {
value = v;
paint();
onPick(v);
}, head, "", "right");
};
return b;
},
// a settings row: what it is, and its control at the end
row(title, description, control) {
const r = el("div", "row pref");
const who = el("div", "who");
who.append(el("div", "name", title));
if (description) who.append(el("div", "sub", description));
r.append(who, control);
return r;
},
// The rows of a plugin's settings, drawn from its schema: true or false
// a switch, one of a few a menu, a number a field kept to its range,
// text a field. onChange gets { key: value } for the one changed.
form(schema, values, onChange) {
const rows = [];
for (const key of schema?.["x-order"] || Object.keys(schema?.properties || {})) {
const p = schema.properties[key];
if (!p) continue;
const value = values?.[key] ?? p.default;
const title = t(p.title), say = p.description ? t(p.description) : "";
let control;
if (p.type === "boolean") control = ui.toggle(!!value, title, (v) => onChange({ [key]: v }));
else if (p.enum?.length) {
control = ui.menu(p.enum.map((v) => ({ v, name: typeof v === "number" ? v.toLocaleString(locale) : t(String(v)) })), value, p.title, (v) => onChange({ [key]: v }));
} else {
const number = p.type === "integer" || p.type === "number";
control = el("input", "set-field");
control.type = number ? "number" : "text";
control.value = value ?? "";
control.setAttribute("aria-label", title);
if (number) {
if (p.minimum !== undefined) control.min = p.minimum;
if (p.maximum !== undefined) control.max = p.maximum;
if (p.type === "integer") control.step = 1;
}
control.onchange = () => {
let v = control.value;
if (number) {
v = Number(v);
const bad = control.value === "" || !Number.isFinite(v) || (p.type === "integer" && !Number.isInteger(v))
|| (p.minimum !== undefined && v < p.minimum) || (p.maximum !== undefined && v > p.maximum);
control.setAttribute("aria-invalid", String(bad));
if (bad) return;
}
onChange({ [key]: v });
};
}
const r = ui.row(title, say, control);
r.dataset.setting = key;
rows.push(r);
}
return rows;
},
};
window.magpie = {
ui,
plugin(id, setup) {
if (plugins.has(id)) throw new Error(`plugin ${id} is registered twice`);
const p = { id, config: { ...(window.bootPrefs?.pluginConfig?.[id] || {}) }, onConfig: [], disposers: [] };
plugins.set(id, p);
try {
setup(context(p));
} catch (err) {
console.error(`[magpie] ${id}: setup`, err);
}
},
// app.js, once it is set up: every page is mounted
start() {
if (started) return;
started = true;
for (const page of pages.values()) run(page, "mount", [page.main]);
},
// a page's hook, behind the boundary; nothing for a page no plugin has
call(key, hook, ...args) {
const page = pages.get(key);
return page ? run(page, hook, args) : undefined;
},
page: (key) => pages.get(key)?.part,
pages: () => [...pages.keys()],
// the plugins' settings as Plugins › Built-in or boot.js has them
configure(id, config) {
const p = plugins.get(id);
if (!p || !config) return;
if (JSON.stringify(p.config) === JSON.stringify(config)) return;
p.config = { ...config };
for (const fn of p.onConfig) {
try { fn(p.config); } catch (err) { console.error(`[magpie] ${id}: config`, err); }
}
},
};
})();
@@ -0,0 +1,713 @@
// The Gateway page (plugins/gateway): the gateway's state and its keys
// (keys.js), how to connect a client, its models and its recent calls. It
// is a page the plugin adds to the window (kernel.js): its markup is the
// html below, and the shell draws it through its hooks — loading before
// the state is in, draft from the state kept, render with the new one —
// behind the kernel's error boundary.
//
// Classic script, loaded before app.js: what runs as it loads touches
// neither the page nor app.js; mount, at magpie.start, wires the page.
// the gateway tab's choices, kept per machine
const gwParams = new URLSearchParams(location.search);
let flavor = gwParams.get("flavor") || localStorage.getItem("magpie.flavor") || "openai"; // which API the snippets speak
let lang = gwParams.get("lang") || localStorage.getItem("magpie.lang") || "shell"; // which snippet
let snipOS = localStorage.getItem("magpie.snipOS") || ""; // the shell the Shell and curl snippets are for (#1514)
let exampleModel = localStorage.getItem("magpie.model") || ""; // the model in the snippets
let decideModel = localStorage.getItem("magpie.decideModel") || ""; // the System One snippets' decision model
let connectFolded = false; // Connect folded away under its heading
try { connectFolded = localStorage.getItem("magpie.gwConnectFolded") === "1"; } catch {}
const expandedCalls = new Set(); // recent-call ids whose wire bodies are open
const callBodies = new Map(); // callRow → its bodies, read when it is opened (#1521)
// recent calls drawn a page at a time, as many as the plugin's setting
// says (callsPage)
let callsPage = 20;
let callsShown = callsPage;
function renderGatewayLoading() {
const page = $("#view-gateway");
page.classList.add("loading");
page.setAttribute("aria-busy", "true");
$("#connectNote").textContent = "";
$("#callsNote").textContent = "";
$("#copyModels").hidden = true;
const gateway = $("#gateway");
gateway.replaceChildren();
const mark = el("span", "skeleton gw-sk-dot");
const who = el("div", "who gw-sk-who");
who.append(el("span", "skeleton gw-sk-title"), el("span", "skeleton gw-sk-sub"));
gateway.append(mark, who, el("span", "skeleton gw-sk-url"));
const connect = $("#connect");
connect.replaceChildren();
connect.hidden = connectFolded;
for (let i = 0; i < 4; i++) {
connect.append(el("span", "skeleton gw-sk-label"));
const value = el("div", "gw-sk-field");
value.append(el("span", "skeleton"), el("span", "skeleton short"));
connect.append(value);
}
const models = $("#gwModels");
models.replaceChildren();
for (let i = 0; i < 4; i++) {
const row = el("div", "row model gw-sk-row");
row.append(el("span", "skeleton gw-sk-model"), el("span", "grow"), el("span", "skeleton gw-sk-provider"));
models.append(row);
}
const activity = $("#activity");
activity.replaceChildren();
for (let i = 0; i < 4; i++) {
const row = el("div", "call gw-sk-call");
row.append(el("span", "skeleton time"), el("span", "skeleton agent"), el("span", "skeleton model"), el("span", "grow"), el("span", "skeleton result"));
activity.append(row);
}
}
function renderGatewayView() {
const page = $("#view-gateway");
page.classList.remove("loading");
page.removeAttribute("aria-busy");
renderGateway();
$("#gatewayKeysBlock").hidden = !providers.gateway.lan;
// not shared, the keys are left out; this line says where they come from,
// as a tunnel to loopback is refused until sharing is on (DD on Discord)
$("#gatewayKeysOff").hidden = !!providers.gateway.lan;
if (!providers.gateway.lan) gatewayKeyDraft = null;
if (gatewayKeyDraft === null && gatewayLimit === null && !$("#gatewayKeys .rename-in")) renderGatewayKeys();
renderConnect();
renderGatewayModels();
renderActivity();
}
// The status card's button (leslie_luo on Discord: told to quit the older
// magpie serving the gateway, with no way to tell which one it was): with
// an older magpie on the port it quits that one, checked to be magpie by
// its process, and this one serves the gateway at once; otherwise it
// restarts the gateway this one serves, or starts it. A magpie of this
// version or newer serving it gets none: that one is not to be quit here.
// What stood in the way stays under it until the gateway's state changes.
let gatewayFix = { busy: false, err: "", when: "" };
const gatewayFixWhen = (g) => [g.running, g.mine, g.version || ""].join("|");
function gatewayFixButton(g, older) {
if (g.running && !g.mine && !older) return null;
// bordered: a plain text button read as words on the card in dark mode
const b = el("button", "text action gw-fix");
b.textContent = gatewayFix.busy
? (older ? t("Quitting magpie {v}…", { v: g.version }) : t(g.running ? "Restarting the gateway…" : "Starting the gateway…"))
: (older ? t("Quit magpie {v} and take over", { v: g.version }) : t(g.running ? "Restart gateway" : "Start gateway"));
b.disabled = gatewayFix.busy;
b.onclick = async () => {
const when = gatewayFixWhen(g);
gatewayFix = { busy: true, err: "", when };
renderGateway();
let out;
try { out = await api(older ? "gateway/take-over" : "gateway/restart", {}); } catch (e) { out = { reason: "error", error: e.message }; }
gatewayFix = { busy: false, err: out?.ok ? "" : gatewayFixSays(out || {}), when };
try { await loadProviders(); } catch {}
renderGateway();
};
return b;
}
// gatewayFixSays is why a take-over or a restart didn't go, in the page's
// language, naming the process it was
function gatewayFixSays(o) {
const p = { port: o.port || "", pid: o.pid || "", path: o.path || "", v: o.version || "", error: o.error || "" };
switch (o.reason) {
case "not-magpie": return t("Port {port} is held by {path} (pid {pid}), which isn't magpie, so magpie leaves it alone. Quit it yourself, or move the gateway to another port in Settings.", p);
// leslie_luo on Discord: an old magpie in OrbStack, its helper named
// as the program to quit
case "container": return t("Port {port} is forwarded by {path} (pid {pid}) to a container or a VM: the magpie {v} answering there runs inside it, out of this magpie's reach. Stop that container (docker ps lists it, docker stop <name> stops it, or stop it in OrbStack or Docker Desktop), or move this magpie's gateway to another port in Settings.", p);
case "unseen": return t("magpie can't see which process holds port {port}: it runs as another user or as administrator. Quit it there.", p);
case "denied": return t("magpie {v} (pid {pid}, {path}) runs as another user or as administrator, so this magpie can't quit it. Quit it there.", p);
case "stuck": return t("magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).", p);
case "respawned": return t("Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.", p);
case "taken": return p.pid
? t("Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.", p)
: t("Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.", p);
case "other": return t("magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.", p);
}
return t("The gateway couldn't be served here: {error}", p);
}
// The status card: dot, state, the URL.
function renderGateway() {
const g = providers.gateway;
const box = $("#gateway");
box.replaceChildren();
// an older magpie keeping the port sends every agent's request its own
// way, without this version's fixes (#506): said in place of the counts
const older = g.running && !g.mine && g.older;
const dot = el("span", "dot " + (older ? "old" : g.running ? "on" : ""));
const who = el("div", "who");
const name = el("div", "name", t("Gateway"));
name.append(el("span", "state", older
? t("running · served by magpie {v}, older than this one", { v: g.version })
: t(g.running ? (g.mine ? "running" : "running · served by another magpie") : "not running")));
const routed = new Set();
for (const p of providers.providers) for (const a of p.agents) if (a.current) routed.add(a.id);
const n = routed.size;
if (older) {
who.append(name, el("div", "sub old", t("Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.", { v: g.version })));
} else who.append(name, el("div", "sub", g.running
? [t(g.models === 1 ? "{n} model" : "{n} models", { n: g.models }), n ? t(n === 1 ? "{n} agent routed through it" : "{n} agents routed through it", { n }) : t("no agent routed through it yet"), t("five APIs, one URL")].join(" · ")
: t("start it with magpie serve, or open magpie at login")));
const fix = gatewayFixButton(g, older);
if (fix) who.append(fix);
if (gatewayFix.err && gatewayFix.when === gatewayFixWhen(g)) who.append(el("div", "sub old err", gatewayFix.err));
// served to other machines' browsers (magpie web), the address shown is
// the one they reach, MAGPIE_PUBLIC_URL's, not this computer's loopback
// (#1551)
const shown = web && g.publicURL || g.url;
const url = el("button", "url");
url.append(el("code", "", shown));
url.title = t("Copy the gateway URL");
url.onclick = () => copy(shown, t("Gateway URL"));
box.append(dot, who, url);
}
// One entry per API the gateway serves: where each SDK's base URL points,
// the env vars the usual tools read, and a request in four dialects.
const FLAVORS = {
openai: {
name: "OpenAI", base: (u) => u + "/v1", baseEnv: "OPENAI_BASE_URL", keyEnv: "OPENAI_API_KEY",
note: "Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.",
curl: (b, m, k = "magpie") => ({ url: `${b}/chat/completions`, headers: [`Authorization: Bearer ${k}`],
body: `{"model": "${m}",\n "messages": [{"role": "user", "content": "hi"}]}` }),
python: (b, m, k = "magpie") => `from openai import OpenAI
client = OpenAI(base_url="${b}", api_key="${k}")
r = client.chat.completions.create(
model="${m}",
messages=[{"role": "user", "content": "hi"}],
)
print(r.choices[0].message.content)`,
node: (b, m, k = "magpie") => `import OpenAI from "openai";
const client = new OpenAI({ baseURL: "${b}", apiKey: "${k}" });
const r = await client.chat.completions.create({
model: "${m}",
messages: [{ role: "user", content: "hi" }],
});
console.log(r.choices[0].message.content);`,
},
responses: {
name: "Responses", base: (u) => u + "/v1", baseEnv: "OPENAI_BASE_URL", keyEnv: "OPENAI_API_KEY",
note: "OpenAI's newer API: reasoning, built-in tool items, encrypted reasoning. Codex speaks this.",
curl: (b, m, k = "magpie") => ({ url: `${b}/responses`, headers: [`Authorization: Bearer ${k}`],
body: `{"model": "${m}", "input": "hi"}` }),
python: (b, m, k = "magpie") => `from openai import OpenAI
client = OpenAI(base_url="${b}", api_key="${k}")
r = client.responses.create(model="${m}", input="hi")
print(r.output_text)`,
node: (b, m, k = "magpie") => `import OpenAI from "openai";
const client = new OpenAI({ baseURL: "${b}", apiKey: "${k}" });
const r = await client.responses.create({ model: "${m}", input: "hi" });
console.log(r.output_text);`,
},
anthropic: {
name: "Anthropic", base: (u) => u, baseEnv: "ANTHROPIC_BASE_URL", keyEnv: "ANTHROPIC_API_KEY",
note: "Messages API. Claude Code reads ANTHROPIC_AUTH_TOKEN instead of the key; the Agents tab sets that for you.",
curl: (b, m, k = "magpie") => ({ url: `${b}/v1/messages`, headers: [`x-api-key: ${k}`, "anthropic-version: 2023-06-01"],
body: `{"model": "${m}", "max_tokens": 1024,\n "messages": [{"role": "user", "content": "hi"}]}` }),
python: (b, m, k = "magpie") => `import anthropic
client = anthropic.Anthropic(
base_url="${b}", api_key="${k}",
)
m = client.messages.create(
model="${m}",
max_tokens=1024,
messages=[{"role": "user", "content": "hi"}],
)
print(m.content[0].text)`,
node: (b, m, k = "magpie") => `import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ baseURL: "${b}", apiKey: "${k}" });
const m = await client.messages.create({
model: "${m}",
max_tokens: 1024,
messages: [{ role: "user", content: "hi" }],
});
console.log(m.content[0].text);`,
},
gemini: {
name: "Gemini", base: (u) => u, baseEnv: "GOOGLE_GEMINI_BASE_URL", keyEnv: "GEMINI_API_KEY",
note: "Google's generateContent API, v1beta. Gemini CLI and the google-genai SDKs speak this.",
curl: (b, m, k = "magpie") => ({ url: `${b}/v1beta/models/${m}:generateContent`, headers: [`x-goog-api-key: ${k}`],
body: `{"contents": [{"parts": [{"text": "hi"}]}]}` }),
python: (b, m, k = "magpie") => `from google import genai
client = genai.Client(api_key="${k}", http_options={"base_url": "${b}"})
r = client.models.generate_content(model="${m}", contents="hi")
print(r.text)`,
node: (b, m, k = "magpie") => `import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: "${k}",
httpOptions: { baseUrl: "${b}" },
});
const r = await ai.models.generateContent({ model: "${m}", contents: "hi" });
console.log(r.text);`,
},
// magpie's own System One API (ARNO on Discord: gateway添加system one
// api 有想法吗): a decision model — Jev, Clef, Bailian's — answers typed
// questions about a state; no SDK speaks it, so no shell variables
systemone: {
name: "System One", base: (u) => u + "/v1", decide: true,
note: "TypeSafe's decision API: a Jev or Clef model answers typed questions (choice, noul, score) about a state, with how sure it is. Clef also reads images: add \"images\": [\"data:image/png;base64,…\"].",
curl: (b, m, k = "magpie") => ({ url: `${b}/systemone`, headers: [`Authorization: Bearer ${k}`],
body: `{"model": "${m}",\n "state": {"message": "My order never arrived, refund it"},\n "questions": {"team": {"type": "choice",\n "instructions": "Which team should answer the message?",\n "criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"}}}}` }),
python: (b, m, k = "magpie") => `import requests
r = requests.post("${b}/systemone",
headers={"Authorization": "Bearer ${k}"},
json={
"model": "${m}",
"state": {"message": "My order never arrived, refund it"},
"questions": {"team": {
"type": "choice",
"instructions": "Which team should answer the message?",
"criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"},
}},
})
a = r.json()["answers"]["team"]
print(a["choice"], a["confidence"])`,
node: (b, m, k = "magpie") => `const r = await fetch("${b}/systemone", {
method: "POST",
headers: { Authorization: "Bearer ${k}", "Content-Type": "application/json" },
body: JSON.stringify({
model: "${m}",
state: { message: "My order never arrived, refund it" },
questions: { team: {
type: "choice",
instructions: "Which team should answer the message?",
criteria: { billing: "Payments and refunds", shipping: "Deliveries", other: "Anything else" },
} },
}),
});
const a = (await r.json()).answers.team;
console.log(a.choice, a.confidence);`,
},
};
// The Shell and curl snippets are written for one shell: PowerShell on
// Windows ($env: in place of export, and the curl.exe that ships with it,
// as plain curl there is Invoke-WebRequest; the body goes in on stdin,
// since Windows PowerShell drops the quotes inside an argument), or a POSIX
// shell (bash, zsh) on macOS and Linux. They start as the shell of the
// machine magpie runs on, and can be switched to the other: a Windows
// desktop's user often runs them on a Linux server over ssh (FourLeafTec,
// #1514). The choice is kept with the snippet language.
const WIN = /^Win/.test(navigator.platform);
const SNIP_OSES = [["windows", "Windows"], ["unix", "macOS · Linux"]];
const snipWin = () => (SNIP_OSES.some(([id]) => id === snipOS) ? snipOS : WIN ? "windows" : "unix") === "windows";
const langs4 = () => [["shell", snipWin() ? "PowerShell" : "Shell"], ["curl", "curl"], ["python", "Python"], ["node", "Node"]];
// A word each shell takes as it is, quoted only where it has to be: a key
// of the user's own can hold any ASCII symbol (", $, `, ', !), and a model
// id brackets ([1m]) that zsh would glob; a comma would make PowerShell
// pass a list.
const plainWord = /^[\w%+=:./-]+$/;
const shQuote = (s) => (plainWord.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`);
// in "…" for a header's spaces, unless it holds what bash expands there
const shHeader = (s) => (/[$`"\\!]/.test(s) ? `'${s.replaceAll("'", `'\\''`)}'` : `"${s}"`);
const psQuote = (s) => (plainWord.test(s) ? s : `'${s.replace(/['‘’‚‛]/g, "$&$&")}'`);
// "…" as the C runtime splits a command line: \" for a quote, and the
// backslashes before one doubled
const winArg = (s) => (plainWord.test(s) ? s : `"${s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`);
const psHeader = (s) => (/[$`"“”„]/.test(s) ? `'${s.replace(/['‘’‚‛]/g, "$&$&")}'` : `"${s}"`);
function curlSnippet({ url, headers, body }) {
headers = [...headers, "Content-Type: application/json"];
// curl reads [ ] { } in a URL as a range unless told not to
const g = /[[\]{}]/.test(url) ? " -g" : "";
// A " inside an argument reaches curl.exe differently from Windows
// PowerShell 5.1 and from PowerShell 7, and whole from neither as
// written; after --% the line goes to curl.exe as it stands, on one line,
// quoted as the C runtime reads a command line. (A %NAME% of a variable
// the shell has is still put in there; a key would have to hold both.)
if (snipWin() && headers.some((h) => h.includes('"'))) return `@'\n${body}\n'@ | curl.exe --%${g} ${winArg(url)} ${headers.map((h) => `-H ${winArg(h)}`).join(" ")} --data-binary "@-"`;
if (snipWin()) return `@'\n${body}\n'@ | curl.exe${g} ${psQuote(url)} \`\n${headers.map((h) => ` -H ${psHeader(h)} \``).join("\n")}\n --data-binary "@-"`;
return `curl${g} ${shQuote(url)} \\\n${headers.map((h) => ` -H ${shHeader(h)} \\`).join("\n")}\n -d '${body.replaceAll("'", `'\\''`).replaceAll("\n", "\n ")}'`;
}
function envSnippet(vars) {
return vars.map(([k, v]) => (snipWin() ? `$env:${k}=${psHeader(v)}` : `export ${k}=${shQuote(v)}`)).join("\n");
}
// every exposed model, as the ids agents use
function gatewayModels() {
// the routing groups first, as the agents' pickers list them
// a group's lists may come as null (#1585): one such group mustn't take
// every model off the list
const out = (providers.gateway.groups || []).filter((g) => g && typeof g.id === "string").map((g) => ({ id: g.id, name: g.name || g.id, icons: g.icons || [], group: true,
provider: { name: [t("routing group"), (g.providers || []).join(", ")].filter(Boolean).join(" · ") },
efforts: g.efforts || [], images: !!g.images, context: g.context, output: g.output, members: g.members || [] }));
// a provider switched off is skipped: the gateway refuses its models, so
// they are not ids an agent can use, and listing them here would show a
// model the picker's own list, the Gateway count and the Connect example
// all say works but a request to it turns away (the same off gate the
// backend's providerEntries and the fallback picker already honour).
// the levels agents are offered: those kept, else all it has; one whose
// levels aren't known (given) offers only those it was given
const offered = (m) => m.kept?.length || m.given ? m.kept || [] : m.efforts || [];
for (const p of providers.providers) { if (p.off) continue; for (const m of p.models) if (m.on) out.push({ id: `${p.id}/${m.id}`, name: m.name, provider: p, context: m.context, output: m.output, efforts: offered(m), images: !!m.images }); }
return out;
}
// Connect is set up once and seldom looked at again, so it folds away under
// its heading, the base URL left beside it; the fold is remembered
// (connectFolded, with the tab's other choices at the top).
function renderConnect() {
const g = providers.gateway;
const box = $("#connect");
box.replaceChildren();
const f = FLAVORS[flavor] || FLAVORS.openai;
// System One's snippets take a decision model, the others any other
const models = gatewayModels().filter((m) => decideEntry(m) === !!f.decide);
let model;
if (f.decide) {
if (!models.some((m) => m.id === decideModel)) decideModel = models[0]?.id || "";
model = decideModel || "provider/jev-latest";
} else {
if (!models.some((m) => m.id === exampleModel)) exampleModel = models[0]?.id || "";
model = exampleModel || "provider/model";
}
// no SDK speaks System One, so it has no shell variables to set
const langs = f.baseEnv ? langs4() : langs4().filter(([id]) => id !== "shell");
const snipLang = langs.some(([id]) => id === lang) ? lang : "curl";
const urls = [g.url, ...(g.lanURLs || [])];
// the address picked is kept (coeo91): an address not offered right now
// (the network not up yet after a start) shows this computer's, and the
// pick comes back with it. With none picked, MAGPIE_PUBLIC_URL is where
// it starts: it says the address other machines use (#1551)
const first = g.publicURL && urls.includes(g.publicURL) ? g.publicURL : g.url;
connectURL = urls.includes(connectWant) ? connectWant : first;
// a gateway MAGPIE_ADDR puts on the network (a Docker image's, whose
// host is another machine to it) is shown with a gateway key everywhere
const remote = connectURL !== g.url || !!g.onNetwork;
const keys = g.lan ? (gatewayKeys || []).filter((k) => !k.off) : [];
if (!keys.some((k) => k.id === connectKeyID)) {
connectKeyID = "";
connectSecret = null;
}
if (!connectKeyID && connectKeyWant && keys.some((k) => k.id === connectKeyWant)) {
queueMicrotask(() => selectConnectKey(connectKeyWant));
} else if (remote && !connectKeyID && keys.length) {
queueMicrotask(() => selectConnectKey(keys[0].id));
}
const key = keys.find((k) => k.id === connectKeyID);
const secret = key ? (connectSecret?.id === key.id ? connectSecret.secret : "") : remote ? "" : "magpie";
const base = f.base(connectURL);
const fold = $("#foldConnect");
fold.setAttribute("aria-expanded", String(!connectFolded));
fold.title = t(connectFolded ? "Show how to connect" : "Fold Connect away");
box.hidden = connectFolded;
// folded, the head keeps the one thing reached for: the address, to copy
const note = $("#connectNote");
note.replaceChildren();
note.classList.toggle("brief", connectFolded);
if (connectFolded) note.append(el("code", "", base), copyBtn(base, "Base URL"));
else note.textContent = t(remote ? "Local network · an enabled gateway key is required" : g.lan && gatewayKeys?.length ? "Use a gateway key to track usage" : "Loopback only · the key can be anything");
box.append(...field("API", segs(Object.entries(FLAVORS).map(([k, v]) => [k, v.name]), flavor, (id) => { flavor = id; localStorage.setItem("magpie.flavor", id); renderConnect(); }), t(f.note)));
const b = el("div", "val");
if (urls.length > 1) b.append(connectPick("connectAddress", "Address", base,
urls.map((u) => ({ v: u, name: f.base(u), note: t(u === g.url ? "This computer" : u === g.publicURL ? "Public address" : "Local network") })), connectURL,
(u) => { connectWant = u; keepPick("magpie.connectAddress", u); renderConnect(); }));
else b.append(el("code", "", base));
b.append(copyBtn(base, "Base URL"));
box.append(...field("Base URL", b, f.baseEnv ? t("What {env} takes.", { env: f.baseEnv }) : t("Requests go to POST {url}.", { url: base + "/systemone" })));
const k = el("div", "val");
const options = keys.map((k) => ({ v: k.id, name: k.name, literalName: true, note: k.masked }));
if (!remote) options.unshift({ v: "", name: "This computer", note: t("Any key · no key attribution") });
const keyLabel = remote || key ? "Gateway key" : "API key";
if (!g.lan) k.append(el("code", "", "magpie"));
else if (options.length) k.append(connectPick("connectKey", keyLabel, key ? key.name : remote ? t("Choose a gateway key") : t("This computer"),
options, connectKeyID, (id) => { connectKeyWant = id; keepPick("magpie.connectKey", id); selectConnectKey(id); }));
else k.append(el("code", "", t("Create a gateway key above to connect")));
if (key) k.append(copyCallerKeyBtn(key));
else if (!remote) k.append(copyBtn("magpie", t("Key")));
box.append(...field(t(keyLabel), k, !f.keyEnv ? t(g.lan && (remote || gatewayKeys?.length)
? "Choose a gateway key to send as Authorization: Bearer; usage is tracked by key."
: "Sent as Authorization: Bearer. The gateway trusts everything on loopback, so any value works.") : t(g.lan && (remote || gatewayKeys?.length)
? "Choose a gateway key to use as {env}; usage is tracked by key."
: "{env}=magpie. The gateway trusts everything on loopback, so any value works.", { env: f.keyEnv })));
const m = el("div", "val");
m.append(el("code", "", model), copyBtn(model, t("Model id")));
box.append(...field(t("Model"), m, f.decide
? t(models.length ? "A decision model (Jev, Clef), as listed below. Click one there to put it in the snippets." : "No decision models yet. Add a System One, Jev or Workers AI provider.")
: t(models.length ? "provider/model, as listed below. Click a model there to put it in the snippets." : "No models yet. Add a provider, or sign in to Codex or Copilot.")));
const ex = el("div", "stack");
const tabs = el("div", "snip-tabs");
tabs.append(segs(langs, snipLang, (id) => { lang = id; localStorage.setItem("magpie.lang", id); renderConnect(); }));
// the shell the Shell and curl snippets are for; Python and Node read the same everywhere
if (snipLang === "shell" || snipLang === "curl") {
const os = segs(SNIP_OSES.map(([id, name]) => [id, t(name)]), snipWin() ? "windows" : "unix", (id) => {
snipOS = id;
try { localStorage.setItem("magpie.snipOS", id); } catch {}
renderConnect();
});
os.classList.add("snip-os");
os.setAttribute("role", "group");
os.setAttribute("aria-label", t("Where the snippet runs"));
os.title = t("Where the snippet runs");
tabs.append(os);
}
ex.append(tabs);
const code = !secret ? t(key ? "Loading gateway key…" : "Create a gateway key above to connect")
: snipLang === "shell" ? envSnippet([[f.baseEnv, base], [f.keyEnv, secret]])
: snipLang === "curl" ? curlSnippet(f.curl(base, model, secret))
: f[snipLang](base, model, secret);
const pre = el("pre", "snip");
const c = el("code");
c.append(highlight(code, snipLang));
pre.append(c);
// the button sits outside the scrolling box, so a long line doesn't carry it off
const wrap = el("div", "snip-wrap");
wrap.append(pre);
if (secret) wrap.append(copyBtn(code, t("Snippet")));
ex.append(wrap);
box.append(...field(t("Example"), ex, snipLang === "shell" ? t("Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.") : ""));
}
let modelQuery = "";
// The model list can be folded away, so Recent calls sits under Connect;
// the fold is remembered.
let modelsFolded = false;
try { modelsFolded = localStorage.getItem("magpie.gwModelsFolded") === "1"; } catch {}
function renderGatewayModels() {
const list = $("#gwModels");
list.replaceChildren();
const all = gatewayModels();
const fold = $("#foldModels");
fold.setAttribute("aria-expanded", String(!modelsFolded));
fold.title = t(modelsFolded ? "Show the models" : "Fold the models away");
$("#modelsCount").textContent = all.length ? String(all.length) : "";
list.hidden = modelsFolded && all.length > 0;
// the search sits in the section head, beside Copy all ids; typing
// redraws only the list, so it keeps its focus
let q = $("#findModel");
if (!q) {
q = input(modelQuery, t("Find a model…"));
q.id = "findModel";
q.className = "find";
q.oninput = () => { modelQuery = q.value; renderGatewayModels(); };
q.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape" && q.value) { q.value = modelQuery = ""; renderGatewayModels(); } };
$("#copyModels").before(q);
}
q.hidden = all.length < 5 || list.hidden;
q.title = t("Words match a model's id, name, provider or a group's models");
const words = modelQuery.trim().toLowerCase().split(/\s+/).filter(Boolean);
const models = q.hidden ? all : all.filter((m) => {
const hay = `${m.id} ${m.name || ""} ${m.provider.name} ${(m.members || []).join(" ")}`.toLowerCase();
return words.every((w) => hay.includes(w));
});
$("#copyModels").hidden = !models.length || list.hidden;
$("#copyModels").onclick = () => copy(models.map((m) => m.id).join("\n"), t("Model ids"));
if (!all.length) {
const empty = el("div", "empty-state", "");
empty.append(el("b", "", t("No models exposed yet")), t("Add a provider, or sign in to Codex or Copilot; their models show up here for every agent."));
list.append(empty);
return;
}
if (!models.length) {
list.append(el("div", "none", t("No models match “{q}”", { q: modelQuery.trim() })));
return;
}
for (const m of models) {
const row = el("div", "row model" + (m.id === (FLAVORS[flavor]?.decide ? decideModel : exampleModel) ? " selected" : ""));
const who = el("div", "who");
const name = el("div", "name", m.id);
if (namedFree(m.id, m.name)) name.append(freeBadge(false));
who.append(name, el("div", "sub", m.name && m.name !== m.id.split("/")[1] ? `${m.name} · ${m.provider.name}` : m.provider.name));
row.append(m.group ? stackIcon(m.icons) : icon(m.provider.icon || "generic"), who, modelInfo(m), copyBtn(m.id, t("Model id")));
row.title = t("Use this model in the snippets");
// a decision model is put in System One's snippets, any other in the
// other APIs'; the API follows the model clicked
row.onclick = () => {
const selection = window.getSelection();
if (selection && !selection.isCollapsed && row.contains(selection.anchorNode)) return;
const so = decideEntry(m);
if (so) { decideModel = m.id; localStorage.setItem("magpie.decideModel", m.id); }
else { exampleModel = m.id; localStorage.setItem("magpie.model", m.id); }
if (so !== !!FLAVORS[flavor]?.decide) { flavor = so ? "systemone" : "openai"; localStorage.setItem("magpie.flavor", flavor); }
renderConnect(); renderGatewayModels();
};
list.append(row);
}
}
// A recent call's bodies, which /api/providers leaves out: forty calls'
// bodies made every refresh of it 20 MB (#1521).
function loadCallBodies(c, id) {
const pending = { busy: true };
callBodies.set(id, pending);
api(`gateway/call?id=${encodeURIComponent(c.id)}`)
.then((body) => { if (callBodies.get(id) === pending) callBodies.set(id, body); })
.catch((e) => { if (callBodies.get(id) === pending) callBodies.set(id, { error: t(e.message) }); })
.finally(() => { if (view === "gateway" && providers) renderActivity(); });
}
// a recent call's row: by the gateway's number for it, as two calls of
// one agent to one model can come in the same instant
const callRow = (c) => (c.id ? `#${c.id}` : `${c.time}|${c.agent}|${c.model}`);
function renderActivity() {
const g = providers.gateway;
// what calls left the ring keep, they let go of
const ids = new Set(g.calls.map(callRow));
for (const id of callBodies.keys()) if (!ids.has(id)) callBodies.delete(id);
for (const id of expandedCalls) if (!ids.has(id)) expandedCalls.delete(id);
const box = $("#activity");
// a body being read keeps its place as new calls come in
const kept = new Map();
for (const item of box.querySelectorAll(".call-item[data-id]")) kept.set(item.dataset.id, [...item.querySelectorAll("pre")].map((p) => p.scrollTop));
box.replaceChildren();
$("#callsNote").textContent = g.running && !g.mine ? t("shown by the magpie that serves the gateway") : "";
const calls = g.calls.slice(0, callsShown);
if (!calls.length) { box.append(el("div", "none", t("No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens."))); return; }
for (const c of calls) {
const id = callRow(c);
const open = expandedCalls.has(id);
const item = el("div", "call-item" + (open ? " open" : "") + (c.status >= 400 ? " bad" : ""));
const r = el("div", "call");
r.setAttribute("role", "button");
r.setAttribute("tabindex", "0");
r.setAttribute("aria-expanded", String(open));
const chev = el("span", "call-chev");
chev.append(svg(CHEV_R, 11, 1.6));
r.append(chev);
r.append(el("span", "when", new Date(c.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit" })));
r.append(el("span", "a", c.agent || "—"));
r.append(el("span", "m", c.model));
r.append(el("span", "p", c.from === c.to ? c.from : `${c.from} → ${c.to}`));
r.append(el("span", "grow"));
r.append(el("span", "st", c.error ? `${c.status} ${c.error}` : `${c.status} · ${ledTook(c.ms)}` + (c.ttft ? " · " + t("TTFT {ms}", { ms: ledTook(c.ttft) }) : "")));
r.title = open ? t("Hide request and response bodies") : t("Show request and response bodies");
const toggle = () => {
if (expandedCalls.has(id)) expandedCalls.delete(id); else expandedCalls.add(id);
renderActivity();
};
r.onclick = toggle;
r.onkeydown = (ev) => {
if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); toggle(); }
};
item.append(r);
if (open) {
if (!callBodies.has(id)) loadCallBodies(c, id);
const body = callBodies.get(id);
const details = el("div", body.busy || body.error ? "" : "call-details");
if (body.busy) details.append(el("div", "none", t("Fetching…")));
else if (body.error) {
details.append(el("div", "call-archive-err", body.error));
const retry = el("button", "text", t("Try again"));
retry.onclick = () => { loadCallBodies(c, id); renderActivity(); };
details.append(retry);
} else details.append(
callBodyPanel("Request Body", body.requestBody, body.requestTruncated, undefined, id + "|req"),
callBodyPanel("Response Body", body.responseBody, body.responseTruncated, id),
);
item.dataset.id = id;
item.append(details);
}
box.append(item);
}
if (g.calls.length > calls.length) {
const more = el("button", "text activity-more");
more.textContent = t("Show {n} more", { n: Math.min(callsPage, g.calls.length - calls.length) });
more.onclick = () => {
callsShown = Math.min(g.calls.length, callsShown + callsPage);
renderActivity();
};
box.append(more);
}
for (const item of box.querySelectorAll(".call-item[data-id]")) {
const tops = kept.get(item.dataset.id) || [];
item.querySelectorAll("pre").forEach((p, i) => { if (tops[i]) p.scrollTop = tops[i]; });
}
}
magpie.plugin("gateway", (ctx) => {
const configured = () => {
callsPage = ctx.config.callsPage || 20;
callsShown = callsPage;
};
configured();
ctx.onConfig(() => {
configured();
magpie.call("gateway", "calls");
});
ctx.slots.add("page", {
key: "gateway",
// what the page draws from: the shell reads /api/providers for it
loads: "providers",
html: `
<div class="list gwcard">
<div class="row gw" id="gateway"></div>
</div>
<section id="gatewayKeysBlock" hidden>
<div class="row-head"><span class="label" data-t>Gateway keys</span><span class="grow"></span><button class="text" id="addGatewayKey" data-t>Add gateway key</button></div>
<p class="usage-note" data-t>Create a gateway key for each client. Usage is counted separately for each key.</p>
<section id="gatewayKeys"></section>
</section>
<p class="usage-note gw-keys-off" id="gatewayKeysOff" hidden><span data-t>Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.</span> <button class="text" id="openLanSettings" data-t>Network and sharing</button></p>
<div class="row-head"><button class="fold" id="foldConnect" aria-expanded="true" aria-controls="connect"><span class="label" data-t>Connect</span></button><span class="grow"></span><span class="note" id="connectNote"></span></div>
<section class="list connect" id="connect"></section>
<div class="row-head"><button class="fold" id="foldModels" aria-expanded="true" aria-controls="gwModels"><span class="label" data-t>Models</span><span class="note" id="modelsCount"></span></button><span class="grow"></span><button class="text" id="copyModels" data-t>Copy all ids</button></div>
<div class="list" id="gwModels"></div>
<div class="row-head"><span class="label" data-t>Recent calls</span><span class="grow"></span><span class="note" id="callsNote"></span></div>
<div class="list activity" id="activity"></div>
`,
mount() {
$("#foldConnect").prepend(svg(CHEV_R, 11, 1.6));
$("#foldConnect").onclick = () => {
connectFolded = !connectFolded;
try { localStorage.setItem("magpie.gwConnectFolded", connectFolded ? "1" : "0"); } catch {}
renderConnect();
backToReader($("#view-gateway"));
};
$("#foldModels").prepend(svg(CHEV_R, 11, 1.6));
$("#foldModels").onclick = () => {
modelsFolded = !modelsFolded;
try { localStorage.setItem("magpie.gwModelsFolded", modelsFolded ? "1" : "0"); } catch {}
renderGatewayModels();
backToReader($("#view-gateway"));
};
$("#openLanSettings").onclick = () => { openSettings(); setSetTab("network", true); };
},
// nothing read yet: the page's skeleton (#123)
loading: renderGatewayLoading,
// opened from another page that had the list: drawn from it at once,
// not left as empty cards until the new one is in (#123)
draft() {
if (!$("#gateway").childElementCount) renderGatewayView();
},
// The page is looked at and left open: coming back to the window
// redraws it only when something on it changed, and when only the calls
// did, only them (an account's last sign-in check isn't on it).
render(was) {
const json = (a) => JSON.stringify(a, (k, v) => (k === "seen" ? undefined : v));
const same = (a, b) => json(a) === json(b);
if (was && !$("#view-gateway").classList.contains("loading") && same({ ...was, gateway: { ...was.gateway, calls: 0 } }, { ...providers, gateway: { ...providers.gateway, calls: 0 } })) {
if (!same(was.gateway.calls, providers.gateway.calls)) renderActivity();
} else renderGatewayView();
},
// the recent calls again, a page of them (the setting changed)
calls() {
if (view === "gateway" && providers && !$("#view-gateway").classList.contains("loading")) renderActivity();
},
open: loadGatewayKeys,
});
});
+33 -6
View File
@@ -38,6 +38,10 @@ type builtinJSON struct {
InUse int `json:"inUse"`
Use string `json:"use,omitempty"` // One or Many, by InUse
Parts []pluginrt.Part `json:"parts,omitempty"`
// Schema is its settings' (pluginrt/schema.go), which the page draws
// a form of; Config their values now
Schema *pluginrt.Schema `json:"schema,omitempty"`
Config map[string]any `json:"config,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"`
@@ -60,7 +64,7 @@ func builtinsState() []builtinJSON {
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}
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, Schema: m.Schema(), Config: c.Config}
if err != nil {
j.Broken, j.Chosen = err.Error(), j.On
}
@@ -87,8 +91,21 @@ func builtinsOff(list []builtinJSON) []string {
return out
}
// builtinConfig is each plugin's settings the window shows, by id, for
// boot.js to hand the page's plugins before they draw.
func builtinConfig(list []builtinJSON) map[string]map[string]any {
out := map[string]map[string]any{}
for _, b := range list {
if b.On && b.Schema != nil {
out[b.ID] = b.Config
}
}
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.
// {"id", "on"} switches one, kept in plugins.yml as the user's own choice,
// and {"id", "config"} sets its settings, only as their schema allows.
// One in use is refused off.
func builtinRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/plugins/builtin", func(rw http.ResponseWriter, r *http.Request) {
@@ -96,8 +113,9 @@ func builtinRoutes(mux *http.ServeMux) {
})
mux.HandleFunc("POST /api/plugins/builtin", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
ID string `json:"id"`
On bool `json:"on"`
ID string `json:"id"`
On *bool `json:"on"`
Config map[string]any `json:"config"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
@@ -117,11 +135,20 @@ func builtinRoutes(mux *http.ServeMux) {
case b.Broken != "":
fail(rw, fmt.Errorf("%s", b.Broken))
return
case !in.On && b.InUse > 0:
case (in.On == nil) == (in.Config == nil):
fail(rw, fmt.Errorf("say on or config"))
return
case in.On != nil && !*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 {
var err error
if in.On != nil {
err = pluginrt.Set(in.ID, *in.On)
} else {
err = pluginrt.SetConfig(in.ID, in.Config)
}
if err != nil {
fail(rw, err)
return
}
+101 -3
View File
@@ -44,11 +44,12 @@ func TestBuiltinSwitch(t *testing.T) {
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 5 {
if len(out) != 6 {
t.Fatalf("the built-ins: %+v", out)
}
for _, b := range out {
if b.On != (b.ID == "library") || b.On != (b.State == pluginrt.Active) {
// the gateway page is essential: on in every preset
if b.On != (b.ID == "library" || b.ID == "gateway") || b.On != (b.State == pluginrt.Active) {
t.Fatalf("after library on: %+v", out)
}
}
@@ -125,6 +126,94 @@ func TestBootSaysBuiltinsOff(t *testing.T) {
}
}
// A plugin's settings are set only as their schema allows, kept in
// plugins.yml, and handed to the page in boot.js; a request says on or
// config, not both.
func TestBuiltinConfig(t *testing.T) {
h := builtinHome(t)
if _, err := pluginrt.Settle(false); err != nil {
t.Fatal(err)
}
gw := func() builtinJSON {
for _, b := range builtinsState() {
if b.ID == "gateway" {
return b
}
}
t.Fatal("no gateway plugin")
return builtinJSON{}
}
if b := gw(); b.Schema == nil || b.Schema.Properties["callsPage"] == nil || b.Config["callsPage"] != int64(20) {
t.Fatalf("before: %+v", b)
}
if rec := postBuiltin(h, `{"id":"gateway","config":{"callsPage":50}}`); rec.Code != http.StatusOK {
t.Fatalf("50: %d %s", rec.Code, rec.Body)
}
if b := gw(); b.Config["callsPage"] != int64(50) || !b.On {
t.Fatalf("after 50: %+v", b)
}
for _, bad := range []string{
`{"id":"gateway","config":{"callsPage":30}}`,
`{"id":"gateway","config":{"other":1}}`,
`{"id":"gateway","on":true,"config":{"callsPage":10}}`,
`{"id":"gateway"}`,
`{"id":"library","config":{"callsPage":10}}`,
} {
if rec := postBuiltin(h, bad); rec.Code != http.StatusBadRequest {
t.Errorf("%s: %d %s", bad, rec.Code, rec.Body)
}
}
if b := gw(); b.Config["callsPage"] != int64(50) {
t.Fatalf("a refused one written: %+v", b)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/boot.js", nil))
if !strings.Contains(rec.Body.String(), `"pluginConfig":{"gateway":{"callsPage":50}}`) {
t.Fatalf("boot.js: %s", rec.Body)
}
}
// Every script a built-in plugin says it has is on disk, loaded by the
// page after the kernel and before app.js, which looks for its pages, and
// named with its hash so a new one isn't read from the cache.
func TestBuiltinClientsLoaded(t *testing.T) {
page, err := os.ReadFile("assets/index.html")
if err != nil {
t.Fatal(err)
}
src := string(page)
at := func(name string) int {
i := strings.Index(src, `<script src="`+name+`"></script>`)
if i < 0 {
t.Fatalf("index.html doesn't load %s", name)
}
return i
}
kernel, app := at("kernel.js"), at("app.js")
if kernel > app {
t.Fatal("kernel.js after app.js")
}
n := 0
for _, m := range pluginrt.Registered() {
for _, c := range m.Client {
name := "plugins/" + m.ID + "/" + c
if _, err := os.Stat(filepath.Join("assets", name)); err != nil {
t.Errorf("%s: %v", name, err)
}
if i := at(name); i < kernel || i > app {
t.Errorf("%s isn't between kernel.js and app.js", name)
}
if !strings.Contains(string(versionedPage(page)), `src="`+name+`?v=`) {
t.Errorf("%s isn't named with its hash", name)
}
n++
}
}
if n == 0 {
t.Fatal("no plugin has a script")
}
}
// Every string of every built-in plugin is said in every language.
func TestBuiltinsTranslated(t *testing.T) {
src, err := os.ReadFile("assets/i18n.js")
@@ -138,7 +227,16 @@ func TestBuiltinsTranslated(t *testing.T) {
}
block, _, _ = strings.Cut(block, "\n },")
for _, m := range pluginrt.Registered() {
for _, s := range []string{m.Name, m.Sub, m.One, m.Many} {
says := []string{m.Name, m.Sub, m.One, m.Many}
if sc := m.Schema(); sc != nil {
for _, p := range sc.Properties {
says = append(says, p.Title, p.Description)
}
}
for _, s := range says {
if s == "" {
continue
}
k, _ := json.Marshal(s)
if !strings.Contains(block, "\n "+string(k)+": ") {
t.Errorf("%s doesn't say %s", lang, k)
+1 -1
View File
@@ -88,7 +88,7 @@ func TestGatewayMode(t *testing.T) {
set("on")
rec := httptest.NewRecorder()
Handler(&zoomWindows{}, nil).ServeHTTP(rec, httptest.NewRequest("GET", "/boot.js", nil))
if strings.Contains(rec.Body.String(), `"gateway"`) {
if strings.Contains(rec.Body.String(), `"gateway":true`) {
t.Fatalf("the app's window was told gateway mode: %s", rec.Body)
}
if on, _ := gatewayMode(false); on {
+16 -1
View File
@@ -941,7 +941,7 @@ Chinese.
`old-webkit.test.cjs` holds the page to Safari 15.0, the WebKit macOS 12 can
have (#220: a regex lookbehind in app.js, a syntax error before Safari 16.4,
left the panel with its headings and nothing working). Every script in
`assets/` is parsed (with the Babel parser Playwright bundles) and may have
`assets/`, the built-in plugins' under `assets/plugins/` among them, is parsed (with the Babel parser Playwright bundles) and may have
no regex lookbehind, v flag or modifiers, class static block, decorator,
import attributes or `using`, in a literal or `new RegExp("…")`; no built-in
newer than 15.0 (`.at`, `findLast`, `structuredClone`, `Object.hasOwn`,
@@ -2376,3 +2376,18 @@ and de. English and Chinese, Chromium and WebKit.
node --test internal/gui/tests/tencent-access-key.test.cjs
go test -tags nogui ./internal/gui -run TestProviderListTellsTencentAccessKey
```
`plugin-kernel.test.cjs` holds the window's plugin kernel (`kernel.js`) to
its error boundary, with the Gateway page, the first page a plugin draws
(`assets/plugins/gateway/`). With the page's drawing made to throw, the page
says "This page stopped working", the error and Try again (role alert,
translated, no sideways scroll); nothing escapes as a page error, Providers
still opens, and back on the page nothing half drawn shows. Fixed, Try again
draws the page whole, translated, with its Connect fold working. The page's
`callsPage` setting shows 10 calls at a time from boot.js's `pluginConfig`,
and 50 once Plugins › Built-in sets it. Chromium and WebKit, every language,
1100 and 420 points.
```sh
node --test internal/gui/tests/plugin-kernel.test.cjs internal/gui/tests/builtins.test.cjs
```
+42 -8
View File
@@ -19,27 +19,38 @@ const assets = path.resolve(__dirname, "../assets");
// as plugins/*'s manifests say them, in pluginrt.Registered's order (by id)
const PLUGINS = [
{ id: "gateway", name: "Gateway page", sub: "The gateway's state and keys, how to connect a client, its models and recent calls", one: "1 gateway key", many: "{n} gateway keys" },
{ 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] };
// a new install's (the Essentials preset): all off but the Gateway page,
// which is essential, and two routing groups the user made
const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], sessions: [false, 0], warmups: [false, 0] };
function builtins(st, broken) {
// the Gateway page's settings, as pluginrt.SchemaOf makes them
const GATEWAY_SCHEMA = {
type: "object",
properties: { callsPage: { type: "integer", title: "Recent calls at a time", description: "How many of the gateway's recent calls the page shows, and how many more each Show more adds", enum: [10, 20, 50, 100], default: 20 } },
"x-order": ["callsPage"],
};
function builtins(st, broken, config) {
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 };
const f = { 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 };
if (p.id === "gateway") Object.assign(f, { schema: GATEWAY_SCHEMA, config });
return f;
});
}
function server(lang, posts, broken) {
const st = structuredClone(START);
const list = () => builtins(st, broken);
const config = { callsPage: 20 };
const list = () => builtins(st, broken, config);
const cur = () => ({
theme: "light", lang, tray: "panel", currency: "usd", textSize: 100, redactWords: [],
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "",
@@ -59,7 +70,13 @@ function server(lang, posts, broken) {
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();
const { id, on, config: change } = req.postDataJSON();
if (change) {
posts.push([id, change]);
if (broken || ![10, 20, 50, 100].includes(change.callsPage)) return route.fulfill({ status: 400, json: { error: "callsPage: not one of [10 20 50 100]" } });
Object.assign(config, change);
return json(list());
}
posts.push([id, on]);
if (broken || (!on && st[id][1] > 0)) return route.fulfill({ status: 400, json: { error: "in use" } });
st[id][0] = on;
@@ -139,13 +156,30 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
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}`);
const gw = rows.find((r) => r.id === "gateway");
assert.deepEqual([gw.on, gw.disabled], ["true", false], `${where}: the Gateway page, on`);
for (const r of rows.filter((r) => r.id !== "groups" && r.id !== "gateway")) 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`);
// the Gateway page's setting, under its row, from its schema: in
// the page's language, its value in the app's menu, saved as picked
const set = page.locator('#builtinList .feat-set[data-of="gateway"][data-setting="callsPage"]');
assert.equal(await set.locator(".name").textContent(), await page.evaluate(() => t("Recent calls at a time")), where);
if (lang !== "en") assert.notEqual(await set.locator(".name").textContent(), "Recent calls at a time", `${where}: translated`);
assert.equal(await page.evaluate(() => document.querySelector('#builtinList .feat-set').previousElementSibling.dataset.id), "gateway", `${where}: under its row`);
assert.equal((await set.locator(".proto.pick").textContent()).trim(), "20", where);
await set.locator(".proto.pick").click();
await page.locator(".proto-menu .pm-item", { hasText: "50" }).click();
await page.waitForFunction(() => document.querySelector('#builtinList .feat-set .proto.pick')?.textContent.trim() === "50");
assert.deepEqual(posts, [["gateway", { callsPage: 50 }]], `${where}: posted`);
assert.equal(await page.evaluate(() => document.querySelectorAll(".proto-menu").length), 0, `${where}: the menu closed`);
posts.length = 0;
assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-plugins"); return v.scrollWidth <= v.clientWidth + 1; }), `${where}: the setting 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"]');
+3 -1
View File
@@ -25,7 +25,9 @@ const { webkit } = require("playwright");
const { babelParse } = require("playwright/lib/transform/babelBundle");
const assets = path.resolve(__dirname, "../assets");
const scripts = async () => (await fs.readdir(assets)).filter((f) => f.endsWith(".js")).sort();
// the page's scripts, the built-in plugins' under plugins/ among them, as
// index.html names them
const scripts = async () => (await fs.readdir(assets, { recursive: true })).map((f) => f.split(path.sep).join("/")).filter((f) => f.endsWith(".js")).sort();
const styles = async () => (await fs.readdir(assets)).filter((f) => f.endsWith(".css")).sort();
const read = (f) => fs.readFile(path.join(assets, f), "utf8");
+145
View File
@@ -0,0 +1,145 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The window's plugin kernel (kernel.js), with the Gateway page, the first
// page a plugin adds (plugins/gateway). A page whose code throws breaks
// only itself: it says what broke and offers Try again, and the other
// pages go on; Try again draws it once its code works. A plugin's setting
// reaches its page: from boot.js before the first paint, and when Plugins
// › Built-in changes it. Every language, both engines, a narrow window.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const now = Date.now();
const calls = Array.from({ length: 60 }, (_, i) => ({
time: new Date(now - (i + 1) * 60e3).toISOString(),
agent: "fixture",
model: `fixture/model-${i}`,
status: 200,
ms: 900,
}));
const providers = {
providers: [{ id: "fixture", name: "Fixture", icon: "generic", models: [{ id: "model-0", name: "Model", on: true }], agents: [] }],
presets: [],
gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", calls, groups: [] },
};
// the Gateway page's code, broken while window.__break says so: its
// drawing throws as a plugin's bug would
const BREAK = `
;(() => {
const real = renderGatewayView;
renderGatewayView = function () {
if (window.__break) throw new Error("fixture: the page broke");
return real();
};
})();
`;
function serve(lang, config) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",pluginConfig:${JSON.stringify(config)}};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/caller-keys") return json({ keys: [] });
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" }[path.extname(file)];
let body;
try { body = await fs.readFile(file); } catch { return route.fulfill({ status: 404, body: "" }); }
if (url.pathname === "/plugins/gateway/client.js") body = body.toString() + BREAK;
await route.fulfill({ body, contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a plugin's page that throws breaks only itself, and Try again draws it`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
const where = `${engine} ${lang} ${width}`;
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [], logged = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("console", (m) => { if (m.type() === "error") logged.push(m.text()); });
await page.addInitScript(() => { window.__break = true; });
await page.route("**/*", serve(lang, {}));
await page.goto("http://magpie.test/?view=gateway");
const card = page.locator("#view-gateway .slot-error");
await card.waitFor();
assert.equal(await card.getAttribute("role"), "alert", where);
assert.equal(await card.locator(".name").textContent(), await page.evaluate(() => t("This page stopped working")), where);
if (lang !== "en") assert.notEqual(await card.locator(".name").textContent(), "This page stopped working", `${where}: translated`);
assert.equal(await card.locator(".sub").textContent(), "fixture: the page broke", `${where}: what broke`);
assert.equal(await page.locator("#view-gateway").getAttribute("aria-busy"), null, `${where}: not left loading`);
assert.ok(logged.some((l) => l.includes("gateway") && l.includes("fixture: the page broke")), `${where}: logged`);
// nothing escaped the boundary, and the card fits
assert.deepEqual(errors, [], where);
assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-gateway"); return v.scrollWidth <= v.clientWidth + 1; }), `${where}: fits`);
// the other pages go on: Providers draws
await page.evaluate(() => show("providers"));
await page.locator("#view-providers #addProvider").waitFor();
assert.equal(await page.locator("#view-gateway").isVisible(), false, `${where}: Providers shown`);
// back on the page, still broken, it still says so and draws nothing
await page.evaluate(() => show("gateway"));
await card.waitFor();
assert.equal(await page.locator("#view-gateway #activity").count(), 0, `${where}: nothing half drawn`);
// fixed, Try again draws it whole, and it keeps working
await page.evaluate(() => { window.__break = false; });
await card.locator(".slot-again").click();
await page.locator("#activity .call-item").first().waitFor();
assert.equal(await card.count(), 0, `${where}: the card gone`);
assert.ok((await page.locator("#gateway").evaluate((g) => g.childElementCount)) > 0, `${where}: the status card`);
// its markup came back translated, and its wiring with it
assert.equal((await page.locator("#foldConnect .label").textContent()).trim(), await page.evaluate(() => t("Connect")), `${where}: translated again`);
await page.locator("#foldConnect").click();
await page.waitForFunction(() => document.querySelector("#connect").hidden);
await page.locator("#foldConnect").click();
await page.waitForFunction(() => !document.querySelector("#connect").hidden);
assert.deepEqual(errors, [], where);
await context.close();
}
}
});
test(`${engine}: the Gateway page shows as many recent calls at a time as its setting says`, 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 = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, { gateway: { callsPage: 10 } }));
await page.goto("http://magpie.test/?view=gateway");
const rows = page.locator("#activity .call-item");
await rows.first().waitFor();
// from boot.js, before the first paint
assert.equal(await rows.count(), 10, `${where}: boot.js's 10`);
const more = page.locator("#activity .activity-more");
assert.equal(await more.textContent(), await page.evaluate(() => t("Show {n} more", { n: 10 })), where);
await more.evaluate((b) => b.click());
assert.equal(await rows.count(), 20, `${where}: 10 more`);
// Plugins › Built-in sets 50 (applyFeatures with the list it posts back)
await page.evaluate(() => applyFeatures([{ id: "gateway", on: true, schema: { type: "object", properties: {}, "x-order": [] }, config: { callsPage: 50 } }]));
await page.waitForFunction(() => document.querySelectorAll("#activity .call-item").length === 50);
assert.equal(await more.textContent(), await page.evaluate(() => t("Show {n} more", { n: 10 })), `${where}: the 10 left`);
assert.deepEqual(errors, [], where);
await context.close();
}
});
}
@@ -27,6 +27,9 @@ function lift(header) {
return source.slice(start, end + 2);
}
const providersSource = lift("function providersWhileFetching() {");
// a plugin's page that reads with Providers (the Gateway page) is polled too
const pageLine = source.match(/^const providersPage = .*$/m);
assert.ok(pageLine, "app.js no longer has providersPage");
// values cross the vm's realm boundary (its Object is not the test's), so what
// is handed to assert is copied into this one first
@@ -39,6 +42,10 @@ function page() {
const script = [
`
let view = "providers", editing = null, adding = false;
const magpie = { page: (v) => (v === "gateway" ? { loads: "providers" } : undefined) };
`,
pageLine[0],
`
const document = { hidden: false };
let providers = { fetching: true, providers: [], gateway: { calls: 0 } };
const timers = [];
@@ -123,6 +130,16 @@ test("arming twice leaves one timer", () => {
assert.equal(p.arm(), 1, "a second arming added a second timer");
});
test("a poll under the Gateway page, a plugin's page that reads with Providers, reads", async () => {
const p = page();
p.refuses();
p.arm();
p.set("view", "gateway");
await p.fire();
assert.equal(plain(p.counts()).api, 1, "it read nothing under the Gateway page");
assert.equal(p.pending(), 1);
});
for (const [guard, set] of [
["another page", (p) => p.set("view", "agents")],
["an open editor", (p) => p.set("editing", "p1")],
+44
View File
@@ -3,6 +3,7 @@ package pluginrt
import (
"errors"
"fmt"
"log"
"maps"
"os"
"path/filepath"
@@ -124,6 +125,16 @@ func Compose(ms []Manifest, f File) []Composed {
c.Enabled, c.Source = *r.Enabled, FromUser
}
for k, v := range r.Config {
// a value its settings don't allow (plugins.yml edited by
// hand) is left out, the one under it kept; the file keeps it
if s := m.Schema(); s != nil {
ok, err := s.Validate(map[string]any{k: v})
if err != nil {
log.Printf("plugins: %s's %s in %s: %v", m.ID, k, Path(), err)
continue
}
v = ok[k]
}
c.Config[k], c.Sources[k] = merge(c.Config[k], v), FromUser
}
}
@@ -194,6 +205,39 @@ func Set(id string, on bool) error {
})
}
// SetConfig sets plugin id's settings in config as the user's own,
// keeping its others and the rest of plugins.yml as they were. Only what
// its settings' schema allows is taken: a key it doesn't have, or a value
// of the wrong kind or out of range, is refused and nothing is written.
func SetConfig(id string, config map[string]any) error {
var s *Schema
for _, m := range Registered() {
if m.ID == id {
if s = m.Schema(); s == nil {
return fmt.Errorf("%s has no settings", id)
}
}
}
if s == nil {
return fmt.Errorf("no built-in plugin %q", id)
}
ok, err := s.Validate(config)
if err != nil {
return err
}
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
}
if f.Plugins[i].Config == nil {
f.Plugins[i].Config = map[string]any{}
}
maps.Copy(f.Plugins[i].Config, ok)
})
}
// SetPreset changes the preset, keeping the user's own rows.
func SetPreset(preset string) error {
if preset != PresetAll && preset != PresetEssentials {
+27
View File
@@ -13,6 +13,7 @@ package pluginrt
import (
"fmt"
"log"
"maps"
"slices"
"sort"
"strconv"
@@ -58,8 +59,20 @@ type Manifest struct {
Parts []Part
// Defaults is its config before plugins.yml's preset and rows
Defaults map[string]any
// Settings is a struct of its settings, their defaults its values
// (schema.go): the window draws their form, and SetConfig takes only
// what it allows. Register adds them to Defaults.
Settings any
// Client are its scripts in the window, under assets/plugins/<id>/:
// they register its parts with the window's kernel (kernel.js).
// TestBuiltinClientsLoaded holds the page to loading each.
Client []string
schema *Schema
}
// Schema is the schema of the plugin's Settings, nil for one with none.
func (m Manifest) Schema() *Schema { return m.schema }
// Part is one thing a plugin puts in the window: a Slot and a Key in it.
type Part struct{ Slot, Key string }
@@ -120,6 +133,20 @@ func Register(m Manifest) {
if _, dup := registry[m.ID]; dup {
panic("pluginrt: two plugins " + m.ID)
}
if m.Settings != nil {
var defs map[string]any
m.schema, defs = SchemaOf(m.Settings)
d := maps.Clone(m.Defaults)
if d == nil {
d = map[string]any{}
}
for k, v := range defs {
if _, set := d[k]; !set {
d[k] = v
}
}
m.Defaults = d
}
registry[m.ID] = m
}
+192
View File
@@ -0,0 +1,192 @@
package pluginrt
import (
"fmt"
"math"
"reflect"
"slices"
"strconv"
"strings"
)
// A plugin's settings are a struct (Manifest.Settings): each exported
// field with a json name is one setting, its value in the struct the
// default. The window draws their form from the Schema made of it (Plugins
// › Built-in, kernel.js's ui.form), and SetConfig takes only what the
// schema allows, so the form, plugins.yml and `magpie plugin dump` can't
// disagree on what a setting is.
//
// type Settings struct {
// CallsPage int `json:"callsPage" title:"Recent calls at a time" description:"…" enum:"10,20,50"`
// }
//
// Tags: title (the row's name, in English; the window translates it),
// description, enum (the values allowed, comma separated), min and max
// (for a number).
// Schema is a plugin's settings as JSON Schema says an object: the window
// draws a form from it. Order is the fields' order, as JSON keeps no order
// of an object's keys.
type Schema struct {
Type string `json:"type"` // "object"
Properties map[string]*Property `json:"properties"`
Order []string `json:"x-order"`
}
// Property is one setting.
type Property struct {
Type string `json:"type"` // boolean, integer, number, string
Title string `json:"title"`
Description string `json:"description,omitempty"`
Enum []any `json:"enum,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
Default any `json:"default"`
}
// SchemaOf is the schema of the settings struct v, and its defaults. A
// field of a kind a form can't draw, or a tag that doesn't parse, is a
// programming error.
func SchemaOf(v any) (*Schema, map[string]any) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Struct {
panic(fmt.Sprintf("pluginrt: settings %T is not a struct", v))
}
s := &Schema{Type: "object", Properties: map[string]*Property{}}
defaults := map[string]any{}
for i := 0; i < rv.NumField(); i++ {
f := rv.Type().Field(i)
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if !f.IsExported() || name == "" || name == "-" {
continue
}
p := &Property{Title: f.Tag.Get("title"), Description: f.Tag.Get("description")}
if p.Title == "" {
panic(fmt.Sprintf("pluginrt: setting %s has no title", name))
}
switch f.Type.Kind() {
case reflect.Bool:
p.Type, p.Default = "boolean", rv.Field(i).Bool()
case reflect.Int, reflect.Int32, reflect.Int64:
p.Type, p.Default = "integer", rv.Field(i).Int()
case reflect.Float64:
p.Type, p.Default = "number", rv.Field(i).Float()
case reflect.String:
p.Type, p.Default = "string", rv.Field(i).String()
default:
panic(fmt.Sprintf("pluginrt: setting %s is a %s, which a form can't draw", name, f.Type))
}
if e := f.Tag.Get("enum"); e != "" {
for _, w := range strings.Split(e, ",") {
x, err := p.parse(strings.TrimSpace(w))
if err != nil {
panic(fmt.Sprintf("pluginrt: setting %s's enum: %v", name, err))
}
p.Enum = append(p.Enum, x)
}
}
for tag, to := range map[string]**float64{"min": &p.Minimum, "max": &p.Maximum} {
if w := f.Tag.Get(tag); w != "" {
x, err := strconv.ParseFloat(w, 64)
if err != nil {
panic(fmt.Sprintf("pluginrt: setting %s's %s: %v", name, tag, err))
}
*to = &x
}
}
if err := p.check(p.Default); err != nil {
panic(fmt.Sprintf("pluginrt: setting %s's default: %v", name, err))
}
s.Properties[name] = p
s.Order = append(s.Order, name)
defaults[name] = p.Default
}
return s, defaults
}
// parse reads w as a value of p's type, for an enum tag.
func (p *Property) parse(w string) (any, error) {
switch p.Type {
case "integer":
return strconv.ParseInt(w, 10, 64)
case "number":
return strconv.ParseFloat(w, 64)
case "boolean":
return strconv.ParseBool(w)
}
return w, nil
}
// check says whether v may be p's value, as it comes from JSON or YAML (a
// number is a float64 from JSON, an int from YAML), and gives it as p's
// type.
func (p *Property) check(v any) error {
_, err := p.value(v)
return err
}
func (p *Property) value(v any) (any, error) {
var out any
switch p.Type {
case "boolean":
b, ok := v.(bool)
if !ok {
return nil, fmt.Errorf("%v is not true or false", v)
}
out = b
case "string":
s, ok := v.(string)
if !ok {
return nil, fmt.Errorf("%v is not text", v)
}
out = s
case "integer", "number":
var f float64
switch n := v.(type) {
case int:
f = float64(n)
case int64:
f = float64(n)
case float64:
f = n
default:
return nil, fmt.Errorf("%v is not a number", v)
}
if math.IsNaN(f) || math.IsInf(f, 0) {
return nil, fmt.Errorf("%v is not a number", v)
}
if p.Minimum != nil && f < *p.Minimum || p.Maximum != nil && f > *p.Maximum {
return nil, fmt.Errorf("%v is out of range", v)
}
if p.Type == "integer" {
if f != math.Trunc(f) {
return nil, fmt.Errorf("%v is not a whole number", v)
}
out = int64(f)
} else {
out = f
}
}
if len(p.Enum) > 0 && !slices.Contains(p.Enum, out) {
return nil, fmt.Errorf("%v is not one of %v", v, p.Enum)
}
return out, nil
}
// Validate gives config as the schema's types, or says the first key or
// value it doesn't allow.
func (s *Schema) Validate(config map[string]any) (map[string]any, error) {
out := map[string]any{}
for k, v := range config {
p := s.Properties[k]
if p == nil {
return nil, fmt.Errorf("no setting %q", k)
}
x, err := p.value(v)
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
out[k] = x
}
return out, nil
}
+112
View File
@@ -0,0 +1,112 @@
package pluginrt
import (
"reflect"
"strings"
"testing"
)
type testSettings struct {
Page int `json:"page" title:"Rows at a time" description:"How many" enum:"10,20,50"`
Ratio float64 `json:"ratio" title:"Ratio" min:"0" max:"1"`
Shown bool `json:"shown" title:"Shown"`
Name string `json:"name" title:"Name"`
skip int
Not int `json:"-"`
}
// A settings struct is its schema, in its fields' order, and its values
// are the defaults.
func TestSchemaOf(t *testing.T) {
s, defs := SchemaOf(testSettings{Page: 20, Ratio: 0.5, Name: "x"})
if !reflect.DeepEqual(s.Order, []string{"page", "ratio", "shown", "name"}) {
t.Fatalf("order: %v", s.Order)
}
if p := s.Properties["page"]; p.Type != "integer" || !reflect.DeepEqual(p.Enum, []any{int64(10), int64(20), int64(50)}) || p.Default != int64(20) || p.Title != "Rows at a time" {
t.Fatalf("page: %+v", p)
}
if p := s.Properties["ratio"]; p.Type != "number" || *p.Minimum != 0 || *p.Maximum != 1 {
t.Fatalf("ratio: %+v", p)
}
if !reflect.DeepEqual(defs, map[string]any{"page": int64(20), "ratio": 0.5, "shown": false, "name": "x"}) {
t.Fatalf("defaults: %v", defs)
}
for _, bad := range []any{struct {
A int `json:"a"`
}{}, struct {
A []int `json:"a" title:"A"`
}{}, struct {
A int `json:"a" title:"A" enum:"1,2"`
}{A: 3}} {
func() {
defer func() {
if recover() == nil {
t.Errorf("%T: no panic", bad)
}
}()
SchemaOf(bad)
}()
}
}
// Only what the schema allows is taken, as JSON and YAML give it.
func TestValidate(t *testing.T) {
s, _ := SchemaOf(testSettings{Page: 20})
ok, err := s.Validate(map[string]any{"page": float64(50), "ratio": 1, "shown": true, "name": "y"})
if err != nil || !reflect.DeepEqual(ok, map[string]any{"page": int64(50), "ratio": 1.0, "shown": true, "name": "y"}) {
t.Fatalf("good: %v %v", ok, err)
}
for _, bad := range []map[string]any{
{"page": 30.0}, {"page": 20.5}, {"page": "20"}, {"ratio": 2.0}, {"shown": "yes"}, {"name": 1}, {"other": 1},
} {
if _, err := s.Validate(bad); err == nil {
t.Errorf("%v taken", bad)
}
}
}
// SetConfig keeps the user's value in plugins.yml, the rest of the file as
// it was; a value the schema refuses writes nothing; Compose leaves out a
// value edited in by hand that it doesn't allow.
func TestSetConfig(t *testing.T) {
home(t)
Register(Manifest{ID: "schema-test", Settings: testSettings{Page: 20}})
m := Registered()[slicesIndex(Registered(), "schema-test")]
if m.Defaults["page"] != int64(20) || m.Schema() == nil {
t.Fatalf("registered: %+v", m)
}
if err := Set("other", false); err != nil {
t.Fatal(err)
}
if err := SetConfig("schema-test", map[string]any{"page": 50.0}); err != nil {
t.Fatal(err)
}
if err := SetConfig("schema-test", map[string]any{"page": 30.0}); err == nil || !strings.Contains(err.Error(), "not one of") {
t.Fatalf("30 taken: %v", err)
}
if err := SetConfig("nope", map[string]any{"page": 50.0}); err == nil {
t.Fatal("an unknown plugin taken")
}
f, _, err := Load()
if err != nil || len(f.Plugins) != 2 || f.Plugins[0].ID != "other" || f.Plugins[1].Config["page"] != 50 {
t.Fatalf("after: %+v %v", f, err)
}
c := byID(Compose([]Manifest{m}, f))["schema-test"]
if c.Config["page"] != int64(50) || c.Sources["page"] != FromUser {
t.Fatalf("composed: %+v", c)
}
f.Plugins[1].Config["page"] = 7
c = byID(Compose([]Manifest{m}, f))["schema-test"]
if c.Config["page"] != int64(20) || c.Sources["page"] != FromDefault {
t.Fatalf("a value it doesn't allow: %+v", c)
}
}
func slicesIndex(ms []Manifest, id string) int {
for i, m := range ms {
if m.ID == id {
return i
}
}
return -1
}
+1
View File
@@ -3,6 +3,7 @@
package all
import (
_ "github.com/yetone/magpie/plugins/gateway"
_ "github.com/yetone/magpie/plugins/groups"
_ "github.com/yetone/magpie/plugins/library"
_ "github.com/yetone/magpie/plugins/otel"
+34
View File
@@ -0,0 +1,34 @@
// Package gateway is the Gateway page: the gateway's state, its keys, how
// to connect a client, the models it serves and its recent calls. The
// gateway itself is core and serves agents with the page off; while a
// gateway key is there, the page that lists and changes them stays on.
//
// It is the first part of the window a plugin draws itself (P1 of
// docs/subsystems/plugin-runtime.md): its scripts register the page with
// the window's kernel, and its one setting's form is drawn from Settings.
package gateway
import (
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/pluginrt"
)
// Settings are the page's settings, at their defaults.
type Settings struct {
CallsPage int `json:"callsPage" title:"Recent calls at a time" description:"How many of the gateway's recent calls the page shows, and how many more each Show more adds" enum:"10,20,50,100"`
}
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "gateway", API: "^1", Requires: []string{"window", "gateway"}, Essential: true,
Name: "Gateway page", Sub: "The gateway's state and keys, how to connect a client, its models and recent calls",
One: "1 gateway key", Many: "{n} gateway keys",
InUse: func() (int, error) {
keys, err := access.List()
return len(keys), err
},
Parts: []pluginrt.Part{{Slot: "nav.page", Key: "gateway"}},
Settings: Settings{CallsPage: 20},
Client: []string{"keys.js", "client.js"},
})
}