diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 0272d068c..e90968d45 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -67,7 +67,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). Claude Code whose requests go to magpie's gateway (`ClaudeThroughMagpie`: its settings' `ANTHROPIC_BASE_URL` is the gateway, either sign-in) is not moved: the gateway already sends its requests to an account with room, and moving the sign-in only took away what the user signed it in for, such as claude.ai connectors (oreoft on Discord set it back more than ten times; `TestClaudeRoutedThroughMagpieKeepsItsSignIn`). Not routed, or with *Only switch Claude Code's sign-in*, it still moves. Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (`routes.Drain`), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (`returnsToFirst`; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, `TestCodexDrainSignInStaysOnTheNext`). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent *Extra usage* row of text (`claudeOveragesWindow`: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; `TestClaudeSwitchOffOverages`). The GUI says the row *In use* in the reader's language. Under the accounts of a Claude Code or Codex with more than one, the switch is a switch of its own, *Switch {agent}'s account automatically* (the `auto-switch` box in app.js; off is `KeepLogin`, posted to `provider/keeplogin`; before 11-11 a *Keep {agent} signed in to* tick that turned it off, which a user read as the switch gone). On, a line under it says what the switch does with that agent's sign-in (`SignInMovesOf`, `signInMoves` on its `/api/providers` row, `signInMovesLine`): left where the user put it while Claude Code's requests go through the gateway (`gateway`), else the share it moves at and whether it comes back to the first (`moves`), each decided as `NextLogin` decides it (`TestSignInMovesSaysWhatSwitchDoes`). Off, it names the account the agent stays on, with a pick of another (`keepLoginAs`). Switch-only always moves the sign-in, so the switch is held on there (sign-in-moves.test.cjs). Beside the switch, an ⓘ mark whose hover card (settingshints.js, the box a `.hint-row` with its `.hint` lines out of sight) says how the switch works and why it is the agent's own use of the account: the sign-in written where the agent keeps its own, as `/login` or `codex login` does; usage read by Claude Code's own `/usage` or where Codex's `/status` reads it; for Claude Code, every request still sent by Claude Code itself straight to Anthropic; and that sharing an account is against the vendor's terms. It promises nothing about bans (autoswitchtip.js, loaded when the switch is drawn). Only where the sign-in moves: `moves`, or `kept` without `routed`, which `SignInMovesOf` sets when Claude Code goes through the gateway, so turning the switch on would move its requests, not its sign-in. Routing (`Allowances`) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (`Current week (Sonnet only)`, `(Fable)`) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (`usedPast`); "Sonnet only" is read as the Sonnet week, `7 days · Sonnet` counting `sonnet`, the window the `seven_day_sonnet` header keeps (#4532, `TestClaudeUsageSonnetOnly`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts the agent can be signed in to (`switchable`, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; `TestNextTakesAccountsThatAreOff`), from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (`TestNextInOrder`). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | -| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing groups page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`; a member is dragged by its number or its row's logo and room around its words, `group-member-row-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing groups page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing groups page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing groups page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | +| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing groups page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). A `free:` before one (`FreePrefix`, `compileRule`, #5903) keeps, of the models the rest matches, those whose catalog entry says `free` (`Entry.Free`, the vendor's or plugin's flag as last read): `free:workbuddy/*`. A $0 price (`PricedFree`), a rate, an account's name or an id with free in it never counts, and the GUI's hint says the flag is no promise of no charge. A provider's `AutoInclude` takes no `free:` (`isIDPattern`). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`; a member is dragged by its number or its row's logo and room around its words, `group-member-row-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing groups page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing groups page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing groups page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A Remote magpie's cards (`GET /v1/magpie/quotas/cards`, `writeCards`) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; `TestRemoteMagpieCardsCarryTheirWholes`). A Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). Routing weighs such a ChatGPT API account by that Codex account's reading too: `Allowances("chatgpt-api")` gives it the Codex account's allowance (`samePlanAllowances`; tmr11235 on X, `TestChatGPTAPIAllowanceIsTheSameAccountsCodexReading`), so Smart no longer puts it after every known account as unknown; one with no Codex twin stays unknown. A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, which `/wham/usage` doesn't tell (`additional_rate_limits` is null). Every reply of the images API, a 200 too, does: `x-codex-active-limit: imagegen_premium` with the window in `x-codex-primary-*` (1440 minutes, `reset-at`), or in the limit's own family (`x-imagegen-premium-primary-*`, as Codex's `parse_all_rate_limits` reads it). The gateway keeps that window per account (`heardCodexImage` in [`codex_image_limits.go`](../../internal/gateway/codex_image_limits.go), from magpie's drawing and from Codex's own relayed `/images/*`; `provider.ImageHeard`), and never takes it for a chat window (`codexHeaderLimits` tells none when the active limit is an image one; #6412, Green14964 on X: the card said "2 minutes" of a 24-hour window). So the row says *Available* with the window's reset, *Used up* when the headers say 100% or while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244, else the heard window's reset for a 429 with that window full, not `quotaRest`'s 15 minutes), and *Unknown* before any drawing, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `TestCodexImageRowFromA200sHeaders`, `TestCodexImageRefusalRestsUntilItsWindow`, `codex-image-row.test.cjs`). The window heard lives in memory only, so after a restart the row is *Unknown* until the next drawing. Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Each card also carries `routing`, each window's span, the model it alone counts and whether it is aside (`provider.ToldRouting` in `writeCards`), which a window's own json leaves out; the magpie reading them lays them back on the windows (`withRouting` in `keepRemoteCards`), and only such a card is weighed by routing (`provider.RemoteAllowance`, #6708, [gateway routing](gateway-routing.md)). Passed on, the cards keep them, so a third magpie weighs them too. A read the test hook dropped (`ForgetRemoteCardsForTest` moves `remoteCardCache.gen` on) is not kept. Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index 3608f8a88..39fe34b00 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -95,6 +95,8 @@ const groupUsage = `usage: * is any run of characters, / too, over the provider/model id in any case (openrouter/*:free, *-free, opencode-zen/*), or re: matching the whole id, in any case too (re:openrouter/.*:(free|beta)); (?-i) in the regexp makes case matter (re:(?-i)openrouter/.*:FREE). + free: before a pattern keeps only the models it matches that their last catalog marks free + (free:workbuddy/*): the vendor's free flag as last read, not a promise of no charge. Quote it for the shell. The group keeps the pattern, not its models: one the vendor adds joins, one it drops leaves. The models you name come first, in your order, then those the patterns match, in the order magpie models lists them; one both named and matched keeps its named place. diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index bd5937c6c..254d66f83 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6620,13 +6620,24 @@ function routingPage(part) { // id, both in any case (provider.compilePattern). The group keeps them, // and the models they match now follow those it names, in the catalog's // order (Group.Matched) - const isPattern = (s) => s.startsWith("re:") || s.includes("*"); + // A free: rule (provider.FreePrefix, #5903) keeps, of the models the + // rest of it matches, those the last catalog marks free (m.free): never + // a $0 price (m.zero), a rate or an id that says free + const isPattern = (s) => s.startsWith("re:") || s.startsWith("free:") || s.includes("*"); function patternRe(p) { try { if (p.startsWith("re:")) return goRe(p.slice(3)); return new RegExp("^" + p.split("*").map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$", "i"); } catch { return null; } } + // patternTest is the models a pattern takes, as provider.compileRule + // reads it; null when it is one magpie can't read + function patternTest(p) { + const free = p.startsWith("free:"), scope = free ? p.slice(5).trim() : p; + if (free && (!scope || scope.startsWith("free:"))) return null; + const r = patternRe(scope); + return r && ((m) => (!free || m.free === true) && r.test(m.id)); + } // goRe is a re: pattern's regexp as Go reads it, in any case: Go's // leading flag group, "(?-i)" to make case matter, is JS's flags (U, // ungreedy, changes no whole-id match). null when it has none or JS @@ -6646,11 +6657,11 @@ function routingPage(part) { // the models served now the patterns match, but those the group names // (at any reasoning): as provider.matchesIn finds them function matchedBy(patterns, named) { - const res = patterns.map(patternRe).filter(Boolean); + const res = patterns.map(patternTest).filter(Boolean); const own = new Set(named.map((id) => splitMember(id)[0])); - return (groups?.models || []).filter((m) => !own.has(m.id) && res.some((r) => r.test(m.id))).map((m) => m.id); + return (groups?.models || []).filter((m) => !own.has(m.id) && res.some((r) => r(m))).map((m) => m.id); } - const patternCount = (p) => { const r = patternRe(p); return r ? (groups?.models || []).filter((m) => r.test(m.id)).length : 0; }; + const patternCount = (p) => { const r = patternTest(p); return r ? (groups?.models || []).filter(r).length : 0; }; const patternWords = (n) => n ? t(n === 1 ? "1 model" : "{n} models", { n }) : t("matches nothing now"); // what a group keeps of its members: those it names, not those its // patterns matched when it was read — they are found again each time @@ -8283,7 +8294,7 @@ function routingPage(part) { const p = pin.value.trim(); if (!p) return ""; if (!isPattern(p)) return status(t("A pattern has a * in it, or starts with re:"), "warn"), null; - if (!patternRe(p)) return status(t("{pattern} is not a regular expression magpie can read", { pattern: p }), "warn"), null; + if (!patternTest(p)) return status(t("{pattern} is not a regular expression magpie can read", { pattern: p }), "warn"), null; if (!d.match.includes(p)) d.match.push(p); pin.value = ""; rematch(); drawPats(); draw(); drawRules(); @@ -8296,7 +8307,8 @@ function routingPage(part) { pbox.append(plist, padd); drawPats(); const pw = el("div"); - pw.append(pbox, el("div", "hint", t("Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression."))); + pw.append(pbox, el("div", "hint", t("Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.")), + el("div", "hint", t("free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge."))); // what few change — patterns, the lists, routing, the waits, the // window, how long a conversation stays, reasoning — folded under // Advanced below the rules, as a provider's editor folds its own (the diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 8bae2e5cf..7a7aacab5 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -156,6 +156,7 @@ magpie.strings({ "A pattern has a * in it, or starts with re:": "模式需要包含 *,或以 re: 开头", "{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能识别的正则表达式", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入组(含供应商日后新增的),排在上方模型之后:* 匹配 provider/model 中任意字符,re: 开头表示正则表达式。", + "free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "模式前加 free: 只保留最近一次目录标为免费的模型,如 free:workbuddy/*。这是目录的标记,不保证不扣费。", "{api} only · after the others": "仅 {api} · 排在其他之后", "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} 是备用的:其提供商同时只用列表中前 {n} 个账号或 Key,所以只有它们都失败后才会试它。", "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} 上次回答了这个对话,但列表中排在它前面的账号能接请求时它只作备用,所以对话回到它们那里。", @@ -929,6 +930,7 @@ magpie.strings({ "A pattern has a * in it, or starts with re:": "模式需要包含 *,或以 re: 開頭", "{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能識別的正規表示式", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入組(含供應商日後新增的),排在上方模型之後:* 匹配 provider/model 中任意字元,re: 開頭表示正規表示式。", + "free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "模式前加 free: 只保留最近一次目錄標為免費的模型,如 free:workbuddy/*。這是目錄的標記,不保證不扣費。", "{api} only · after the others": "僅 {api} · 排在其他之後", "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} 是備用的:其供應商同時只用清單中前 {n} 個帳號或 Key,所以只有它們都失敗後才會試它。", "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} 上次回答了這個對話,但清單中排在它前面的帳號能接請求時它只作備用,所以對話回到它們那裡。", @@ -1680,6 +1682,7 @@ magpie.strings({ "A pattern has a * in it, or starts with re:": "パターンには * を含めるか、re: で始めてください", "{pattern} is not a regular expression magpie can read": "{pattern} は magpie が読める正規表現ではありません", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "パターンに一致するモデルは、プロバイダが今後追加するものも含めてすべて、上のモデルの後にグループに入ります。* は provider/model の任意の文字列、re: で始めると正規表現です。", + "free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "パターンの前に free: を付けると、直近のカタログで無料とされたモデルだけを含めます(例: free:workbuddy/*)。カタログの表示であり、課金されない保証ではありません。", "{api} only · after the others": "{api} のみ · 他の後", "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} は予備です。このプロバイダーは一覧の先頭から {n} 個のアカウントやキーだけを同時に使うので、それらがすべて失敗したときだけ試されます。", "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} がこの会話に前回答えましたが、一覧でその前にあるアカウントがリクエストを受けられる間は予備なので、会話はそちらに戻ります。", @@ -2443,6 +2446,7 @@ magpie.strings({ "A pattern has a * in it, or starts with re:": "Ein Muster enthält ein * oder beginnt mit re:", "{pattern} is not a regular expression magpie can read": "{pattern} ist kein regulärer Ausdruck, den magpie lesen kann", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "Jedes Modell, auf das ein Muster passt, ist in der Gruppe, jetzt und sobald Anbieter neue auflisten, nach den Modellen oben: * steht für beliebige Zeichen in provider/model, re: leitet einen regulären Ausdruck ein.", + "free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "free: vor einem Muster behält nur die Modelle, die der letzte Katalog als kostenlos markiert hat, etwa free:workbuddy/*. Das ist die Markierung des Katalogs, keine Zusage, dass nichts berechnet wird.", "{api} only · after the others": "nur {api} · nach den anderen", "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} ist in Reserve: Von seinem Anbieter nehmen nur die ersten {n} Konten oder Schlüssel der Liste gleichzeitig Anfragen an, also wird es erst versucht, wenn sie alle fehlgeschlagen sind.", "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} hat diese Unterhaltung zuletzt beantwortet, ist aber in Reserve, solange die Konten davor in der Liste Anfragen annehmen können, also geht die Unterhaltung zu ihnen zurück.", diff --git a/internal/gui/tests/group-free-rule.test.cjs b/internal/gui/tests/group-free-rule.test.cjs new file mode 100644 index 000000000..25108df04 --- /dev/null +++ b/internal/gui/tests/group-free-rule.test.cjs @@ -0,0 +1,124 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A group's free: rule (#5903, provider.FreePrefix): in the editor's +// pattern box free:wb/* takes, of WorkBuddy's models, only those the +// catalog marks free (free: true), never one priced at $0 (zero), at a +// rate or with free in its id, nor another provider's free one. It shows +// its live count as any pattern does, and one line says the flag is the +// last catalog's, not a promise of no charge. Saved, the rule is sent as +// typed. In English and Chinese; every language has the line. +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 models = [ + { id: "wb/hy4free", name: "hy4free", providerName: "WorkBuddy", icon: "generic", free: true }, + { id: "wb/glm-5.1", name: "glm-5.1", providerName: "WorkBuddy", icon: "generic" }, + { id: "wb/hy3", name: "hy3", providerName: "WorkBuddy", icon: "generic", free: true }, + { id: "wb/deepseek-v4-free", name: "deepseek-v4-free", providerName: "WorkBuddy", icon: "generic" }, + { id: "wb/hy-zero", name: "hy-zero", providerName: "WorkBuddy", icon: "generic", zero: true }, + { id: "wb/hy4flash-exp4", name: "hy4flash-exp4", providerName: "WorkBuddy", icon: "generic", free: true }, + { id: "cl/mimo", name: "mimo", providerName: "Cline", icon: "generic", free: true }, + { id: "an/claude-opus-5-5", name: "claude-opus-5-5", providerName: "Anthropic", icon: "generic" }, +]; +const members = ["an/claude-opus-5-5"]; +const groups = () => ({ + models, pools: [], + groups: [{ id: "pool", name: "Pool", members, match: [], matched: [], fast: [], off: [], routing: "order", ready: true, patterns: [], + memberInfo: members.map((id) => ({ id, ready: true })) }], +}); +const LINE = "free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge."; + +const words = { + en: { edit: "Edit", save: "Save", add: "Add pattern", advanced: "Advanced", three: "3 models", line: LINE }, + zh: { edit: "编辑", save: "保存", add: "添加模式", advanced: "高级", three: "3 个模型", line: "模式前加 free: 只保留最近一次目录标为免费的模型,如 free:workbuddy/*。这是目录的标记,不保证不扣费。" }, +}; + +function serve(lang, posts) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json(groups()); + if (url.pathname.startsWith("/api/groups/")) { + posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") }); + return json(groups()); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + 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 r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: a free: rule takes the models the catalog marks free`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 2000 }, reducedMotion: "reduce" })).newPage(); + t.after(() => browser.close()); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=groups"); + const card = page.locator(".rt-group", { hasText: "Pool" }); + await card.waitFor(); + await card.locator("button", { hasText: w.edit }).click(); + const ed = page.locator(".rt-gedit"); + const names = () => ed.locator(".fallback:not(.rt-pats) .fbrow .n > span:first-child").allTextContents(); + await ed.locator(".fallback:not(.rt-pats) .fbrow").first().waitFor(); + assert.deepEqual(await names(), ["claude-opus-5-5"]); + + const adv = ed.locator("details.rt-gadv"); + if (!(await adv.evaluate((d) => d.open))) await adv.locator("summary").click(); + assert.equal(await adv.locator(".hint", { hasText: w.line }).count(), 1, "the line says what free: is"); + const pbox = ed.locator(".rt-pats"); + await pbox.locator("input").fill("free:wb/*"); + await pbox.locator("button", { hasText: w.add }).click(); + assert.deepEqual(await names(), ["claude-opus-5-5", "hy4free", "hy3", "hy4flash-exp4"], "only those marked free, of WorkBuddy's, in the catalog's order"); + const rule = pbox.locator(".fbrow").first(); + assert.equal(await rule.locator("code").textContent(), "free:wb/*"); + assert.equal(await rule.locator("small").textContent(), w.three, "its live count"); + + // the plain pattern beside it is as it was: every one of WorkBuddy's + await pbox.locator("input").fill("wb/*-free"); + await pbox.locator("button", { hasText: w.add }).click(); + assert.deepEqual(await names(), ["claude-opus-5-5", "hy4free", "hy3", "deepseek-v4-free", "hy4flash-exp4"]); + await pbox.locator(".fbrow").nth(1).locator("button").click(); + assert.deepEqual(await names(), ["claude-opus-5-5", "hy4free", "hy3", "hy4flash-exp4"]); + // free: with nothing after it is refused, the box keeping it + await pbox.locator("input").fill("free:"); + await pbox.locator("button", { hasText: w.add }).click(); + assert.equal(await pbox.locator(".fbrow").count(), 1); + assert.equal(await pbox.locator("input").inputValue(), "free:"); + await pbox.locator("input").fill(""); + + const b = ed.locator("button.primary", { hasText: w.save }); + await b.scrollIntoViewIfNeeded(); + await b.click(); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); + const sent = posts.find((p) => p.path === "/api/groups/save"); + assert.deepEqual(sent.body.members, ["an/claude-opus-5-5"], "only the model named is sent"); + assert.deepEqual(sent.body.match, ["free:wb/*"], "the rule as typed"); + + const missing = await page.evaluate((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]), LINE); + assert.deepEqual(missing, [], "every language has the line"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/routing-levels.test.cjs b/internal/gui/tests/routing-levels.test.cjs index e35f5a892..8e4200681 100644 --- a/internal/gui/tests/routing-levels.test.cjs +++ b/internal/gui/tests/routing-levels.test.cjs @@ -101,11 +101,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // window's foot as the editor grew, wheeled to as the reader would: // WebKit's own scroll left a sliver of it over the footer and clicked // the footer) - await page.mouse.move(550, 600); - for (let i = 0; i < 10 && (await row().boundingBox()).y > 1400 - 260; i++) { - await page.mouse.wheel(0, 300); - await page.waitForTimeout(150); - } + const wheelToRow = async () => { + await page.mouse.move(550, 600); + for (let i = 0; i < 10 && (await row().boundingBox()).y > 1400 - 260; i++) { + await page.mouse.wheel(0, 300); + await page.waitForTimeout(150); + } + }; + await wheelToRow(); await row().locator(".segs .opt", { hasText: w.named }).click(); assert.equal(await row().locator(".hint").textContent(), w.namedHint); assert.deepEqual(await chips().allTextContents(), ["none", "minimal", "low", "medium", "high", "xhigh", "max"]); @@ -131,6 +134,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await row().waitFor(); assert.equal(await row().locator(".segs .opt.on").textContent(), w.named); assert.deepEqual(await lit(), ["medium", "xhigh"]); + await wheelToRow(); // as above: the row can open under the foot await chips().filter({ hasText: /^medium$/ }).click(); await chips().filter({ hasText: /^xhigh$/ }).click(); await save(); diff --git a/internal/provider/autolist.go b/internal/provider/autolist.go index 97e6639e7..ee0f2bd4c 100644 --- a/internal/provider/autolist.go +++ b/internal/provider/autolist.go @@ -153,7 +153,7 @@ func CleanAutoInclude(in []string) ([]string, error) { if p == "" || slices.Contains(out, p) { continue } - if !IsPattern(p) { + if !isIDPattern(p) { return nil, fmt.Errorf("%q is a model's id, not a rule: a rule has a * in it, or starts with %s (magpie provider models +%s picks that one)", p, RegexpPrefix, p) } if _, err := compilePattern(p); err != nil { diff --git a/internal/provider/groupmatch.go b/internal/provider/groupmatch.go index 834fcc5da..bba1df23e 100644 --- a/internal/provider/groupmatch.go +++ b/internal/provider/groupmatch.go @@ -31,11 +31,29 @@ import ( // "(?-i)" in it makes case matter from there on: "re:(?-i)openrouter/.*:FREE". const RegexpPrefix = "re:" +// FreePrefix starts a group's member rule that takes, of the models the +// rest of it matches, only those their catalog marks free (Entry.Free, +// catalog.Model's: the vendor's or its plugin's own word, as the catalog +// was last read): "free:workbuddy/*" is WorkBuddy's free models, today's +// and those its next list marks so (#5903). The flag alone decides: a +// model listed at $0, at a rate of 0, on an account named Free or with +// "free" in its id is not taken for one, and the rule is no promise that +// a request costs nothing — the flag is the catalog's, not the bill's. +// The rest is a glob, a "re:" pattern or an id, matched as on its own. +const FreePrefix = "free:" + // IsPattern reports whether a member as typed is a pattern rather than a -// model's id: a regular expression ("re:…") or a glob with "*" in it. No -// vendor's model id has a "*" in it, so a glob can't be taken for one. +// model's id: a regular expression ("re:…"), a free rule ("free:…") or a +// glob with "*" in it. No vendor's model id has a "*" in it or starts +// with either prefix, so none can be taken for one. func IsPattern(s string) bool { s = strings.TrimSpace(s) + return strings.HasPrefix(s, FreePrefix) || isIDPattern(s) +} + +// isIDPattern is IsPattern for a rule over ids alone, as a provider's +// AutoInclude takes them: a regular expression or a glob. +func isIDPattern(s string) bool { return strings.HasPrefix(s, RegexpPrefix) || strings.Contains(s, "*") } @@ -85,19 +103,54 @@ func compilePattern(p string) (matcher, error) { return regexp.MustCompile("(?i)^" + strings.Join(parts, ".*") + "$"), nil } +// rule is a group's pattern compiled: the ids it matches, and with free +// set only the models among them their catalog marks free (FreePrefix). +type rule struct { + ids matcher + free bool +} + +// takes reports whether the rule puts e in its group. +func (r rule) takes(e Entry) bool { + return (!r.free || e.Free) && r.ids.MatchString(e.ID) +} + +// compileRule is a group's pattern as the rule it means: a "free:" one's +// scope is compiled as a pattern of its own, and each model it matches +// must be marked free besides. +func compileRule(p string) (rule, error) { + scope, free := strings.CutPrefix(p, FreePrefix) + if !free { + x, err := compilePattern(p) + return rule{ids: x}, err + } + scope = strings.TrimSpace(scope) + switch { + case scope == "": + return rule{}, fmt.Errorf("%q names no models after %s: free:workbuddy/* is WorkBuddy's models its catalog marks free", p, FreePrefix) + case strings.HasPrefix(scope, FreePrefix): + return rule{}, fmt.Errorf("%q says %s twice", p, FreePrefix) + } + x, err := compilePattern(scope) + return rule{ids: x, free: true}, err +} + // CleanPatterns are a group's patterns as they are kept: trimmed, each // once, every one one magpie can read. func CleanPatterns(in []string) ([]string, error) { var out []string for _, p := range in { p = strings.TrimPrefix(strings.TrimSpace(p), "magpie/") + if scope, ok := strings.CutPrefix(p, FreePrefix); ok { + p = FreePrefix + strings.TrimPrefix(strings.TrimSpace(scope), "magpie/") + } if p == "" || slices.Contains(out, p) { continue } if !IsPattern(p) { - return nil, fmt.Errorf("%q is a model's id, not a pattern: a pattern has a * in it, or starts with %s", p, RegexpPrefix) + return nil, fmt.Errorf("%q is a model's id, not a pattern: a pattern has a * in it, or starts with %s or %s", p, RegexpPrefix, FreePrefix) } - if _, err := compilePattern(p); err != nil { + if _, err := compileRule(p); err != nil { return nil, err } out = append(out, p) @@ -106,9 +159,11 @@ func CleanPatterns(in []string) ([]string, error) { } // PatternMatches reports whether a pattern matches a "provider/model" id. +// A free rule's scope is matched (FreePrefix): the flag is the model's, +// not its id's, and a caller asks this of a model the rule took. func PatternMatches(pattern, id string) bool { - x, err := compilePattern(pattern) - return err == nil && x.MatchString(id) + r, err := compileRule(pattern) + return err == nil && r.ids.MatchString(id) } // matchesIn are the models g's patterns match among entries — the models @@ -119,10 +174,10 @@ func matchesIn(entries []Entry, g Group) []string { if len(g.Match) == 0 { return nil } - var res []matcher + var res []rule for _, p := range g.Match { - if x, err := compilePattern(p); err == nil { - res = append(res, x) + if r, err := compileRule(p); err == nil { + res = append(res, r) } } named := map[string]bool{} @@ -135,7 +190,7 @@ func matchesIn(entries []Entry, g Group) []string { if named[e.ID] || slices.Contains(out, e.ID) { continue } - if slices.ContainsFunc(res, func(x matcher) bool { return x.MatchString(e.ID) }) { + if slices.ContainsFunc(res, func(r rule) bool { return r.takes(e) }) { out = append(out, e.ID) } } @@ -276,9 +331,9 @@ func PatternHits(g Group) []PatternHit { out := make([]PatternHit, 0, len(g.Match)) for _, p := range g.Match { h := PatternHit{Pattern: p} - if x, err := compilePattern(p); err == nil { + if r, err := compileRule(p); err == nil { for _, e := range entries { - if x.MatchString(e.ID) { + if r.takes(e) { h.Models++ } } diff --git a/internal/provider/groupmatch_test.go b/internal/provider/groupmatch_test.go index a7cbbcb18..9a1daa8ac 100644 --- a/internal/provider/groupmatch_test.go +++ b/internal/provider/groupmatch_test.go @@ -3,9 +3,14 @@ package provider import ( "encoding/json" "os" + "path/filepath" "slices" "strings" "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/settings" ) func patternHome(t *testing.T) { @@ -323,3 +328,128 @@ func TestRegexpPatternLookahead(t *testing.T) { t.Errorf("auto-include lookahead refused: %v", err) } } + +// freePlugins are WorkBuddy's and Cline's plugins signed in, their models +// as each lists them (#5903): WorkBuddy's hy4free, hy3 and hy4flash-exp4 +// marked free (its "credits": "x0.00"), glm-5.1 at a rate, one with "free" +// in its id that isn't marked so, and one at a rate of 0 not marked free. +func freePlugins(t *testing.T, wb []plugin.Model) { + t.Helper() + claudeHome(t) + t.Setenv("MAGPIE_BUN", "") + write := func(name string, v any) { + t.Helper() + b, _ := json.Marshal(v) + os.MkdirAll(settings.Dir(), 0o700) + if err := os.WriteFile(filepath.Join(settings.Dir(), name), b, 0o600); err != nil { + t.Fatal(err) + } + } + wbSpec, clSpec := "@magpie-community/opencode-workbuddy-auth", "@magpie-community/opencode-cline-auth" + write("plugins.json", map[string]any{"plugins": []map[string]any{{"spec": wbSpec}, {"spec": clSpec}}}) + write("plugin-auth.json", map[string]map[string]any{"workbuddy": {"type": "api", "key": "wb-1234"}, "cline": {"type": "api", "key": "sk-cline-1234"}}) + t.Cleanup(func() { plugin.UseCached(nil) }) + listWorkBuddy(wb) +} + +// listWorkBuddy is the plugins' catalog as read again, WorkBuddy listing wb. +func listWorkBuddy(wb []plugin.Model) { + wbSpec, clSpec := "@magpie-community/opencode-workbuddy-auth", "@magpie-community/opencode-cline-auth" + plugin.UseCached([]plugin.Provider{ + {ID: "workbuddy", Spec: wbSpec, Name: "WorkBuddy", Methods: []plugin.Method{{Type: "api", Label: "API key"}}, Accounts: []plugin.Account{{Key: "workbuddy", Type: "api"}}, Models: wb}, + {ID: "cline", Spec: clSpec, Name: "Cline", Methods: []plugin.Method{{Type: "api", Label: "API key"}}, Accounts: []plugin.Account{{Key: "cline", Type: "api"}}, + Models: []plugin.Model{{ID: "cline-free/mimo-v2.6-flash", Name: "MiMo V2.6 Flash (free)", Free: true}}}, + }) +} + +// A group's free: rule (#5903) takes, of the models its scope matches, +// only those their catalog marks free: within the provider it names, as +// the catalog was last read. A model at $0, at a rate of 0 or with free in +// its id is not taken, nor one of another provider; the catalog marking +// another free, or one free no longer, changes the group with no save, and +// the patterns that were there before match as they did. +func TestGroupFreeRule(t *testing.T) { + wb := []plugin.Model{ + {ID: "hy4free", Name: "Hy4 Free", Free: true}, + {ID: "glm-5.1", Name: "GLM 5.1", Rate: 1}, + {ID: "hy3", Name: "Hy3", Free: true}, + {ID: "deepseek-v4-free", Name: "DeepSeek V4 Free"}, + {ID: "hy-rate0", Name: "Hy Rate 0", Rate: 0}, + {ID: "hy4flash-exp4", Name: "Hy4 Flash Exp4", Free: true}, + } + freePlugins(t, wb) + if err := Save(Provider{ID: "or", Name: "OR", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"x:free", "y"}}); err != nil { + t.Fatal(err) + } + // a model the user priced at $0 is not one its catalog marks free + if err := SetModelPrice("or/y", &catalog.Price{}); err != nil { + t.Fatal(err) + } + if p, _ := Find("or"); p == nil || !p.PricedFree(settings.Load(), "y") { + t.Fatal("or/y is not priced free: the fixture tests nothing") + } + for _, g := range []Group{ + {Name: "WB Free", Members: []string{"free:workbuddy/*"}}, + {Name: "All Free", Match: []string{"free:*"}}, + {Name: "WB", Match: []string{"workbuddy/*"}}, + {Name: "OR Free", Match: []string{"or/*:free"}}, + } { + if err := SaveGroup(g); err != nil { + t.Fatalf("%s: %v", g.Name, err) + } + } + wbFree := []string{"workbuddy/hy4free", "workbuddy/hy3", "workbuddy/hy4flash-exp4"} + g, _, _ := FindGroup("group/wb-free") + if !slices.Equal(g.Match, []string{"free:workbuddy/*"}) || !slices.Equal(g.Members, wbFree) { + t.Fatalf("free:workbuddy/*: match %v members %v (served %v)", g.Match, g.Members, IDs()) + } + if got := routedIDs(t, "group/wb-free"); !slices.Equal(got, wbFree) { + t.Fatalf("routed: %v", got) + } + if hits := PatternHits(g); len(hits) != 1 || hits[0].Models != 3 { + t.Fatalf("hits: %+v", hits) + } + if got := routedIDs(t, "group/all-free"); !slices.Equal(got, append(slices.Clone(wbFree), "cline/cline-free/mimo-v2.6-flash")) { + t.Fatalf("free:*: %v", got) + } + // the rules there before are as they were + if got := routedIDs(t, "group/wb"); len(got) != len(wb) { + t.Fatalf("workbuddy/*: %v", got) + } + if got := routedIDs(t, "group/or-free"); !slices.Equal(got, []string{"or/x:free"}) { + t.Fatalf("or/*:free: %v", got) + } + // the next catalog: hy3 free no longer, hy5 new and free, hy4free gone + listWorkBuddy([]plugin.Model{ + {ID: "hy3", Name: "Hy3", Rate: 0.5}, + {ID: "hy4flash-exp4", Name: "Hy4 Flash Exp4", Free: true}, + {ID: "hy5", Name: "Hy5", Free: true}, + }) + if got := routedIDs(t, "group/wb-free"); !slices.Equal(got, []string{"workbuddy/hy4flash-exp4", "workbuddy/hy5"}) { + t.Fatalf("after the catalog changed: %v", got) + } +} + +// A free: rule is said as a pattern and kept as typed, magpie/ and spaces +// trimmed; one naming nothing, or free: twice, is refused. A provider's +// AutoInclude, over ids alone, reads free: as it did before. +func TestFreeRuleSyntax(t *testing.T) { + if !IsPattern("free:workbuddy/hy3") || !IsPattern("free:re:workbuddy/hy.*") { + t.Error("IsPattern") + } + got, err := CleanPatterns([]string{" free: magpie/workbuddy/* ", "free:re:workbuddy/hy.*", "free:workbuddy/*"}) + if err != nil || !slices.Equal(got, []string{"free:workbuddy/*", "free:re:workbuddy/hy.*"}) { + t.Fatalf("clean: %v %v", got, err) + } + for _, p := range []string{"free:", "free: ", "free:free:x/*", "free:re:x/(a"} { + if _, err := CleanPatterns([]string{p}); err == nil { + t.Errorf("%q taken", p) + } + } + if !PatternMatches("free:workbuddy/*", "workbuddy/hy3") || PatternMatches("free:workbuddy/*", "cline/hy3") { + t.Error("PatternMatches over a free rule's scope") + } + if _, err := CleanAutoInclude([]string{"free:x"}); err == nil { + t.Error("an auto-include rule over ids took free:x") + } +} diff --git a/site/public/docs/ja/routing-groups.html b/site/public/docs/ja/routing-groups.html index eec19a622..618eb717b 100644 --- a/site/public/docs/ja/routing-groups.html +++ b/site/public/docs/ja/routing-groups.html @@ -193,7 +193,7 @@

ルーティンググループは異なるプロバイダーのモデルをまとめます。たとえば Claude サブスクリプションの Opus と Copilot の Opus、あるいは複数の無料モデルです。エージェントはモデルとして group/<id> を選び、magpie はグループのルーティングとルールに従って各リクエストを送ります。グループは ルーティング ページの ルーティンググループ にあり、新しいグループ で作ります。

  1. magpie が自分でグループを見つける二つ以上のプロバイダーが提供するモデルは自動でグループ(auto-<モデル>)になり、設定は不要です。不要なら グループを自動で作成 をオフにします。
  2. -
  3. 入れられるものprovider/model で書いた任意のモデル、別のグループ(8 段まで)、パターン。openrouter/*:free なら後から増える無料モデルも入ります。
  4. +
  5. 入れられるものprovider/model で書いた任意のモデル、別のグループ(8 段まで)、パターン。openrouter/*:free なら後から増える無料モデルも入ります。パターンの前に free: を付けると、直近のカタログで無料とされたモデルだけになります(例: free:workbuddy/*)。カタログの表示であり、課金されない保証ではありません。
  6. グループのルーティング上のものに加えて、重み付け(モデルごとの重み)と 手動(選んだモデルだけ、切り替えなし)があります。
  7. ルールターンの長さ、画像の有無、求められた推論の強さ、エージェントで、ターンを最初にどのモデルへ送るかを決めます。
diff --git a/site/public/docs/routing-groups.html b/site/public/docs/routing-groups.html index 935d5abb0..70ade8324 100644 --- a/site/public/docs/routing-groups.html +++ b/site/public/docs/routing-groups.html @@ -193,7 +193,7 @@

A routing group puts models from different providers together: Opus from a Claude subscription and from Copilot, say, or several free models. An agent picks group/<id> as its model, and magpie sends each request as the group's routing and rules say. Groups are under Routing groups on the Routing page; New group makes one.

  1. magpie finds groups by itselfA model two or more of your providers serve becomes a group of them (auto-<model>), with nothing to set. Switch off Find groups on their own if you don't want them.
  2. -
  3. What goes inAny model as provider/model, another group (up to 8 deep), or a pattern: openrouter/*:free takes in free models the vendor adds later too.
  4. +
  5. What goes inAny model as provider/model, another group (up to 8 deep), or a pattern: openrouter/*:free takes in free models the vendor adds later too. free: before a pattern keeps only the models the last catalog marks free, as in free:workbuddy/*: the vendor's flag, not a promise of no charge.
  6. A group's routingBesides the ones above, a group can go By weight (each model's weight) or Manual (only the model you pick, with no failover).
  7. RulesWhich model a turn goes to first, by its length, an image, the reasoning asked for or the agent.
diff --git a/site/public/docs/zh/routing-groups.html b/site/public/docs/zh/routing-groups.html index 13f6ecf64..e590c6bc5 100644 --- a/site/public/docs/zh/routing-groups.html +++ b/site/public/docs/zh/routing-groups.html @@ -193,7 +193,7 @@

路由组把不同供应商的模型放在一起,比如官方 Claude 订阅里的 Opus 和 Copilot 里的 Opus,或者几个免费模型。Agent 选 group/<id> 作为模型,magpie 按组的路由方式和规则决定每个请求交给谁。组在 路由 页的 路由组 里,用 新建组 创建。

  1. magpie 自己会找组两个及以上供应商都提供的模型,自动成为一个组(auto-<模型>),不用设置。不想要可以关掉 自动创建路由组。
  2. -
  3. 组里放什么任意模型,用 provider/model 写;也可以放另一个组(最多 8 层),或者用通配符:openrouter/*:free 会把以后新出的免费模型也加进来。
  4. +
  5. 组里放什么任意模型,用 provider/model 写;也可以放另一个组(最多 8 层),或者用通配符:openrouter/*:free 会把以后新出的免费模型也加进来。模式前加 free: 只保留最近一次目录标为免费的模型,如 free:workbuddy/*;这是厂商目录的标记,不保证不扣费。
  6. 组的路由方式除了上面几种,组还有 按权重(按每个模型的权重)和 手动(只用你选的那个,不切换)。
  7. 规则可以按一轮的长度、是否带图、要求的推理强度或 Agent,决定一轮先交给哪个模型。