Commit Graph
5 Commits
Author SHA1 Message Date
yetone 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 6a900e0d0):
- gofmt -l: clean
- mote-run go vet -tags nogui ./internal/... ./plugins/...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok
- mote-run go test -tags nogui -count=1 -timeout 45m ./... (log kept
  whole): every package ok except three. internal/middleware's
  TestPointsLoadErrors was mine: its load-error text now names
  onAccount. The test is fixed in this commit, and the package and
  plugins/middleware were rerun ok at this tree. The other two are red
  on main and already filed: internal/cli TestLibraryMCPHub (#4140,
  TempDir cleanup) and internal/gui TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514, SearchAll from b09349d17)
- Rebased again on origin/main 20482d71f (it changed
  internal/gateway/affinity.go): mote-run go test -tags nogui -count=1
  ./internal/middleware ./internal/gateway ./plugins/middleware: all ok
  (gateway 846s)

Not tried: a real MOD_Probe against real Codex accounts. Not changed:
probe keys can still reach deactivated accounts (out of scope).
2026-11-01 02:19:26 +08:00
yetone 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 (cec54c1d0) and new builds alternated:
  old  13.2 / 13.3 / 12.2 wakeups/s, 0.40 / 0.35 / 0.42 ms CPU/s
  new   7.9 /  8.6 wakeups/s,         0.22 / 0.30 ms CPU/s
What's left is the Go runtime itself, awake.Keep's 5s tick and the 5s
looks for other processes' writes.

Tests: TestKeepFreshFollowsPluginsYml now also runs KeepFresh with a 1h
interval and needs Set to apply at once; TestStrategiesFollowOwnWrite
needs a plugin turned off through plugin.SetOff to stop being served
within 2s, with no refresh by hand; TestWritten. With the Written cases
replaced by a nil channel, both of the first two went red (applied = 1,
want 0; still served 2s after). Run at this head: go test -count=1
-timeout 45m ./internal/filememo ./internal/plugin ./internal/pluginrt
./internal/middleware ./internal/otlp ./internal/settings
./internal/access: all ok. GOOS=linux and GOOS=windows go vet -tags
nogui ./internal/...: clean. gofmt -l internal: clean.

Not run: the full suite and internal/gateway's tests (gateway.go only
changes KeepFresh's interval argument, and it compiles under vet); the
macOS app with its window open (only headless serve was measured).
2026-10-25 23:45:34 +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 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.
2026-10-15 23:08:05 +08:00
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