Commit Graph
15 Commits
Author SHA1 Message Date
yetone 6a450c4982 agent: Shelley, magpie's models as its custom models (on X, tweet 2120109384315658393)
"Can support Shelley?" Shelley is boldsoftware/shelley (Apache-2.0, Go,
`shelley serve`). It keeps models and profiles in its SQLite database,
not in a config file, so magpie talks to a running Shelley through the
same API its own Models and Profiles pages use, on the Unix socket it
opens for its CLI ($SHELLEY_SOCKET, else shelley.sock / shelley-N.sock in
$XDG_CONFIG_HOME/shelley or ~/.config/shelley; read from its source).

- Connect: each magpie model is a custom model (POST /api/custom-models,
  provider_type openai, endpoint = the gateway's /v1, Shelley's own
  gateway key, model_name = the catalog id, reasoning/images/max_tokens
  from the catalog). Picking one makes it the default profile's model
  (PUT /api/profiles/{name} with the whole profile, as the API requires)
  and clears a thinking level the model can't take.
- The user's own values: the profile's model and thinking level are
  stashed once and put back on Disconnect (to the server's default if
  that model is gone); only the custom models magpie made (ids stashed)
  are deleted, so a model the user pointed at the gateway by hand stays.
- Sync re-points magpie's models when the gateway port moves; Check names
  a model left on an old address. Shelley not running is an error on a
  pick and nothing on Sync/Check; turned off while Shelley is uninstalled,
  the takeout is stashed and done when Shelley answers again (Alma's way).
- A notice: new conversations start on the pick, an open one keeps its
  model. i18n for zh, zh-TW, ja, de.
- Icon: Shelley's own S mark from its assets, one tone. README (en, zh),
  site index, docs/reference.md, docs/integrating.md, site integrate
  pages (en, zh), docs/subsystems/agent-wiring.md.
- Library: listed as "not looked at (#5897)" like the other new agents.
- Shelley has no Windows build, so there is no Windows or WSL wiring.

Run (mote refused SSH for the whole session, kex reset, so runs went to
the Linux VM and the Windows box):
- Real binary: shelley v0.1718.926152762 linux_amd64 (sha256 66cb5acb…
  checked) in a sandbox HOME/XDG_CONFIG_HOME/-db on the Linux VM, with a
  throwaway test driving it against a fake OpenAI upstream at
  MAGPIE_ADDR: connect made custom model glm-4-6-… and the default
  profile's model; POST /api/conversations/new sent two
  /v1/chat/completions with model=relay/glm-4.6, auth magpie-shelley,
  UA Shelley/58d5f200; disconnect left the profile as before and no
  custom models. Check "" and Drift nil while connected.
- Linux (wsl-run, nogui): go vet ./internal/agent ./internal/agentenv
  ./internal/library; go test ./internal/agent ./internal/agentenv
  ./internal/library ./internal/profile ./internal/sessions: ok except
  TestGrokInstalled (#3548, red on base too) and, before its fix here,
  TestEveryAgentInLibrary. internal/cli times out there in
  TestEveryAgentFieldNameWritesNothing (43m, the #5234 class).
- Windows (win-run): go vet ./internal/agent ./internal/agentenv;
  GOOS=darwin and GOOS=linux -tags nogui vet; the Shelley, applied,
  rewire, disconnect, mark and kept tests: red only in
  TestAppliedOfParsesAnUnchangedFileOnce (#5950),
  TestAsideOfflineDisconnectRestoresWithoutDaemon (#5951) and the #4786
  allocation tests, all red on base d4b4a188e too. internal/cli
  TestHelpOnEveryCommandDoesNothing, TestEveryAgentFieldNameWritesNothing
  and internal/library TestEvery*: ok.
- GUI (node --test, chromium + webkit) i18n-keys, i18n-en-no-cjk,
  agent-notice-lang, gui-de, gui-ja, gui-zh-tw, icon-one-tone, icon-tile,
  routing-client-icons, usage-agent-filter-icons, agent-connect,
  agent-models, agent-layout, on the Windows box at the rebased head:
  110 tests, 107 pass. Red: gui-ja "ja has every zh string" ({model}
  twice, #5943) and icon-one-tone webkit voyage-color (#5962), both red
  at origin/main a1ba92ad8 too.
- At the rebased head 2a9c7b715 (on origin/main a1ba92ad8), Linux:
  vet of agent, agentenv, library ok; go test agent, agentenv, library,
  profile ok except TestGrokInstalled (#3548). Pushed on ca7a39291,
  which changes only internal/gateway (MiniMax drawing); not rerun.
- gofmt -l clean.

Broken by hand: not restoring the profile's model on Disconnect turns
TestShelley and TestShelleyThinkingLevel red; not deleting magpie's
custom models turns TestShelley and TestShelleyKeepsHandWired red.

Not tried: a real model upstream (the upstream was a fake), macOS (mote
unreachable; the darwin build was vetted only), the GUI against a real
Shelley, Shelley's web UI after the switch.
2026-11-10 21:52:19 +08:00
yetone 18726b9fb6 statusline: a held key is told how to see its line, ?format=json, and /v1/magpie/limit says what holds a key (steven_4422)
steven_4422 (Discord, #feedback): POST /v1/magpie/statusline answered 403
gateway_key_held to a key held to Claude's models, while GET
/v1/magpie/limit told the same key {"limited": false}. They asked for the
line scoped to what the key may use, /limit to agree, and a JSON line for
claude-hud's external usage snapshot.

The scoped view already exists (#2216): the status line goes through
scopeQuotas like the quotas routes, so a held key its owner turns Quotas
on for (Gateway -> Gateway keys, or `magpie gateway-key quotas <id> on`)
is told the accounts it may use of each provider whose every model it may
use, and nothing else. Its 403 never said so. Decision: the switch stays
the gate for every held key, budget, models or accounts alike. What holds
a key says nothing of whether its holder is the owner or a friend (#1981
was a friend's budget key seeing every account's email), and only the
owner knows that, so a model- or account-held key is not told quotas by
default either. The every-model rule of #2216 stays.

- scopeQuotas' refusal (heldQuotasOff) names the switch and what it then
  tells. heldRefused, for the routes the switch doesn't open
  (concurrency, trace, a card outside the scope, writeCards' told-none),
  is unchanged.
- GET /v1/magpie/limit tells a held key heldTo (budget, models,
  accounts), models, quotas and, with it on, quotaProviders (the
  providers newQuotaScope tells it). No account is named. `limited`
  keeps its meaning (the budget) for remote magpies that read it.
- ?format=json on the status line: {"text", "model", "accounts"}, the
  cards the line shows in /v1/magpie/quotas?kept=1's shape (windows'
  used, resetsAt), through the same scope.
- Docs: reference.md, integrating.md, gateway-routing.md; site docker
  and remote pages in en, zh, ja.

Run at this head (4a9cfb52e + this), on mote:
- gofmt -l clean; go vet, GOOS=windows go vet, GOOS=linux go vet -tags
  nogui on internal/gateway: clean.
- go test -run 'TestStatusline|TestHeldKey|TestRemoteMagpieShowsHeldKey|KeyLimit'
  ./internal/gateway: ok.
- TestStatuslineHeldKeyScope (new): this computer and a key held to
  nothing see alpha One, alpha Two and beta; a key held to alpha/* sees
  alpha's two; one held to alpha's Two sees Two alone; one held to
  alpha/m1 sees nothing; the same through ?format=json; Quotas off is
  403 gateway_key_held naming the switch, as text and JSON; /limit's
  heldTo, quotas and quotaProviders for each, and no account id.
Broken by hand, each red: the scope dropped from the handler (every
held key saw every card, text and JSON); /limit's held block skipped;
scopeQuotas back on heldRefused.
Not run before the push: the full suite (mote had three full suites of
other sessions running at load ~70; it runs after, per the rules). Not
tried: a real Claude Code or claude-hud on another computer, a real
Claude account behind a held key, Windows and Linux test runs.
2026-11-05 00:24:13 +08:00
yetone 8a80796805 gateway: the native route passes any path of a keyed provider's own API on, at its host
axelburks (Discord #feedback) asked for /v1/magpie/native/<provider>/...
to reach the whole of a vendor's API, not only Ark's image and video
task paths. Now GET, POST, PUT, PATCH and DELETE of
/v1/magpie/native/<provider>/<path> go to the provider's host at /<path>
(not under the base's /v1 or /api/v3), with the query and body as they
came and the answer streamed back as it comes.

Guards:
- API-key providers only (nativeKeyed): no subscription, OAuth or plugin
  account, no remote magpie, no Vertex. 403 otherwise.
- The gateway's own guards as every route: lanGuard's Host check,
  corsGuard (foreign Origin, null, *.localhost without a key), a key
  beyond loopback, read-only keys refused (PUT/PATCH added to
  readOnlyRefused), and a key held to models/accounts/limits refused
  (nativeHeld, as before).
- nativeTarget refuses an empty path, "." / ".." segments (encoded too,
  across %2F), a backslash, a (encoded) leading slash, "://", a
  scheme-like first segment, and any URL whose host or scheme parsed back
  isn't the base's. 400, vendor not asked.
- The caller's Authorization, x-api-key, api-key, x-goog-api-key,
  Cookie, ?key=, Origin/Referer/Sec-*/X-Forwarded-*/Cf-*, hop and
  X-Magpie-* headers are dropped; Sign puts the provider's key in the
  way it takes one. Set-Cookie, Alt-Svc and HSTS don't come back.
- With masking on, a JSON body is masked (fails closed) and restored in
  the answer; a non-JSON body is a 415. Only a masked request's answer
  goes through restoring; every other answer streams in 32KB reads,
  never held whole.
- Each request is a Requests row and a usage record (Operation
  "native"), with tokens when a JSON or SSE answer reports them.
- Ark's short paths (nativeArkPath) keep their old code path, under the
  key's base, unchanged (nativeArk).

Docs: gateway-routing.md (table row, native route section),
reference.md (path table + paragraph), integrating.md, site
integrate.html en and zh.

Run (mote, darwin arm64, Go 1.26.8):
- go test -count=3 -run 'Native|ReadOnly' ./internal/gateway: ok
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., gofmt -l: clean
- Rebased on origin/main b61c71448 (851468ecb): gofmt -l, go vet
  (darwin, linux nogui, windows) of the touched packages, and go test
  -count=1 -timeout 45m ./internal/gateway ./internal/access: both ok.
- Rebased again on origin/main 34116ec01 (five commits, only the
  gateway-routing doc overlapping, merged clean), 5880a1412:
  gofmt -l, the three go vets of internal/gateway, and go test -run
  'Native|ReadOnly' ./internal/gateway: ok. The whole gateway package
  was not rerun there. The last rebase, over 11d9d0a3a (a routing GUI
  commit sharing no file with this one), was not run again.
- Before the rebase, the same packages at 083821dc9:
  access ok; gateway FAIL on TestSocketTurnBodiesFreed only ("1 of 12
  socket turn bodies still kept"), already filed as #5250 for the same
  symptom on a loaded mote; alone it passes 5 of 5 on this tree
  (-count=5), and the change doesn't touch the Responses socket.

Broken by hand, each red on its test:
- no "."/".." segment check: TestNativeAnyStaysOnTheHost (a/%2e%2e/b,
  ..%2Fx, a%2F..%2Fb reached the vendor)
- nativeKeyed always true: TestNativeAnyRefusals
- nativeHeld skipped: TestNativeAnyRefusals
- caller headers not dropped: TestNativeAnyForwardsAtTheHost
- ?key= passed on: TestNativeAnyForwardsAtTheHost
- route on POST/GET/DELETE only (the old registration):
  TestNativeAnyForwardsAtTheHost
- masking skipped: TestNativeAnyMasks
- no Flush: TestNativeAnyStreamsAsItComes (20s, nothing before the last
  byte)
- no sniffer: TestNativeAnyRecordsUsage
- no lanGuard: TestNativeAnyRefusesPagesWithoutAKey (rebound Host and
  another machine reached the vendor)

Not tried: a real call to Ark or any other vendor through the route;
everything here is against httptest vendors.
2026-11-04 22:05:21 +08:00
yetone d8501848a7 gateway: an Ark image request's own fields go to Ark, and watermark and response_format are the caller's
axelburks on Discord listed what /v1/images/generations did to a Seedream
request against Ark's images API (docs 82379/1541523). Checked against
those docs and draw.go / draw_volcengine.go; the real ones:

- Image params were dropped. drawing read OpenAI's fields alone, so
  sequential_image_generation and its options (a group of up to 15),
  optimize_prompt_options, tools, layer_decomposition and every other
  Ark field never reached Ark. Now the request's fields magpie doesn't
  read (drawingRead) are drawing.Extra, from a JSON body or a multipart
  form, masked as the prompt is (fails closed), and sent to Ark as they
  came; a form's values are typed as Ark takes them (formValue, with
  Ark's text fields kept as text). layer_decomposition with an image
  needs no prompt.
- watermark and response_format were forced. Every request went with
  watermark false and response_format b64_json. Now watermark false is
  magpie's default only, and a caller's watermark wins; response_format
  "url" asks Ark for its URL and answers it, anything else still asks
  b64_json.
- stream true would have gone to Ark and come back as events this route
  can't read: it is a 400 that names
  /v1/magpie/native/<provider>/images/generations.
Kept as it was: n stays OpenAI's, that many requests, each one image or
one group.

Tests: TestArkImagesPassOnTheirOwnFields (a group, optimize_prompt_options,
a caller's watermark, tools and url reach Ark as sent; a form's fields
typed; stream refused naming the native route). Docs: gateway-routing.md
(the Ark images row and paragraph), docs/integrating.md and the site's
integrate page (en, zh) on the vendor fields and the native route.

Run on mote at the head of this stack (the Ark video fields, the native
route and the Ark image fields, three commits on af9ac3d25):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/gui
  ./internal/access: gateway and access ok; gui red only in
  TestMainWindowCorners/macOS_26_SDK (#3949, red on main).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. gofmt -l: nothing.
- No GUI file or script changes in this stack, so no GUI run.
The commits between were not run on their own at this base.

Broken by hand, each red, then put back:
- Extra not merged into Ark's request: TestArkImagesPassOnTheirOwnFields red
- response_format url not asked of Ark: TestArkImagesPassOnTheirOwnFields red

Not tried: no real Ark image was drawn (no money spent); the shapes are
from Ark's docs, on a fake Ark.

Credit: axelburks on Discord.
2026-11-03 18:46:55 +08:00
yetone af9ac3d25d gateway: /v1/models lists image and video models when ?kind= asks for them, chat models alone by default
axelburks on Discord asked that /v1/models return the image and video
models too, so a client can find them. It listed chat models alone, with
no way to ask for the others.

Decided: they are listed only when asked for, with ?kind=image,video
(or ?kind=chat,image,video, or ?kind=all), each row marked "kind":
"image" or "kind": "video". Without ?kind= the list is the same chat
list as before. Why not add them by default:
- Agents and clients offer every id this list gives as a model to chat
  with: OpenCode's and Cherry Studio's model lists, ZCode's and others'
  pasted ?format=text. An image or video id there would sit in their chat
  pickers and fail on the first message (an image model on
  /v1/chat/completions).
- OpenAI's own list mixes gpt-image and sora in with nothing to tell them
  apart, so a client has no field it would already read to skip them.
- magpie's own callers that want them already ask (another magpie's
  drawers header, kind=image/video/decision on the MCP list); ?kind=
  gives any other client the same.
An unknown kind is a 400 that names the kinds, not read as none. A
gateway key held to models or accounts sees only its own image and video
models, as on the chat list (drawerObjects/videomakerObjects already
check modelAllowed and accountServes). Unticked image and video models
(HiddenDrawers, HiddenVideomakers) are left out.

TestModelsListMediaOnlyWhenAsked: the default list and ?kind=chat have no
image or video row (so no agent's chat picker that reads it can offer
one), ?format=text likewise; ?kind=image / video / image,video / all give
them, marked; a bad kind is 400.

Docs: docs/integrating.md, providers-accounts.md, site docs (en, zh).

Run on mote, this change rebased on f4c664a09:
- go test -count=1 -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway ./internal/gui: catalog, provider and gateway ok;
  gui red only in TestMainWindowCorners/macOS_26_SDK (#3949, red on main).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. gofmt -l: nothing.
- GUI: the 51 provider-*, drawers, image-models, i18n and
  video-models-hide files, both engines, every language, wide and narrow:
  1161 of 1188 ok. The 27 reds are 5 files that are red the same 27 at
  origin/main d1cdce130 run alone: provider-fetch-again (#3292/#5057),
  provider-models-rest (#4396), provider-picks-stay (#4397),
  provider-levels-scroll (#4395), provider-typed (#4673).
  video-models-hide: 22 of 22 ok.
- The whole GUI suite (all files) ran earlier at this change on 8af751987,
  347 of 19153 red at load 100 to 200; the 66 files with a red, run again
  alone, are red in the same tests at origin/main 17f2387e1 (all filed:
  #4388, #4391, #4398, #4320, #4541/#5013, #2564, #4244, #4304 and the
  above).
Rebased again onto d1cdce130 (sessions, Cursor mover, library and routing
plugins, group-unlists; nothing this change touches but gateway.go,
which merged clean) and run there: TestCoreScriptBudget and internal/gui's
new tests, the gateway's ?kind= and video tests, internal/provider and
internal/catalog, video-models-hide 22 of 22: ok.

Broken by hand, each red, then put back:
- listKinds' default returning all three kinds:
  TestModelsListMediaOnlyWhenAsked red
- an unknown kind let through: TestModelsListMediaOnlyWhenAsked red

Not tried: no real client was pointed at ?kind=; the agents' pickers were
checked by what they read (the default list, unchanged), not by opening
each one.

Credit: axelburks on Discord.
2026-11-03 18:34:19 +08:00
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 44d8c742bf remote magpie: the guide names Settings → Network and sharing → Share on local network
The Remote magpie provider's guide, its "isn't shared" message and the
gateway's LAN errors said "Settings → Share on local network", but that
switch sits under Settings → Network and sharing. Every place now names
the real path: the en key and its zh, zh-TW, ja and de words in i18n.js,
app.js's message key, the preset's EndpointHint, the gateway's and
agent's English errors, docs/reference.md, docs/integrating.md,
README.zh-CN.md and the remote and docker pages of the site (en, zh, ja).
errRemoteNotShared names no Settings path and app.js matches its prefix,
so it is left as it is.

Run at base 673651e8d with this change:
- gofmt -l: clean. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- GUI (playwright 1.62.0, chromium and webkit, every language): 12 files
  that reach the strings, 121 of 122. The red, quota-name-translated
  (webkit en, 2px past its quota at 440px), fails the same at
  673651e8d without this change; it is #2228.
- go test -timeout 45m ./...: every package ok but internal/gui,
  where TestCoreScriptBudget failed: app.js was 1,338,819 bytes at
  673651e8d itself, over its 1,337,735 budget; origin/main 34ad18ed8
  (#3367) moved code out. This change adds 24 bytes to app.js.

Run again after the rebase onto origin/main 34ad18ed8: gofmt -l clean,
go vet of internal/gui, gateway, provider, agent and tui clean,
go test ./internal/gui/ ok (TestCoreScriptBudget passes), and the same
12 GUI files 121 of 122 with the same #2228 red.
2026-10-23 18:01:03 +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
yetoneandggbdpq b566745b8a gateway: the model list says each model's reasoning levels as plain names too, for Catwalk clients (#2576)
Clients of the Catwalk schema (Crush and kin) read reasoning_levels, a
flat array of names, to know which reasoning efforts a model takes, and
drop reasoning_effort from requests to a model that names none. magpie's
/v1/models said the levels only as objects (supported_reasoning_levels,
[{"effort":"low"},...]), which such a client reads as none (cyancity).
modelObject now also says reasoning_levels: the same e.Efforts in the same
order, [] when there are none, never null. The objects stay as they were.

Every row built by modelObject carries it: the provider/model rows,
routing groups, bare ids, /v1/models/{id}, deciders, and Claude Desktop's
and Claude Science's lists. Muse's list has its own shape and the
image/video rows say no levels, so neither changes. No gateway default
for thinking, no thinking/enable_thinking aliases and no
default_reasoning_effort, as decided on the issue. Docs: reference.md,
integrating.md and the site's integrate page (en, zh) name the field.

ggbdpq's patch (base a69cd070); the review folded its test into
TestModelsListReasoning, which now checks reasoning_levels on every row it
already checks (groups included, and [] on a/plain and b/mixed) and on
GET /v1/models/b/sol.

Run (macOS arm64, sandbox HOME, pinned GOMODCACHE/GOCACHE):
- broken by hand two ways: the key renamed, TestModelsListReasoning red
  ("b/sol: reasoning_levels <nil>; want [medium,high]", and the single
  model); slices.Clone(e.Efforts) (null when empty), red ("a/plain:
  reasoning_levels <nil>; want []"). Green restored.
- this tree, as 1160f2e7d before the bodies were reworded (with the
  #2578 commit, on origin/main ebf3f48f7):
  gofmt -l clean; GOOS=darwin, linux and windows go vet -tags nogui
  ./... clean; go test -tags nogui -timeout 45m ./... under pipefail,
  exit 0, 66 packages ok. The same was green at 18828ea1a (on
  6f950653f) and d6881341d (on ed0335f75).
- rebased onto e085d6e92 (six commits, gateway.go and i18n.js among
  them, no conflict) after that run: gofmt and vet of internal/gateway and
  internal/gui clean, and their Models, Desktop, Science and
  ProviderModelsSayDesktopNumber tests ok; the full suite was not rerun
  there.
Not tried: a real Crush or Catwalk client.

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-10-17 13:11:41 +08:00
Leon Zhao c6bd4e9707 agent: let Lody confirm local provider imports
Offer Lody a versioned import link for Claude, Codex, Pi, DSH,
Kimi Code, Grok and Bub. Export only loopback endpoints and the public
magpie-lody token. Leave Lody data untouched and show a confirmation hint
when the app exposes no public import-status reader.

Verified: go test -tags nogui ./... in a temporary HOME with pinned Go
caches; native, Linux nogui and Windows vet/build; gofmt and diff checks;
17 Chromium/WebKit import-row and locale checks. The actual Lody parser
accepted all seven targets with IPv4, localhost, IPv6 and canonical ports.

Negative controls: removing registration fails
TestLodyDetectionAndRegistration with "Lody missing from Agents";
removing URL handoff fails TestLodyImportHandoff with
"Lody import was not handed to the desktop". Restored tests pass.

Desktop launch and Linux/Windows runtime behavior were not exercised.

Cherry-picked onto main (4a6bf80f4) from Leeeon233/magpie
feat/lody-integration (ab6c6dd27): README lists resolved with Lody after
Cindy beside main's new agents; /api/open keeps main's OpenURL error path
(#2043) and takes lody:// beside cindy://; the test's fake Windows
returns OpenURL's error as main's interface now does.
2026-10-15 21:18:41 +08:00
yetone 3d3a834d62 gateway: a held key its owner lets see quotas is told those of the providers and accounts it may use, not none (#2216, Kenoia)
#1981 refused every quota route to a gateway key held to a budget, models
or accounts, so a Remote magpie set up with such a key showed none of the
providers it may use. A key's owner can now let it be told them:
access.Key.Quotas, set from the key's new "Quotas" badge on the Gateway
page or `magpie gateway-key quotas <id> on|off`. Off stays the default,
so #1981's answer is unchanged for every key until its owner says so.

With it on, /v1/magpie/quotas (and ?kept=1), /quotas/history,
/quotas/cards and POST /quotas/refresh go through scopeQuotas
(internal/gateway/quotas_scope.go):
- a provider is told only when the key may use every model the catalog
  lists of it: a key with some of a provider's models is told nothing of
  it, since the models it may not use spend the same quota;
- of those, only cards of accounts and keys AllowsAccount lets it use,
  matched by the card's User against AccountIDs (a name two accounts
  share needs both; a card no account is known by only where the key's
  list names none of that provider's); a provider's only key's card,
  named by no one, is that key's;
- cards read from another magpie (From) are never told;
- a refresh of a card outside the scope is 403 gateway_key_held, one
  naming no card reads again only the scope's cards, not ReadAllCards;
- a scope with no card answers the cards routes 403 gateway_key_held, so
  the remote shows the key's own card rather than "nothing read".
/v1/magpie/concurrency and /v1/magpie/usage still refuse a held key.

Run at the reviewed head:
- gofmt -l: clean; go vet ./... (darwin), GOOS=linux -tags nogui,
  GOOS=windows: clean.
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, after the
  rebase onto 7be68467f (#2227's several limits; conflicts in access,
  the CLI usage and test, keys.js and providers-accounts.md resolved by
  keeping both): every package ok but internal/gateway, whose
  TestTranslatedSilenceStillTimesOut went red once at load ~95 (its
  400ms deadline also covers the response headers; filed #2248) and
  passed 5 of 5 alone. Before the rebase the whole suite was ok, with
  agent and gateway rerun at -timeout 40m after the 10m timeout under
  load.
- TestHeldKeyToldItsOwnQuotas (new): a provider-wide key sees A only,
  a key with A/m1 sees nothing of A, an account-held key sees only its
  key's card, a provider's only key, a key told nothing gets 403 from
  the cards route, Quotas-off still 403 everywhere, refreshes outside
  the scope 403. Broken by hand, each red: scope returned nil (every
  card told), every[id] forced true (partial models), the account check
  skipped, the refresh check removed, the only-key rule removed, and the
  told-none 403 removed. TestHeldKeyToldNoAccounts (#1981) still green.
- TestRemoteMagpieShowsHeldKeyItsQuotas (new): a magpie with this one as
  its Remote magpie provider, through a key held to alpha's Two, shows
  office/alpha's Two card beside the key's own; a key told none shows its
  own card alone. Red with the told-none 403 removed ("nothing read on
  that magpie yet").
- TestGatewayKeyQuotasCLI (new): show, on, off, bad values refused.
- GUI: gateway-key-quotas.test.cjs (new) in chromium and webkit, at 1100
  and 420, in en, zh, zh-TW, ja, de: 20/20; red when the badge sends the
  value it already has.
- The badge is a gateway key row's: off, it folds to no width until the
  row is hovered (the row had no room left at 390px: gateway-connect-keys
  went red in en until it did), and on a phone it is shown like the
  row's other controls (phone-rows went red until its rule won).
- GUI, 119 files matching gateway|key|usage|quota|remote|i18n|caller|
  web-|phone|narrow, both engines, concurrency 2: 1349/1385. The reds
  besides phone-rows (since fixed, above): quota-count-wrap and
  quota-name-translated webkit (#2228), usage-agents-hide (#2211) and
  usage-fold chromium en/zh (#2163), each red alike on a fresh
  origin/main. gateway-key-quotas, gateway-connect-keys, phone-rows and
  gateway-key-groups rerun: 38/38; after the rebase every gateway-*,
  phone-rows and key-limit file, both engines: 210/210.

Not tried: a real Remote magpie against a second machine with a held key;
the GUI badge in the Linux and Windows apps.
2026-10-15 02:29:11 +08:00
yetone 12ecb6d8e9 gateway: a gateway key held to a budget, models or accounts is told none of this magpie's accounts, only its own limit and routes (#1981)
321sssrt-bit shared magpie on the LAN with a gateway key held to a budget,
and that key still read every account's quota and balance. A held key
(heldKey: a budget, models or accounts) is someone else's to use, so it
now gets 403 with code gateway_key_held (refuseHeld) on
/v1/magpie/quotas, quotas/history, quotas/cards, POST quotas/refresh and
/v1/magpie/concurrency. That holds from loopback as well as the LAN, the
same as usageSummary already did. /v1/magpie/route tells it only the
routes of its own requests. Route.callerKey is set by trace.beginFor at
all five begin sites, so a route begun without it fails closed. It still
reads its own limit at /v1/magpie/limit. Unrestricted keys and the local
owner are unchanged.

Client side (remote magpie): a 403 gateway_key_held drops the cards kept
from before and shows only the key's own card, instead of "isn't shared".
The cache is now keyed by provider and key (remoteCardsID), so a changed
key never shows what the old one was told, and keepRemoteCards keeps a
read only over one asked before it, so a slow pre-held answer can't bring
cards back.

Decided against letting an account-held key see its own accounts' cards:
that would still show the host's account email and balance to the key's
holder.

Run:
- New TestHeldKeyToldNoAccounts covers keys held by budget, models and
  accounts plus one held to nothing, from 127.0.0.1 and 192.168.1.9.
  Every route goes red with the refuseHeld calls or the route filter
  removed by hand.
- New TestRemoteMagpieHeldKeyShowsOnlyItsOwnCard goes red with the
  errKeyHeld mapping removed. TestRemoteMagpieCardsKeptByKey goes red with
  the cache keyed by p.ID alone.
- gofmt -l and go vet (darwin, linux -tags nogui, windows) are clean.
- go test -tags nogui ./internal/gateway ./internal/provider -count=1
  passes in a sandbox HOME.

Not tried: two real machines over the LAN; the tests drive the handler
with LAN remote addresses. An older client shows "isn't shared" (or its
cached cards until they expire) against an updated host until it updates
too.
2026-10-13 17:59:36 +08:00
yetone d4c2512d2d usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
  one record or an array, in usage.jsonl's shape:
  - the post may carry up to 5000 records and 32 MiB;
  - t, agent, provider, model and rid are required.
  Each field is checked: unknown fields, quoted numbers, negative or absurd
  counts, a status outside 100-599, a cost over 10000 USD, and a t more
  than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
  whole post with a 400 that names error.index and error.param, and nothing
  is written. A past t is otherwise taken as given, so history can be
  backfilled. The reply gives accepted and skipped counts and each
  record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
  shared, behind the Host check). A browser page also needs a key, since
  corsGuard lets localhost pages and Origin null through. A held key is
  refused.
- usage.IngestReported writes under usage.mu to the same file as
  usage.Append. Rows carry source "reported" and no caller key. A rid
  already reported is skipped, as is one repeated in the post. The set of
  reported rids is read back from the log: one scan after a restart (lines
  without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
  flag; packed flags widened to uint16). Otherwise it is priced at
  magpie's prices.
- Display:
  - SourceReported is a source of its own: RequestPage.Reported,
    ?via=reported, and Ledger now honours via.
  - The Requests tab gains a fourth cell "reported by apps", shown once
    there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
  - a key's budget/spend limit (budget.counts);
  - window holds, and the log start that decides whether a window can be
    reckoned (logSnapshot.firstOwn);
  - gateway sessions and Vias;
  - Codex's sealed answers and remembered model.
  There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
  site integrate.html (en, zh).

Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.

Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
  - usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
    languages, 1180 and 420 wide, light and dark);
  - usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
    usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
  - 40 posts of 5000 took 0.40 s (worst batch 18 ms);
  - the first post after a restart took 0.45 s (rid rescan), a later one
    1.6 ms;
  - the cold index build took 2.1 s (as for gateway rows);
  - page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
  - summary all took 215 ms, 30d 20 ms.

Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
  cost; the block pricer overwriting own cost; the Reported split;
  fromBrowser's key rule; skipping bad records instead of refusing; the
  max-records and body limits; the ingest lock (race); both locks;
  firstOwn -> first; the IsReported guards in windowHolds,
  buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.

Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
2026-10-13 06:32:03 +08:00
yetone b6a263b9fd gateway, usage: the Usage page's numbers are read over the gateway, and a Claude Code subagent's call says which subagent and which started it (HoGee_xxl on X)
HoGee_xxl wants their own usage app to read magpie over the gateway,
which had no /api/usage counterpart, and asked for subagents' parent ids.

- GET /v1/magpie/usage (the /api/usage summary, ?period=) and
  GET /v1/magpie/usage/requests (the /api/usage/requests ledger page, same
  filters, offset/limit) on the gateway. The builders moved out of gui into
  internal/usageapi so both serve the same JSON; gui keeps aliases and sets
  usageapi.Clients for agent names (gateway can't import agent). Guard as
  /v1/magpie/quotas: this machine, or another with an enabled gateway key,
  behind the same Host check. A key held to a budget, models or accounts is
  refused the summary (403) and gets the ledger filtered to its own
  CallerKey, with callerKeys/agents/providers/accounts cut to its own rows
  (usageapi.OwnPage): those facets are drawn from every call in the period.
  `path` is left out for another machine.
- usage.Record gains subagent and parent_agent; session stays the parent
  conversation. Gateway rows take them from x-claude-code-agent-id and
  x-claude-code-parent-agent-id; session-file rows from the file name
  (<session>/subagents[/workflows/<run>]/agent-<id>.jsonl, no cache version
  bump) and the parentAgentId of the agent-<id>.meta.json beside it. Both
  packed into the request page's text columns (now 29, msg at 29).
  Codex sub-threads: only kind, as before; no spawned thread on disk to
  take a parent shape from.

Run: real Claude Code 2.1.296 under a sandbox CLAUDE_CONFIG_DIR against a
local fake Anthropic endpoint that made it spawn a subagent from a
subagent: the nested request carried X-Claude-Code-Agent-Id=a143287ac46b82a96
and X-Claude-Code-Parent-Agent-Id=a99ca20c03d1813d8, the first-level one
the agent id only, Session-Id the parent's throughout; the nested meta.json
had parentAgentId. Tests use those bytes. TestUsageOverGateway goes red
with OwnPage, the CallerKey pin, or the header read removed (each tried).
gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
GOOS=windows go vet ./...; set -o pipefail; go test ./... green.
2026-10-10 20:47:00 +08:00
yetone df95ac6bc2 docs, site: Integrating your app or agent with magpie, at docs/integrating.md and usemagpie.ai/docs/integrate (#918, Magixyne)
A developer of an AI app asked how to work with magpie and whether an app can
register itself after one confirmation. The page says what exists: the
gateway (find it via /api/hello and settings.json's port, the OpenAI,
Anthropic, Responses and Gemini endpoints, /v1/models' fields), how a key
magpie-<id> or the User-Agent's first word names the app in Usage, a row on
the Agents page by an adapter PR in internal/agent (config-edit, Cindy-style
own import link confirmed in the app, or a local API) with what the PR needs,
what plugins can and can't do, and what isn't there: no link or API registers
an app or installs a plugin, and magpie://import adds providers only. English
and Chinese pages, linked from every docs page's nav and footer.
TestThirdPartyAppIsCountedAsItself pins the attribution the page promises.
go vet and the gateway tests pass; site node tests pass; pages checked in
headless Chromium (no errors, TOC, no horizontal scroll at 390px).
2026-10-05 22:46:35 +08:00