Files
magpie/docs/subsystems/gateway-middleware.md
T
JoeyWu-tech 430e3050d8 gateway: magpie's own searches and image descriptions go without the agent's middleware (#3695)
aiirobyte (#3695): the gateway exited five times on 2026-10-26, and
every client was refused until it was started again. The one exit with
a stack died of "fatal error: concurrent map read and map write": two
of seenBody's goroutines in middleware.(*Run).Tried at once, one of
them in moejs's InternGoString.

A request's middleware runs in runtimes of the request's own
(serveAgent). Only one goroutine may use a runtime at a time (moejs),
and Run has no lock to hold callers to it. serve runs each try's
onProvider on them (triedOn) through the Tried the request's context
carries. For a model that can't see, magpie has each image of the
request described (seenBody), up to four at a time, and each
description is a request it makes of its own gateway on a context made
from the agent's (magpieChose(ctx)). So the descriptions carried the
agent's Tried and ran onProvider on one runtime from as many
goroutines. A model that can't search has its searches made the same
way (searchWith): a search is asked beside the agent's own stream,
which goes through the middleware's onEvent, and beside the round's
other searches, so one search is enough to share the runtime when the
middleware has onEvent. The runtime's maps were read and written from
two goroutines and the gateway died. When it didn't, the calls' values
crossed. In the runs below, hooks threw on values that weren't there
("Cannot read properties of undefined (reading 'push')", and "(reading
'messages')"), and a description went out as
{"0":0,"messages":[0,{"content":[0,{"image_url":0}],...}],...}, its
max_tokens, system prompt, text and image each turned into 0. An
earlier run of the same break (tree e1c90a00, this code with older
comments) had one image asked about twice and another never.

ownAsk takes the request's Tried off the context of those two asks, so
they go without the agent's middleware, as serveAgent's comment already
said of them ("search and vision stand-ins") and as magpie's other own
requests (titles, the classifier) go. The agent's own tries are as
before: each runs onProvider once, on its runtime. The subsystem page
now says why, and the user docs (en, zh, ja) name searches and image
descriptions among magpie's own requests.

Going without also keeps what the docs tell a hook. Its ctx.protocol,
ctx.model and ctx.stream are the agent's request's, while a
description's body is a Chat request and a search's an Anthropic one,
whatever the agent speaks. A description is also kept for later
requests (sights), so one asked through a request's middleware was
handed to later requests, other agents' too. The one community
middleware with onProvider, antigravity-cloak, rewrites Claude Code's
and Codex's lines in the system prompt, which a description's or a
search's prompt, magpie's own, doesn't have.

Not changed: the report's other fixes, a lock over the runtime, one ask
at a time, or a Run per ask. Each keeps the gateway up but still runs
the agent's middleware on asks that are magpie's own, which the docs
say go without it, and with the first two onProvider still gets bodies
its ctx doesn't describe. With ownAsk nothing else uses a request's Run
from two goroutines (holdWriter's keepalive writes under the h.mu the
handler's writes hold). magpieChose is left as it is: it says whose
pick a call is, and its other callers, Codex's thread titles,
descriptions and predictions (codex_titles.go), run before serveAgent
with no Tried to take off.

What was run (tree 4f97ac18, on origin/main 865df247, go1.26.8,
linux/amd64):
- TestImagesDescribedWithoutTheAgentsMiddleware, new: a text-only model
  asked with four images, and a middleware whose onProvider adds a line
  naming the provider's model. The four descriptions reach the model
  that sees without the line, the text model's request has it, and
  onProvider is called once, with no failure.
- TestSearchesWithoutTheAgentsMiddleware, new: a model that can't
  search makes two web_search calls in one round, with a middleware that
  has onProvider and onEvent. Both searches reach the searcher without
  the line, the model is asked twice, its first ask with it (the second
  goes on from that ask's body), and no hook failed.
- Both, without -race: -count=50 -v, 100 PASS; -count=40 three more
  times, ok.
- go test -tags nogui -race -count=20 -cpu 1,2 ./internal/gateway with
  this -run, ok, no race:
  'WithoutTheAgentsMiddleware|TestMiddleware|TestTextOnlyModel|TestVisionSetting|TestImageThatCant|TestGroupsTextOnly|TestDescriberThatCant|TestSeerPicks|TestManyImages|TestWebSearch'
- Broken by hand, each run with -race -count=1, then without -race at
  -count=40 three times:
  - main's vision.go: the test red, onProvider called 5 times (each
    description and the agent's try), 3 of the calls throwing "Cannot
    read properties of undefined" (reading 'push' twice, 'messages'
    once), the fourth description reaching the model that sees through
    the middleware as the mangled body above, races reported. At
    -count=40 all three runs died: of "concurrent map read and map
    write" in InternGoString (intern.go:167) twice, and of "concurrent
    map writes" in internASCII (intern.go:195) once.
  - main's search.go: the test red, both searches through the
    middleware, races reported. At -count=40 each run had 40 of 40 red,
    and none died.
  - ownAsk returning the context as it is: both tests red, races
    reported. At -count=40 all three runs died of "concurrent map read
    and map write" in InternGoString.
- A real run: magpie built at 865df247 and at this tree (go build -tags
  nogui -buildvcs=false), magpie serve in a sandbox HOME, a provider (a
  local server) with a text-only model and one that sees (from its
  /v1/models' modalities), Settings' vision model set to the one that
  sees, and a middleware added with magpie plugin add whose onProvider
  adds a line. 200 requests to the text-only model on
  /v1/chat/completions, four new images each, twice per build.
  865df247's gateway answered 6 and died on the 7th request, of
  "concurrent map read and map write" at the report's intern.go:167 in
  InternGoString, reached from Run.Tried; in the other run it answered
  7 and died on the 8th, of "concurrent map writes". 24 and 28
  descriptions reached the vendor, all but one with the line; that
  one's onProvider threw "Cannot read properties of undefined (reading
  'push')", so it went as it was. This tree's answered 200 of 200 both
  times, its 800 descriptions without the line and its 200 text
  requests with it.
- gofmt -l lists nothing; GOOS=linux, windows and darwin go vet -tags
  nogui ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go
  build -tags nogui ./... and GOOS=windows go build ./...: exit 0
  each. go vet and go build without the tag on linux: exit 1 (this box
  has no GTK or WebKitGTK dev packages).
- node --test site/*.test.mjs, as CI runs it (node v22.22.1): 45 pass
  (none of them reads plugins.html).
- Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp
  (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout
  45m, log kept): 65 ok, and 7 red, none in what this changes:
  - agent TestCodexDriftReached and TestCodexBehindReverseProxy: #3398;
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
    and TestZedAppPath: #3141;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git,
    #3641.
  - edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram: this
    box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks, the package's only red:
    this box's /tmp/.git, #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    this box's millions of open fds, #3649.
  - pii TestFindJoinsTextsAndMapsBack, TestGPUDeathMovesToCPU,
    TestServeStartsWithoutResidencyHeartbeat and TestWarm: #3741, fixed
    on main by c84f859d.
  - provider: "fatal error: close of synctest channel from outside
    bubble", #3632; the package's tests after it didn't run.

Not tried: macOS, Windows (built and vetted only), the reporter's
middleware (the report doesn't name it), a real vision model or
searcher.
2026-10-27 15:47:49 +08:00

11 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, short name or the name without its scope (plugin.Called: agent-aider, which was its short name before agent-, tools- and page- came off too); 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,antigravity-cloak} 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, runs any asynchronous request hooks through Bun, 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.Tried runs each onProvider on the body each time serve tries it on a provider, just before that try is sent (triedOn in the candidate loop of gateway.go; serveAgent puts the runs that are gwmw.Tried on the request's context). ctx.provider says which: id, name, account (the subscription's kind, as accountAgent gives it: claude, antigravity, …; absent for a key) and model, the model's id there. Every try starts again from the body onRequest left, so what one provider is sent changes no other try's: this is how a plugin acts on one vendor only, for an agent such as Claude Desktop whose model names say nothing of where they go. null and ctx.reject turn nothing away here; the request has been routed.
  4. 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.
  5. 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. A search or an image's description asked while an agent's request is served is made on that request's context, and takes the request's middleware off it (ownAsk): the runtimes are the request's, which one goroutine may use at a time (moejs), and Run has no lock to hold callers to it, and these asks go beside it and each other, so images described at once ran onProvider on one runtime and the gateway died of concurrent map read and map write. Nor does the hooks' ctx describe them: a description's body is Chat and a search's Anthropic, whatever ctx.protocol names, and ctx.model and ctx.stream are the agent's (#3695, TestImagesDescribedWithoutTheAgentsMiddleware, TestSearchesWithoutTheAgentsMiddleware). 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, each onProvider 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 (an onProvider returning null too), 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|TestMiddlewareOnProviderPerTry|WithoutTheAgentsMiddleware' ./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 packages/antigravity-cloak