diff --git a/docs/reference.md b/docs/reference.md index fb11ad71f..c873a74de 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1426,6 +1426,12 @@ strategies in Plugins › Built-in). It stays on while a provider or group is routed by one of them. Turned off, the pickers offer Smart alone, and a provider or group still set to one of them is tried in its listed order. +Your own routing groups are the built-in plugin `groups` (Routing groups in +Plugins › Built-in), which stays on while you have one. The groups magpie +finds for a model two providers serve don't need it. Turned off, the gateway +doesn't list or serve a group of your own, and the Routing page has no New +group button; `magpie groups` still lists them. + **Make first** sets the accounts' order. How much that order counts depends on the routing: diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 154ab606b..b98e29775 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -29,7 +29,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) | | TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) | | HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | -| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | +| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight`. `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index 97a0283cd..0a2d163b8 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -187,8 +187,18 @@ the core. The five other routings are the built-in plugin `rotation`'s. | Off | A routing no strategy serves is its listed order. `routingOf` in the gateway reads it as `order` wherever the core asks about a routing (a turn's mark, `sinks`, a rotate group's sessions, a group's heads), so nothing of the routing is left half on. | [`routing.go`](../../internal/gateway/routing.go) | | `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) | -Groups are next on this point: `planGroup` behind it, the `groups` plugin -serving it. +The user's own routing groups are the `groups` plugin's on this point. The +groups magpie finds (a model two providers serve, `auto-`) stay the +core's, as Smart does: they are how a model several providers serve is one +model with failover, which a new install has with the Essentials preset, +where `groups` is off. `planGroup` and the walk over a group's members are +the core's either way: a strategy only orders a pool, and a group off is +not offered at all. + +| Part | What it does | Source | +| --- | --- | --- | +| `GateGroups`, `ServeGroups` | The gateway holds `GateGroups` while it serves (`ListenAndServe`), and the plugin holds `ServeGroups` while it is on. Gated with none served, `groupsIn` leaves out every group not `Auto`, so `Groups`, `FindGroup`, `GroupFor`, the catalog, `/v1/models` and a group's `Unlists` go without them: a request for one is a model not served. A process not serving the gateway (the CLI, the TUI) is never gated and lists them all. Nothing built from the groups is kept past a call, so a flip is seen by the next lookup. Gated and off, a lookup that finds a group of the user's own first asks the gate's refresh (the gateway's is `pluginrt.Refresh`), at most once a second and never from inside one, then looks again: a group made a moment ago turns the plugin on and is served by the request that asks for it, not after `KeepFresh`'s next look (`TestOwnGroupRefreshesTheGate`). | [`group_serve.go`](../../internal/provider/group_serve.go), [`group.go`](../../internal/provider/group.go), [`gateway.go`](../../internal/gateway/gateway.go) | +| `plugins/groups` | Requires `window` and `providers`, not Essential. Apply holds `ServeGroups`. `InUse` is `provider.NamedGroups`: the groups providers.json holds that are neither Auto nor hidden, read from the file, never through the gate (else off would count none and stay off); an unreadable file is an error, so it stays on. The `routing` plugin's `InUse` is the same count. The gateway's `KeepFresh` watches providers.json, so a group made with `magpie group add` turns it on within 2s, and a request for it before then turns it on itself (the gate's refresh, above); the window's New group button is `data-feature="groups"`. | [`groups.go`](../../plugins/groups/groups.go), [`routing.go`](../../plugins/routing/routing.go) | The other points follow in this order: middleware (the JS gateway middleware becomes one consumer of it, with its place, API and fail-open policy unchanged; redaction fails closed), then @@ -288,5 +298,11 @@ remembering its layer (`Source`): the parity run with the plugin on; `TestRotationOnAndOff` turns it off), and `routing-save.test.cjs` (Smart alone with it off, every width and engine). +- P3 groups: `go test ./internal/provider/ -run 'TestOwnGroupsWaitOnThePlugin|TestNamedGroupsUnreadable'`, + `go test ./plugins/groups/` (`TestOnServesOffDoesNot`, `TestInUse`) and + `go test ./internal/gateway/` whole (its `TestMain` holds + `ServeGroups`, the parity run with the plugin on; `TestGroupsOnAndOff` + turns it off: the user's group leaves `/v1/models` and isn't served, + the found one is both). - By hand, under a sandbox HOME: `magpie plugin builtin`, `magpie plugin builtin on groups`, `magpie plugin dump`, and a plugins.yml broken by hand. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d44b55dbc..da8fb77f7 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -477,6 +477,15 @@ func (s *Server) ListenAndServe(ctx context.Context) error { // `magpie plugin builtin`) come and go here too stopObservers := usage.ServeObservers() defer stopObservers() + // and the user's own routing groups are served while plugins/groups is + // on (provider.GateGroups); one made a moment ago turns it on as it is + // looked up, not on KeepFresh's next look + stopGroups := provider.GateGroups(func() { + if _, err := pluginrt.Refresh(); err != nil { + log.Printf("plugins: %v", err) + } + }) + defer stopGroups() freshCtx, stopFresh := context.WithCancel(ctx) defer stopFresh() go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path()) diff --git a/internal/gateway/groups_off_test.go b/internal/gateway/groups_off_test.go new file mode 100644 index 000000000..bac197919 --- /dev/null +++ b/internal/gateway/groups_off_test.go @@ -0,0 +1,46 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// The router strategy point's groups with plugins/groups on and off: on, a +// group of the user's own is listed and answers; off, in the process +// serving the gateway, it is neither, while the group magpie found for a +// model two providers serve is listed and answers either way. +func TestGroupsOnAndOff(t *testing.T) { + fresh(t) + v := &keyed{} + serveOn(t, "pa", "ka", []string{"m", "x"}, v) + serveOn(t, "pb", "kb", []string{"m"}, v) + if err := provider.SaveGroup(provider.Group{Name: "Mine", Members: []string{"pa/x", "pb/m"}}); err != nil { + t.Fatal(err) + } + s := New() + check := func(when string, mine bool) { + t.Helper() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil)) + list := rec.Body.String() + if strings.Contains(list, `"group/mine"`) != mine || !strings.Contains(list, `"group/auto-m"`) { + t.Fatalf("%s: models %s", when, list) + } + code, body := postAs(t, s, "", `{"model":"group/mine","messages":[{"role":"user","content":"hi"}]}`) + if (code == 200) != mine { + t.Fatalf("%s: group/mine %d %s", when, code, body) + } + if code, body := postAs(t, s, "", `{"model":"group/auto-m","messages":[{"role":"user","content":"hi"}]}`); code != 200 { + t.Fatalf("%s: group/auto-m %d %s", when, code, body) + } + } + check("on", true) + t.Run("off", func(t *testing.T) { + withoutGroups(t) + check("off", false) + }) + check("on again", true) +} diff --git a/internal/gateway/main_test.go b/internal/gateway/main_test.go index bac27a827..d1268e9bc 100644 --- a/internal/gateway/main_test.go +++ b/internal/gateway/main_test.go @@ -19,6 +19,7 @@ const standInsEnv = "MAGPIE_GATEWAY_TEST_STAND_INS" func TestMain(m *testing.M) { serveRotation() + groupsServed = provider.ServeGroups() code, err := isolatedTests(m) if err != nil { fmt.Fprintln(os.Stderr, err) @@ -135,3 +136,18 @@ func withoutRotation(t *testing.T) { rotation = nil t.Cleanup(serveRotation) } + +// groupsServed is plugins/groups on, as for a user with a group of their +// own: the gateway's tests serve their groups. +var groupsServed func() + +// withoutGroups is plugins/groups off for t, in a process serving the +// gateway (provider.GateGroups): the user's own groups aren't served. +func withoutGroups(t *testing.T) { + groupsServed() + stop := provider.GateGroups(nil) + t.Cleanup(func() { + stop() + groupsServed = provider.ServeGroups() + }) +} diff --git a/internal/provider/group.go b/internal/provider/group.go index f9065e3f3..921a91efc 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -313,6 +313,9 @@ func groupsIn(entries []Entry) []Group { } out = append(out, withMatches(entries, g.own())) } + if !served(f.Groups) { // plugins/groups is off: the user's own aren't served + out = slices.DeleteFunc(out, func(g Group) bool { return !g.Auto }) + } if f.NoAutoGroups { return orderedGroups(out, f.GroupOrder) } diff --git a/internal/provider/group_serve.go b/internal/provider/group_serve.go new file mode 100644 index 000000000..60be9496a --- /dev/null +++ b/internal/provider/group_serve.go @@ -0,0 +1,117 @@ +package provider + +import ( + "slices" + "sync" + "sync/atomic" + "time" +) + +// The user's own routing groups — those not Auto, made on the Routing page +// or with `magpie group` — are plugins/groups' to serve (P3 of +// docs/subsystems/plugin-runtime.md). In the process serving the gateway +// (GateGroups), while that plugin is off (no ServeGroups held), they are +// neither listed nor routed: Groups, FindGroup, GroupFor and the catalog +// leave them out. The groups magpie finds (Auto) are the core's either +// way, as Smart is: they are how a model several providers serve is one +// model with failover, which a new install, the groups plugin off, has. +// +// The plugin stays on while the user has a group of their own +// (NamedGroups), so off, there is none to leave out but one added since +// the plugin last looked: a lookup that finds one asks the gate's refresh +// (the gateway's plugin runtime) first, which turns the plugin on, so a +// group made a moment ago with `magpie group add` is served at once. A +// process not serving the gateway (the CLI, the TUI) lists them all. +var groupGate struct { + sync.Mutex + gated int // GateGroups calls not yet stopped + served int // ServeGroups calls not yet removed + refresh func() // the last GateGroups' refresh +} + +// groupRefreshing: a refresh is under way, so a lookup it makes (a plugin's +// InUse) doesn't start another; refreshed: when the last one began, so a +// plugins.yml that can't be read, which leaves the plugin off, is asked +// again at most once a second, not on every lookup +var ( + groupRefreshing atomic.Bool + groupRefreshed atomic.Int64 +) + +// GateGroups makes the user's own groups wait on ServeGroups until stop: +// the gateway calls it as it starts serving. refresh, when not nil, is +// asked to bring the plugins up to date when a lookup gated finds a group +// of the user's own (served). +func GateGroups(refresh func()) (stop func()) { + groupGate.Lock() + groupGate.refresh = refresh + groupGate.Unlock() + return holdGate(&groupGate.gated) +} + +// ServeGroups serves the user's own groups until remove: plugins/groups +// calls it while it is on. +func ServeGroups() (remove func()) { + return holdGate(&groupGate.served) +} + +// holdGate holds n until the func it gives is called. Nothing built from +// the groups is kept past one call (only the file is, while a request +// holds it), so the next lookup sees the change. +func holdGate(n *int) func() { + groupGate.Lock() + *n++ + groupGate.Unlock() + var once sync.Once + return func() { + once.Do(func() { + groupGate.Lock() + *n-- + groupGate.Unlock() + }) + } +} + +// GroupsServed says whether the user's own groups are served here now. +func GroupsServed() bool { + groupGate.Lock() + defer groupGate.Unlock() + return groupsServedLocked() +} + +// served says whether the user's own groups among gs are served: gated and +// not, gs holding one asks the refresh once and looks again. +func served(gs []Group) bool { + groupGate.Lock() + ok, refresh := groupsServedLocked(), groupGate.refresh + groupGate.Unlock() + if ok || refresh == nil || !slices.ContainsFunc(gs, func(g Group) bool { return !g.Auto && !g.Hidden }) { + return ok + } + now := time.Now().UnixNano() + if now-groupRefreshed.Load() < int64(time.Second) || !groupRefreshing.CompareAndSwap(false, true) { + return false + } + groupRefreshed.Store(now) + refresh() + groupRefreshing.Store(false) + return GroupsServed() +} + +func groupsServedLocked() bool { return groupGate.gated == 0 || groupGate.served > 0 } + +// NamedGroups counts the user's own groups in providers.json, served or +// not; a file that can't be read is an error, not none. +func NamedGroups() (int, error) { + f, err := read() + if err != nil { + return 0, err + } + n := 0 + for _, g := range f.Groups { + if !g.Auto && !g.Hidden { + n++ + } + } + return n, nil +} diff --git a/internal/provider/group_serve_test.go b/internal/provider/group_serve_test.go new file mode 100644 index 000000000..21c6d8ce7 --- /dev/null +++ b/internal/provider/group_serve_test.go @@ -0,0 +1,126 @@ +package provider + +import ( + "os" + "path/filepath" + "slices" + "testing" +) + +// The user's own groups wait on plugins/groups only where the gateway is +// served: ungated (the CLI, the TUI) they are listed; gated, only while +// ServeGroups is held. The groups magpie finds are listed either way, and +// NamedGroups, which keeps the plugin on, counts the user's own regardless. +func TestOwnGroupsWaitOnThePlugin(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", "") + if err := store(file{Groups: []Group{{ID: "mine", Name: "Mine", Members: []string{"a/x", "b/y"}}}}); err != nil { + t.Fatal(err) + } + entries := []Entry{ + {ID: "a/x", Model: "x", Provider: Provider{ID: "a"}}, {ID: "b/y", Model: "y", Provider: Provider{ID: "b"}}, + {ID: "a/m", Model: "m", Provider: Provider{ID: "a"}}, {ID: "b/m", Model: "m", Provider: Provider{ID: "b"}}, + } + listed := func() []string { + var ids []string + for _, e := range groupEntries(entries) { + ids = append(ids, e.ID) + } + slices.Sort(ids) + return ids + } + both, found := []string{"group/auto-m", "group/mine"}, []string{"group/auto-m"} + check := func(when string, want []string) { + t.Helper() + if got := listed(); !slices.Equal(got, want) { + t.Fatalf("%s: %v, want %v", when, got, want) + } + if n, err := NamedGroups(); n != 1 || err != nil { + t.Fatalf("%s: NamedGroups %d, %v", when, n, err) + } + } + check("ungated", both) + stop := GateGroups(nil) + check("gated, plugin off", found) + remove := ServeGroups() + check("plugin on", both) + remove() + remove() // once + check("plugin off again", found) + stop() + check("gateway stopped", both) +} + +// A providers.json that can't be read is not "no groups": the plugin that +// counts them stays on. +func TestNamedGroupsUnreadable(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", "") + if err := os.MkdirAll(filepath.Dir(Path()), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(Path(), 0o755); err != nil { // a folder where the file goes + t.Fatal(err) + } + if _, err := NamedGroups(); err == nil { + t.Fatal("no error for a providers.json that can't be read") + } +} + +// Gated and off, a lookup that finds a group of the user's own asks the +// gateway's refresh first (which turns the plugin on), so one made a +// moment ago is served at once, not on the runtime's next look; a refresh +// that leaves it off is asked at most once a second, and never for the +// groups magpie found alone. +func TestOwnGroupRefreshesTheGate(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", "") + entries := []Entry{{ID: "a/m", Model: "m", Provider: Provider{ID: "a"}}, {ID: "b/m", Model: "m", Provider: Provider{ID: "b"}}} + asked := 0 + var remove func() + defer func() { + if remove != nil { + remove() + } + }() + refresh := func() { + asked++ + if asked == 2 { + remove = ServeGroups() // the plugin found in use, turned on + } + } + defer GateGroups(refresh)() + groupRefreshed.Store(0) + groupEntries(entries) + // a found group the user edited is kept in the file, Auto still + if err := store(file{Groups: []Group{{ID: "auto-m", Name: "m", Auto: true, Members: []string{"b/m", "a/m"}}}}); err != nil { + t.Fatal(err) + } + groupEntries(entries) + if asked != 0 { + t.Fatalf("refreshed %d times with found groups alone", asked) + } + if err := store(file{Groups: []Group{{ID: "mine", Name: "Mine", Members: []string{"a/m"}}}}); err != nil { + t.Fatal(err) + } + has := func() bool { + return slices.ContainsFunc(groupEntries(entries), func(e Entry) bool { return e.ID == "group/mine" }) + } + if has() || asked != 1 { + t.Fatalf("a refresh that leaves it off: listed %v, asked %d", has(), asked) + } + has() + if asked != 1 { + t.Fatalf("asked again within a second: %d", asked) + } + groupRefreshed.Store(0) + if !has() || asked != 2 { + t.Fatalf("a refresh that turns it on: listed %v, asked %d", has(), asked) + } +} diff --git a/plugins/groups/groups.go b/plugins/groups/groups.go index 065b75212..72e104284 100644 --- a/plugins/groups/groups.go +++ b/plugins/groups/groups.go @@ -1,6 +1,12 @@ -// Package groups is routing groups' part of the window: several models -// agents pick as one, each request sent to the right one and on to the -// next when one fails. While the user has a group, it stays on. +// Package groups is routing groups: several models agents pick as one, +// each request sent to the right one and on to the next when one fails. +// While the user has a group, it stays on. +// +// It serves the user's own groups on the gateway's router strategy point +// (P3 of docs/subsystems/plugin-runtime.md): Apply holds +// provider.ServeGroups, and off, the gateway neither lists nor routes them. +// The groups magpie finds (one model several providers serve) are the +// core's, on or off. package groups import ( @@ -13,15 +19,12 @@ func init() { ID: "groups", API: "^1", Requires: []string{"window", "providers"}, Name: "Routing groups", Sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails", One: "1 group in use", Many: "{n} groups in use", - InUse: func() (int, error) { - n := 0 - for _, g := range provider.Groups() { - if !g.Auto && !g.Hidden { - n++ - } - } - return n, nil - }, + // a providers.json that can't be read is not known, so it stays on + InUse: provider.NamedGroups, Parts: []pluginrt.Part{{Slot: "part", Key: "groups"}}, + Apply: func(c *pluginrt.Ctx) error { + c.OnDispose(provider.ServeGroups()) + return nil + }, }) } diff --git a/plugins/groups/groups_test.go b/plugins/groups/groups_test.go new file mode 100644 index 000000000..cbe2fa384 --- /dev/null +++ b/plugins/groups/groups_test.go @@ -0,0 +1,77 @@ +package groups + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/pluginrt" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +func TestMain(m *testing.M) { testenv.Main(m) } + +func manifest(t *testing.T) pluginrt.Manifest { + t.Helper() + for _, m := range pluginrt.Registered() { + if m.ID == "groups" { + return m + } + } + t.Fatal("groups not registered") + return pluginrt.Manifest{} +} + +func sandbox(t *testing.T) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache")) +} + +// Where the gateway is served, the user's own groups are served while the +// plugin is on, and not while it is off. +func TestOnServesOffDoesNot(t *testing.T) { + sandbox(t) + defer provider.GateGroups(nil)() + rt := pluginrt.New([]pluginrt.Manifest{manifest(t)}) + defer rt.Stop() + served := func(want bool) { + t.Helper() + if provider.GroupsServed() != want { + t.Fatalf("served: %v, want %v (%+v)", !want, want, rt.Statuses()) + } + } + served(false) + rt.Reconcile(map[string]bool{"groups": true}, nil) + served(true) + rt.Reconcile(map[string]bool{"groups": false}, nil) + served(false) + rt.Reconcile(map[string]bool{"groups": true}, nil) + served(true) +} + +// It counts the user's own groups; a providers.json that can't be read +// keeps it on. +func TestInUse(t *testing.T) { + sandbox(t) + inUse := manifest(t).InUse + if n, err := inUse(); n != 0 || err != nil { + t.Fatalf("no file: %d, %v", n, err) + } + if err := provider.SaveGroup(provider.Group{Name: "Mine", Members: []string{"a/x", "b/y"}}); err != nil { + t.Fatal(err) + } + if n, err := inUse(); n != 1 || err != nil { + t.Fatalf("one group: %d, %v", n, err) + } + if err := os.WriteFile(provider.Path(), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := inUse(); err == nil { + t.Fatal("no error for a providers.json that can't be read") + } +} diff --git a/plugins/routing/routing.go b/plugins/routing/routing.go index db667d365..7ddd7fc35 100644 --- a/plugins/routing/routing.go +++ b/plugins/routing/routing.go @@ -15,15 +15,7 @@ func init() { ID: "routing", API: "^1", Requires: []string{"window", "gateway"}, Essential: true, Name: "Routing", Sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", One: "1 group in use", Many: "{n} groups in use", - InUse: func() (int, error) { - n := 0 - for _, g := range provider.Groups() { - if !g.Auto && !g.Hidden { - n++ - } - } - return n, nil - }, + InUse: provider.NamedGroups, Parts: []pluginrt.Part{{Slot: "nav.page", Key: "routing"}}, Client: []string{"i18n.js", "routing.css", "client.js"}, })