From b04cca35c8345ef60ff2f740ff7c97ef707e005e Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 24 Oct 2026 14:24:11 +0800 Subject: [PATCH] factory 0.1.38: Standard usage only, a plugin option that stops an account once a Standard window is used up (#349) A new switch in magpie's plugin options, standard_only ("Standard usage only"), off by default, read at each usage reading. When on, limitWindows reports the Standard 5 hours / 7 days / 30 days windows with no notModels and never aside (extra usage or not), so they count every model, Droid Core's open models included. Droid Core's windows become aside (shown only) and Extra usage stays aside. Off, the windows are exactly as before. magpie only leaves an account out before sending when it is held at a usage cap (gateway perKeyBarred/capHeld; order routing tries a used-up account and benches it only after Factory refuses). The README says to pair the option with an account cap (magpie provider account-cap factory 99): then a held account is out before affinity, the next account takes the same model, and with every account held magpie answers 429 without sending. Run at this commit, rebased on origin/main 74be632 (TMPDIR and HOME under a scratch dir; the factory run was at d1b6500): - bun test packages/factory: 174 pass, 0 fail - bun test (whole repo): 2383 pass, 0 fail, exit 0 - bun scripts/check.mjs: exit 0 Broken by hand, usage.test.mjs's two new tests: - index.mjs back to origin/main: both red - usage not passing the option to limitWindows: the switch test red - Droid Core's windows not aside under the option: both red Not tried: a real Factory account, a real magpie host reading the switch, or routing with a cap set (read from magpie's source only). --- packages/factory/README.md | 24 ++++++++++++ packages/factory/index.mjs | 50 +++++++++++++++++++++---- packages/factory/package.json | 2 +- packages/factory/usage.test.mjs | 66 +++++++++++++++++++++++++++++++-- 4 files changed, 130 insertions(+), 12 deletions(-) diff --git a/packages/factory/README.md b/packages/factory/README.md index 0fadefd..465982c 100644 --- a/packages/factory/README.md +++ b/packages/factory/README.md @@ -115,6 +115,30 @@ magpie plugin add @magpie-community/opencode-factory-auth magpie plugin login factory ``` +## Standard usage only (optional) + +In magpie, open the Factory provider, turn on **Standard usage only** under +**Plugin options**, and save (or set `"pluginOptions": {"factory": +{"standard_only": true}}` in magpie's settings.json). It is off by default, +applies to every Factory account, and takes effect at each account's next +usage reading. + +When on, the plugin reports the Standard 5 hours, 7 days and 30 days +windows as counting every model, Droid Core's open models too, whether or +not the account has Extra usage. Droid Core's windows and Extra usage are +still shown but never keep an account in routing. + +magpie leaves an account out before sending only when it is held at a +usage cap, so pair the option with a cap on each account, for example +`magpie provider account-cap factory 99`. An account is then +skipped once any Standard window reaches the cap, the request goes to the +next account with the same model, and when every account is held magpie +answers 429 without sending. Without a cap, an account whose Standard +usage is gone is still tried, and Factory may serve a Droid Core model +from Core or Extra usage. Readings lag, so the last requests before a +window fills still go out; to never spend Extra usage, turn it off in +Factory. + ## Claude Code through magpie Factory's Anthropic route requires Droid's fixed client preamble and diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index ca8cac9..a79e09b 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -983,11 +983,19 @@ function dollars(cents) { return "$" + ((lo % 2 === 0 ? lo : lo + 1) / 100).toFixed(2) } +// STANDARD_ONLY is the switch (magpie's plugin options, off by default) +// that keeps an account in routing only while its Standard usage lasts +// (magpie-community/plugins#349) +const STANDARD_ONLY = "standard_only" + // limitWindows turns the limits into windows: standard's by their span, // then Droid Core's, then the extra usage left. For routing, standard counts // the vendors' models and Core the open ones Factory hosts; with extra usage -// to spend, a window used up stops neither. -function limitWindows(l) { +// to spend, a window used up stops neither. standardOnly (STANDARD_ONLY on) +// makes standard's windows count every model, Core's too, extra usage or +// not, and leaves Droid Core's and the extra usage to be shown only: an +// account stops when any of standard's windows is used up. +function limitWindows(l, standardOnly = false) { const out = [] const cents = typeof l.extraUsageBalanceCents === "number" ? l.extraUsageBalanceCents : null const extra = l.extraUsageAllowed === true && cents !== null && cents > 0 @@ -1003,9 +1011,16 @@ function limitWindows(l) { const win = { name: prefix + name, used: Math.min(Math.max(used, 0), 100), span } const end = windowEnd(w.windowEnd) if (end) win.resetsAt = end - if (extra) win.aside = true - if (core) win.models = CORE - else win.notModels = CORE + if (standardOnly) { + if (core) { + win.aside = true + win.models = CORE + } + } else { + if (extra) win.aside = true + if (core) win.models = CORE + else win.notModels = CORE + } out.push(win) } } @@ -1676,7 +1691,16 @@ function anthropicBody(body) { return changed ? JSON.stringify(request) : body } -export const FactoryAuthPlugin = async ({ client }) => { +export const FactoryAuthPlugin = async ({ client, magpie }) => { + // standardOnly is the user's STANDARD_ONLY as magpie has it now, read at + // each usage reading so a change needs no restart; false outside magpie + const standardOnly = () => { + try { + return magpie?.option?.(PROVIDER, STANDARD_ONLY) === true + } catch { + return false + } + } // the session id this process's requests carry const session = crypto.randomUUID() // serializes checking, rotating and saving tokens: WorkOS rotates the @@ -1870,7 +1894,7 @@ export const FactoryAuthPlugin = async ({ client }) => { l = await limits() } if (!l?.limits?.standard) return { error: "Factory: the account reported no limits", signIn } - return { windows: limitWindows(l), signIn } + return { windows: limitWindows(l, standardOnly()), signIn } } catch (e) { if (e?.lapsed) signIn = "expired" return { error: e?.message ?? String(e), signIn } @@ -1924,6 +1948,16 @@ export const FactoryAuthPlugin = async ({ client }) => { // droid's FACTORY_API_KEY: the key is the bearer, never renewed { type: "api", label: "Factory API key (fk-…)", placeholder: "fk-…" }, ], + // magpie's own switches (input.magpie.option), read at each usage + // reading + options: [ + { + key: STANDARD_ONLY, + label: "Standard usage only", + description: + "Keeps an account in routing only while its Standard usage lasts: once any Standard window (5 hours, 7 days, 30 days) is used up, magpie moves every model, Droid Core's too, to the next account until the window resets. Droid Core and Extra usage are shown but never keep an account in routing.", + }, + ], // magpie renews the sign-in MAGPIE_LEAD before its end, before its // requests and usage ask for it, and saves what this gives. Under // the same lock as the renewal before a request, so the two never @@ -2068,4 +2102,4 @@ export const FactoryAuthPlugin = async ({ client }) => { } // for tests -export const _internal = { contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels } +export const _internal = { STANDARD_ONLY, contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels } diff --git a/packages/factory/package.json b/packages/factory/package.json index e1bb42f..cd8a3b0 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-factory-auth", - "version": "0.1.37", + "version": "0.1.38", "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/factory/usage.test.mjs b/packages/factory/usage.test.mjs index dc624a1..161a304 100644 --- a/packages/factory/usage.test.mjs +++ b/packages/factory/usage.test.mjs @@ -34,7 +34,7 @@ const account = (over = {}) => ({ ...over, }) -async function plugin(auth, serve) { +async function plugin(auth, serve, magpie) { const seen = [] globalThis.fetch = async (url, init = {}) => { const u = new URL(String(url)) @@ -43,8 +43,8 @@ async function plugin(auth, serve) { return serve(u.pathname, h, init) } const client = { auth: { set: async ({ body }) => (auth = body) } } - const hooks = await FactoryAuthPlugin({ client }) - return { usage: () => hooks.auth.usage(async () => auth), seen, auth: () => auth } + const hooks = await FactoryAuthPlugin({ client, magpie }) + return { usage: () => hooks.auth.usage(async () => auth), seen, auth: () => auth, hooks } } const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) @@ -137,3 +137,63 @@ test("a token put in an org on the way renews it, as the built-in's factoryMendO }) expect((await p.usage()).signIn).toBe("renewed") }) + +// Standard usage only (#349): standard's windows stop the account for every +// model, extra usage or not; Droid Core's and the extra usage are shown only +test("standard usage only: standard's windows count every model and stop the account; Core's and extra usage are shown only", () => { + expect(_internal.limitWindows(LIMITS, true)).toEqual([ + { name: "5 hours", used: 42, span: 18000, resetsAt: "2026-10-01T05:00:00.000Z" }, + { name: "7 days", used: 10, span: 604800, resetsAt: "2026-10-12T00:00:00.000Z" }, + { name: "30 days", used: 100, span: 2592000, resetsAt: "2026-10-26T07:33:20.000Z" }, + { name: "Droid Core · 5 hours", used: 100, span: 18000, resetsAt: "2026-10-01T05:00:00.000Z", aside: true, models: CORE }, + { name: "Extra usage", used: 0, display: "$12.50", aside: true }, + ]) + // no extra usage: the same, Core's still aside + const w = _internal.limitWindows({ limits: { standard: { weekly: { usedPercent: 100 } }, core: { weekly: { usedPercent: 3 } } }, extraUsageAllowed: false }, true) + expect(w).toEqual([ + { name: "7 days", used: 100, span: 604800 }, + { name: "Droid Core · 7 days", used: 3, span: 604800, aside: true, models: CORE }, + ]) +}) + +test("standard usage only is a switch magpie shows, off by default, read at each usage reading", async () => { + let on = false + const asked = [] + const magpie = { + option: (provider, key) => { + asked.push(provider + "/" + key) + return on + }, + } + const p = await plugin(account(), (path) => (path === "/api/billing/limits" ? json(LIMITS) : new Response("", { status: 404 })), magpie) + // declared as magpie's host keeps a switch: a key of [a-z0-9_-], a label, off unless said + const o = p.hooks.auth.options + expect(o).toEqual([{ key: "standard_only", label: "Standard usage only", description: expect.any(String) }]) + expect(o[0].key).toMatch(/^[a-z0-9_-]{1,40}$/) + expect(o[0].label.length).toBeLessThanOrEqual(60) + expect(o[0].description.length).toBeLessThanOrEqual(300) + expect(o[0].default).toBeUndefined() + + const off = await p.usage() + expect(off.windows[0]).toEqual({ name: "5 hours", used: 42, span: 18000, resetsAt: "2026-10-01T05:00:00.000Z", aside: true, notModels: CORE }) + on = true + const now = await p.usage() + expect(now.windows.map((w) => [w.name, !!w.aside, w.notModels ?? null, w.models ?? null])).toEqual([ + ["5 hours", false, null, null], + ["7 days", false, null, null], + ["30 days", false, null, null], + ["Droid Core · 5 hours", true, null, CORE], + ["Extra usage", true, null, null], + ]) + expect(asked).toEqual(["factory/standard_only", "factory/standard_only"]) + + // outside magpie (OpenCode gives no magpie), or a host whose option throws: off + const q = await plugin(account(), (path) => (path === "/api/billing/limits" ? json(LIMITS) : new Response("", { status: 404 }))) + expect((await q.usage()).windows[0].notModels).toEqual(CORE) + const r = await plugin(account(), (path) => (path === "/api/billing/limits" ? json(LIMITS) : new Response("", { status: 404 })), { + option: () => { + throw new Error("no host") + }, + }) + expect((await r.usage()).windows[0].aside).toBe(true) +})