diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 610cf0d42..639349268 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -33,7 +33,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | 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 — in a WSL distro, the distro's own, of the ones running now — 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; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), 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. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). 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) | | A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Weekly pace, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (`provider.Group.Within`, set on `Member.Via`, so the trace's `Subs` and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. `TestFreeFirstReachesAGroupInItLeftOnTheDefault`. 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`, `weight`, `free` (free first), `fast` (speed first) or, a group's only, `cheap` (cheapest first). `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. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour. 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, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), 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) | +| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first) or, a group's only, `cheap` (cheapest first). `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. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour. 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, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), 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`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `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) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index eef912d45..aad14c5af 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -164,7 +164,7 @@ A 401 marks the account's sign-in by default (`notePluginSignIn` in [`plugins.go ## A model's free and rate -magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rate` in [`providers.go`](../../internal/plugin/providers.go)), and a model is free only by its own `free: true` or a $0 list price (`FreeModel` in [`models.go`](../../internal/provider/models.go)). A plugin sets `free` from the vendor's word; the guide says so ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)). +magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rate` in [`providers.go`](../../internal/plugin/providers.go)), and a model is free only by its own `free: true`, a $0 list price or the user counting its whole provider free (`Provider.CountFree`) (`FreeModel` in [`models.go`](../../internal/provider/models.go)). A plugin sets `free` from the vendor's word; the guide says so ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)). ## A model that gives no text diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 533c8c1f7..47fde320a 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -138,6 +138,9 @@ const providerUsage = `usage: (Settings' redaction leaves its requests as written, at any address: your call, so mind a relay that passes them on to a vendor; a subscription or a plugin's provider too, whose vendor gets them so; never another magpie) + magpie provider set modelscope free=yes + (every model of it counts as free, so a Free first routing spends it before + paid ones, as a free daily quota; prices and Usage's costs stay as listed) magpie provider add "My Relay" url=https://relay.example.com/v1 key=sk-… balance=https://relay.example.com/api/usage/token balance.path='$data.total_available / 500000' magpie provider set my-relay balance.path='(1 - credits.monthlyCredits / 70) %' magpie provider set my-relay balance.method=POST @@ -847,6 +850,9 @@ func showProvider(p provider.Provider) error { } kv("unmasked", "yes"+muted.Render(why)) } + if p.CountFree { + kv("free", "yes"+muted.Render(" counted free by Free first and Cheapest routing; prices and Usage's costs stay as listed")) + } if p.NativeCompaction { kv("compaction", "native"+muted.Render(" Codex's own, sealed by the key or account that answers it")) } @@ -1191,6 +1197,19 @@ func applyPairs(p *provider.Provider, pairs []string) error { return fmt.Errorf("unmasked=yes|no, not %q", v) } p.Unredacted = v == "yes" + case "free": + // yes: every model of it counts as free for Free first and + // Cheapest routing, by the user's word (jiabubu on Discord: + // ModelScope's free daily quota); prices and Usage's costs + // stay as listed (provider.CountFree) + switch strings.ToLower(v) { + case "yes", "on": + p.CountFree = true + case "no", "off": + p.CountFree = false + default: + return fmt.Errorf("free=yes|no, not %q", v) + } case "context": if err := setContext(p, "*", v); err != nil { return err diff --git a/internal/cli/providers_free_cli_test.go b/internal/cli/providers_free_cli_test.go new file mode 100644 index 000000000..ba70bc697 --- /dev/null +++ b/internal/cli/providers_free_cli_test.go @@ -0,0 +1,42 @@ +package cli + +import ( + "strings" + "testing" +) + +// magpie provider set free=yes counts every model of a provider free for +// Free first (jiabubu on Discord: ModelScope's free daily quota), show +// says so, free=no takes it back, and any other value is refused and +// leaves the saved one alone. +func TestProviderSetFree(t *testing.T) { + groupsHome(t) + if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "free=yes"}) }); err != nil { + t.Fatal(err) + } + if p := mustFind(t, "a"); !p.CountFree || !p.FreeModel("whatever") { + t.Fatalf("free=yes: %+v", p) + } + out, err := printed(t, func() error { return providerCmd([]string{"provider", "a"}) }) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "counted free") { + t.Fatalf("show doesn't say it is counted free:\n%s", out) + } + for _, v := range []string{"maybe", "", "--help"} { + err := providerCmd([]string{"provider", "set", "a", "free=" + v}) + if err == nil || !strings.Contains(err.Error(), "free=yes|no") { + t.Errorf("free=%q: %v", v, err) + } + if !mustFind(t, "a").CountFree { + t.Errorf("a refused free=%q turned it off", v) + } + } + if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "free=no"}) }); err != nil { + t.Fatal(err) + } + if mustFind(t, "a").CountFree { + t.Fatal("free=no left it on") + } +} diff --git a/internal/gateway/countfree_test.go b/internal/gateway/countfree_test.go new file mode 100644 index 000000000..09cd8ad67 --- /dev/null +++ b/internal/gateway/countfree_test.go @@ -0,0 +1,92 @@ +package gateway + +import ( + "net/http" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// A provider the user counts free (provider.CountFree; jiabubu on Discord: +// ModelScope's free daily quota) is spent first by Free first, though its +// vendor's list says nothing of it being free and it is listed second. Its +// price stays as set: the mark orders the routing, it doesn't +// reprice what Usage counts. Cheapest first weighs it at +// nothing too. Turned off, the listed order is back. +func TestFreeFirstSpendsTheProviderTheUserCountsFree(t *testing.T) { + fresh(t) + var paid, mine atomic.Int32 + answer := func(n *atomic.Int32) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + n.Add(1) + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"id":"ok","choices":[{"message":{"role":"assistant","content":"hi"}}]}`)) + } + } + serveOn(t, "paidv", "sk-paid", []string{"m"}, answer(&paid)) + serveOn(t, "mine", "sk-mine", []string{"m"}, answer(&mine)) + // both priced, the marked one dearer: nothing but the user's word says + // it costs them nothing + for id, pr := range map[string]catalog.Price{"paidv/m": {Input: 1, Output: 2}, "mine/m": {Input: 3, Output: 15}} { + if err := provider.SetModelPrice(id, &pr); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ + Name: "G", Members: []string{"paidv/m", "mine/m"}, Routing: provider.FreeFirst, + }); err != nil { + t.Fatal(err) + } + if err := provider.SetCountFree("mine", true); err != nil { + t.Fatal(err) + } + + s := New() + first := func() Weighed { + t.Helper() + code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"x"}]}`) + if code != 200 { + t.Fatalf("code %d: %s", code, body) + } + last := s.trace.routes[len(s.trace.routes)-1] + if len(last.Order) != 2 { + t.Fatalf("the trace should weigh both members: %+v", last.Order) + } + return last.Order[0] + } + if w := first(); w.Provider != "mine" || !w.Free { + t.Fatalf("Free first went to %q (free %v) first, want the one counted free", w.Provider, w.Free) + } + if mine.Load() != 1 || paid.Load() != 0 { + t.Fatalf("answered by mine %d, paid %d", mine.Load(), paid.Load()) + } + // what Usage counts a call at + if pr, ok := provider.EffectivePrice("mine", "m"); !ok || pr.Input != 3 || pr.Output != 15 { + t.Fatalf("counting it free repriced it: %+v %v", pr, ok) + } + + // Cheapest first weighs it at nothing too, though its set price is + // the dearer + if err := provider.SaveGroup(provider.Group{ + Name: "G", Members: []string{"paidv/m", "mine/m"}, Routing: provider.Cheapest, + }); err != nil { + t.Fatal(err) + } + if w := first(); w.Provider != "mine" { + t.Fatalf("Cheapest first went to %q first, want the one counted free", w.Provider) + } + if err := provider.SaveGroup(provider.Group{ + Name: "G", Members: []string{"paidv/m", "mine/m"}, Routing: provider.FreeFirst, + }); err != nil { + t.Fatal(err) + } + + if err := provider.SetCountFree("mine", false); err != nil { + t.Fatal(err) + } + if w := first(); w.Provider != "paidv" || w.Free { + t.Fatalf("turned off, Free first went to %q (free %v) first, want paidv as listed", w.Provider, w.Free) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index e929f1d8d..f314914d6 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7838,11 +7838,8 @@ function modelPrefsOfDraft() { return x && Object.keys(x).length ? x : undefined; } -// proxyPicker: the proxy one provider's requests go through (#237) — the -// one in Settings, none, or its own — so Codex can go through a proxy -// while a vendor at home goes direct. The draft keeps the choice as -// proxyMode ("" global, "direct", "custom") and the address as proxyURL; -// proxyOfDraft is what is saved. +// proxyPicker: one provider's proxy (#237): Settings', none or its own, +// as proxyMode ("" global, "direct", "custom") and proxyURL const PROXY_HINT = { "": "Follows the proxy in Settings", direct: "Requests to it go direct, whatever the proxy in Settings", @@ -7870,12 +7867,8 @@ function proxyPicker() { return box; } -// concurrencyField: how many requests each of the provider's keys or -// accounts may have out at the vendor at once (Discord, Lemon: a Codex -// account is risk-controlled past five or six); more wait their turn and -// go in order. The draft keeps what is typed as concurrency, "" for none -// set — a plugin's provider then takes what its plugin says, shown as the -// placeholder — and concurrencyOfDraft is what is saved. +// concurrencyField: requests each key or account has out at once (Lemon: +// Codex risk control past five); "" takes the plugin's, as its placeholder function concurrencyField(p) { const plugin = p?.pluginConcurrency || 0; const box = input(draft.concurrency ?? "", plugin ? t("{n}, as its plugin says", { n: plugin }) : t("No limit"), "number"); @@ -7910,10 +7903,8 @@ function concurrencyField(p) { ...field(t("Queue wait"), wait, t("Seconds a request waits for a free slot before it is turned away. 0 or empty waits as long as it takes")), ]; } -// priceRateField: what the provider charges against the official price -// (ITea312, #819), as a relay bills 0.8× or 1.5× of it: the Usage page's -// costs are its list price, else its maker's, times this. Empty is the -// price as listed; steps of 0.001. +// priceRateField: a relay's rate on the official price (#819), which +// Usage's costs are multiplied by; empty is the price as listed function priceRateField() { const box = input(draft.priceRate ?? "", t("1, the official price")); box.classList.add("price-rate"); @@ -7921,18 +7912,21 @@ function priceRateField() { box.oninput = () => { draft.priceRate = box.value; }; return field(t("Price rate"), box, t("Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set")); } +// countFreeField: provider.CountFree (jiabubu: a free daily quota) +function countFreeField() { + const [l, c] = tick(t("Count its models as free"), !!draft.countFree); + l.classList.add("count-free"); + c.onchange = () => { draft.countFree = c.checked; }; + return field(t("Free for me"), l, t("For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.")); +} // a provider's hours at its own rate (#2463), drawn by ratewindows.js function rateWindowsField() { const box = el("div", "stack rate-windows"), d = draft; import("./ratewindows.js").then(() => rateWindowsPaint(box, d), statusErr); return field(t("Rate windows"), box); } -// pluginOptionsField: the switches a plugin declares for its provider -// (auth.options, #2038, Vocllum), each an Off/On beside the plugin's own -// words for it, put in as text. One the plugin asks to confirm is asked -// before it is turned on. A change is kept in the draft as -// pluginOptions[key] and saved with the provider; nothing runs when it is, -// the plugin reads the value when it next wants it. +// pluginOptionsField: a plugin's declared switches (auth.options, #2038), +// confirmed first where it asks, kept as draft.pluginOptions[key] function pluginOptionsField(sub) { const opts = sub?.plugin?.options || []; if (!opts.length) return []; @@ -8059,7 +8053,7 @@ function advancedSet(d, p) { !!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) || [d.concurrency, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || !!d.rateWindows?.length || - !!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff) || + !!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff) || !!d.fallback?.length || !!p?.balanceToken?.set; } function priceRateError(ed) { @@ -9217,7 +9211,7 @@ function baseAPIOf(p) { // draftOf is a saved provider as its editor's form holds it. function draftOf(p) { - return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; + return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; } // duplicateProvider opens the Add form on a copy of p (#268): its URLs, @@ -9537,7 +9531,7 @@ function drawEditor(p, presetID) { if (perAccount) proxies.append(perAccount); advIn.append(...field(t("Proxy"), proxies)); advIn.append(...concurrencyField(p)); - advIn.append(...priceRateField(), ...rateWindowsField()); + advIn.append(...priceRateField(), ...countFreeField(), ...rateWindowsField()); if (p.cline) advIn.append(...upstreamField()); advIn.append(...unmaskRow("")); ed.append(...pluginOptionsField(subOf(a.agent))); @@ -9581,7 +9575,7 @@ function drawEditor(p, presetID) { if (priceTypedError(ed)) return; const picked = accountModelsDraft(p); if (picked === false) return pickError(); - const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) }; + const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, countFree: !!draft.countFree, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) }; saving(saveBtn, t("Saving…")); saveAccountModelsDraft(picked).then(() => savePluginOptions(subOf(a.agent))).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); }; bar.append(cancel, saveBtn); @@ -9764,7 +9758,7 @@ function drawEditor(p, presetID) { if (perKey) proxies.append(perKey); advIn.append(...field(t("Proxy"), proxies)); advIn.append(...concurrencyField(p)); - advIn.append(...priceRateField(), ...rateWindowsField()); + advIn.append(...priceRateField(), ...countFreeField(), ...rateWindowsField()); if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField()); @@ -10182,6 +10176,7 @@ function drawEditor(p, presetID) { body.pinUpstream = !!draft.pinUpstream; if (twoKeyHeaders()) body.authHeader = draft.authHeader || ""; body.unredacted = !!draft.unredacted && unmaskable(); + body.countFree = !!draft.countFree; if (tlsTakes()) body.insecureTLS = !!draft.insecureTLS && onHTTPS(); if (custom) body.limitRestOff = !!draft.limitRestOff; if (!decideOnly(p || pr)) body.nativeCompaction = !!draft.nativeCompaction && carriesCompaction(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 65d12a9d5..a6da41649 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2279,6 +2279,9 @@ const I18N = { "A number of your own, up to 1000": "自定义数字,最大 1000", "No limit": "不限制", "Price rate": "价格倍率", + "Free for me": "对我免费", + "Count its models as free": "把它的模型算作免费", + "For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "适用于免费额度,比如每日免费额度:「免费优先」会先用它的模型,再用付费的;「最便宜优先」把它们算作不花钱。价格和用量统计的费用保持原样。", "Plugin options": "插件选项", "{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} 声明了这些选项,并在工作时读取;更改选项不会自行运行任何操作。", "Turn on {name}?": "开启「{name}」?", @@ -6491,6 +6494,9 @@ const I18N = { "A number of your own, up to 1000": "自定義數字,最大 1000", "No limit": "不限制", "Price rate": "價格倍率", + "Free for me": "對我免費", + "Count its models as free": "把它的模型算作免費", + "For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "適用於免費額度,例如每日免費額度:「免費優先」會先用它的模型,再用付費的;「最便宜優先」把它們算作不花錢。價格和用量統計的費用維持原樣。", "Plugin options": "外掛選項", "{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} 宣告了這些選項,並在工作時讀取;變更選項不會自行執行任何動作。", "Turn on {name}?": "開啟「{name}」?", @@ -10682,6 +10688,9 @@ const I18N = { "A number of your own, up to 1000": "任意の数(最大 1000)", "No limit": "上限なし", "Price rate": "価格倍率", + "Free for me": "自分には無料", + "Count its models as free": "このモデルを無料として扱う", + "For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "毎日の無料枠のような無料分に。「無料優先」は有料のものより先にこのモデルを使い、「最安優先」はコストなしとして扱います。価格と使用量で数える費用はそのままです。", "Plugin options": "プラグインのオプション", "{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} が宣言し、動作中に読み取ります。変更しても、それだけで何かが実行されることはありません。", "Turn on {name}?": "「{name}」をオンにしますか?", @@ -14903,6 +14912,9 @@ const I18N = { "A number of your own, up to 1000": "Eine eigene Zahl, bis 1000", "No limit": "Kein Limit", "Price rate": "Preisfaktor", + "Free for me": "Für mich kostenlos", + "Count its models as free": "Seine Modelle als kostenlos zählen", + "For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "Für ein Gratiskontingent, etwa ein tägliches: „Kostenlos zuerst“ nutzt seine Modelle vor bezahlten, und „Günstigste zuerst“ rechnet sie als kostenlos. Preise und die Kosten in der Nutzung bleiben wie gelistet.", "Plugin options": "Plugin-Optionen", "{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} legt diese fest und liest sie bei der Arbeit; eine Änderung löst selbst nichts aus.", "Turn on {name}?": "{name} einschalten?", diff --git a/internal/gui/countfree_test.go b/internal/gui/countfree_test.go new file mode 100644 index 000000000..77edc24db --- /dev/null +++ b/internal/gui/countfree_test.go @@ -0,0 +1,49 @@ +package gui + +import ( + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// jiabubu on Discord: the editor's "Count its models as free" is saved on +// a preset (ModelScope, whose free daily quota is the case) and on a +// provider the user typed in, given back by /api/providers for the editor +// to open with, and turned off by a save that says so. +func TestProviderSaveKeepsCountFree(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := http.NewServeMux() + providerRoutes(mux, nil) + do := func(method, path, body string) string { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) + if w.Code != 200 { + t.Fatalf("%s: %d %s", path, w.Code, w.Body) + } + return w.Body.String() + } + do("POST", "/api/provider/save", `{"id":"modelscope","name":"ModelScope","preset":"modelscope","key":"ms-k","countFree":true,"new":true}`) + if p, err := provider.Find("modelscope"); err != nil || !p.CountFree || !p.FreeModel("any-model-of-it") { + t.Fatalf("the preset's mark wasn't kept: %+v %v", p, err) + } + if !strings.Contains(do("GET", "/api/providers", ""), `"countFree":true`) { + t.Fatal("/api/providers doesn't give the mark back") + } + do("POST", "/api/provider/save", `{"id":"modelscope","from":"modelscope","name":"ModelScope","preset":"modelscope","key":"","countFree":false}`) + if p, err := provider.Find("modelscope"); err != nil || p.CountFree { + t.Fatalf("turned off, it stayed: %+v %v", p, err) + } + + do("POST", "/api/provider/save", `{"id":"box","name":"Box","chat":"http://127.0.0.1:9/v1","key":"k","countFree":true,"new":true}`) + if p, err := provider.Find("box"); err != nil || !p.CountFree { + t.Fatalf("a typed-in provider's mark wasn't kept: %+v %v", p, err) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 872e93eae..224f9b9dc 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -103,6 +103,9 @@ type providerJSON struct { // on this machine or the local network, set to go unmasked by // Settings' redaction (provider.Unredacted) Unredacted bool `json:"unredacted"` + // every model of it counted free by the user's word, for Free first + // and Cheapest (provider.CountFree) + CountFree bool `json:"countFree,omitempty"` // a provider the user added whose own HTTPS host's certificate is // taken as it is (provider.InsecureTLS, #2383); TakesInsecureTLS: it // may be, being the user's own and not a preset's or a sign-in's @@ -640,7 +643,7 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(), Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, - Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, + Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.Picks(), Models: []modelJSON{}, Agents: []providerAgent{}, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate, @@ -1480,6 +1483,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { pr.Searches = in.Searches pr.PinUpstream = in.PinUpstream pr.Unredacted = in.Unredacted + pr.CountFree = in.CountFree pr.NativeCompaction = in.NativeCompaction pr.PassUserAgent = in.PassUserAgent pr.AuthHeader = in.AuthHeader diff --git a/internal/gui/tests/provider-count-free.test.cjs b/internal/gui/tests/provider-count-free.test.cjs new file mode 100644 index 000000000..6eebdc255 --- /dev/null +++ b/internal/gui/tests/provider-count-free.test.cjs @@ -0,0 +1,149 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// "Count its models as free" (jiabubu on Discord: ModelScope's free daily +// quota) is the user's word that a provider costs them nothing, so Free +// first spends it first. The editor's Free for me row, under Advanced +// beside Price rate, opens as it was saved (and opens Advanced when on), +// and Save posts it: for a provider of keys and for a signed-in account. +// In every language, in both engines, wide and narrow. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const base = { + icon: "generic", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "qwen3", name: "Qwen3", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "ms-…1234" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false, unredacted: false, +}; +const scope = { ...base, id: "modelscope", name: "ModelScope", preset: "modelscope", chat: "https://api-inference.modelscope.cn/v1" }; +const counted = { ...base, id: "free-relay", name: "Free Relay", chat: "https://relay.example.com/v1", countFree: true }; +const codex = { + id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] }, + proxy: "", +}; + +function serve(lang, posts) { + const providers = { providers: [scope, counted, codex], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const TICK = "Count its models as free"; +const STRINGS = [ + "Free for me", TICK, + "For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [900, 440]) { + const open = async (t, name) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + let page; + t.after(async () => { + if (process.env.ARTIFACT_DIR && page) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name.replace(/\W+/g, "-")}-count-free.png`), fullPage: true }); + } + await browser.close(); + }); + page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: name }).click(); + await page.locator(".editor .bar").waitFor(); + const tick = await page.evaluate((k) => t(k), TICK); + return { page, errors, posts, tick }; + }; + const adv = (page) => page.locator(".editor details.advanced"); + const unfold = async (page) => { + await adv(page).waitFor({ state: "attached" }); + if (!(await adv(page).evaluate((d) => d.open))) await adv(page).locator(":scope > summary").click(); + }; + const box = (page, tick) => page.locator(".editor label.tick.count-free", { hasText: tick }).locator("input"); + const save = async (page, posts) => { + const n = posts.length; + const label = await page.evaluate(() => t("Save")); + await page.locator(".editor .bar").getByRole("button", { name: label, exact: true }).click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.at(-1); + }; + const fits = async (page, tick) => { + const r = await page.locator(".editor label.tick.count-free").boundingBox(); + assert.ok(r && r.width > 60 && r.x >= 0 && r.x + r.width <= width, `the row fits: ${JSON.stringify(r)}`); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + assert.equal(await page.locator(".editor label.tick.count-free").textContent(), tick); + }; + + test(`${engine} ${lang} ${width}: ModelScope is counted free and saved so`, async (t) => { + const { page, errors, posts, tick } = await open(t, "ModelScope"); + assert.equal(await adv(page).evaluate((d) => d.open), false, "nothing set opens Advanced"); + await unfold(page); + assert.equal(await box(page, tick).isChecked(), false, "opens off"); + await box(page, tick).scrollIntoViewIfNeeded(); + await fits(page, tick); + await box(page, tick).check(); + const saved = await save(page, posts); + assert.equal(saved.action, "save"); + assert.equal(saved.body.id, "modelscope"); + assert.equal(saved.body.countFree, true); + if (lang !== "en") { + const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [lang, STRINGS]); + assert.deepEqual(missing, [], `every string has its ${lang}`); + } + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: one saved counted free opens Advanced ticked, and is saved off`, async (t) => { + const { page, errors, posts, tick } = await open(t, "Free Relay"); + assert.equal(await adv(page).evaluate((d) => d.open), true, "set, it opens Advanced"); + assert.equal(await box(page, tick).isChecked(), true); + await box(page, tick).scrollIntoViewIfNeeded(); + await box(page, tick).uncheck(); + const saved = await save(page, posts); + assert.equal(saved.body.id, "free-relay"); + assert.equal(saved.body.countFree, false); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: a signed-in account is counted free too`, async (t) => { + const { page, errors, posts, tick } = await open(t, "Codex"); + await unfold(page); + assert.equal(await box(page, tick).isChecked(), false); + await box(page, tick).scrollIntoViewIfNeeded(); + await fits(page, tick); + await box(page, tick).check(); + const saved = await save(page, posts); + assert.equal(saved.action, "save"); + assert.equal(saved.body.id, "codex"); + assert.equal(saved.body.countFree, true); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 3ca520748..5aa9d4e68 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -1741,8 +1741,12 @@ func (p Provider) PaidBesideFree(model string) bool { // // A model neither listed free nor priced is not free: nothing says it costs // nothing, and the routes that go by this put it with the paid ones, so a -// pool without free models behaves as In order. +// pool without free models behaves as In order. The user's word is +// something: every model of a provider they count free is (CountFree). func (p Provider) FreeModel(model string) bool { + if p.CountFree { + return true + } for _, m := range p.Available() { if strings.EqualFold(m.ID, model) { if m.Free { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 69e12db7b..4c54d33b1 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -212,6 +212,13 @@ type Provider struct { // a price the user set for one of its models stands as set. 0 is the // price as listed; at most three decimals (PriceRateOK). PriceRate float64 `json:"priceRate,omitempty"` + // CountFree is the user's word that the provider costs them nothing + // (jiabubu on Discord: ModelScope's free daily quota): every model of + // it counts as free where routing weighs that, as a model its vendor + // lists free does (FreeModel: Free first spends it first, Cheapest + // weighs it at nothing). Prices and the costs Usage counts stay as + // listed: it says what to spend first, not what a call cost. + CountFree bool `json:"countFree,omitempty"` // RateWindows are the time-of-day windows it bills at its own rate // (#2463): a peak at 2× or 3×, a discount off peak. The first window // that holds a call's time multiplies the price again, on top of @@ -806,6 +813,8 @@ func withPicks(a, pk Provider) Provider { // what it bills against the official price (#819): an account's editor // sets it as a key provider's does (PaulT on Discord, Codex) a.PriceRate = pk.PriceRate + // counted free by the user's word, every account alike + a.CountFree = pk.CountFree // the hours the provider bills at its own rate (#2463), as the editor // keeps them for the account like the rest of these a.RateWindows = pk.RateWindows @@ -943,7 +952,7 @@ func Save(p Provider) error { if p.ID == "kiro" { key = p.Key } - p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)} + p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, CountFree: p.CountFree, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)} } else { p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart if subscriptionID(p.ID) && !stored(p.ID) { @@ -1157,6 +1166,7 @@ func AddCopy(p Provider, from string) (string, error) { } p.Searches = p.Searches || src.Searches p.Unredacted = p.Unredacted || src.Unredacted + p.CountFree = p.CountFree || src.CountFree p.NativeCompaction = p.NativeCompaction || src.NativeCompaction p.PassUserAgent = p.PassUserAgent || src.PassUserAgent if p.Website == "" { diff --git a/internal/provider/routing.go b/internal/provider/routing.go index b3e42921f..955e4d8fa 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -100,6 +100,18 @@ func SetCapCareful(id string, on bool) error { return Save(*p) } +// SetCountFree has every model of a provider count as free for the +// routings that weigh it, or go by its vendor's word again +// (Provider.CountFree). +func SetCountFree(id string, on bool) error { + p, err := Find(id) + if err != nil { + return err + } + p.CountFree = on + return Save(*p) +} + // SetKeepLogin keeps Codex or Claude Code signed in to the account the // user made first (Provider.KeepLogin), or lets magpie move it on again. // Either way it is no longer kept on one of the user's choosing