Commit Graph
5 Commits
Author SHA1 Message Date
yetone b0d0092be5 middleware: a streaming request's runtimes let its body go once its request hooks are done (#3383)
A request keeps its middleware runtimes until its reply has streamed,
so its hooks share ctx.state, and moejs kept the body each hook was
given, parsed, in the runtime's registers until End: a long context's
body was alive for the whole reply, ~10 MB for a 7 MB body. The report's
inuse profile had 448 MB under moejs ParseJSON with many agents
streaming at once. Request and Tried now call ReleaseCallData on the
request's runtimes once their hooks are done; ctx, and what ctx.state
holds, stay. Not after each onEvent: an event is small and its hooks run
a thousand times a reply.

Run:
- TestStreamingRequestHoldsNoBody: 8 requests streaming with a 7 MB
  body hold under 7 MB, and onEvent still reads ctx.state; with the
  release commented out by hand it fails ("8 streaming requests hold 69
  MB, their body is 7 MB").
- go test -count=1 ./internal/middleware/ ./internal/gwmw/: ok.
- go test -count=1 -run 'Middleware|Think|Strateg' ./internal/gateway/
  ./plugins/...: ok.
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui
  clean for internal/middleware.
2026-10-24 21:00:05 +08:00
yetone e44b9aef33 middleware: onProvider changes what one provider a request is tried on is sent
A JS gateway middleware can export onProvider(body, ctx). The gateway
calls it on each try, just before the body goes to that provider, with
ctx.provider = {id, name, account, model}: account is the subscription's
kind (claude, antigravity, …), absent for a key. Every try starts again
from the body onRequest left, so a change for one provider never reaches
another in a routing group. null and ctx.reject turn nothing away there.
A hook that throws or runs past 250ms leaves the try's body as it was.

A plugin could act only before routing until now, by the model name the
agent asked for. Claude Desktop asks for opaque aliases, so a plugin
couldn't tell which vendor a request was going to. The first user is
@magpie-community/middleware-antigravity-cloak: it changes only what an
Antigravity account is sent, so that Antigravity stops refusing Claude
Code's system prompt (xzplzpl on X). magpie itself still sends every
prompt as the agent wrote it.

- gwmw.To and gwmw.Tried; middleware.Run.Tried runs the hooks.
- serveAgent puts the runs on the request's context, and serve's
  candidate loop calls triedOn before the Antigravity foresight, so it
  judges the body that will be sent.
- Docs: gateway-middleware.md, reference.md, integrating.md, and the
  hooks table and community list in site docs plugins.html (en, zh, ja).

Run:
- go test ./... -timeout 45m in a sandbox HOME (macOS, at de671719a):
  every package ok but two. internal/middleware's TestPointsLoadErrors
  pinned the old list of exports; it now says onProvider too, and the
  package is green. internal/gateway's
  TestTranslatedStreamKeepsClientAlive/chat_to_responses went red under
  the full run's load (#2737, numbers added there); -count=10 alone is
  10/10 green, and with no middleware triedOn returns the body as is.
- TestMiddlewareOnProviderPerTry (gateway): a group a/m1 (500) then b/m1;
  a got "asked for a/A/m1/key", b got "asked". With the triedOn call
  replaced by `_ = triedOn` it is red (sent a:"asked" b:"asked").
- TestOnProvider (middleware): per-try bodies, throw and null fail open
  and are counted, a reject is a no-op, a nil Run passes through.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  on the changed packages.
- node --test internal/gui/tests/plugin-middleware.test.cjs: 24 pass.
- Real use: a sandbox magpie built from this tree, a real Antigravity
  account, the plugin installed from its folder. Real Claude Code 2.1.302
  (`claude -p` with a sandbox CLAUDE_CONFIG_DIR, model
  antigravity/gemini-3-flash) got its answer. With the plugin's
  {"off": true} the same run got the 400 "Resource has been exhausted".
  Direct /v1/messages with the billing line, the Agent SDK line, and
  Claude Code's three blocks: 200 each with the plugin on, 400 each with
  it off.
2026-10-18 00:50:14 +08:00
yetone e80fc7dc5d tests: TestFailOpen cuts only the spin short, not the throw and the string
It set the request limit to 50ms for all three hooks. In a full
go test ./... run (on bff7cbd24) the string case ran past 50ms
under load, and was counted "took too long" instead of "returned neither":
  state {... Calls:3 AvgMicro:44471 Failures:3 Last:onRequest: took too long ...}
Now the throw and the string run under the normal 250ms limit, and only
the spin gets 50ms.

Reproduced by injection: an 80ms busy loop in the string hook gives that
exact state line on the old test and passes on the new one. -race
-count=20 passes.
2026-10-16 22:58:41 +08:00
yetone 1d9fbeaff3 gateway: a keepalive goes to the agent as it is written when Privacy masking or a middleware wraps the reply, not with the first event after it (#2402, moonshardx)
Cause: codex-cli's developer messages (permissions, writable roots under
the home, git email) contain things Settings → Privacy masks. A masked
request's reply goes through redact.Writer, which restores values one
SSE event at a time and buffered everything up to the next blank line.
holdWriter's ": keepalive\n" is a comment with no blank line after it, so
every one waited in that buffer for the vendor's first event: six came
together at 96.5s, and Cloudflare's 100s read timeout gave a 524. A plain
{"input": ...} body has nothing to mask, its reply isn't wrapped, and its
keepalives went out live, which is the bisection in the issue.
middleware's writer (a JS onEvent) had the same buffer.

Fix: both writers pass through whole comment lines and blank lines
at the head of the buffer as soon as they arrive. The head of the buffer
is always where an event starts, so these lines belong to no event. A
comment inside an event stays there. In redact, an event held for a
placeholder's tail stays held, so the placeholder still comes back whole.

Tests: TestQuietCodexStreamKeptAliveThroughReplyWriters (gateway, over
HTTP): the issue's Codex-shaped Responses body, masked / a middleware
only, a vendor that sends response.created and stays silent until the
client has read a keepalive (3s cap), keepaliveEvery 40ms injected. Unit
tests TestWriterStreamKeepaliveNotHeld (redact, with a placeholder split
around keepalives) and TestStreamKeepaliveNotHeld (middleware).

Broken by hand: disabled the pass-through in redact/writer.go and
the masked subtest went red after 4.7s, as did the redact unit test.
Disabled it in middleware/run.go and the middleware subtest went red,
as did the middleware unit test. Each one is green again with the fix.

Run (sandbox HOME, -tags nogui -p 1): go test ./internal/redact/
./internal/middleware/ (whole packages) ok; go test ./internal/gateway/
-run 'Keep|Quiet|Redact|Mask|Middleware|Codex|Held|Unredact|Placeholder|Silent'
ok (129s). gofmt -l clean; go vet -tags nogui for darwin, linux and
windows on the three packages ok. Not tried with a real Codex account
behind a real Cloudflare Tunnel.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone eebd0b4222 plugin, gateway, gui: a plugin can be gateway middleware — onRequest, onEvent and onResponse run in magpie's gateway on what agents send and get back (moejs) — a plugin could only be a subscription provider, run in the Bun host, a process away from the gateway. A plugin may now declare middleware (package.json magpie.middleware, or a *.middleware.js / .mjs file), run in-process by moejs (pure-Go JS engine): compiled once, one runtime per request from a pool, so every hook of a request shares ctx.state. onRequest(body, ctx) sees the agent's body in its own API before routing; what it returns is the body the next middleware and the gateway get, undefined leaves the bytes as they were, ctx.reject(status, msg) answers with an error in the agent's API's shape. onEvent(ev, ctx) sees each SSE event's JSON (export const events = [...] filters by name; an object changes it, null drops it, undefined passes the bytes through untouched; data: [DONE] is no JSON and passes by). onResponse(body, ctx) sees a whole JSON reply, with ctx.status. ctx has protocol, model, stream, path, agent, the plugin's options and state. A hook that throws, returns a non-object or runs past its limit (250ms request/response, 50ms an event, 1s load; interrupted) leaves the request or reply as it was and is counted and logged (60 lines a minute); a compressed reply passes as-is. Files are reloaded within a second of a change. Only agents' requests run through it (serveAgent at the gateway's agent entry points and the Codex backend), never magpie's own titles, classifier or stand-ins; it sees bodies before redaction. A middleware-only package is skipped by the Bun host. The Plugins page marks a middleware with a chip, its hooks, calls and µs per call (JSON in and out counted), failures in red with the last error, and a load error. en/zh/ja/de; docs/reference.md and usemagpie.ai/docs/plugins#middleware (en/zh/ja) with an alias example. Tested with a real DeepSeek account through magpie web --gateway in a sandbox HOME: an alias middleware served "fast" and named it in message_start, a reject came back as 403 permission_error, a Chat stream uppercased; real Claude Code (sandbox CLAUDE_CONFIG_DIR) did Read, Bash and Glob tool turns through three middlewares with 0 failures: ≈1–1.6µs an event, 0.2–0.7ms an onRequest that parses and rewrites Claude Code's ≈80KB body. Real use found two bugs fixed here: [DONE] parsed as JSON (SyntaxError on every Chat stream) and stats leaving out the JSON time. internal/middleware tests (chain, undefined keeps bytes, reject, fail-open on throw/spin/string with the runtime reused, async hook, load errors, off and Bun skip, reload, split/CRLF/filtered/dropped stream events, [DONE] untouched, whole reply and gzip, 64 in parallel; BenchmarkEvent ≈0.9µs, 11 allocs) and TestMiddlewareThroughGateway (alias routed, events by protocol, redaction still upstream, reject in Anthropic's shape; fails without the change) are new; plugin-middleware.test.cjs (Chromium and WebKit, en and zh: chip, hooks and stats, failures with last error, broken and off, no left border) fails without it. The other plugin GUI tests and click-scroll pass in WebKit. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass (internal/provider failed once under load and passes alone). 2026-10-05 19:14:31 +08:00