ac4af582301a4e8a29245dbba767eba31334ddf9
14
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e40675cc19 |
middleware: onAccount can pass an account over for a request (bm_rabbit)
bm_rabbit (Discord) is building MOD_Probe, a middleware that tells
Codex accounts apart and needs to keep some requests off some of them.
onProvider could only change a try's body, never which account took
it.
A JS middleware may now export onAccount(account, ctx). The gateway
calls it before each try on a subscription account, at the top of the
candidate loop (accountSkipped). That is before anything of the try is
done: no Codex reset is spent, no body is built, nothing is sent.
account is {ref, provider, name, kind, model}. ref is 32 hex
characters: an HMAC-SHA256 of the middleware's name and the account's
agent, lower-cased user and plan. Its key is random, made once per
install in account-ref.key in magpie's config folder. It is written to
a temp file and linked into place, so it never writes over a key that
is there. The ref is the same on every request and after a restart,
and different for each middleware. The email can't be found from it
without the key. A key file that can't be read is never overwritten:
that process uses a key of its own and logs it.
{skip: true} passes the account over for this request. The next
candidate is asked, as past an account that can't be used. The call's
fallback gets a "passed over by middleware <name>" line, and the
account is not rested or held against. When the last candidate is
passed over, nothing is sent (no fail-open). The agent gets the
failure of a candidate asked before it, or, if there was none, the
usual 404 "none of <model>'s models is ready".
Anything else uses the account: undefined, {}, null, a throw, or going
past the 250ms limit. The last three count as failures. A key's try
asks no onAccount. ctx.account holds the same object for the hooks
after it on that try, and is taken away on a key's try. ownAsk clears
the Accounts runs with the Tried ones.
Note: the plan is part of the ref, so a plan change gives the account
a new ref.
Docs: docs/subsystems/gateway-middleware.md (runtime path step 4,
limits, fail open, verification), docs/reference.md,
docs/integrating.md, and site/public/docs/{,zh/,ja/}plugins.html (an
onAccount row in the hooks table). The Bun plugin host is unchanged:
middleware runs in moejs in the gateway, not in host.js.
Tests:
- internal/middleware TestOnAccount: the ref is stable across runs and
a key reload; it differs between two middlewares, users, plans and
kinds, and is the same when only case differs; no email or plan
reaches the hook. {skip:true} names the middleware; undefined,
{skip:false}, throw and null use the account (2 failures counted);
ctx.account reaches onProvider; a key's try clears it.
- internal/middleware TestAccountRefKey: the key file is made at 0600,
read back, never written over when unreadable, and no temp file is
left behind.
- internal/gateway TestOnAccountSkipMovesToNextAccount: two Codex
accounts, Ordered. The first is passed over, only acct-2 is sent
the request, acct-1 doesn't rest, and the same holds on a second
request.
- internal/gateway TestOnAccountSkipEveryAccount: every account passed
over gives a 404 "…models is ready", nothing is sent, nobody rests.
Broken by hand, each on mote, each red, then restored:
- skip ignored in accountSkipped: both gateway tests red (acct-1
reached; 200 instead of 404)
- fail open on the last candidate: SkipEveryAccount red (200)
- the skipped account rested: both gateway tests red (rests)
- a random key per ref: TestOnAccount (refs changed between requests)
and TestAccountRefKey red
- the middleware name left out of the hash: TestOnAccount red (two
middlewares told one ref)
- an unreadable key overwritten: TestAccountRefKey red
Run at this commit's tree (rebased on origin/main
|
||
|
|
60520ddb3b |
moejs: v0.1.0-alpha.11, at its new module path github.com/MoeForge/moejs
Gateway middleware and agent plugins run on moejs. alpha.11 moves the
module to github.com/MoeForge/moejs; every other API change since
alpha.4 is an addition. What magpie gets: faster calls, loops, property
lookups and JSON.parse, allocation-free await, a bytecode verifier, a
correct default.pgo, and Intl / toLocaleString in plugin code.
Checked against both tags' source: every name magpie uses (NewRuntime,
Options, Compile, Link, Hook, Value, Arg, Undefined, NativeFunc,
Referrer, the Promise results, Exception) has the same signature, and
Options' defaults (shared frozen builtins, no timers) are unchanged.
fetch, Streams, URL, node:fs and node:buffer live in the separate
webapi and node packages, installed only on request; magpie installs
neither, so a plugin still reaches no network or file.
Intl's CLDR, Unicode, ICU and V8 material is compiled into every build,
and moejs asks a program that includes it to carry sections 1 to 4 of
its notices. THIRD_PARTY_NOTICES holds them verbatim. Release archives
ship no LICENSE today either; that is not changed here.
Doc and site links (docs/, site/public/docs/{,zh/,ja/}plugins.html)
point at the new repo.
Run on mote at this tree: gofmt; go build -trimpath -s -w (60,670,658
bytes on origin/main
|
||
|
|
de49433ff8 |
filememo: another process's writes to magpie's files are watched for, not polled every 5s (#3185)
An idle magpie still woke a dozen times on each 5s beat: the loops that follow plugins.yml, settings.json, providers.json, the plugin list, tools and access each looked at the disk for what the CLI or a second magpie wrote. The gateway now watches those files' folders (fsnotify: FSEvents, inotify, ReadDirectoryChangesW), and a change from another process wakes the same loops at once, as magpie's own writes do (filememo.Written). With the watch running the loops look for a change they missed only once a minute (OthersEvery); where the folders can't be watched, or the watch errs, they go on looking every 5s. Run at |
||
|
|
466cafa0cf |
idle: the loops that look every few seconds wake together on the clock's beat (#3185)
An idle magpie serve still woke ~6 times a second with nothing to do. Its loops each kept a ticker of their own, started at their own instant: awake.Keep (5s), the plugin config's KeepFresh (5s), the middleware observer (5s), OTel's session watch (5s idle), the Codex daemon check (15s), dsh's wiring (30s), the model lists' look (1m). Every one woke the process apart, a few threads each time. internal/beat's Next(every) fires at the next multiple of every on the clock, so the 5s loops come due at one instant, the 15s and 30s ones on every third and sixth of it, and the runtime runs timers due together in one wakeup. Each loop now waits on beat.Next instead of its ticker. No channel is shared between callers (a synctest bubble's channel reached from another crashes the process, #3632). Run at this head ( |
||
|
|
091153bf71 |
idle: the loops following magpie's files wake on its own writes, not a 1-2s poll (#3185)
An idle `magpie serve` (no providers, no requests) woke 12-13 times a
second. A runtime trace showed the wakers were polling loops: the
middleware observer's refresh every 1s, pluginrt.KeepFresh's stat of five
files every 2s, OTel's session watch every 2s and its exporter tick every
5s, all with nothing to do.
Now filememo.Forget, which every write magpie makes of settings,
providers, sign-ins and caller keys already calls, also closes a channel
(filememo.Written). The plugins.json, tools and plugins.yml saves call it
too. The middleware observer, KeepFresh and OTel's session watch wait on
it, and look every filememo.OthersEvery (5s) only for what another
process (the CLI, a second magpie) wrote. Each takes the channel before
it looks, so a write made during a look isn't missed. middleware's
current() also reloads at once when filememo's generation moved, rather
than after its 1s skip. OTel's session watch waits 5s, not 2s, while
sessions aren't exported, and its exporter's timer runs only while a
batch holds something.
Measured: sandbox HOME, MAGPIE_ADDR=127.0.0.1:3481, `magpie serve`,
proc_pid_rusage (idle + interrupt wakeups) over 30s after 40s warm-up,
old (
|
||
|
|
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.
|
||
|
|
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
|
||
|
|
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.
|
||
|
|
386d341e70 |
tests: onUsage's tests don't wait out the price catalog's first load — TestOnUsageNeverBlocks went red in a full run at load 70–100
The first row a process prices through the catalog loads it: ≈1.5–2s on an idle machine, measured. TestOnUsageRows' row carries its own cost and never loads it, so TestOnUsageNeverBlocks was the first to, and its until (10s) held the load as well as the queue's three 100ms rows; in a full suite at load 70–100 the rows were never all given (12.31s, "never: the queued rows given"). TestDocsExample, run alone, waited for the same load. serve() now prices one row once before a test's rows go in. Injected: with until cut to 1s, origin/main fails TestOnUsageNeverBlocks and TestDocsExample alone, each "never: the row(s) given"; with this change both pass, 3 of 3. Not reproduced by rerunning: 15 of 15 passed under 28 CPU burners. Ran: gofmt; go vet -tags nogui ./internal/middleware/ for darwin, linux, windows; go test -tags nogui -race -count=5 ./internal/middleware/ ok. Full suite: the batch this goes out with ran go test -tags nogui -timeout 45m ./... with every package ok but internal/middleware (this red); internal/middleware ok after. |
||
|
|
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
|
||
|
|
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.
|
||
|
|
4ac4d9ba99 |
plugins: the gateway's middleware point; JS middleware and privacy masking are built-in plugins, masking fails closed (P3)
P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:
- Agent: a middleware on an agent's request in its own API and on its reply.
serveAgent runs each registered one. The JS gateway middleware is the one
there (middleware.Chain), registered by the new built-in plugin
`middleware`. Its place, API, limits and fail-open are unchanged. InUse is
middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
back. The new built-in plugin `redact` serves masking.Masker (in
internal/masking, since settings imports redact). InUse is masking.Wanted.
It fails closed: masking asked for with no masker serving, or a masker that
panics, is a 503 "nothing was sent" at every call site that masked before
(serve, count_tokens, embeddings and audio, transcriptions, images, video,
search stand-ins and their queries, the Codex backend).
With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.
Run (on origin/main
|
||
|
|
cb406c8425 |
plugins: a plugin can add an agent magpie has no setup of its own for
Plugins could be subscription providers or gateway middleware. Now a third
kind: an agent plugin, so a user whose agent magpie doesn't ship can still
put it on magpie.
- internal/agentplug: a plugin's magpie.agent module (or a *.agent.js file)
exports agent = {id, name, config, format?, model, prefix?, bin?, dir?,
ua?, icon?, notice?} and an optional connect({gateway, model, models,
agent}) returning the other keys to write. Compiled in moejs, reloaded
when plugins.json or the file changes; why one didn't load is kept.
- internal/jsmod: module compiling (imports kept inside the plugin), moved
out of middleware so both share it.
- internal/agent/plugged.go: each becomes an Agent (Plugin set) after
magpie's own. JSON, YAML and env files are edited key by key, comments
kept; what each key held is stashed typed under plugin:<id>:<path>, and
its own model or Disconnect puts every key back. A built-in id is
refused; a connect that throws writes nothing. Key magpie-<id>; usage
names it by key or ua (usage.PluginAgents).
- GUI Plugins page: an Agent kind chip and glyph, a Discover "Agents"
section (market kind "agent"), and an installed row line "Adds X to
Agents" or why it didn't load. zh, zh-TW, ja, de strings.
- Docs: site Plugins page (en, zh, ja) "Agent plugins", reference.md,
agent-wiring.md, gateway-middleware.md.
Run:
- go test ./... (all ok); gofmt -l clean; GOOS=linux go vet -tags nogui
./... and GOOS=windows go vet ./... clean.
- TestPluggedYAML, TestPluggedJSONUnwire, TestPluggedRefused.
- GUI: plugin-agent.test.cjs 22/22 (en, zh, zh-TW, ja, de; 980 and 420;
chromium and webkit); all plugin-*.test.cjs, i18n-keys,
deprecated-subscriptions, filter-ime: 315 pass, 0 fail.
- Real use, in a sandbox HOME: an Aider plugin (~/.aider.conf.yml, prefix
openai/, connect writes openai-api-base/key) installed in a dev build;
picking DeepSeek V4.1 Flash on the Agents page wired the file keeping the
user's comment and keys; real aider 0.86.2 `--message` answered through
magpie from the real DeepSeek account; usage.jsonl recorded agent aider,
provider deepseek, 200; Disconnect restored the file byte for byte.
|
||
|
|
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). |