plugin, gateway: a plugin reports its models' load, and busy models can go last (axelburks on Discord)

axelburks (Discord #feedback): an in-house vendor queues requests to
its busy models, and the plugin could only put the load in the model's
name, which changed only when magpie re-read the list.

- A provider plugin calls input.magpie.load(provider, {"<model id>":
  0-100 | null}) whenever it likes, from its own timer. host.js
  (reportLoad) clamps each number to 0-100, null clears a model, every
  other value is dropped, at most 1000 a call, and it returns the count
  taken. A provider that isn't a string or loads that isn't an object
  throws a TypeError. It goes to Go as an unasked {event:"load"}.
- internal/plugin/load.go keeps each by provider and lowercased model
  id. ModelLoad answers unknown once a load is older than LoadFresh
  (5 minutes), never idle. model@size falls back to its model.
- The provider editor shows it by the model as a grey ctx badge
  ("87%", titled "87% busy now, as its plugin says").
- Settings > Network and sharing > Busy models last (settings.BusyLoad,
  POST /api/settings/busy-load, Off by default, over 50/70/80/90% or
  1-99 by hand): restLast puts a model reported over it behind the
  ready candidates, ahead of the resting. The trace row has busy:<load>.
  At a new turn affine moves a conversation off it (Why "busy",
  busyBehind); within a turn it stays. after, readyForNew and leastHeld
  skip it. Unknown load, a lone candidate, or all busy: nothing moves.
- Docs: site plugins page (en, zh, ja) "Model load" section and input
  table; docs/subsystems provider-plugins.md and gateway-routing.md.

Run, all on mote via mote-run at a42736807's tree rebased on
origin/main b683f1c0e:
- go test ./internal/plugin ./internal/gateway -run
  'ModelLoad|TestBusy' -v: TestPluginReportsModelLoad,
  TestModelLoadGoesStale, TestBusyModelGoesBehind,
  TestBusyModelNotKeptAtNewTurn pass.
- Broken by hand, each red: host.js not sending the event
  (TestPluginReportsModelLoad "the plugin's loads never arrived"), the
  busy case off in restLast (TestBusyModelGoesBehind order), the affine
  "busy" case off (TestBusyModelNotKeptAtNewTurn "kept true, why
  session").
- go test ./internal/gui -run Budget: ok. No budget raised. app.js
  +86 bytes, two comments trimmed to fit. The settings row lives in
  plugins/gateway/settings.js.
- node --test model-load, i18n-keys, bare-ids, model-rate: 69/69 pass.
  model-load is Chromium and WebKit, 420 and 900 wide, en zh zh-TW ja
  de.
- gofmt -l: empty. go vet ./... (darwin), GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go build: ok.

Not run before the push (owner: push and tag first): go test ./...
-timeout 45m and the whole GUI suite. mote and the WSL box were each
running another session's full suite. Both run next, and any red gets
its own commit.
Not tried: a real plugin and vendor reporting load. The plugin side is
tested through the real Bun host with a plugin written in the test.
This commit is contained in:
yetone
2026-11-01 13:45:40 +08:00
parent b683f1c0e1
commit 8d8df06399
22 changed files with 777 additions and 34 deletions
+1
View File
@@ -206,6 +206,7 @@ recorded as a prediction failure (`noPrediction`).
- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.
- A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X, `OnMasked` in [`masked.go`](../../internal/gateway/masked.go), set by the GUI; nil under `magpie serve`), after `maskrec.Hold` and with its text around placeholders (`Snips`, `Back`) taken out. [`mask_alert.go`](../../internal/gui/mask_alert.go) keeps the records while `settings.MaskAlert` is on (off until turned on, in Settings → Usage, hidden with masking) and says only the values a record masked for the first time (`maskrec.Fresh`, [`first.go`](../../internal/maskrec/first.go): each placeholder by the key of the first record that had it, read from memory and the days kept, so a conversation's history sent again each turn, or after a restart, is not news; a value sent as written is not one masked). A burst is gathered for `maskGather` (3s) and said as one, and one is said at most every `maskGap` (1 minute), what came in between said after it. It says each kind with its count and up to two agents, never a value nor its hint; a click opens the Masking page on the latest record (`clickView`, `masking&key=`). A held-back request (`noteBlocked`) is not said; a value whose records have all aged out (30 days) is new again. `TestFreshOnlyTheFirstTime`, `TestMaskAlertFirstTimeOnly`, `TestMaskAlertNeverSaysTheValue`, `TestMaskAlertCoalesces`, `mask-alert.test.cjs`.
- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do, and so does the last account left (a Codex or other subscription account; `quotaHeld` still holds keys alone, and `autoReset` lifts the rest of an account it spends a reset of): before, an account last in an in-order group, out of its quota, was never rested, so every request a relay ahead of it failed for a moment went on to it and ended on its 429 (dbydd on Discord; `TestGroupSpentLastAccountRests`). Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.
- A model its plugin reports busier than the user's *Busy models last* (`settings.BusyLoad`, 1 to 99, off by default; axelburks on Discord) goes behind the ready candidates, ahead of the resting ones (`restLast`, `busyOf`), and its trace row has `busy` with the load. The load comes from the plugin through `plugin.ModelLoad` (see [provider plugins](provider-plugins.md#a-models-load)); one not reported in the last 5 minutes is unknown and keeps its place. A lone candidate is asked whatever its load. A conversation it answered moves, at its next turn, to the ready one that leads (`affine`'s Why `busy`, `busyBehind`); within a turn it stays. A turn going round (`after`), a new conversation spread (`readyForNew`) or In turn (`leastHeld`) never lands on it past a ready one. When every candidate is busy, nothing moves.
- A key resting after an outage that names no time is asked again in the background (`rest_probe.go`, heatonz on Discord). Behind ready keys, `probeOne` never asks it before its rest ends, though its vendor may be back in a minute. `restAfterMarked` marks the rest `Probed` when it is a key's own (not an account's or a plugin's, not one model's `restID`), `failOther` by `backoff` after a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whose `List` asks over the network (`Provider.ListAsks`), and long enough for a first ask. `keepProbingRests`, started in `ListenAndServe`, then asks the vendor's model list with that key through its proxy (`Provider.List`, which saves nothing) 1, 2, 5 and then every 10 minutes into the rest, while it is the same rest. When the list answers, the rest is lifted as Try now lifts it (`liftedLocked`, `unsink`, the trace's lift). Not asked: rate limits (a list answers while the chat endpoint still refuses, and lifting one early would undo Sink), quota, credit, a Retry-After or reset, a refused key (401, 403, 400), restrictions and verification, each of which ends on its own time or the vendor's. A key a probe lifted that fails again within 30 minutes isn't asked again until it answers a request (`probeMissed`, `probeAnswered` in `served`): the list answered for the vendor, not for its chat. Only the loop's own `Server` asks (`restProbes.asking`), so a test's `Server` never reaches the network. The cost is one list per resting key per step, never one per request. The key list (`KeyRest.Probed`) and Routing's words for the try (`restHow`) add "checked in the background, back as soon as it answers". `TestRestProbeLiftsAKeyBackUp`, `TestRestProbeLeavesOtherRests`, `TestRestProbeOnlyByARunningLoop`, `rest-probed.test.cjs`.
- A provider whose keys are on different plans (`KeyAccount.Plan`, `PlansMixed`; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through `WithKey`, which moves it there (`atKeyPlan`), on the first try and on a failover alike. `perKeyBarred` leaves out a key whose plan's list lacks the model (`PlanServing`: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same `perKeyBarred` and `WithKey`; a video started on a mixed provider names its key in the task id (`videoStart.onKey`, `keyMark`) so its poll goes to that key's plan. `TestKeyPlansEachToItsOwnEndpoint`.
- A subscription's account whose own model list lacks the model (`Account.Lists`: an Antigravity account's `fetchAvailableModels`, a plugin account's `models`) isn't planned while another of its accounts lists it (`perKeyBarred`'s `left`, `planned.unlisted`, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (`unservedTry`: `modelRefused`, or Code Assist's 404 NOT_FOUND, `codeAssistModelMissing`), before any later member or fallback (`unlistedNext`, `askUnlisted` moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (`allowedCandidates`). `TestUnlistedAccountAskedAfterModelRefused`, `TestUnlistedAccountNotAskedForOtherRefusals`.
+8
View File
@@ -76,6 +76,14 @@ The user's values are kept in `settings.PluginOptions` by the plugin's own provi
The provider's editor lists them under *Plugin options* (`pluginOptionsField` in [`app.js`](../../internal/gui/assets/app.js), the values from `/api/providers`' `plugins[].options[].on`), an Off/On each beside the plugin's label and description, put in as text, in the window's language (`optionWords`: its `labels`/`descriptions`/`confirms` by the language, then by its first part, so zh-TW reads zh, else the plain one). One with `confirm` asks it before it is turned on. Changes wait for Save, which posts each changed one before the provider. While an option that says `filtersModels` is on, as saved (the list was read with it), the Models field says so under the chips (`pluginFilterNote`): "Only some models are listed: the plugin option “…” is on.", with the option's label in the window's language. Off, or with no such option, nothing is said.
## A model's load
A plugin can say how busy each model is (axelburks on Discord: an in-house vendor queues requests to its busy models, and a load put in the model's name changed only when the list did). It calls `input.magpie.load(provider, {"<model id>": 0–100 | null})` whenever it likes, from its own timer, as usage data refreshes; magpie never asks. The host ([`host.js`](../../internal/plugin/host.js) `reportLoad`) throws a TypeError for a provider that isn't a string of 1–200 characters or a `loads` that isn't a plain object, clamps each finite number to 0–100, sends `null` as -1 (cleared), drops every other value and an id over 200 characters, takes at most 1000, and sends what is left as an unasked `{event:"load", provider, loads}` (`dispatch` in [`host.go`](../../internal/plugin/host.go)). It returns how many it took.
[`load.go`](../../internal/plugin/load.go) keeps each by the plugin's provider id and the model id lowercased, with when it came (`noteLoads`, at most 1000 a provider). `ModelLoad(provider, model, now)` answers it, a model@size falling back to its model, and unknown once it is older than `LoadFresh` (5 minutes): a plugin that stops reporting leaves its models unknown, never idle. Nothing is saved; a restart starts with none known.
The provider editor shows it by the model as a grey badge (`/api/providers`' `models[].load`, `loadTag` in app.js). Routing reads it only when the user sets *Busy models last* (`settings.BusyLoad`, `POST /api/settings/busy-load {at}`, off by default): see `restLast` and `busyBehind` in [gateway routing](gateway-routing.md).
## A plugin whose upstream searches
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api relay, say) can say its upstream answers a web search tool by itself (#2027). Its `config` hook sets `searches: true` on the provider; the host passes it through (`plugin.Provider.Searches`), and [`pluginProvider`](../../internal/provider/plugins.go) sets the provider's `Searches`, as a custom provider's "Searches the web by itself" does (#359). [`searchesItself`](../../internal/gateway/search.go) honours it for a plugin's provider only, on Anthropic's or Responses' API, and only for one the plugin has a model on: a client's `web_search` then goes to the plugin's `fetch` as sent, not through magpie's search. Another sign-in's `Searches` is never read, and Codex's and Grok's stay as they were. As with a relay, `searchRank` leaves it out, so magpie never picks it to search for other models; Settings can name it by hand (`namedSearcherRank`).
+19 -3
View File
@@ -120,6 +120,8 @@ type Affinity struct {
// at a new turn: backFromStandIn), "credits" (a Codex account gone
// onto its credits answered it, set to spend them only after
// everything else, and one not on its credits leads: lastBehind),
// "busy" (its plugin says the model is busier than settings.BusyLoad
// and one that isn't leads, at a new turn: busyBehind),
// "strict" (Stays: Strict, kept whatever it is).
Why string `json:"why"`
// Main is, for a conversation kept strictly on a provider's fallback,
@@ -596,6 +598,12 @@ func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, fr
// has cached, the conversation goes to one not on its credits,
// within a turn too, as that is what the credits would pay for
a.Why = "credits"
case !a.Within && busyBehind(pl.order, at):
// its plugin says the model is busy past the user's BusyLoad,
// and one that isn't leads: the next turn goes there rather than
// wait in the vendor's queue (axelburks on Discord). Within a
// turn it stays, on the reasoning it sealed for the tool loop
a.Why = "busy"
case !a.Within && backToMain(pl.order, at):
// a provider's fallback is its emergency path, not a place a
// conversation stays: once one of the provider's own keys or
@@ -821,7 +829,7 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can
seat := func(c candidate) string { return c.who() + "/" + provider.WithMemberEffort(c.model, c.effort) }
best := -1
for i, c := range cs {
if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || lastBehind(pl.order, i) || ready && i > 0 && !readyForNew(pl.order, i) {
if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || lastBehind(pl.order, i) || busyBehind(pl.order, i) || ready && i > 0 && !readyForNew(pl.order, i) {
continue
}
if best < 0 || held[seat(c)] < held[seat(cs[best])] {
@@ -847,7 +855,7 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can
// lowShare.
func readyForNew(order []Weighed, i int) bool {
w := order[i]
return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare) && !lastBehind(order, i)
return w.Rest == nil && !w.Aside && !standsIn(order, i) && !(w.Known && w.Used >= lowShare) && !lastBehind(order, i) && !busyBehind(order, i)
}
// standsIn says whether order[i] is a provider's fallback while one of the
@@ -862,6 +870,14 @@ func standsIn(order []Weighed, i int) bool {
return i < len(order) && order[i].Fallback && !order[0].Fallback
}
// busyBehind says whether order[i] is a model its plugin says is busy
// (Weighed.Busy) while one that isn't leads: restLast put it behind the
// ready ones, and spreading conversations or taking turns never brings
// it forward past them.
func busyBehind(order []Weighed, i int) bool {
return i > 0 && i < len(order) && order[i].Busy > 0 && order[0].Busy == 0
}
// lastBehind says whether order[i] is a Codex account on its credits set
// to spend them last (Weighed.CreditsLast) while one that isn't leads:
// restLast put it behind every such one, and spreading a conversation or
@@ -919,7 +935,7 @@ func spreadsSessions(mode, routing string) bool {
func after(cs []candidate, pl planned, at int) ([]candidate, planned) {
for d := 1; d < len(cs); d++ {
i := (at + d) % len(cs)
if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || lastBehind(pl.order, i) {
if pl.order[i].Rest != nil || pl.order[i].Aside || standsIn(pl.order, i) || lastBehind(pl.order, i) || busyBehind(pl.order, i) {
continue // a turn goes round the keys routed over only
}
if i > 0 {
+133
View File
@@ -0,0 +1,133 @@
package gateway
import (
"net/http"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
func busyLoadAt(t *testing.T, at int) {
t.Helper()
s := settings.Load()
was := s.BusyLoad
s.BusyLoad = at
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
s := settings.Load()
s.BusyLoad = was
settings.Save(s)
})
}
// A model its plugin says is busier than settings.BusyLoad goes behind
// the ready candidates, ahead of those resting after a failure
// (axelburks on Discord: an in-house vendor queues requests to its busy
// models). One with no load reported, or one older than
// plugin.LoadFresh, keeps its place; so does every one with the setting
// off, as it is by default.
func TestBusyModelGoesBehind(t *testing.T) {
plugin.ForgetLoads()
t.Cleanup(plugin.ForgetLoads)
now := time.Now()
plugin.NoteLoadsForTest("inhouse", map[string]float64{"big": 92, "mid": 60}, now)
plugin.NoteLoadsForTest("inhouse", map[string]float64{"old": 99}, now.Add(-plugin.LoadFresh-time.Minute))
p := provider.PluginForTest("inhouse-plugin", "inhouse")
c := func(model string) candidate { return candidate{p: p, model: model, rest: "inhouse-plugin/" + model} }
resting := candidate{p: provider.Provider{ID: "down"}, model: "m", rest: "down-busy-test"}
restingUntil.Lock()
restingUntil.m[resting.restKey()] = time.Now().Add(time.Minute)
restingUntil.Unlock()
t.Cleanup(func() { restingUntil.Lock(); delete(restingUntil.m, resting.restKey()); restingUntil.Unlock() })
order := func() ([]string, []float64) {
in := []candidate{c("big"), c("mid"), resting, c("old"), c("none")}
out, pl := restLast(in, planned{order: make([]Weighed, len(in))})
var got []string
var busy []float64
for i, x := range out {
got = append(got, x.rest)
busy = append(busy, pl.order[i].Busy)
}
return got, busy
}
same := func(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
off := []string{"inhouse-plugin/big", "inhouse-plugin/mid", "inhouse-plugin/old", "inhouse-plugin/none", "down-busy-test"}
if got, _ := order(); !same(got, off) {
t.Fatalf("off: %v, want %v", got, off)
}
busyLoadAt(t, 80)
want := []string{"inhouse-plugin/mid", "inhouse-plugin/old", "inhouse-plugin/none", "inhouse-plugin/big", "down-busy-test"}
got, busy := order()
if !same(got, want) {
t.Fatalf("over 80: %v, want %v", got, want)
}
if busy[3] != 92 || busy[0] != 0 || busy[1] != 0 {
t.Fatalf("the trace's Busy = %v", busy)
}
busyLoadAt(t, 50)
want = []string{"inhouse-plugin/old", "inhouse-plugin/none", "inhouse-plugin/big", "inhouse-plugin/mid", "down-busy-test"}
if got, _ := order(); !same(got, want) {
t.Fatalf("over 50: %v, want %v", got, want)
}
// a lone candidate is tried whatever its load
if out, pl := restLast([]candidate{c("big")}, planned{order: make([]Weighed, 1)}); len(out) != 1 || pl.order[0].Busy != 0 {
t.Fatalf("lone: %+v", pl.order)
}
}
// A conversation a model answered that has since gone busy goes to the
// ready one that leads at its next turn, whatever it cached; within a
// turn it stays, on the reasoning it sealed. A turn going round, or a new
// conversation spread, never lands on the busy one past a ready one.
func TestBusyModelNotKeptAtNewTurn(t *testing.T) {
p := provider.PluginForTest("inhouse-plugin", "inhouse")
cs := []candidate{{p: p, model: "mid", rest: "inhouse-plugin/mid"}, {p: p, model: "big", rest: "inhouse-plugin/big"}}
pl := planned{order: []Weighed{{Who: "mid"}, {Who: "big", Busy: 92}}}
h := http.Header{}
h.Set("x-claude-code-session-id", "busy-load-kept")
turn := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
within := []byte(`{"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"f","arguments":"{}"}}]},{"role":"tool","tool_call_id":"c1","content":"ok"}]}`)
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, turn, turn, cs, pl)
answered(key, cs[1], 1, Usage{CacheRead: 50_000})
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, within, within, cs, pl)
if got[0].rest != "inhouse-plugin/big" || !aff.Kept {
t.Fatalf("within a turn: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
}
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, turn, turn, cs, pl)
if got[0].rest != "inhouse-plugin/mid" || aff.Kept || aff.Why != "busy" {
t.Fatalf("a new turn: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
}
// every one busy: kept where it was
both := planned{order: []Weighed{{Who: "mid", Busy: 85}, {Who: "big", Busy: 92}}}
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, turn, turn, cs, both)
if got[0].rest != "inhouse-plugin/big" || !aff.Kept {
t.Fatalf("all busy: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
}
if got, _ := after(append([]candidate(nil), cs...), planned{order: append([]Weighed(nil), pl.order...)}, 0); got[0].rest != "inhouse-plugin/mid" {
t.Fatalf("turn went to %s", got[0].rest)
}
if readyForNew(pl.order, 1) {
t.Fatal("a new conversation may go to the busy one")
}
}
+26 -5
View File
@@ -30,6 +30,7 @@ import (
"sync"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -1083,7 +1084,10 @@ func asideOf(cs []candidate, q provider.Provider, fallback bool, from provider.P
// restLast moves those resting after a recent failure behind the rest,
// and a Codex account set to spend its credits last that has gone onto
// them (creditsLast) behind both, those in their own order.
// them (creditsLast) behind both, those in their own order. Ahead of the
// resting, a model its plugin says is busier than the user's
// settings.BusyLoad (busyOf) goes behind the ready ones: it answers, only
// after a wait in its vendor's queue (axelburks on Discord).
func restLast(out []candidate, pl planned) ([]candidate, planned) {
if len(out) == 1 {
if r, ok := restingOf(out[0]); ok {
@@ -1093,25 +1097,42 @@ func restLast(out []candidate, pl planned) ([]candidate, planned) {
return out, pl
}
now := time.Now()
var ready, resting, last []candidate
var wReady, wResting, wLast []Weighed
over := settings.Shared().BusyLoad
var ready, busy, resting, last []candidate
var wReady, wBusy, wResting, wLast []Weighed
for i, c := range out {
r, isResting := restingOf(c)
if isResting {
pl.order[i].Rest = &r
}
load, isBusy := busyOf(c, over, now)
switch {
case c.creditsLast(now):
pl.order[i].CreditsLast = true
last, wLast = append(last, c), append(wLast, pl.order[i])
case isResting:
resting, wResting = append(resting, c), append(wResting, pl.order[i])
case isBusy:
pl.order[i].Busy = load
busy, wBusy = append(busy, c), append(wBusy, pl.order[i])
default:
ready, wReady = append(ready, c), append(wReady, pl.order[i])
}
}
pl.order = append(append(wReady, wResting...), wLast...)
return append(append(ready, resting...), last...), pl
pl.order = append(append(append(wReady, wBusy...), wResting...), wLast...)
return append(append(append(ready, busy...), resting...), last...), pl
}
// busyOf is the load c's plugin last reported for its model, and whether
// that is over the percent over (settings.BusyLoad; 0 is off). A model
// with no load reported, or none within plugin.LoadFresh, isn't busy:
// unknown is never taken for idle nor for busy.
func busyOf(c candidate, over int, now time.Time) (float64, bool) {
if over <= 0 {
return 0, false
}
load, _, ok := plugin.ModelLoad(c.p.PluginProvider(), c.model, now)
return load, ok && load > float64(over)
}
// probeOne keeps, of the candidates resting after a failure, only the one
+4
View File
@@ -345,6 +345,10 @@ type Weighed struct {
// to spend them only after everything else: tried after every
// candidate not on its credits (restLast)
CreditsLast bool `json:"creditsLast,omitempty"`
// Busy: the load its plugin reported for the model, a percent over
// the user's settings.BusyLoad, so it was tried after every ready
// candidate that isn't (restLast)
Busy float64 `json:"busy,omitempty"`
// Rank: its place in its provider's own list of accounts or keys, the
// order the provider's page shows and a drag sets (#217); routing may
// weigh them in another
+19
View File
@@ -1498,6 +1498,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
// how agents' lists name models, set on its own for the agents to be told
in.PlainNames, in.PlainOwnNames = cur.PlainNames, cur.PlainOwnNames
in.BareModelIDs = cur.BareModelIDs // set on its own (bare-ids below)
in.BusyLoad = cur.BusyLoad // and so is this (busy-load below)
in.CodexAgentsV1 = cur.CodexAgentsV1
in.FullContext = cur.FullContext // set on its own (full-context below)
in.CompactAt = cur.CompactAt // and so is the threshold
@@ -1744,6 +1745,24 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, settingsState())
})
// the load over which a model its plugin says is busy goes behind
// the others (settings.BusyLoad, axelburks on Discord): 0 for off
mux.HandleFunc("POST /api/settings/busy-load", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ At int }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
s := settings.Load()
if s.BusyLoad != in.At {
s.BusyLoad = in.At
if err := settings.Save(s); err != nil {
fail(rw, err)
return
}
}
writeJSON(rw, settingsState())
})
// whether Codex's OpenAI models say multi-agent V1 (#141): Codex's lists
// are written again and asked for again
mux.HandleFunc("POST /api/settings/codex-agents-v1", func(rw http.ResponseWriter, r *http.Request) {
+12 -6
View File
@@ -5252,6 +5252,14 @@ function rateTag(rate = 0, was = 0) {
return tag;
}
// loadTag: how busy its plugin says the model is now (magpie.load)
function loadTag(n) {
if (n == null) return null;
const g = el("span", "badge ctx", Math.round(n) + "%");
g.title = t("{n}% busy now, as its plugin says", { n: Math.round(n) });
return g;
}
// modelTells: what tells apart the models of one list that would show the
// same label (sunset on Discord). items are the list's entries, label(x)
// what each shows, id(x) its id, and key(x) the part of the list it is
@@ -11163,9 +11171,7 @@ function renderModels(p) {
for (const m of p.models) {
const on = draft.chosen.includes(m.id);
if (f && !m.id.toLowerCase().includes(f) && !(m.name || "").toLowerCase().includes(f) && !(m.default || "").toLowerCase().includes(f)) continue;
// past the first 80 only the picked are drawn, till the rest are
// asked for: a picked model is never out of sight (#685: 10 picked,
// 7 shown, and "4 more, filter to find them" with no names to filter by)
// past the first 80 only the picked are drawn, till the rest are asked for (#685)
if (picksOnly && !on) { unpicked++; continue; }
if (shown >= 80 && !f && !showAll && !on) { hidden++; continue; }
const c = el("button", "mchip pick" + (on ? " on" : served.has(m.id) ? " auto" : "") + (noAPI(m) ? " noapi" : ""));
@@ -11178,11 +11184,11 @@ function renderModels(p) {
if (free) c.append(el("span", "badge free", t("free")));
const rate = rateTag(m.rate, m.rateWas);
if (rate) c.append(rate);
const load = loadTag(m.load);
if (load) c.append(load);
const ctx = contextTag(m.context, m.name);
if (ctx) c.append(ctx);
// the number Claude Desktop's menu says beside this model, which it
// names after its own catalog (#2578), so a row of that menu can be
// matched to this provider
// the number Claude Desktop's menu says beside this model (#2578)
if (m.desktop) {
const d = el("span", "badge ctx", m.desktop);
d.title = t("The number Claude Desktop's menu shows beside this model");
+16
View File
@@ -3242,6 +3242,10 @@ const I18N = {
"Network and sharing": "网络与共享",
"Model ids without the provider": "不带供应商的模型 ID",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "网关的模型列表还会以模型自己的 ID 列出每个模型,如 codex/gpt-5.6-sol 旁的 gpt-5.6-sol,供从其他代理迁来的应用使用。多个供应商都提供的模型,按“供应商”中的顺序发往它们",
"Busy models last": "繁忙的模型靠后",
"A model its plugin says is busier than this goes after the others a request could go to, as its vendor makes it wait. One with no load reported in the last 5 minutes keeps its place": "插件报告负载高于此值的模型,排在请求可去的其他模型之后,因为它的供应商会让请求排队等待。最近 5 分钟内没有报告负载的模型保持原位",
"Over {n}%": "高于 {n}%",
"{n}% busy now, as its plugin says": "插件报告当前负载 {n}%",
"Session terminal": "会话终端",
"The terminal a session opens in": "打开会话时使用的终端",
"System default ({name})": "系统默认({name})",
@@ -7550,6 +7554,10 @@ const I18N = {
"Network and sharing": "網路與共享",
"Model ids without the provider": "不帶供應商的模型 ID",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "閘道的模型列表還會以模型自己的 ID 列出每個模型,如 codex/gpt-5.6-sol 旁的 gpt-5.6-sol,供從其他代理遷來的應用使用。多個供應商都提供的模型,按「供應商」中的順序發往它們",
"Busy models last": "繁忙的模型靠後",
"A model its plugin says is busier than this goes after the others a request could go to, as its vendor makes it wait. One with no load reported in the last 5 minutes keeps its place": "外掛回報負載高於此值的模型,排在請求可去的其他模型之後,因為它的供應商會讓請求排隊等待。最近 5 分鐘內沒有回報負載的模型保持原位",
"Over {n}%": "高於 {n}%",
"{n}% busy now, as its plugin says": "外掛回報目前負載 {n}%",
"Session terminal": "會話終端機",
"The terminal a session opens in": "開啟會話時使用的終端機",
"System default ({name})": "系統預設({name})",
@@ -11869,6 +11877,10 @@ const I18N = {
"Network and sharing": "ネットワークと共有",
"Model ids without the provider": "プロバイダなしのモデル ID",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "ゲートウェイのモデル一覧に、各モデルを自身の ID でも載せます(codex/gpt-5.6-sol の隣に gpt-5.6-sol)。ほかのプロキシから移ってきたアプリ向けです。複数のプロバイダが提供するモデルは「プロバイダ」の順に送られます",
"Busy models last": "混雑しているモデルを後回しに",
"A model its plugin says is busier than this goes after the others a request could go to, as its vendor makes it wait. One with no load reported in the last 5 minutes keeps its place": "プラグインがこの値より混雑していると報告したモデルは、リクエストの送り先になるほかのモデルの後に回します。ベンダーの順番待ちになるためです。直近 5 分間に負荷の報告がないモデルは元の位置のままです",
"Over {n}%": "{n}% 超",
"{n}% busy now, as its plugin says": "プラグインの報告では現在 {n}% の負荷",
"Session terminal": "セッション用ターミナル",
"The terminal a session opens in": "セッションを開くターミナル",
"System default ({name})": "システムのデフォルト({name})",
@@ -16199,6 +16211,10 @@ const I18N = {
"Network and sharing": "Netzwerk und Freigabe",
"Model ids without the provider": "Modell-IDs ohne Anbieter",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "Die Modellliste des Gateways nennt jedes Modell auch bei seiner eigenen ID, etwa gpt-5.6-sol neben codex/gpt-5.6-sol, für Apps, die von einem anderen Proxy kommen. Ein Modell, das mehrere Anbieter bereitstellen, geht an sie in der Reihenfolge unter Anbieter",
"Busy models last": "Ausgelastete Modelle zuletzt",
"A model its plugin says is busier than this goes after the others a request could go to, as its vendor makes it wait. One with no load reported in the last 5 minutes keeps its place": "Ein Modell, das laut seinem Plugin stärker ausgelastet ist als dieser Wert, kommt nach den anderen, an die eine Anfrage gehen könnte, da sein Anbieter sie warten lässt. Ein Modell ohne gemeldete Last in den letzten 5 Minuten behält seinen Platz",
"Over {n}%": "Über {n} %",
"{n}% busy now, as its plugin says": "laut seinem Plugin gerade zu {n} % ausgelastet",
"Session terminal": "Sitzungs-Terminal",
"The terminal a session opens in": "Das Terminal, in dem eine Sitzung öffnet",
"System default ({name})": "Systemstandard ({name})",
+4
View File
@@ -405,6 +405,10 @@
<div class="who"><div class="name" data-t>Model ids without the provider</div><div class="sub" data-t>The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order</div></div>
<div id="bareIdsSegs"></div>
</div>
<div class="row pref" id="busyLoadRow">
<div class="who"><div class="name" data-t>Busy models last</div><div class="sub" data-t>A model its plugin says is busier than this goes after the others a request could go to, as its vendor makes it wait. One with no load reported in the last 5 minutes keeps its place</div></div>
<div id="busyLoadSegs"></div>
</div>
</div>
<div class="row-head"><span class="label" data-t>Local network</span></div>
<div class="list prefs" id="lanList"></div>
@@ -78,11 +78,25 @@ function renderPort(s) {
// lists each model by its own id as well, gpt-5.6-sol beside
// codex/gpt-5.6-sol. Posted on its own; off by default.
function renderBareIds(s) {
renderBusyLoad(s); // the row under it
$("#bareIdsSegs").replaceChildren(segs([[false, t("Off")], [true, t("On")]], !!s.bareModelIDs, (on) =>
writingPrefs(api("settings/bare-ids", { on })).then((ns) => { prefs = state.settings = ns; renderSettings(); })
.catch((e) => { status(t(e.message), "err"); renderSettings(); })));
}
// renderBusyLoad: the load past which a model its plugin says is busy
// (magpie.load) goes behind the others (settings.BusyLoad, axelburks on
// Discord); one set in settings.json to another number is shown too
function renderBusyLoad(s) {
const at = s.busyLoad || 0;
const opts = [0, 50, 70, 80, 90];
if (!opts.includes(at)) opts.push(at);
opts.sort((a, b) => a - b);
$("#busyLoadSegs").replaceChildren(segs(opts.map((n) => [n, n ? t("Over {n}%", { n }) : t("Off")]), at, (n) =>
writingPrefs(api("settings/busy-load", { at: n })).then((ns) => { prefs = state.settings = ns; renderSettings(); })
.catch((e) => { status(t(e.message), "err"); renderSettings(); })));
}
// renderCORS: the web pages whose scripts may call the gateway from a
// browser (#1051), by origin — a row to add one, and one row each to take
// it away. A page listed calls with a gateway key; none listed, no page
+26 -19
View File
@@ -19,6 +19,7 @@ import (
"github.com/yetone/magpie/internal/autostart"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
@@ -38,25 +39,28 @@ type modelJSON struct {
Given bool `json:"given,omitempty"` // its levels aren't known: Efforts are those it can be given, Kept those it was
// Reasonless: the user said it takes no reasoning ask
// (provider.SetModelReasonless): none of Efforts is kept, and none is sent
Reasonless bool `json:"reasonless,omitempty"`
Images bool `json:"images"` // agents are told it can see images
ImageSet bool `json:"imageSet,omitempty"` // the user said so, rather than its vendor
Own bool `json:"ownImages,omitempty"` // its vendor's answer, which a staged Restore default shows
On bool `json:"on"` // exposed to agents
Best bool `json:"best,omitempty"` // the newest of its family in the list: what Best in family serves (provider.NewestInFamily)
Context int `json:"context,omitempty"` // the window agents are told: the user's, else Listed
Output int `json:"output,omitempty"` // the reply limit agents are told: provider.ReplyLimit within Context (provider.OutputWithin)
Listed int `json:"listed,omitempty"` // its window before the user's: its vendor's list's, else models.dev's
Max int `json:"max,omitempty"` // the most its context may be set to, above Listed
Free bool `json:"free,omitempty"` // costs the subscription nothing
Rate float64 `json:"rate,omitempty"` // the credits a request costs the subscription, as a multiple
RateWas float64 `json:"rateWas,omitempty"` // the rate before a discount running now
API string `json:"api,omitempty"` // the one API the user said it is asked on
Auto []string `json:"auto,omitempty"` // the APIs its vendor's list says it is served on, what Auto asks it on
NoAPI bool `json:"noAPI,omitempty"` // the provider has a URL for none of them: agents aren't offered it (provider.NoAPIFor, #2094)
Same string `json:"same,omitempty"` // the model the user said it is the same as, for the groups magpie finds (#583)
Merge string `json:"merge,omitempty"` // what those groups merge it by when the user says nothing
Kind string `json:"kind,omitempty"` // what the user said it makes: image or video (#1399)
Reasonless bool `json:"reasonless,omitempty"`
Images bool `json:"images"` // agents are told it can see images
ImageSet bool `json:"imageSet,omitempty"` // the user said so, rather than its vendor
Own bool `json:"ownImages,omitempty"` // its vendor's answer, which a staged Restore default shows
On bool `json:"on"` // exposed to agents
Best bool `json:"best,omitempty"` // the newest of its family in the list: what Best in family serves (provider.NewestInFamily)
Context int `json:"context,omitempty"` // the window agents are told: the user's, else Listed
Output int `json:"output,omitempty"` // the reply limit agents are told: provider.ReplyLimit within Context (provider.OutputWithin)
Listed int `json:"listed,omitempty"` // its window before the user's: its vendor's list's, else models.dev's
Max int `json:"max,omitempty"` // the most its context may be set to, above Listed
Free bool `json:"free,omitempty"` // costs the subscription nothing
Rate float64 `json:"rate,omitempty"` // the credits a request costs the subscription, as a multiple
RateWas float64 `json:"rateWas,omitempty"` // the rate before a discount running now
// Load is how busy its plugin last said the model is, a percent, when
// that was within plugin.LoadFresh (magpie.load); nil when unknown
Load *float64 `json:"load,omitempty"`
API string `json:"api,omitempty"` // the one API the user said it is asked on
Auto []string `json:"auto,omitempty"` // the APIs its vendor's list says it is served on, what Auto asks it on
NoAPI bool `json:"noAPI,omitempty"` // the provider has a URL for none of them: agents aren't offered it (provider.NoAPIFor, #2094)
Same string `json:"same,omitempty"` // the model the user said it is the same as, for the groups magpie finds (#583)
Merge string `json:"merge,omitempty"` // what those groups merge it by when the user says nothing
Kind string `json:"kind,omitempty"` // what the user said it makes: image or video (#1399)
// Vendor is the provider's own id of a model the user lists by
// another (provider.SetModelID), "" for one listed by its own; IDs
// says the provider's models can be given ids at all (a key's)
@@ -844,6 +848,9 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
}
window := p.WindowOf(m)
j := modelJSON{ID: m.ID, Name: m.Name, Efforts: provider.EffortsOf(m), On: on, Context: window, Output: provider.OutputWithin(window, p.ReplyLimitIn(m, set)), Listed: provider.ListedWindow(m), Max: m.MaxContext, Free: m.Free, Rate: m.Rate, RateWas: m.RateWas, Images: images, ImageSet: imageSet, Own: own, Best: newest[m.ID]}
if l, _, ok := plugin.ModelLoad(p.PluginProvider(), m.ID, time.Now()); ok {
j.Load = &l
}
if i := slices.IndexFunc(most, func(c catalog.Model) bool { return c.ID == m.ID }); j.Max == 0 && i >= 0 {
j.Max = most[i].MaxContext
}
+184
View File
@@ -0,0 +1,184 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A model's load, as its plugin reports it (magpie.load, axelburks on
// Discord: our vendor's busy models make requests queue, and the load put
// in the model's name only changed when the list did): a small grey
// number by the model on the provider editor's chips, its title saying
// what it is; a model with no load reported shows none. And Settings ›
// Network and sharing › Busy models last: Off by default, a threshold
// posted on its own as settings/busy-load, one set in settings.json to
// another number shown as picked, no click scrolling the page. Every
// language, Chromium and WebKit, at a narrow and a wide window; no
// backend, the API is faked here.
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 { watchSettingsReads, settingsDrawn, wheelTo } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const fetched = new Date(Date.now() - 3600e3).toISOString();
const inhouse = {
id: "inhouse", name: "In-house", icon: "generic", host: "llm.example.com", chat: "https://llm.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [
{ id: "big", name: "Big", on: false, load: 87.4 },
{ id: "small", name: "Small", on: false, load: 0 },
{ id: "quiet", name: "Quiet", on: false },
],
chosen: [], fetched, agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
};
function settingsPayload(over) {
return {
theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd",
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "",
version: "0.1.1220", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
proxyNow: "none", proxySource: "none", login: false,
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lan: false, lanURLs: [],
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
...over,
};
}
function server(lang, posted, over = {}) {
let cur = settingsPayload({ lang, ...over });
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx });
if (url.pathname === "/api/providers") return json({ providers: [inhouse], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/settings/busy-load") {
const body = req.postDataJSON();
posted.push(["busy-load", body]);
cur = { ...cur, busyLoad: body.at };
return json(cur);
}
if (url.pathname === "/api/settings") {
if (req.method() === "POST") posted.push(["settings", req.postDataJSON()]);
return json(cur);
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const want = {
en: { busy: "87% busy now, as its plugin says", idle: "0% busy now, as its plugin says", name: "Busy models last", off: "Off", over: (n) => `Over ${n}%`, sub: "last 5 minutes" },
zh: { busy: "插件报告当前负载 87%", idle: "插件报告当前负载 0%", name: "繁忙的模型靠后", off: "关闭", over: (n) => `高于 ${n}%`, sub: "5 分钟" },
"zh-TW": { busy: "外掛回報目前負載 87%", idle: "外掛回報目前負載 0%", name: "繁忙的模型靠後", off: "關閉", over: (n) => `高於 ${n}%`, sub: "5 分鐘" },
ja: { busy: "プラグインの報告では現在 87% の負荷", idle: "プラグインの報告では現在 0% の負荷", name: "混雑しているモデルを後回しに", off: "オフ", over: (n) => `${n}% 超`, sub: "5 分間" },
de: { busy: "laut seinem Plugin gerade zu 87 % ausgelastet", idle: "laut seinem Plugin gerade zu 0 % ausgelastet", name: "Ausgelastete Modelle zuletzt", off: "Aus", over: (n) => `Über ${n} %`, sub: "5 Minuten" },
};
const view = (page) => page.locator("#view-settings").evaluate((v) => v.scrollTop);
async function open(engine, width, t, name) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 420 }, reducedMotion: "reduce" })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${name}.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
return page;
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [420, 900]) {
for (const lang of Object.keys(want)) {
const w = want[lang];
test(`${engine} ${width} ${lang}: a model's load shows by it`, async (t) => {
const page = await open(engine, width, t, `${lang}-model-load`);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, []));
await page.goto("http://magpie.test/?view=providers");
const editor = page.locator("#modal:not([hidden]) .editor");
await page.locator(".row.provider", { hasText: "In-house" }).click();
await editor.locator(".mchips .mchip").first().waitFor();
const chips = await editor.locator(".mchips .mchip").evaluateAll((cs) => cs.map((c) => {
const b = [...c.querySelectorAll(".badge")].find((x) => /%$/.test(x.textContent));
return [c.querySelector("span").textContent, b ? [b.textContent, b.title] : null];
}));
assert.deepEqual(chips, [["Big", ["87%", w.busy]], ["Small", ["0%", w.idle]], ["Quiet", null]]);
// grey and small as the context badge, no colour of its own
const look = await editor.locator(".mchip .badge", { hasText: "87%" }).evaluate((b) => {
const s = getComputedStyle(b), ctx = document.createElement("span");
ctx.className = "badge ctx";
b.parentNode.append(ctx);
const c = getComputedStyle(ctx), out = [s.color === c.color, s.backgroundColor === c.backgroundColor, s.fontSize, s.backgroundImage];
ctx.remove();
return out;
});
assert.deepEqual(look, [true, true, "9px", "none"]);
const border = await page.evaluate(() => [...document.querySelectorAll(".mchip, .mchip *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1));
assert.deepEqual(border, [], "no border stripes");
assert(await editor.evaluate((e) => e.scrollWidth <= e.clientWidth + 1), "the editor scrolls sideways");
assert.deepEqual(errors, []);
});
test(`${engine} ${width} ${lang}: busy models go last, or not`, async (t) => {
const page = await open(engine, width, t, `${lang}-busy-load`);
const errors = [], posted = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posted));
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=network");
await settingsDrawn(page);
const segs = page.locator("#busyLoadSegs .opt");
await segs.first().waitFor();
const row = page.locator("#busyLoadRow");
assert(await row.isVisible(), "the row is drawn");
assert.equal((await row.locator(".name").textContent()).trim(), w.name);
assert((await row.locator(".sub").textContent()).includes(w.sub), "the sub says how long a load counts");
assert.deepEqual((await segs.allTextContents()).map((s) => s.trim()), [w.off, w.over(50), w.over(70), w.over(80), w.over(90)]);
assert.equal(await segs.nth(0).evaluate((b) => b.classList.contains("on")), true, "off by default");
assert.equal(await row.locator("select").count(), 0, "no native select");
assert(await page.locator("#view-settings").evaluate((v) => v.scrollWidth <= v.clientWidth + 1), "the settings scroll sideways");
const rb = await row.boundingBox(), sb = await page.locator("#busyLoadSegs").boundingBox();
assert(sb.x + sb.width <= rb.x + rb.width + 1, "the switch runs out of its row");
await wheelTo(page, segs.nth(3), 200);
const before = await view(page);
await segs.nth(3).click();
await page.locator("#busyLoadSegs .opt.on", { hasText: w.over(80) }).waitFor();
await page.waitForTimeout(400);
assert.equal(await view(page), before, "the click scrolled the page");
assert.deepEqual(posted, [["busy-load", { at: 80 }]]);
await segs.nth(0).click();
await page.locator("#busyLoadSegs .opt.on", { hasText: w.off }).waitFor();
assert.deepEqual(posted, [["busy-load", { at: 80 }], ["busy-load", { at: 0 }]]);
assert.equal(await view(page), before, "the click scrolled the page");
assert.deepEqual(errors, []);
});
}
}
}
test("a threshold set by hand is shown as picked", async (t) => {
const page = await open(process.env.BROWSER || "chromium", 900, t, "busy-load-own");
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server("en", [], { busyLoad: 75 }));
await page.goto("http://magpie.test/?view=settings&tab=network");
const segs = page.locator("#busyLoadSegs .opt");
await segs.first().waitFor();
assert.deepEqual((await segs.allTextContents()).map((s) => s.trim()), ["Off", "Over 50%", "Over 70%", "Over 75%", "Over 80%", "Over 90%"]);
assert.equal((await page.locator("#busyLoadSegs .opt.on").textContent()).trim(), "Over 75%");
assert.deepEqual(errors, []);
});
+5
View File
@@ -63,6 +63,9 @@ type message struct {
Title string `json:"title"`
Variant string `json:"variant"`
Count int `json:"count"`
// Loads is a "load" event's models and how busy each is, a percent;
// -1 clears one (magpie.load in host.js)
Loads map[string]float64 `json:"loads"`
}
type callState uint8
@@ -1178,6 +1181,8 @@ func (h *host) dispatch(m message) {
// account's lapse into logins.json (#1935)
tell(func() { f(m.Provider, m.Account, m.Said) })
}
case "load":
noteLoads(m.Provider, m.Loads, time.Now())
case "toast":
log.Printf("plugin: %s %s", m.Title, m.Message)
case "log":
+27 -1
View File
@@ -1264,7 +1264,7 @@ async function loadPlugins(list) {
// magpie's own (OpenCode has none): the plugin's options as the user
// set them in magpie, read when wanted, so a change reaches the
// plugin without a restart (#2038)
magpie: { option: optionValue, options: optionValues },
magpie: { option: optionValue, options: optionValues, load: reportLoad },
}
// pi's packages and extensions are loaded as pi loads them (pi.js)
let pi
@@ -1955,6 +1955,32 @@ function optionValues(provider) {
return out
}
// reportLoad is magpie.load(provider, loads): how busy each of the
// provider's models is now, as a plugin knows from its vendor, for the
// model list to show and routing to weigh (axelburks on Discord). loads
// maps a model id to a percent, 0 to 100 (as a usage window's used), or
// to null to say it isn't known any more. Called whenever the plugin
// likes, from its own timer: a model's load counts for five minutes from
// the call that reported it, so a plugin that stops calling leaves its
// models unknown, never idle. It returns the count of models taken.
const LOAD_MODELS = 1000
function reportLoad(provider, loads) {
if (typeof provider !== "string" || !provider || provider.length > 200) throw new TypeError("magpie.load: provider must be a provider id")
if (!loads || typeof loads !== "object" || Array.isArray(loads)) throw new TypeError("magpie.load: loads must map model ids to a number from 0 to 100, or null")
const out = {}
let n = 0
for (const [id, v] of Object.entries(loads)) {
if (n >= LOAD_MODELS) break
if (!id || id.length > 200) continue
if (v === null) out[id] = -1 // cleared
else if (typeof v === "number" && Number.isFinite(v)) out[id] = Math.min(100, Math.max(0, v))
else continue
n++
}
if (n) send({ event: "load", provider, loads: out })
return n
}
// optionValue is one of provider's options as it stands; false for a key
// its plugin doesn't declare.
function optionValue(provider, key) {
+98
View File
@@ -0,0 +1,98 @@
package plugin
import (
"strings"
"sync"
"time"
)
// LoadFresh is how long a model's load counts from the plugin's call that
// reported it (magpie.load in host.js). Past it the load is unknown: a
// plugin that stopped reporting says nothing of how busy the vendor is
// now, and routing never takes its silence for idle.
const LoadFresh = 5 * time.Minute
// loadModels caps the models one provider keeps a load for, as host.js
// caps one call's; a plugin reporting new ids every call can't grow it.
const loadModels = 1000
type modelLoad struct {
pct float64
at time.Time
}
// loads are the models' loads the plugins reported, by plugin provider
// id and then by the model id lowercased.
var loads = struct {
sync.Mutex
m map[string]map[string]modelLoad
}{m: map[string]map[string]modelLoad{}}
// noteLoads keeps a "load" event's models: each a percent from 0 to 100,
// -1 clearing it. Models the event doesn't name keep theirs, each till
// its own LoadFresh runs out.
func noteLoads(provider string, got map[string]float64, now time.Time) {
if provider == "" || len(got) == 0 {
return
}
loads.Lock()
defer loads.Unlock()
m := loads.m[provider]
if m == nil {
m = map[string]modelLoad{}
loads.m[provider] = m
}
for id, v := range got {
k := strings.ToLower(id)
if v < 0 || v != v {
delete(m, k)
continue
}
m[k] = modelLoad{pct: min(v, 100), at: now}
}
if len(m) > loadModels {
for k, l := range m {
if now.Sub(l.at) > LoadFresh || len(m) > loadModels {
delete(m, k)
}
}
}
if len(m) == 0 {
delete(loads.m, provider)
}
}
// ModelLoad is how busy the plugin provider's model is, a percent from
// 0 to 100 as its plugin last reported it, and when (a model@size has its
// model's load unless reported itself); ok is false when the
// plugin never reported it, cleared it, or reported it more than
// LoadFresh before now.
func ModelLoad(provider, model string, now time.Time) (pct float64, at time.Time, ok bool) {
if provider == "" || model == "" {
return 0, time.Time{}, false
}
k := strings.ToLower(model)
loads.Lock()
l, ok := loads.m[provider][k]
if i := strings.LastIndexByte(k, '@'); !ok && i > 0 {
// grok-4.7@256k is the model grok-4.7 at a context size: as busy
l, ok = loads.m[provider][k[:i]]
}
loads.Unlock()
if !ok || now.Sub(l.at) > LoadFresh {
return 0, time.Time{}, false
}
return l.pct, l.at, true
}
// NoteLoadsForTest is a "load" event's loads reported at at, for a test.
func NoteLoadsForTest(provider string, got map[string]float64, at time.Time) {
noteLoads(provider, got, at)
}
// ForgetLoads drops every load reported, for a test.
func ForgetLoads() {
loads.Lock()
loads.m = map[string]map[string]modelLoad{}
loads.Unlock()
}
+94
View File
@@ -0,0 +1,94 @@
package plugin
import (
"context"
"os"
"path/filepath"
"testing"
"time"
)
// A plugin reports its models' loads through input.magpie.load (axelburks
// on Discord: an in-house vendor's busy models queue requests), when it
// likes, from its own timer: magpie keeps each, a percent within 0 to 100,
// matched by id whatever its case, and a null clears one. What isn't a
// number is dropped, and a call that isn't a provider and a map throws.
func TestPluginReportsModelLoad(t *testing.T) {
sandbox(t)
ForgetLoads()
t.Cleanup(ForgetLoads)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
dir := filepath.Join(t.TempDir(), "loadco")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
src := `export default async (input) => {
let threw = 0
for (const bad of [[5, {}], ["loadco", null], ["loadco", [1]], ["", {}]]) {
try { input.magpie.load(...bad) } catch (e) { if (e instanceof TypeError) threw++ }
}
const n = input.magpie.load("loadco", { Big: 87.5, small: 0, over: 250, under: -3, word: "busy", nan: NaN, inf: Infinity, threw })
input.magpie.load("loadco", { taken: n })
setTimeout(() => input.magpie.load("loadco", { small: null, later: 12 }), 50)
return {}
}
`
if err := os.WriteFile(filepath.Join(dir, "index.js"), []byte(src), 0o644); err != nil {
t.Fatal(err)
}
if _, err := Add(ctx, filepath.Join(dir, "index.js")); err != nil {
t.Fatal(err)
}
if ls, err := Plugins(ctx); err != nil || len(ls) != 1 || ls[0].Error != "" {
t.Fatalf("Plugins = %+v, %v", ls, err)
}
// the timer's call comes last: once it is in, so is everything before it
for {
if _, _, ok := ModelLoad("loadco", "later", time.Now()); ok {
break
}
if ctx.Err() != nil {
t.Fatal("the plugin's loads never arrived")
}
time.Sleep(10 * time.Millisecond)
}
now := time.Now()
for model, want := range map[string]float64{"big": 87.5, "BIG": 87.5, "over": 100, "under": 0, "threw": 4, "taken": 5, "later": 12} {
if got, _, ok := ModelLoad("loadco", model, now); !ok || got != want {
t.Errorf("ModelLoad(%s) = %v, %v; want %v", model, got, ok, want)
}
}
for _, model := range []string{"small", "word", "nan", "inf", "nobody"} {
if got, _, ok := ModelLoad("loadco", model, now); ok {
t.Errorf("ModelLoad(%s) = %v, want unknown", model, got)
}
}
if _, _, ok := ModelLoad("other", "big", now); ok {
t.Error("another provider's model has loadco's load")
}
}
// A load counts for LoadFresh from the call that reported it, then is
// unknown, never taken for idle; a model@size has its model's load.
func TestModelLoadGoesStale(t *testing.T) {
ForgetLoads()
t.Cleanup(ForgetLoads)
at := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
noteLoads("p", map[string]float64{"m": 80, "n": 10}, at)
noteLoads("p", map[string]float64{"n": 20}, at.Add(4*time.Minute))
if got, _, ok := ModelLoad("p", "m@256k", at.Add(LoadFresh)); !ok || got != 80 {
t.Fatalf("m@256k at LoadFresh = %v, %v", got, ok)
}
later := at.Add(LoadFresh + time.Second)
if got, _, ok := ModelLoad("p", "m", later); ok {
t.Fatalf("m past LoadFresh = %v, want unknown", got)
}
if got, _, ok := ModelLoad("p", "n", later); !ok || got != 20 {
t.Fatalf("n, reported again = %v, %v", got, ok)
}
noteLoads("p", map[string]float64{"n": -1}, later)
if _, _, ok := ModelLoad("p", "n", later); ok {
t.Fatal("a cleared load is still known")
}
}
+7
View File
@@ -115,6 +115,13 @@ func subscriptionID(id string) bool {
// IsPlugin is whether the provider is a plugin's.
func (p Provider) IsPlugin() bool { return p.Account != nil && p.Account.plugin != nil }
// PluginForTest is the provider id served by the plugin's provider
// pluginID, for a test to build a candidate of.
func PluginForTest(id, pluginID string) Provider {
pp := plugin.Provider{ID: pluginID}
return Provider{ID: id, Account: &Account{Agent: "plugin", User: id, plugin: &pp}}
}
// PluginProvider is the id OpenCode knows the plugin's provider p is by
// (grok, kiro), whatever magpie names it; "" for one no plugin gives.
func (p Provider) PluginProvider() string {
+8
View File
@@ -473,6 +473,11 @@ type Settings struct {
// haiku needed more than 8): from 1 to ClassifyTimeoutMost, 0 for
// ClassifyTimeoutDefault. ClassifyWait reads it.
ClassifyTimeout int `json:"classifyTimeout,omitempty"`
// BusyLoad puts a model whose plugin reports it busier than this
// percent behind the others it could go to (plugin.ModelLoad,
// axelburks on Discord): from 1 to 99, 0 for off. A model with no
// load reported, or one older than plugin.LoadFresh, keeps its place.
BusyLoad int `json:"busyLoad,omitempty"`
// Searcher is the provider that searches the web for a model that
// can't: "<provider>" with the small model magpie picks of it,
// "<provider>/<model>", or empty for the one magpie picks
@@ -1960,6 +1965,9 @@ func saveOwn(s Settings, recording, reads bool) error {
if s.ClassifyTimeout < 0 || s.ClassifyTimeout > ClassifyTimeoutMost {
return fmt.Errorf("a routing group's classifier is given from 1 to %d seconds, or 0 for %d, not %d", ClassifyTimeoutMost, ClassifyTimeoutDefault, s.ClassifyTimeout)
}
if s.BusyLoad < 0 || s.BusyLoad > 99 {
return fmt.Errorf("busy models go last over a load from 1 to 99%%, or 0 for off, not %d", s.BusyLoad)
}
if s.UsageAlert < 0 || s.UsageAlert > 100 {
return fmt.Errorf("a usage alert is at a percentage from 1 to 100, or 0 for off, not %d", s.UsageAlert)
}
+24
View File
@@ -82,6 +82,7 @@
<a href="#signin-state">サインイン状態</a>
<a href="#usage">使用量</a>
<a href="#checkin">チェックイン</a>
<a href="#load">モデルの負荷</a>
<a href="#input">プラグインに渡されるもの</a>
<a href="#ids">プロバイダ id</a>
<a href="#test">テスト</a>
@@ -573,6 +574,28 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
</table></div>
<p><code>streak</code> は連続日数、<code>message</code> はそのまま表示されます。例外を投げた hook や、上の表にない outcome を返したものは <code>failed</code> です。アカウントのスコープで実行されるので、<code>client.auth.set</code> で更新したトークンはそのアカウントに保存されます。</p>
<h2 id="load"><a class="anchor" href="#load">モデルの負荷</a></h2>
<p>混雑したモデルへのリクエストを待たせるベンダーなら、プラグインは <code>input.magpie.load(provider, loads)</code> で各モデルの混み具合を magpie に伝えられます。magpie 独自のもので、OpenCode にはありません。<code>loads</code> はモデル id から 0〜100 のパーセントへの対応で、<code>null</code> はもう分からないことを表します。プラグインは自分のタイマーで好きなときに呼びます。magpie からは求めません。</p>
<div class="code">
<span class="lang">plugin</span>
<pre><span class="k">export default async</span> (input) =&gt; {
<span class="k">const</span> report = <span class="k">async</span> () =&gt; {
<span class="k">const</span> r = <span class="k">await</span> fetch(<span class="s">`${BASE}/load`</span>).then((r) =&gt; r.json()).catch(() =&gt; <span class="k">null</span>)
<span class="k">if</span> (r) input.magpie?.load?.(<span class="s">"acme"</span>, { <span class="s">"acme-large"</span>: r.large, <span class="s">"acme-small"</span>: r.small })
}
report()
setInterval(report, 60_000) <span class="c">// 5 分以内にまた報告しないと、負荷は不明に戻ります</span>
<span class="k">return</span> { auth: { <span class="c">/* … */</span> } }
}</pre>
</div>
<ul>
<li><b>値。</b>数値は 0〜100 に収められ、それ以外(文字列、<code>NaN</code>)は捨てられます。モデル id は大文字小文字を区別せず、<code>model@256k</code> は個別に報告がなければ元のモデルの負荷になります。1 回の呼び出しで最大 1000 モデルまで受け取り、受け取った数を返します。provider が文字列でない、または <code>loads</code> がオブジェクトでないと <code>TypeError</code> を投げます。</li>
<li><b>鮮度。</b>各モデルの負荷は報告した呼び出しから 5 分間有効で、その後は不明になり、0 とはみなしません。報告をやめたプラグインのモデルは元の位置のままです。呼び出しで触れなかったモデルは、自分の 5 分が切れるまで前回の負荷を保ちます。</li>
<li><b>表示。</b>プロバイダーの編集画面で、モデルの横に小さな灰色の数字で出ます。</li>
<li><b>ルーティング。</b>設定 › ネットワークと共有 › 混雑しているモデルを後回しに でしきい値を選ぶと(既定はオフ。50、70、80、90% 超、または settings.json の <code>busyLoad</code> に 1〜99)、それより混雑していると報告されたモデルは、リクエストが行ける他の候補の後ろ、失敗後に休んでいる候補の前に回ります。そのモデルが答えた会話は次のターンで先頭の候補に移り、ターンの途中では移りません。負荷が分からないモデルは元の位置のままです。ルーティングのトレースには <code>busy</code> と負荷が出ます。</li>
</ul>
<p>古いホスト向けのプラグインは、上の例のように先に <code>input.magpie?.load</code> を確かめます。</p>
<h2 id="input"><a class="anchor" href="#input">プラグインに渡されるもの</a></h2>
<p>magpie は OpenCode の <code>PluginInput</code> の内容を、OpenCode サーバーなしで意味をなす範囲でプラグインに渡します:</p>
<div class="table-wrap"><table>
@@ -586,6 +609,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<tr><td><code>project</code></td><td><code>{ id: "magpie", worktree }</code>。</td></tr>
<tr><td><code>$</code></td><td>Bun のシェル。</td></tr>
<tr><td><code>serverUrl</code></td><td>プレースホルダーです。背後に OpenCode サーバーはありません。</td></tr>
<tr><td><code>magpie.option</code>、<code>.options</code>、<code>.load</code></td><td>magpie 独自:ユーザーが設定したプラグインのオプションと、<a href="#load">モデルの負荷</a>。</td></tr>
</table></div>
<p>magpie が呼び出すフックは <code>config</code>、<code>auth</code>(そのメソッド、<code>loader</code>、<code>usage</code>、<code>refresh</code>、<code>checkin</code>)、<code>provider.models</code>、<code>chat.headers</code> です。プラグインのほかのフック(<code>tool</code>、<code>event</code>、<code>chat.params</code>、…)は呼び出されません。ツールはエージェント自身が実行します。</p>
+24
View File
@@ -82,6 +82,7 @@
<a href="#signin-state">Sign-in state</a>
<a href="#usage">Usage</a>
<a href="#checkin">Check-in</a>
<a href="#load">Model load</a>
<a href="#input">What a plugin is given</a>
<a href="#ids">Provider ids</a>
<a href="#test">Testing</a>
@@ -573,6 +574,28 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
</table></div>
<p><code>streak</code> is the days in a row, and <code>message</code> is shown as it is. A hook that throws, or answers no outcome above, is <code>failed</code>. It runs in the account’s scope, so a token it renews with <code>client.auth.set</code> is saved to that account.</p>
<h2 id="load"><a class="anchor" href="#load">Model load</a></h2>
<p>A vendor that queues requests to a busy model can have the plugin say how busy each model is, with <code>input.magpie.load(provider, loads)</code>, magpie’s own (OpenCode has none). <code>loads</code> maps a model id to a percent from 0 to 100, or to <code>null</code> to say it isn’t known any more. The plugin calls it whenever it likes, from its own timer: magpie doesn’t ask for it.</p>
<div class="code">
<span class="lang">plugin</span>
<pre><span class="k">export default async</span> (input) =&gt; {
<span class="k">const</span> report = <span class="k">async</span> () =&gt; {
<span class="k">const</span> r = <span class="k">await</span> fetch(<span class="s">`${BASE}/load`</span>).then((r) =&gt; r.json()).catch(() =&gt; <span class="k">null</span>)
<span class="k">if</span> (r) input.magpie?.load?.(<span class="s">"acme"</span>, { <span class="s">"acme-large"</span>: r.large, <span class="s">"acme-small"</span>: r.small })
}
report()
setInterval(report, 60_000) <span class="c">// within five minutes, or the load is unknown again</span>
<span class="k">return</span> { auth: { <span class="c">/* … */</span> } }
}</pre>
</div>
<ul>
<li><b>Values.</b> A number is clamped to 0–100; anything else (a string, <code>NaN</code>) is dropped. Model ids match whatever their case, and <code>model@256k</code> has its model’s load unless reported itself. One call takes up to 1000 models and returns how many it took. A provider that isn’t a string, or a <code>loads</code> that isn’t an object, throws a <code>TypeError</code>.</li>
<li><b>Freshness.</b> Each model’s load counts for five minutes from the call that reported it. After that it is unknown, never 0: a plugin that stops calling leaves its models where they were. A model a call doesn’t name keeps its last load until its own five minutes run out.</li>
<li><b>Where it shows.</b> The provider editor shows it by the model, a small grey number.</li>
<li><b>Routing.</b> With Settings › Network and sharing › Busy models last set (Off by default; over 50, 70, 80 or 90%, or <code>busyLoad</code> in settings.json from 1 to 99), a model reported busier than that goes behind every other candidate a request could go to, ahead of those resting after a failure. A conversation it answered moves to the one that leads at its next turn; within a turn it stays. A model with no load known keeps its place. The Routing trace says <code>busy</code> with the load.</li>
</ul>
<p>A plugin written for older hosts checks <code>input.magpie?.load</code> first, as above.</p>
<h2 id="input"><a class="anchor" href="#input">What a plugin is given</a></h2>
<p>magpie hands a plugin what OpenCode’s <code>PluginInput</code> has, as far as it has meaning without an OpenCode server:</p>
<div class="table-wrap"><table>
@@ -586,6 +609,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<tr><td><code>project</code></td><td><code>{ id: "magpie", worktree }</code>.</td></tr>
<tr><td><code>$</code></td><td>Bun’s shell.</td></tr>
<tr><td><code>serverUrl</code></td><td>A placeholder; no OpenCode server is behind it.</td></tr>
<tr><td><code>magpie.option</code>, <code>.options</code>, <code>.load</code></td><td>magpie’s own: the plugin’s options as the user set them, and <a href="#load">its models’ load</a>.</td></tr>
</table></div>
<p>The hooks magpie calls are <code>config</code>, <code>auth</code> (its methods, <code>loader</code>, <code>usage</code>, <code>refresh</code> and <code>checkin</code>), <code>provider.models</code> and <code>chat.headers</code>. A plugin’s other hooks (<code>tool</code>, <code>event</code>, <code>chat.params</code>, …) are not called. The agent runs its own tools.</p>
+24
View File
@@ -82,6 +82,7 @@
<a href="#signin-state">登录状态</a>
<a href="#usage">用量</a>
<a href="#checkin">签到</a>
<a href="#load">模型负载</a>
<a href="#input">插件能拿到什么</a>
<a href="#ids">供应商 id</a>
<a href="#test">测试</a>
@@ -573,6 +574,28 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
</table></div>
<p><code>streak</code> 是连续天数,<code>message</code> 原样显示。抛出异常,或返回的 outcome 不在上表里,都算 <code>failed</code>。它在账号的作用域里运行,所以用 <code>client.auth.set</code> 续期的 token 会存到这个账号。</p>
<h2 id="load"><a class="anchor" href="#load">模型负载</a></h2>
<p>供应商在模型繁忙时会让请求排队的,插件可以用 <code>input.magpie.load(provider, loads)</code> 告诉 magpie 每个模型有多忙。这是 magpie 自己的接口,OpenCode 没有。<code>loads</code> 把模型 id 映射到 0 到 100 的百分比,或映射到 <code>null</code> 表示不再知道。插件按自己的节奏、用自己的定时器随时调用,magpie 不会来要。</p>
<div class="code">
<span class="lang">plugin</span>
<pre><span class="k">export default async</span> (input) =&gt; {
<span class="k">const</span> report = <span class="k">async</span> () =&gt; {
<span class="k">const</span> r = <span class="k">await</span> fetch(<span class="s">`${BASE}/load`</span>).then((r) =&gt; r.json()).catch(() =&gt; <span class="k">null</span>)
<span class="k">if</span> (r) input.magpie?.load?.(<span class="s">"acme"</span>, { <span class="s">"acme-large"</span>: r.large, <span class="s">"acme-small"</span>: r.small })
}
report()
setInterval(report, 60_000) <span class="c">// 五分钟内要再报一次,否则负载又变成未知</span>
<span class="k">return</span> { auth: { <span class="c">/* … */</span> } }
}</pre>
</div>
<ul>
<li><b>取值。</b>数字会被限制在 0–100;其他值(字符串、<code>NaN</code>)丢弃。模型 id 不区分大小写,<code>model@256k</code> 没单独报时用它所属模型的负载。一次最多 1000 个模型,返回收下的个数。provider 不是字符串,或 <code>loads</code> 不是对象,会抛出 <code>TypeError</code>。</li>
<li><b>时效。</b>每个模型的负载从报告它的那次调用起算五分钟有效,之后就是未知,绝不当作 0:插件不再报告时,它的模型保持原位。一次调用没提到的模型,保留上次的负载,直到它自己的五分钟到期。</li>
<li><b>在哪显示。</b>供应商编辑页里模型旁边的灰色小数字。</li>
<li><b>路由。</b>在 设置 › 网络与共享 › 繁忙的模型靠后 选了阈值(默认关闭;可选高于 50、70、80 或 90%,或在 settings.json 里把 <code>busyLoad</code> 设为 1 到 99)后,报告负载高于它的模型会排到请求能去的其他候选之后,但仍在失败后休息的候选之前。它答过的对话在下一轮换到排在最前的那个;同一轮之内不换。没有已知负载的模型保持原位。路由追踪里显示 <code>busy</code> 和负载值。</li>
</ul>
<p>为旧版宿主写的插件先检查 <code>input.magpie?.load</code>,如上例。</p>
<h2 id="input"><a class="anchor" href="#input">插件能拿到什么</a></h2>
<p>magpie 交给插件的是 OpenCode <code>PluginInput</code> 里的内容,只要它在没有 OpenCode 服务端时还有意义:</p>
<div class="table-wrap"><table>
@@ -586,6 +609,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<tr><td><code>project</code></td><td><code>{ id: "magpie", worktree }</code>。</td></tr>
<tr><td><code>$</code></td><td>Bun 的 shell。</td></tr>
<tr><td><code>serverUrl</code></td><td>占位值,后面没有 OpenCode 服务端。</td></tr>
<tr><td><code>magpie.option</code>、<code>.options</code>、<code>.load</code></td><td>magpie 自己的:用户设置的插件选项,以及<a href="#load">模型负载</a>。</td></tr>
</table></div>
<p>magpie 调用的钩子是 <code>config</code>、<code>auth</code>(它的 methods、<code>loader</code>、<code>usage</code>、<code>refresh</code> 和 <code>checkin</code>)、<code>provider.models</code> 和 <code>chat.headers</code>。插件的其他钩子(<code>tool</code>、<code>event</code>、<code>chat.params</code> 等)不会被调用,工具由 agent 自己运行。</p>