Files
magpie/docs/subsystems/gateway-middleware.md
T
yetone 3f913b3de6 plugins: a JS gateway plugin serves routings (strategies) and watches usage rows (onUsage); plugins/middleware is "JS gateway plugins" (P4)
A plugin's gateway module (magpie.middleware, or its alias magpie.gateway,
or a *.gateway.js file) may now export, besides onRequest/onEvent/onResponse:

- strategies: {name: (pool, seats, options) => order}. Each is a routing
  "<short name>/<name>", registered with routes.Register while the plugin is
  on and loaded and removed when it goes off or reloads. Seats are
  routes.Seat in camelCase JSON. 20ms each; it fails open: a throw, a timeout
  or a result that isn't an order of the seats means the listed order. The
  failure is counted and logged, rate-limited. A file's name is made into a
  routing-safe prefix.
- onUsage(row, options): gets an allow-listed usage row (no bodies, prompts,
  error text, sessions or request ids). The rows come from a bounded queue
  (1024) with one worker, off the request path; a full queue drops the row
  and counts it, and a request never waits. 250ms each.

plugins/middleware is renamed "JS gateway plugins", with a new Sub
(en/zh/zh-TW/ja/de). It registers usage.Observe(middleware.Points()). Off,
no JS hook, strategy or onUsage runs. InUse is unchanged.

providers.json keeps a routing of the form <plugin>/<name> as saved
(provider.PluginRouting) in provider and group Save, whether or not a
plugin serves it now. Before this, `group set g routing=pick/last`
stored nothing.

GUI: the settings state carries jsRoutings. Provider and group routing
pickers offer the served ones, marked data-feature=middleware. A saved
routing that no plugin serves now shows as it is, with a hint. The
Plugins page's line shows routings, how often they were asked, onUsage
rows and dropped rows. The CLI accepts `group set <id> routing=<plugin>/<name>`.
`magpie plugin` lists a module's routings and onUsage; a strategy-only
module had printed nothing after "gateway middleware".

Docs: docs/subsystems/gateway-middleware.md (Routings and usage rows,
limits, verification) and plugin-runtime.md (P4: community plugins at
every point). site/public/docs plugins.html in en, zh and ja has an
example: internal/middleware/testdata/spread.gateway.js, which
TestDocsExample runs.

What was run (worktree on 4df1ba0c6, -p 2):
- gofmt -l: clean. go vet on internal/{middleware,cli,gui,plugin,provider}
  and plugins/...: darwin, GOOS=linux -tags nogui, GOOS=windows; all
  clean, run after the last Go change.
- go test, after the last Go change: internal/middleware ok,
  plugins/middleware ok, internal/provider ok (210s), internal/cli ok
  (203s). Earlier in the work: internal/plugin ok (385s), internal/pluginrt
  ok, internal/gui (Go) ok (320s), and plugins/... ok. The first
  plugins/... run printed a bare FAIL line that `tail` cut off before its
  cause showed. The rerun was all ok; the cause is unknown.
- GUI, both engines (routing-*, group-*, builtins, i18n-keys, gui-de/ja/zh-tw,
  plugin-middleware): 1220 tests, 1204 pass, 16 fail.
  - routing-manual (4): mine. A group's own "manual" was offered a second
    time as a routing no plugin serves. Fixed in client.js withJS. The
    coordinator is rerunning routing-manual, keys-fold, group-fold,
    intent-entry and routing-js alone in both engines, so that rerun is
    not recorded here.
  - routing-model-rest: red alone too, and red on untouched 4df1ba0c6
    (3/20). It is #2115; I commented there with the webkit cases.
  - group-member-weight webkit de 420 is #2387.
  - group-from-model-add webkit zh: it passes alone 2 of 2. Under load it
    waits a fixed 2s for the save post. Filed as #2388.
  - routing-keys-fold (webkit zh/ja/de), routing-group-fold (goto timeout)
    and routing-intent-entry (browser launch timeout 180s) are load
    timeouts. The coordinator is rerunning them alone.
- routing-js.test.cjs (new) passed in chromium en and zh, before the full run.

Broken by hand, each test went red, then restored:
- the permutation check: TestStrategyFailsOpen;
- the queue's non-blocking send: TestOnUsageNeverBlocks ("Ledger waited
  2.04s");
- the allow-list: TestUsageRowAllowList;
- unregister on off: TestStrategiesServedWhileOn and
  TestStrategiesStopWithServe;
- the CLI pattern: TestParseRoutingStays;
- Observe in plugins/middleware: TestOnServesStrategies;
- PluginRouting in provider.go and in group.go: TestPluginRoutingKept;
- the prefix sanitizing: TestRoutingFromFileName;
- the CLI list line: TestPluginListSaysMiddleware;
- the GUI's data-feature mark and its unserved-saved entry: routing-js.

Real use: a sandbox HOME, the gateway served on 127.0.0.1:3682 by a
-tags nogui build, a fake vendor on 3681, and providers fa (key ka) and
fb (key kb) in group g. pick.gateway.js has strategy last (reverse) and an
onUsage that logs.
- `group set g routing=pick/last` stored it.
- A request to group/g reached the vendor with Bearer kb, and the
  "usage-row fb m in=5 keys=17" line was logged.
- `plugin off pick.gateway.js`: Bearer ka (listed order), no onUsage,
  routing still pick/last.
- `plugin on`: Bearer kb and onUsage again.
- `plugin builtin off middleware` says "in use and stays on", as InUse
  should.
- Not tried: the GUI against that gateway, or a real vendor account.
2026-10-15 22:36:59 +08:00

9.6 KiB
Raw Blame History

Gateway middleware

A plugin can be a JS gateway plugin: JavaScript that magpie runs inside its gateway on the requests agents send and the replies they get back (middleware), on the order a pool's accounts or keys are tried in (strategies), and on each usage row (onUsage), whatever provider serves them. It is separate from the provider plugins in Provider and plugin ownership, which run on Bun in the plugin host. Middleware runs in the gateway's own process on moejs, a JavaScript engine written in Go, because it sits on every request and every streamed event.

Responsibilities and sources of truth

Part Responsibility Source
Discovery Find a plugin's gateway module: magpie.middleware (or its alias magpie.gateway) in its package.json, or a path to a *.middleware.js / *.gateway.js (or .mjs) file plugin.Middleware in internal/plugin/middleware.go
Bun host Skip a plugin that is middleware only (no main, no exports) Middleware(...) check in host.go
Load and run Compile, pool runtimes, call hooks with limits, count calls and failures internal/middleware: middleware.go, run.go
Gateway Run the chain on agents' requests only, as one gwmw.Agent on the gateway's middleware point; the built-in plugin middleware registers it (middleware.Chain), and with that plugin off no middleware runs serveAgent in internal/gateway/middleware.go, called from gateway.go and codex_backend.go; internal/gwmw, plugins/middleware; Plugin runtime
Routings and usage A module's strategies are routings <short name>/<name> (routes.Register) and its onUsage gets allow-listed usage rows, both while the gateway serves middleware.Points() (a usage.Observer the middleware plugin registers) points.go
GUI and CLI Show each middleware's hooks, calls, µs per call, failures and load error; its routings and how often they were asked; its usage rows and those dropped. The routings served are jsRoutings in the settings state, offered in every routing picker; magpie group set <id> routing=<plugin>/<name> takes one middleware.States(); pluginEntryJSON.Middleware in internal/gui/plugins.go, mwLine in plugins.js, listPlugins in plugins_cli.go
Options A middleware's options in plugins.json, as ctx.options; set by name, spec or short name; a package's magpie.options is only the editor's example SetOptions, ShortName in store.go; pluginOptions in plugins_cli.go; optionsEditor in plugins.js
Kind Whether a plugin is a provider, middleware or both, shown on every card and row, also for one that is off isMiddleware, middlewareOnly in pluginEntryJSON; kind: "middleware" market entries (market.json, the community registry.json); kindChip in plugins.js
Community middleware Ready-made packages (@magpie-community/middleware-<name>), mostly New API's channel settings packages/{param-override,model-map,system-prompt,word-guard,think-tags} in magpie-community/plugins, tested with scripts/middleware.mjs
User docs The hooks, ctx and an example for plugin authors usemagpie.ai/docs/plugins#middleware (site/public/docs/*plugins.html)

plugins.json is the source of truth for which middleware is installed and on, in its order; a middleware that is off isn't loaded.

Runtime path

  1. serveAgent establishes the gateway session identity and optional recording, then calls Begin on each registered gwmw.Agent (the JS chain's is middleware.Begin) with the request's protocol, model, stream flag, path and agent. With no middleware it calls serve directly.
  2. Run.Request passes the agent's body, in its own API, to each onRequest in turn. An object returned is the body the next middleware and the gateway get; undefined keeps the bytes as they were. ctx.reject(status, message) stops the chain, and the agent gets that error in its API's shape (writeError).
  3. Run.Wrap wraps the response writer when some middleware has onEvent or onResponse. An SSE reply is split into events. Each event whose data is a JSON object goes to every onEvent that wants its name (export const events): an object replaces it, null drops it, and undefined writes the original bytes. data: [DONE] and other non-object data pass by. A whole JSON reply is buffered for onResponse, with ctx.status set. A reply with a Content-Encoding passes as-is.
  4. Run.End returns the runtimes to their pools.

Each middleware gets one runtime for the whole request, so its hooks share ctx.state. Runtimes come from a per-middleware sync.Pool and modules are compiled once per load. Compiling a plugin's module (imports kept inside the plugin) is internal/jsmod, which agent plugins (Agent wiring) share.

Only requests agents send go through serveAgent. magpie's own requests (thread titles, the router's classifier, the search and vision stand-ins) call serve directly. Middleware sees bodies before redaction, which still applies upstream, through the redact plugin's masker; masking asked for with no masker serving sends nothing (Plugin runtime).

Routings and usage rows

Points() is the gateway's observer for both (plugins/middleware registers it with usage.Observe; only the gateway process serves it). While served it looks at the loaded modules once a second and registers each strategy as <short name>/<name>: the package's short name, or a file's base name less .middleware/.gateway and its extension. A reload or the module going off removes them, and a pool routed by one no plugin serves is tried in its listed order (routingOf).

  • A strategy is strategies[name], a function (pool, seats, options) or an object with order. seats are routes.Seat in camelCase JSON (key, account, known, learns, used, soon in unix ms, pace, weight, resting, tokens). It returns an order of the seat indexes.
  • Each module has one runtime for its strategies and onUsage, so they share module state; one call runs at a time.
  • onUsage(row, options) gets a row of the allow-list in usageRow: time, operation, agent, provider and its account and key, the caller's key, model, requested, served, tokens, ms, ttftMs, status, errType, kind, rejected, tries and cost. No bodies, prompts, errors' text, sessions or request ids. Rows are queued (1024) and taken by one worker, off the request path; a full queue drops the row and counts it.
  • A routing of this form (provider.PluginRouting: a name of A-Za-z0-9._-, a slash, a name) is kept in providers.json as saved, by a provider's and a group's Save alike, whether or not a plugin serves it now, so turning a plugin off and on again keeps the groups routed by it. A file's base name is made into such a name (other characters become -). magpie group set <id> routing=<plugin>/<name> takes the same form.

Constraints and failure behavior

  • Limits: 250ms for onRequest and onResponse, 50ms for each onEvent, 1s to load. A hook past its limit is interrupted.
  • Fail open: a hook that throws, returns something that is neither an object, null nor undefined, or is interrupted leaves the request or event as it was. The failure is counted and kept as the last error, and logged at most 60 lines a minute.
  • A middleware imports only relative files; packages must be bundled into it.
  • Reload: a change to plugins.json or to a middleware file is picked up by the next request at most a second later (stamp).
  • A strategy has 20ms, waiting for its runtime included; one that throws, runs out of time or returns what isn't an order of the seats leaves them in their listed order (fail open), counted and logged as a failure. onUsage has 250ms and fails open the same way. A request never waits for onUsage.
  • Stats count the whole call, including parsing JSON into the runtime and writing it back. Calls are counted in the process that runs the gateway, so magpie plugin shows hooks and load errors only.

Measured with a real account and real Claude Code: about 1–1.6µs an event, 0.2–0.7ms an onRequest that parses and rewrites Claude Code's ~80KB body. BenchmarkEvent is about 0.9µs, 11 allocations.

Verification

go test -tags nogui ./internal/middleware   # TestStrategy*, TestOnUsage*, TestDocsExample: points.go
go test -tags nogui -run 'TestParseRouting|TestPluginListSaysMiddleware' ./internal/cli
go test -tags nogui -run TestPluginRoutingKept ./internal/provider
go test -tags nogui -run TestOnServesStrategies ./plugins/middleware
node --test internal/gui/tests/routing-js.test.cjs
go test -tags nogui -run TestMiddlewareThroughGateway ./internal/gateway
go test -tags nogui -run TestPluginListSaysMiddleware .
go test -tags nogui -run "TestSetOptionsShortName|TestBuiltinMarket" ./internal/plugin
go test -tags nogui -bench Event ./internal/middleware
node --test internal/gui/tests/plugin-middleware.test.cjs
# in magpie-community/plugins: each package runs its cases.json through the hooks
bun test packages/think-tags packages/model-map packages/param-override packages/system-prompt packages/word-guard