Commit Graph
8 Commits
Author SHA1 Message Date
keeuu 75e769a9f9 routing: Free first spends the models that cost nothing before the ones that spend (#3054)
A provider or group can be routed `free`. Seats whose model the vendor
serves at no cost to the allowance or credits go first, in listed order.
The rest follow, also in listed order. Free means the vendor's own
catalog.Model.Free word, or else a $0 list price on every count
(provider.FreeModel). A pool with no free model behaves as In order.

routes.Seat gains Free and Strategy gains ByFree. weighRouted works Free
out only for a strategy that weighs by it, so other routings never read
a model list for it.

It is wired through every list a routing appears in:
- both save whitelists;
- plugins/rotation's Builtin;
- app.js's ROUTINGS (appScriptBudget 1,269,000 → 1,271,000 for the
  description) and the Routing page's options, hints and trace text;
- zh-TW, ja and de strings;
- the TUI's routings;
- the CLI's aliases (free, free-first).

Written by keeuu (issue #3054, three commits), squashed onto dee5c9d75
and reviewed:
- the harm checks were clean;
- FreeModel runs only for ByFree, so its Available() walk costs nothing
  for other routings;
- accounts can list different models, so Free first means something for
  a provider's own accounts too, not only for groups.

Run at this head:
- gofmt -l: clean.
- go vet: darwin (internal/routes, provider, gateway, cli, tui, gui);
  GOOS=windows ./internal/...; GOOS=linux -tags nogui ./... — all clean.
- go test ./internal/routes ./internal/provider -run
  'Free|Routing|Strateg|Builtin' ok; ./internal/gateway -run
  'FreeFirst|Weigh|Routing' ok.
- Broken by hand: with FreeFirst returning paid before free,
  internal/routes' Free tests and
  TestFreeFirstGroupSpendsTheFreeMemberFirst go red. Restored, green.
- go test ./... -count=1 -timeout 45m, at load average ~460 from other
  sessions: 62 packages ok, 3 red:
  - internal/gui TestMainWindowCorners (#1936/#2645, AppKit window
    killed at its deadline under load);
  - internal/gateway TestClaudeAccountsSpentFallBackToCodex ("no
    answer"): ok alone in 46s;
  - internal/agent timed out at 45m inside TestSnowSmallModel (1s in):
    the package is ok alone in 1519s.
- GUI, both engines (node --test, playwright 1.62.0), 23 files:
  account-arrange, builtins, context-text, context-scroll-end,
  context-window, group-member-weight, key-weight, rate-limited-sink,
  routing-reset-deadline, routing-compaction, routing-key-windows,
  routing-save, routing-sealed-task, routing-weight-chip, search-keys,
  i18n-keys, panel-routing-pick, panel-routing-providers, panel-routing,
  routing-columns, gui-de, gui-ja, gui-zh-tw. 230 of 236 pass.
  routing-save (the 6/7 counts), routing-columns, i18n-keys and the three
  language files are green.
  - account-arrange "every mode" (#2200): red in both engines, alone,
    and on origin/main dee5c9d75 too.
  - builtins chromium "Plugins › Built-in" (#2960): a 5s wait for the
    Plugins page. Red alone and on dee5c9d75 too; the webkit run checks
    the new Routing strategies subtitle and passes.
  - context-window and context-text, single cases in different
    language/engine pairs on each run: 5s waits under load (#1544,
    #2900). Untouched by this change.

Co-authored-by: keeuu <159448501+keeuu@users.noreply.github.com>
2026-10-20 20:08:25 +08:00
yetone 81a24cf8fe groups: a found group is listed as auto/<model id as the vendor spells it>
ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.

What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
  public one). Every old form is still accepted as input forever:
  provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
  gateway (validateModel), keys, stats, affinity and usage, so both ids
  route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
  (allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
  exists, found groups are listed by their old id (AutoRefsOn) and
  auto/<x> means that provider's model. Documented in
  docs/subsystems/gateway-routing.md.

Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).

Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.

Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
  nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
  gateway, whose failures were the tests' expected ids (updated here)
  and two regressions now fixed (bare ids; desktop models hiding groups
  by prefix). Every failing test passes on rerun. Load average was
  ~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
  TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
  10.19s), and it fails the same in a git-archive export of 33dbdcc52.
- agent and gateway in full, -p 2 -timeout 120m: gateway ok (2996s).
  agent failed four tests that still expected the old ids
  (TestOmp/PiModelsAskedOnTheirNativeAPI, TestReseatFoundGroupsOff,
  TestReseatKeepsAFoundGroupWithAProviderOff); updating them showed the
  Reseat bug above. After the fix, go test -count=1 -timeout 120m
  ./internal/agent/: ok (1000s, load ~160-220).
- GUI files the change reaches, chromium and webkit: group-found-off and
  the routing files pass, except routing-bodies, routing-model-rest,
  routing-keys-fold and routing-request-metrics, which fail the same with
  33dbdcc52's JS.

Broken by hand and watched red, then restored: CanonicalRef in
validateModel (both-ids routing test), allows() (key tests both ways),
the Save refusal and AutoRefsOn checks in Ref/CanonicalRef (provider
named auto), catalog.Lists' preference (models.dev lookup of the part
after auto/), renameFoundGroups' applied.json check and its SyncCatalog
call (user values kept), PublicRef in visible.go, the codexcat prefix,
samePick in Reseat (TestReseatFoundGroupsOff: opus left on the gone
group).
TestBareModelIDsShared was red before the bare.go fix.

Not verified: no real agent, vendor or models.dev client run; no run on
the Windows box. Settings pickers (vision, title model) holding a saved
group/auto-... value may show it as saved. codexcat can't tell a stored
"auto" provider apart, so its models lose the "text only" hint. The
pre-existing reds above are not filed.
2026-10-20 00:18:51 +08:00
yetone 3f913b3de6 plugins: a JS gateway plugin serves routings (strategies) and watches usage rows (onUsage); plugins/middleware is "JS gateway plugins" (P4)
A plugin's gateway module (magpie.middleware, or its alias magpie.gateway,
or a *.gateway.js file) may now export, besides onRequest/onEvent/onResponse:

- strategies: {name: (pool, seats, options) => order}. Each is a routing
  "<short name>/<name>", registered with routes.Register while the plugin is
  on and loaded and removed when it goes off or reloads. Seats are
  routes.Seat in camelCase JSON. 20ms each; it fails open: a throw, a timeout
  or a result that isn't an order of the seats means the listed order. The
  failure is counted and logged, rate-limited. A file's name is made into a
  routing-safe prefix.
- onUsage(row, options): gets an allow-listed usage row (no bodies, prompts,
  error text, sessions or request ids). The rows come from a bounded queue
  (1024) with one worker, off the request path; a full queue drops the row
  and counts it, and a request never waits. 250ms each.

plugins/middleware is renamed "JS gateway plugins", with a new Sub
(en/zh/zh-TW/ja/de). It registers usage.Observe(middleware.Points()). Off,
no JS hook, strategy or onUsage runs. InUse is unchanged.

providers.json keeps a routing of the form <plugin>/<name> as saved
(provider.PluginRouting) in provider and group Save, whether or not a
plugin serves it now. Before this, `group set g routing=pick/last`
stored nothing.

GUI: the settings state carries jsRoutings. Provider and group routing
pickers offer the served ones, marked data-feature=middleware. A saved
routing that no plugin serves now shows as it is, with a hint. The
Plugins page's line shows routings, how often they were asked, onUsage
rows and dropped rows. The CLI accepts `group set <id> routing=<plugin>/<name>`.
`magpie plugin` lists a module's routings and onUsage; a strategy-only
module had printed nothing after "gateway middleware".

Docs: docs/subsystems/gateway-middleware.md (Routings and usage rows,
limits, verification) and plugin-runtime.md (P4: community plugins at
every point). site/public/docs plugins.html in en, zh and ja has an
example: internal/middleware/testdata/spread.gateway.js, which
TestDocsExample runs.

What was run (worktree on 4df1ba0c6, -p 2):
- gofmt -l: clean. go vet on internal/{middleware,cli,gui,plugin,provider}
  and plugins/...: darwin, GOOS=linux -tags nogui, GOOS=windows; all
  clean, run after the last Go change.
- go test, after the last Go change: internal/middleware ok,
  plugins/middleware ok, internal/provider ok (210s), internal/cli ok
  (203s). Earlier in the work: internal/plugin ok (385s), internal/pluginrt
  ok, internal/gui (Go) ok (320s), and plugins/... ok. The first
  plugins/... run printed a bare FAIL line that `tail` cut off before its
  cause showed. The rerun was all ok; the cause is unknown.
- GUI, both engines (routing-*, group-*, builtins, i18n-keys, gui-de/ja/zh-tw,
  plugin-middleware): 1220 tests, 1204 pass, 16 fail.
  - routing-manual (4): mine. A group's own "manual" was offered a second
    time as a routing no plugin serves. Fixed in client.js withJS. The
    coordinator is rerunning routing-manual, keys-fold, group-fold,
    intent-entry and routing-js alone in both engines, so that rerun is
    not recorded here.
  - routing-model-rest: red alone too, and red on untouched 4df1ba0c6
    (3/20). It is #2115; I commented there with the webkit cases.
  - group-member-weight webkit de 420 is #2387.
  - group-from-model-add webkit zh: it passes alone 2 of 2. Under load it
    waits a fixed 2s for the save post. Filed as #2388.
  - routing-keys-fold (webkit zh/ja/de), routing-group-fold (goto timeout)
    and routing-intent-entry (browser launch timeout 180s) are load
    timeouts. The coordinator is rerunning them alone.
- routing-js.test.cjs (new) passed in chromium en and zh, before the full run.

Broken by hand, each test went red, then restored:
- the permutation check: TestStrategyFailsOpen;
- the queue's non-blocking send: TestOnUsageNeverBlocks ("Ledger waited
  2.04s");
- the allow-list: TestUsageRowAllowList;
- unregister on off: TestStrategiesServedWhileOn and
  TestStrategiesStopWithServe;
- the CLI pattern: TestParseRoutingStays;
- Observe in plugins/middleware: TestOnServesStrategies;
- PluginRouting in provider.go and in group.go: TestPluginRoutingKept;
- the prefix sanitizing: TestRoutingFromFileName;
- the CLI list line: TestPluginListSaysMiddleware;
- the GUI's data-feature mark and its unserved-saved entry: routing-js.

Real use: a sandbox HOME, the gateway served on 127.0.0.1:3682 by a
-tags nogui build, a fake vendor on 3681, and providers fa (key ka) and
fb (key kb) in group g. pick.gateway.js has strategy last (reverse) and an
onUsage that logs.
- `group set g routing=pick/last` stored it.
- A request to group/g reached the vendor with Bearer kb, and the
  "usage-row fb m in=5 keys=17" line was logged.
- `plugin off pick.gateway.js`: Bearer ka (listed order), no onUsage,
  routing still pick/last.
- `plugin on`: Bearer kb and onUsage again.
- `plugin builtin off middleware` says "in use and stays on", as InUse
  should.
- Not tried: the GUI against that gateway, or a real vendor account.
2026-10-15 22:36:59 +08:00
yetone 8ef14be3e6 gateway: an effort=auto group leaves a turn the agent sent with reasoning none alone and asks no classifier, so its pick and what went out agree (#2247, sryimnoob123)
The classifier's pick was recorded but never applied when the agent asked for none, costing a classifier call per turn. The outer effort in the routing record is what the agent asked; the effort sent is tries[].effort on the try marked picked:true, which the groups help now says. Thanks to ggbdpq for the reproduction.

Run at this head (on 6485056e1, with the #2245/#2246/#2247 fixes together): gofmt -l clean; go vet ./... for darwin and windows, and linux -tags nogui; the full go test ./... in a sandbox HOME, all green. The new test fails on the old code and passes with the fix.
2026-10-15 04:46:57 +08:00
yetone c4e6abf3cc gui, cli: a model id typed with a space in it stays one model, "Opus 5.5" not Opus and 5.5 (#1976)
elonnzhang on #1976: on a Baidu OneAPI relay, typing `Opus 5.5` in the
provider editor's add box (or the add form's Models field) and pressing
Enter added two models, `Opus` and `5.5`. Both read the box with
split(/[,\s]+/), while their hints say "comma separated".

- app.js: one typedIds() for both, split at commas (and line breaks)
  with each id trimmed. chosenIds() (the add box, and an id left in it
  at Save) and the add form's Models field use it.
- CLI siblings, which split the same way: `magpie provider set
  models=` now splits at commas only. A group's models=, models-=,
  fast= and weight= split at commas, and an item with a space that
  names no model the group can have is still split at its spaces, so
  `models=m,b/x a/m` (TestApplyGroupPairs) still works. levels= and
  `magpie visible` (effort levels and family names) are unchanged.
- Tests: the reporter's two GUI assertions in models-add-and-icons
  (from their fork branch). A new model-id-space.test.cjs covers both
  boxes in en, zh, zh-TW, ja and de, Chromium and WebKit, at 1100 and
  420 wide. TestModelIDsKeepTheirSpace covers the CLI. The fork's change
  to provider-add-models.test.cjs is not taken: filling the Models field
  there replaces the picks it holds, so it failed on its own terms.

Run: on the old split, model-id-space fails (4/4 for en and de at 420
in Chromium) and TestModelIDsKeepTheirSpace fails (models = ["Opus"
"5.5" ...]). With the whole-item check forced off, it fails on members.
With the fix: model-id-space 40/40, models-add-and-icons 4/4 and
provider-add-models 4/4 pass. `go test -tags nogui ./internal/cli` is
ok. gofmt is clean, and go vet passes for darwin, linux (-tags nogui)
and windows.
Not tried: a real relay with a spaced model id served end to end.
2026-10-13 18:16:03 +08:00
yetone eba7187368 gateway, provider, cli, gui: a group can route By weight, each member's share set beside it (#1910, DD on Discord)
DD asked for weighted round robin as a group routing, next to In turn.
A provider's keys could already route by weight (#841). Groups could not.

What changes:
- provider: Group.Weights maps a member's spelling to its weight, 1 to
  1000. A member left out, or set to 0, weighs 1. SaveGroup accepts
  routing "weight". It also cleans weights the way it cleans fast and
  off: it strips :fast, drops weights of members that are gone and of
  members weighing 1, and refuses a weight below 0 or above 1000.
  Weights follow a member when it is renamed (RenameMember, Rename,
  RenameGroup) and survive Share/Import.
- gateway: planLevel treats each member of a weight-routed group as one
  unit: a model with its keys in its provider's order, or a nested group
  routed its own way. weightedUnits orders the units by smooth WRR on a
  round per group ("group/<id>"), sharing wrrPick with the keys. The
  round's pick goes first and the rest stay in member order for
  failover. A unit whose head is resting leaves the round. When a
  conversation is kept on another member (session/turn/cache/strict),
  the charge moves to that member (wrrSeat, wrrMove).
- cli: routing=weight (also weighted, wrr). weight=<model>=<n>[,...]
  sets weights and keeps the rest; weight= on its own clears them. The
  group view shows "· weight N" for each member.
- tui: By weight is in the group routing list.
- gui: the group editor offers By weight. Each member then shows
  "Weight N · S%", its share among the members that are on. Clicking it
  edits the number in place: Enter or blur keeps it, Escape cancels,
  and a value outside 1 to 1000 shows a warning. The trace header uses
  group wording for a weight-routed group. Strings are added in zh,
  zh-TW, ja and de.
- docs: reference.md, gateway-routing.md, and site start pages in en,
  zh and ja.

Run:
- go test -tags nogui ./internal/provider ./internal/cli ./internal/tui:
  ok.
- ./internal/gateway: ok in 988s with -timeout 45m. The first run hit
  the default 10m timeout at load average ~170. The test running at
  that moment had been running for 2s; it was not a hang.
- go vet -tags nogui on those packages, for darwin, GOOS=linux and
  GOOS=windows: clean. gofmt -l: clean.
- New group-member-weight.test.cjs: 8/8 in Chromium and WebKit, en and
  zh at 1100, en and de at 420. The WebKit de 420 case also passed six
  runs at once.
- gui-zh-tw, gui-ja, gui-de, i18n-keys, routing-*, group-*,
  panel-routing*, settings-groups and agent-model-groups: all green
  except two.
  - routing-steady (WebKit) is #1804. It is red 2/3 alone on origin/main
    e1b70c13d too.
  - routing-save-blank (chromium en) was red under load only, and 3/3
    green alone. The overshoot in its wheel loop is filed as #1924.

Broken by hand, each red, then restored:
- byWeight forced false:
  --- FAIL: TestWeightedGroup (weighted_group_test.go:69 its turn ...)
- cleanWeights call skipped:
  --- FAIL: TestSaveGroupWeights (groupweight_test.go:39 weights map[...
  an/claude-opus-5-5:0 ... oa/gpt-6.1-sol:high:fast:3 ...])
- CLI weight case renamed:
  --- FAIL: TestGroupWeightCLI (unknown field "weight")
- GUI chip not appended: group-member-weight chromium en 1100 timed out
  on the weight button.
- Not red: the test's "moved nothing" check. A scroll forced on click,
  or padding added above, did not turn it red, because the view's own
  scroll guard and scroll anchoring hold the clicked row in place. It
  only shows that the row stays under the pointer.

Not tried: real accounts through a running gateway. The routing is
proven by the plan-level test with synthetic providers only.
2026-10-13 13:10:30 +08:00
yetone 908c910931 gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)
miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.

The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
  goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
  capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
  moving;
- one removed, turned off, barred or not allowed for the key counts as
  gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.

Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).

Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
  ./internal/provider ./internal/tui ./internal/cli: ok. The three
  TestStrictAffinity* tests fail on the code before this commit (200
  where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
  zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
  fails 15 of 15 in chromium. routing-*.test.cjs pass but for
  routing-steady's webkit 1.69px shift, which fails on the old assets
  too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
  the push.

Not tried: a real agent conversation held on a real rate-limited
account.

Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.
2026-10-12 23:16:54 +08:00
yetone 23e764d0e0 cli: magpie's commands move from the root into internal/cli; the root keeps only main.go
The root held 89 .go files (30 commands, 59 tests). They move as they are
to internal/cli (package cli), with git mv so history follows them. The
only code change is main() becoming cli.Main(version): the root's new
main.go keeps `var version` in package main, so -ldflags "-X
main.version=…" in the Makefile, the Dockerfile and magpie-releases, and
every workflow, work unchanged. go-winres's rsrc_windows_*.syso still land
next to package main in the root.

Tests that read testdata by a root-relative path now go up one level
(../plugin/testdata/fake, ../sessions/testdata). Five subsystem doc links
point at internal/cli/.

Run:
- go build ./..., gofmt -l, go vet on darwin, linux and windows (nogui)
- builds with tags production, dev, "production nogui"; windows
  -H windowsgui; linux CGO_ENABLED=0
- make release-cli TARGETS="darwin/arm64 linux/amd64 windows/amd64
  android/arm64" VERSION=9.9.9-tidy: all four built, binary prints
  "magpie 9.9.9-tidy"
- docker build --build-arg VERSION=7.7.7-tidy: container prints
  "magpie 7.7.7-tidy"
- go test ./internal/cli (default and nogui): 152 tests, the same count
  as the root on main
- go test ./...: all packages pass (agent, gateway, library, provider
  timed out at 10m under other sessions' load and passed rerun alone
  with -timeout 40m; none of them changed)
- the built binary in a sandbox HOME: version, help, ls, providers,
  claude, and an unknown command's error
2026-10-12 20:40:22 +08:00