provider, gui: smart routing spends WorkBuddy credits that expire soonest first (cdredfox on X)

WorkBuddy's Credits window had no reset, so in a Smart group every
WorkBuddy account ranked alike. workbuddy plugin 0.1.14 (plugins f0274d6)
reads WorkBuddy's own package lists (billing/meter/get-user-resource-paid-
packages and -free-packages, the calls WorkBuddy's client makes) and reports
on the Credits window when the soonest-ending package that still has credits
ends (runsOutAt) and how many credits it holds (runsOut). The daily Free
Plan slice (CapacityType 4) and code 001 aren't counted: they renew daily.

magpie carries runsOutAt from the plugin's usage window into QuotaWindow and
the routing Limit. Allowance.Renewal, which only Smart ranks on, treats it
as the window's reset when it is sooner than the real one. Pace, the tiers,
For, Full and resting are unchanged. The mover's min is raised to 0.1.14 so
moved users get the plugin. The usage card and account meter say "232.4
expire in 5h" in every language.

Run:
- plugin: bun test, 63 pass; 2 of the 3 new tests fail on 0.1.13's
  index.mjs. Verified live on a workbuddy-ai account in a sandbox HOME:
  Bonus Pack 232.4 left ending 10-12T16:39Z ranked before Pro (10-28).
- TestWorkBuddyCreditsRunOutForRouting and
  TestSmartSpendsWorkBuddyCreditsRunningOutFirst: both fail with the
  Renewal change removed by hand.
- GUI: credits-run-out.test.cjs in webkit and chromium, 5 languages, at
  360/440/1000px, red on the old app.js; with i18n-keys, quota-*,
  panel-usage, reset-each-title, usage-fold: 117 pass.
- go test ./... green (agent and gateway rerun with -timeout 30m after the
  default 10m ran out under load from other sessions; 378s and 492s).
- gofmt -l clean; GOOS=linux and windows go vet of provider, plugin,
  gateway clean.

Not tried: the CN workbuddy site (its token was stale, 401), so the CN
package list is assumed to have the same shape. The built-in WorkBuddy
(not moved users) doesn't get this. The account-line tooltip has no GUI
test of its own.
This commit is contained in:
yetone
2026-10-11 20:07:19 +08:00
parent b755607e63
commit 6f1b432759
15 changed files with 277 additions and 7 deletions
+6 -1
View File
@@ -1217,7 +1217,12 @@ each of these groups ordered by the share used.
when the weeks renew in the same hour. Reset times are compared to the
hour, by the clock: 13:55 and 14:05 are different hours, 14:05 and
14:55 the same. An account
with no week (Claude Enterprise) goes by its 5 hours. A Claude account
with no week (Claude Enterprise) goes by its 5 hours. Credits that
run out before their window renews, or that have no reset at all
(WorkBuddy's packages, each ending on its own day), count as renewing
when they run out: of several WorkBuddy accounts, the one whose credits
left end first goes first. The daily Free Plan credits aren't counted,
since they end at the same midnight on every account. A Claude account
magpie knows nothing of yet goes first once, to learn what it has left
from the answer; any other unknown account goes after those known.
- **In order**: the accounts in their order. The first takes every request
+1 -1
View File
@@ -54,7 +54,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a stream under a type that says neither JSON nor a stream goes through as it comes (`sseStart` reads its first bytes); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun: `eventLead`) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`), rather than handed what came as its whole reply.
- Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held.
- A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop`. A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off.
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
- A resting candidate is tried last, never dropped (`restLast`). A lone candidate is tried even while it rests, because there is no other.
- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while at least `cacheWorth` (1024) tokens were read from the cache and the cache isn't cold (`cacheCold`, 5 minutes).
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
@@ -0,0 +1,65 @@
package gateway
import (
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// cdredfox on X: in a Smart group of WorkBuddy accounts, the one whose
// credits left run out first goes first, since what it has left is lost
// then; the Credits window has no reset, so before they all ranked alike
// and kept their order. Its share used still decides first: one all but
// spent waits behind, whatever its credits' end.
func TestSmartSpendsWorkBuddyCreditsRunningOutFirst(t *testing.T) {
old := allowances
defer func() { allowances = old }()
now := time.Now()
share := map[string]provider.Allowance{}
allowances = func(string) map[string]provider.Allowance { return share }
p := provider.Provider{ID: "workbuddy-ai", Account: &provider.Account{Agent: "workbuddy-ai", User: "a@x.com"}}
acct := func(user string) candidate {
return candidate{p: provider.Provider{ID: "workbuddy-ai", Account: &provider.Account{Agent: "workbuddy-ai", User: user}}, model: "hy3", rest: "workbuddy-ai#" + user}
}
credits := func(used float64, in time.Duration) provider.Allowance {
l := provider.Limit{Used: used, Amount: used * 22.5, Of: 2250, Unit: "credits"}
if in > 0 {
l.RunsOut = now.Add(in)
}
return provider.Allowance{l}
}
order := func(cs ...candidate) string {
got, _ := weigh(p, cs, "hy3", provider.Chat)
var s []string
for _, c := range got {
s = append(s, c.p.Account.User[:1])
}
return strings.Join(s, "")
}
share["a@x.com"] = credits(10, 18*24*time.Hour)
share["b@x.com"] = credits(30, 30*time.Hour)
if got := order(acct("a@x.com"), acct("b@x.com")); got != "ba" {
t.Fatalf("credits ending sooner first: %s", got)
}
// one not known (an older plugin) after those known
share["a@x.com"] = credits(10, 0)
if got := order(acct("a@x.com"), acct("b@x.com")); got != "ba" {
t.Fatalf("not known last: %s", got)
}
// ending the same hour: their order, for the cache
hour := now.Truncate(time.Hour).Add(31 * time.Hour).Sub(now)
share["a@x.com"] = credits(10, hour+40*time.Minute)
share["b@x.com"] = credits(30, hour+10*time.Minute)
if got := order(acct("a@x.com"), acct("b@x.com")); got != "ab" {
t.Fatalf("same hour keeps order: %s", got)
}
// all but spent: behind, though its credits end first
share["a@x.com"] = credits(10, 18*24*time.Hour)
share["b@x.com"] = credits(99, 30*time.Hour)
if got := order(acct("b@x.com"), acct("a@x.com")); got != "ab" {
t.Fatalf("spent last: %s", got)
}
}
+20
View File
@@ -11984,6 +11984,8 @@ function accountQuota(data, user, capFor = () => 0, settable = null) {
m.title = resetText(at, at.toLocaleString());
if (used >= 80) m.append(el("span", "aq-r", resetInText(at)));
}
const out = runsOutText(w, (at) => at.toLocaleString());
if (out) m.title = [m.title, out].filter(Boolean).join("\n");
if (w.tiers) m.title = tiersText(w);
line.append(settable ? settable(m, w) : m);
}
@@ -12520,6 +12522,16 @@ function resetInText(at) {
return at <= Date.now() ? t("Reset time passed") : t("resets {in}", { in: untilText(at) });
}
// runsOutText: when the soonest of what a window has left is lost, apart
// from its reset (WorkBuddy's credits come in packages that each end on
// their own day, runsOutAt): "232.4 credits expire tomorrow 00:39"; ""
// when not known or past. Smart routing spends such an account first.
function runsOutText(w, when = resetClock) {
const at = w.runsOutAt ? new Date(w.runsOutAt) : null;
if (!at || !(at > Date.now()) || !(w.runsOut > 0)) return "";
return t("{n} expire {when}", { n: countFormat.format(w.runsOut) + (w.unit ? " " + t(w.unit) : ""), when: when(at) });
}
// accountAction changes which account a provider uses, or which it has,
// and leaves its editor open on the result.
async function accountAction(path, body, okMsg, confirmed = false) {
@@ -15953,6 +15965,14 @@ function quotaWindows(sub) {
quota.append(r);
quota.title = resetText(at, at.toLocaleString());
}
// credits that run out before then, or with no reset at all
const out = runsOutText(w);
if (out) {
if (!r) quota.append(r = el("div", "quota-reset"));
else r.append(" · ");
r.append(el("span", "", out + " ·"), " ", el("span", "", untilText(new Date(w.runsOutAt))));
quota.title = [quota.title, runsOutText(w, (at) => at.toLocaleString())].filter(Boolean).join("\n");
}
// what the whole window holds, by what magpie routed in it (Chiao), on
// the reset's line, so the window keeps its three rows
if (w.holds) {
+4
View File
@@ -2705,6 +2705,7 @@ const I18N = {
"A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.": "API key 只能查到自身剩余额度。要在用量页显示整个账户余额,请在 {p} 的设置中生成系统访问令牌并粘贴到这里,不作他用。",
"Antigravity hasn't set this account up — hover for why": "Antigravity 还没为这个账号开通,悬停查看原因",
"Resets {when}": "重置于 {when}",
"{n} expire {when}": "{n} 将于 {when} 过期",
// a model family's figure (Antigravity's Gemini, Claude)
"Every model ({n})": "全部模型({n})",
"By family": "按系列",
@@ -6981,6 +6982,7 @@ const I18N = {
"A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.": "API key 只能查到自身剩餘額度。要在用量頁顯示整個帳戶餘額,請在 {p} 的設定中生成系統存取權杖並貼上到這裡,不作他用。",
"Antigravity hasn't set this account up — hover for why": "Antigravity 還沒為這個帳號開通,懸停檢視原因",
"Resets {when}": "重置於 {when}",
"{n} expire {when}": "{n} 將於 {when} 過期",
"Every model ({n})": "全部模型({n})",
"By family": "按系列",
"One figure a model family, its most used model's": "每個模型系列一個數字,取其中用得最多的模型",
@@ -11261,6 +11263,7 @@ const I18N = {
"A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.": "キーでわかるのはそのキー自体の残りだけです。使用量ページにアカウント全体の残高を表示するには、{p} の設定でシステムアクセストークンを生成し、ここに貼り付けてください。それ以外には使いません。",
"Antigravity hasn't set this account up — hover for why": "Antigravity はこのアカウントをまだ設定していません — ホバーで理由を表示",
"Resets {when}": "{when} にリセット",
"{n} expire {when}": "{n}は {when} に失効",
"Every model ({n})": "すべてのモデル({n})",
"By family": "ファミリー別",
"One figure a model family, its most used model's": "モデルファミリーごとに 1 つの数値(最もよく使われているモデルの値)",
@@ -15540,6 +15543,7 @@ const I18N = {
"A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.": "Ein Schlüssel liefert nur sein eigenes Restguthaben. Für das Guthaben des gesamten Kontos auf der Seite „Nutzung“ erzeugen Sie in den Einstellungen von {p} ein System Access Token und fügen es hier ein; es wird für nichts anderes verwendet.",
"Antigravity hasn't set this account up — hover for why": "Antigravity hat dieses Konto nicht eingerichtet – für den Grund darüberfahren",
"Resets {when}": "Zurückgesetzt {when}",
"{n} expire {when}": "{n} verfallen {when}",
"Every model ({n})": "Alle Modelle ({n})",
"By family": "Nach Familie",
"One figure a model family, its most used model's": "Ein Wert je Modellfamilie, der ihres meistgenutzten Modells",
@@ -0,0 +1,88 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// cdredfox on X: WorkBuddy's credits come in packages that each end on
// their own day, and the Credits window has no reset. The plugin says when
// the soonest credits left run out (runsOutAt, runsOut), and the Usage
// card says so under the window, "232.4 credits expire tomorrow 00:39 ·
// in 21h", in every language, at a phone's width too, and in its tooltip.
// A window without it, or whose credits ran out already, says nothing of
// it.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const soon = (h) => new Date(Date.now() + h * 3600e3).toISOString();
const credits = (runsOutAt) => ({ name: "Credits", used: 100 * 17.6 / 2250, display: "17.6 / 2250", amount: 17.6, limit: 2250, unit: "credits", ...(runsOutAt ? { runsOutAt, runsOut: 232.4 } : {}) });
const quotas = [
{ provider: "workbuddy-ai", name: "WorkBuddy AI", icon: "workbuddy-color", plan: "Pro", user: "a@example.com", windows: [credits(soon(30))] },
{ provider: "workbuddy-ai", name: "WorkBuddy AI", icon: "workbuddy-color", plan: "Pro", user: "b@example.com", windows: [credits("")] },
{ provider: "workbuddy-ai", name: "WorkBuddy AI", icon: "workbuddy-color", plan: "Pro", user: "c@example.com", windows: [credits(soon(-1))] },
];
function serve(lang) {
const settings = { lang, theme: "light", currency: "usd", chineseUnits: lang.startsWith("zh") };
const state = { agents: [], profiles: [], settings };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/gateway/trace") return url.searchParams.get("wait") ? new Promise(() => {}) : json({ mine: true, now: new Date().toISOString(), seq: 0, totals: {}, routes: [] });
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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)];
try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); }
};
}
const want = {
en: /^232\.4 credits expire .+ · in (29|30)h$/,
zh: /^232\.4 积分 将于 .+ 过期 · (29|30) 小时后$/,
"zh-TW": /^232\.4 積分 將於 .+ 過期 · (29|30) 小時後$/,
ja: /^232\.4 クレジットは .+ に失効 · (29|30) ?時間後$/,
de: /^232\.4 Credits verfallen .+ · in (29|30) Std\.?$/,
};
for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) {
test(`${name}: credits that run out say when, under their window, at 360 and 440px in every language`, async () => {
const browser = await engine.launch();
try {
for (const lang of Object.keys(want)) {
for (const width of [360, 440, 1000]) {
const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=usage");
await page.locator(".subscription-card .quota").nth(2).waitFor();
const got = await page.evaluate(() => [...document.querySelectorAll(".subscription-card .quota")].map((q) => {
const card = q.closest(".subscription-card").getBoundingClientRect();
const r = q.querySelector(".quota-reset");
const b = r?.getBoundingClientRect();
return { text: r?.textContent.replace(/\s+/g, " ").trim() ?? "", title: q.title,
inCard: !b || (b.left >= card.left - 1 && b.right <= card.right + 1),
cut: !!r && [...r.children].some((s) => s.scrollWidth > s.clientWidth + 1) };
}).concat([{ pageScroll: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1 }]));
const at = `${lang} ${width}px`;
const { pageScroll } = got.pop();
assert.equal(got.length, 3, at);
const [a, b, c] = got;
assert.match(a.text, want[lang], at);
assert.ok(a.title.includes("232.4"), `${at}: tooltip ${a.title}`);
assert.ok(a.inCard && !a.cut, `${at}: "${a.text}" is cut or past its card`);
assert.equal(b.text, "", `${at}: not known says nothing`);
assert.equal(c.text, "", `${at}: run out already says nothing`);
assert.equal(pageScroll, false, `${at}: the page scrolls sideways`);
await page.close();
}
}
} finally { await browser.close(); }
});
}
+5
View File
@@ -877,6 +877,11 @@ type UsageWindow struct {
Models []string `json:"models"`
NotModels []string `json:"notModels"`
Aside bool `json:"aside"`
// RunsOutAt (RFC 3339) is when the soonest credits left in the window
// are lost, and RunsOut how many, when the vendor's credits expire
// apart from the window's reset (WorkBuddy's packages)
RunsOutAt string `json:"runsOutAt"`
RunsOut float64 `json:"runsOut"`
}
// Checkin is what came of an account's daily check-in, as the plugin's
+1 -1
View File
@@ -16,7 +16,7 @@ func init() {
for _, w := range []*wbSite{wbCN, wbAI} {
movers[w.id] = &mover{
pkg: "@magpie-community/opencode-workbuddy-auth",
min: "0.1.13", // an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659)
min: "0.1.14", // the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659)
agents: []string{w.id},
out: func() ([]Moving, error) {
var out []Moving
+3
View File
@@ -151,6 +151,9 @@ func quotaOfPlugin(q SubscriptionQuota, u plugin.Usage) SubscriptionQuota {
if t, err := time.Parse(time.RFC3339, x.ResetsAt); err == nil {
w.ResetsAt = &t
}
if t, err := time.Parse(time.RFC3339, x.RunsOutAt); err == nil {
w.RunsOutAt, w.RunsOut = &t, x.RunsOut
}
if set := idSetOf(x.Models); set != nil {
w.matches = set.has
} else if set := idSetOf(x.NotModels); set != nil {
+14 -1
View File
@@ -131,6 +131,9 @@ type Limit struct {
// again — at Restarts, which routing takes for the window's renewal
// when it is the sooner. Zero when none will be spent so.
ResetRunsOut time.Time
// RunsOut is when the soonest of what the window has left is lost,
// apart from its reset (QuotaWindow.RunsOutAt): zero when not known.
RunsOut time.Time
}
// Restarts is when an auto-used reset starts the account's windows again,
@@ -234,7 +237,11 @@ func (a Allowance) Count(model string, now time.Time) (amount, of float64, unit
// Renewal is For's renews as routing ranks them: a window not started,
// or whose reset has passed, that says how long it runs is taken to
// renew that long from now — a five hours not started renews within five
// hours, the soonest of an account that has nothing longer (#576).
// hours, the soonest of an account that has nothing longer (#576). One
// whose credits left run out before it renews (Limit.RunsOut) renews
// then, as what is left is lost then all the same: WorkBuddy's accounts,
// whose credits have no reset, go by the package that ends first
// (cdredfox on X).
func (a Allowance) Renewal(model string, now time.Time) []time.Time {
model = strings.ToLower(model)
restart := a.Restarts(now)
@@ -249,6 +256,9 @@ func (a Allowance) Renewal(model string, now time.Time) []time.Time {
l.Resets = now.Add(l.Span)
}
}
if l.RunsOut.After(now) && (l.Resets.IsZero() || l.RunsOut.Before(l.Resets)) {
l.Resets = l.RunsOut
}
l.Resets = restarted(l.Resets, restart)
ls = append(ls, l)
}
@@ -678,6 +688,9 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance {
case w.ResetSecs > 0:
l.Resets = now.Add(time.Duration(w.ResetSecs) * time.Second)
}
if w.RunsOutAt != nil {
l.RunsOut = *w.RunsOutAt
}
a = append(a, l)
}
return a
+6
View File
@@ -39,6 +39,12 @@ type QuotaWindow struct {
Amount float64 `json:"amount,omitempty"`
Limit float64 `json:"limit,omitempty"`
Unit string `json:"unit,omitempty"`
// RunsOutAt is when the soonest of what is left is lost, and RunsOut
// how much (in Unit), when it runs out apart from the window's reset:
// WorkBuddy's credits come in packages that each end on their own
// day. Smart routing takes it for the window's renewal (cdredfox on X).
RunsOutAt *time.Time `json:"runsOutAt,omitempty"`
RunsOut float64 `json:"runsOut,omitempty"`
// Family is the model family a per-model window belongs to (Antigravity's
// "Gemini 3.1 Pro (High)" is Gemini's), for the GUI to show one figure a
// family, the tightest; each window is still here, and routing reads
@@ -0,0 +1,61 @@
package provider
import (
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
)
// cdredfox on X: WorkBuddy's credits come in packages that each end on
// their own day, and the Credits window has no reset. The plugin (0.1.14)
// says when the soonest credits left run out (runsOutAt), and Smart
// routing takes it for the window's renewal, so the account whose credits
// end first is spent first. The window is the one workbuddy 0.1.14 sends
// for the WorkBuddy AI account it was tried on: the Bonus Pack's 232.4
// credits end 10-13 00:39:27 +08.
func TestWorkBuddyCreditsRunOutForRouting(t *testing.T) {
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
credits := func(runsOutAt string) plugin.Usage {
return plugin.Usage{Plan: "Pro", Windows: []plugin.UsageWindow{{Name: "Credits", Used: 100 * 17.6 / 2250,
Display: "17.6 / 2250", Amount: 17.6, Limit: 2250, Unit: "credits", RunsOutAt: runsOutAt, RunsOut: 232.4}}}
}
q := quotaOfPlugin(SubscriptionQuota{}, credits("2026-10-12T16:39:27.000Z"))
w := q.Windows[0]
at := time.Date(2026, 10, 12, 16, 39, 27, 0, time.UTC)
if w.RunsOutAt == nil || !w.RunsOutAt.Equal(at) || w.RunsOut != 232.4 || w.ResetsAt != nil {
t.Fatalf("window: %+v", w)
}
if r := allowanceOf(q.Windows, now).Renewal("hy3", now); len(r) != 1 || !r[0].Equal(at) {
t.Fatalf("renewal: %v, want %v", r, at)
}
// an older plugin, or a list it couldn't read: not known, as before
q = quotaOfPlugin(SubscriptionQuota{}, credits(""))
if q.Windows[0].RunsOutAt != nil {
t.Fatalf("no runsOutAt: %+v", q.Windows[0])
}
if r := allowanceOf(q.Windows, now).Renewal("hy3", now); len(r) != 1 || !r[0].IsZero() {
t.Fatalf("renewal not known: %v", r)
}
// already past: not known, the window isn't taken as renewing then
q = quotaOfPlugin(SubscriptionQuota{}, credits("2026-10-11T11:00:00Z"))
if r := allowanceOf(q.Windows, now).Renewal("hy3", now); len(r) != 1 || !r[0].IsZero() {
t.Fatalf("passed: %v", r)
}
// a window that resets says so, and runs out later: its reset stands;
// sooner, what is left is lost then, and that is its renewal
reset := now.Add(48 * time.Hour)
a := Allowance{{Used: 10, Resets: reset, RunsOut: now.Add(72 * time.Hour)}}
if r := a.Renewal("m", now); !r[0].Equal(reset) {
t.Fatalf("later run-out moved the reset: %v", r)
}
a[0].RunsOut = now.Add(24 * time.Hour)
if r := a.Renewal("m", now); !r[0].Equal(now.Add(24 * time.Hour)) {
t.Fatalf("sooner run-out: %v", r)
}
// the share used and the rest are the window's, as before: For,
// Full and the rest don't read RunsOut
if used, _ := a.For("m", now); used != 10 {
t.Fatalf("used: %v", used)
}
}
+1 -1
View File
@@ -170,7 +170,7 @@
<div class="callout"><b>何もしなくてもできるグループ。</b> すでに持っているモデルを提供する 2 つ目のプロバイダを追加すると(Claude サブスクリプションと Copilot の Claude Opus、DeepSeek 自身の API と OpenRouter の DeepSeek など)、magpie はそれを提供するすべてのプロバイダにまたがるグループ <code>group/auto-&lt;model&gt;</code> を自動で作ります。名前はベンダーごとの表記の違い(<code>deepseek/deepseek-chat</code>、<code>deepseek-chat</code>)を吸収して照合されます。エージェントにこれを選ぶとリクエストがすべてに分散されます。不要なものは <code>magpie group rm</code> で非表示にできます。</div>
<div class="table-wrap"><table>
<tr><th>ルーティング</th><th>先に使われるもの</th></tr>
<tr><td>スマート <code>smart</code></td><td>デフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。失敗後に休止中のものは最後に回ります。</td></tr>
<tr><td>スマート <code>smart</code></td><td>デフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。リセットのないクレジット(WorkBuddy のパッケージはそれぞれの日に失効します)は、残りのうち最も早く失効する時点で判断されるため、クレジットが最も早く失効する WorkBuddy アカウントが先になります。失敗後に休止中のものは最後に回ります。</td></tr>
<tr><td>順番どおり <code>order</code></td><td>最初のモデルが応答できなくなるまでそれを使い、次へ進みます。</td></tr>
<tr><td>持ち回り <code>rotate</code></td><td>各会話の次のターンを、次のメンバーのアカウントやキーに送り、負荷を分散します。</td></tr>
<tr><td>使用量の少ない順 <code>usage</code></td><td>利用枠の残りが最も多いアカウントやキー。</td></tr>
+1 -1
View File
@@ -170,7 +170,7 @@
<div class="callout"><b>Groups you get without doing anything.</b> Add a second provider that serves a model you already have — Claude Opus from your Claude subscription and from Copilot, DeepSeek from its own API and from OpenRouter — and magpie makes it a group by itself, <code>group/auto-&lt;model&gt;</code>, over every provider that serves it. The name is matched however each vendor spells it (<code>deepseek/deepseek-chat</code>, <code>deepseek-chat</code>). Pick it for an agent to spread its requests over all of them; <code>magpie group rm</code> hides one you don’t want.</div>
<div class="table-wrap"><table>
<tr><th>Routing</th><th>What goes first</th></tr>
<tr><td>Smart <code>smart</code></td><td>The default. Over the members’ accounts and keys together (a group in the group as one, see below): of the subscriptions with quota to spare, the one whose allowance renews soonest. The week decides; an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later. One resting after a failure goes last.</td></tr>
<tr><td>Smart <code>smart</code></td><td>The default. Over the members’ accounts and keys together (a group in the group as one, see below): of the subscriptions with quota to spare, the one whose allowance renews soonest. The week decides; an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later. Credits with no reset (WorkBuddy’s packages, each ending on its own day) count as renewing when the soonest of those left run out, so the WorkBuddy account whose credits end first goes first. One resting after a failure goes last.</td></tr>
<tr><td>In order <code>order</code></td><td>The first model until it can’t answer, then the next.</td></tr>
<tr><td>In turn <code>rotate</code></td><td>Each conversation’s next turn goes to the next member’s account or key, spreading the load.</td></tr>
<tr><td>Least used <code>usage</code></td><td>The account or key with the most of its allowance left.</td></tr>
+1 -1
View File
@@ -170,7 +170,7 @@
<div class="callout"><b>不用手动建的组。</b>再加一个供应商,只要它提供的模型和已有的同名(比如 Claude 订阅和 Copilot 都有 Claude Opus,DeepSeek 官方 API 和 OpenRouter 都有 DeepSeek),magpie 就会自动把它们组成一个路由组:<code>group/auto-&lt;模型&gt;</code>,包含所有提供这个模型的供应商。名字按各家不同的写法匹配(<code>deepseek/deepseek-chat</code> 和 <code>deepseek-chat</code> 算同一个)。给 Agent 选这个组,请求就会分摊到这些供应商上;不想要的可以用 <code>magpie group rm</code> 隐藏。</div>
<div class="table-wrap"><table>
<tr><th>路由</th><th>谁排在前面</th></tr>
<tr><td>智能 <code>smart</code></td><td>默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。失败后在休息的排最后。</td></tr>
<tr><td>智能 <code>smart</code></td><td>默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。没有重置时间的积分(WorkBuddy 的积分包,各自到期)按剩余积分最早过期的时间算,所以积分最先过期的 WorkBuddy 账号排第一。失败后在休息的排最后。</td></tr>
<tr><td>按顺序 <code>order</code></td><td>先用第一个模型,它答不了再换下一个。</td></tr>
<tr><td>轮流 <code>rotate</code></td><td>会话的每一轮交给下一个成员的账号或 Key,均摊负载。</td></tr>
<tr><td>最少使用 <code>usage</code></td><td>剩余额度最多的账号或 Key 排第一。</td></tr>