From f0274d69f73c260d960bcb4d00b02449caa6a8ef Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 11 Oct 2026 19:39:13 +0800 Subject: [PATCH] workbuddy 0.1.14: the Credits window says when the soonest credits left run out (runsOutAt, runsOut), for magpie's smart routing to spend those first (cdredfox on X) cdredfox: with several WorkBuddy accounts in one smart routing group, the account whose credits expire soonest should be used first. WorkBuddy's own client lists each package with its end (the billing page's paid and free package lists); the plugin now reads them too. - /billing/meter/get-user-resource-paid-packages and -free-packages, asked as the client asks: PageSize 200 up to 10 pages, Status [0,3], its COMMODITY_CODES (without them the API answers 10001 "PackageCodes required"), NeedRenewInfo / today's SlicePeriod (UTC+8). - A package's end is DeductionEndTime, else ExpiredTime, else CycleEndTime read as UTC+8 (the API's own DeductionEndTime for the same package says so). Only packages the summary counts, with credits left; the daily Free Plan slice (CapacityType 4, code 001) is left out, since it ends at the same midnight on every account. - The soonest end goes on the Credits window as runsOutAt (RFC 3339) and the credits lost then as runsOut. A list that can't be read leaves both out; the card stands as before. Run: HOME= bun test in packages/workbuddy, 63 pass (3 new); with index.mjs back at 0.1.13, 2 of the 3 new go red. Tried live on a real WorkBuddy AI account: packagesOf + runsOutOf gave the Bonus Pack's 232.4 credits ending 2026-10-12T16:39:27Z, before Pro's 10-28T16:40:52Z, with the Free Plan slice left out. Not tried on a CN workbuddy account (its stored token here is stale); the paths and body are the same on both. --- packages/workbuddy/README.md | 9 ++++ packages/workbuddy/index.mjs | 88 +++++++++++++++++++++++++++++-- packages/workbuddy/package.json | 2 +- packages/workbuddy/usage.test.mjs | 66 +++++++++++++++++++++++ 4 files changed, 160 insertions(+), 5 deletions(-) diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index da1b9a2..6509a1e 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -119,6 +119,15 @@ is used. A model's reasoning levels are its variants (`reasoningEffort`). +## Credits in magpie + +magpie's usage card shows the account's credits from the resource summary. +It also says when the soonest credits left run out (`runsOutAt`, and how +many: `runsOut`), from the paid and free package lists WorkBuddy's own +client reads. The daily Free Plan slice isn't counted: it ends at the same +midnight on every account. magpie's smart routing spends the account whose +credits run out first. + ## Not here magpie's built-in WorkBuddy does more than this package: diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 858a956..7de7933 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -917,13 +917,13 @@ const statusText = (n) => STATUS_TEXT[n] || `HTTP ${n}` // meter asks the billing API as magpie's built-in did, its errors said // the same: WorkBuddy's message, else its code, else the HTTP status. -async function meter(site, a, path) { +async function meter(site, a, path, body = {}) { const res = await fetch(site.endpoint + path, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "WorkBuddy/" + UA_VERSION, Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "", "X-Domain": domainOf(site, a), "X-Product": "SaaS", "X-IDE-Type": "WorkBuddy", ...enterpriseHeaders(a) }, - body: "{}", + body: JSON.stringify(body), signal: AbortSignal.timeout(20000), }) let env = {} @@ -969,6 +969,76 @@ function usageOf(sum, plan) { return out } +// The packages' codes, as WorkBuddy's own client lists them when it asks +// for each package's credits (its COMMODITY_CODES): the API refuses a +// detail list without them (10001 "PackageCodes required"). +const CODE = (n, s) => `TCACA_code_${n}_${s}` +const PAID_CODES = [CODE("002", "AkiJS3ZHF5"), CODE("005", "maRGyrHhw1"), CODE("003", "FAnt7lcmRT"), CODE("023", "4xbGhMrE6q"), + CODE("026", "BaESVICNoi"), CODE("027", "0FCGVA6vSa"), CODE("009", "0XmEQc2xOf"), CODE("038", "OhvqZtiPKr"), CODE("036", "lupO5WgNdG")] +const DAILY_CODE = CODE("001", "PqouKr6QWV") +const FREE_CODES = [DAILY_CODE, CODE("008", "cfWoLwvjU4"), CODE("035", "ArVxJcGDsm"), CODE("006", "DbXS0lrypC"), CODE("039", "KRcQj7wUat"), + CODE("040", "mi9rCYg46x"), CODE("007", "nzdH5h4Nl0"), CODE("028", "NtpWi0jzXs"), CODE("037", "WxOD3MpI2o"), CODE("029", "6wCGEWquYy"), + CODE("030", "BjSt89qTvr")] +// a slice package (CapacityType 4) is refreshed each day: its credits are +// lost at the same midnight on every account, so they tell none apart +const SLICE = "4" + +// beijing is WorkBuddy's own time ("2026-10-13 00:39:27" is UTC+8, as its +// DeductionEndTime for the same package says). +const beijing = (ms) => new Date(ms + 8 * 3600_000).toISOString().slice(0, 19).replace("T", " ") + +// packagesOf is every package of the account with credits, paid and free, +// as WorkBuddy's client asks for them: active and used-up (Status 0, 3), +// up to 10 pages of 200. +async function packagesOf(site, a, now = Date.now()) { + const day = beijing(now).slice(0, 10) + const lists = [ + ["/billing/meter/get-user-resource-paid-packages", { PackageCodes: PAID_CODES, NeedRenewInfo: true }], + ["/billing/meter/get-user-resource-free-packages", { PackageCodes: FREE_CODES, SlicePeriodStartTime: day + " 00:00:00", SlicePeriodEndTime: day + " 23:59:59" }], + ] + const out = [] + for (const [path, extra] of lists) { + for (let page = 1; page <= 10; page++) { + const d = await meter(site, a, path, { PageNumber: page, PageSize: 200, Status: [0, 3], ...extra }) + const got = d?.Accounts ?? [] + out.push(...got) + if (got.length < 200 || out.length >= (d?.TotalCount ?? 0)) break + } + } + return out +} + +// endOf is when a package's credits are lost: its DeductionEndTime, else +// ExpiredTime, else the cycle's end (UTC+8), as WorkBuddy's client reads it. +function endOf(p) { + const ms = Number(p?.DeductionEndTime) + if (ms > 0) return ms + for (const v of [p?.ExpiredTime, p?.CycleEndTime]) { + if (typeof v !== "string" || !v.trim()) continue + const t = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(v.trim()) ? Date.parse(v.trim().replace(" ", "T") + "+08:00") : Date.parse(v) + if (t > 0) return t + } + return 0 +} + +// runsOutOf is the soonest moment credits left in one of the account's +// packages are lost, and how many (cdredfox on X): smart routing spends +// the account whose credits expire first. Only packages the summary +// counts, with credits left, and not the daily slice; null when none. +function runsOutOf(sum, packages, now = Date.now()) { + const counted = new Set((sum?.Packages ?? []).map((p) => p?.PackageCode)) + let at = 0, amount = 0 + for (const p of packages ?? []) { + if (!counted.has(p?.PackageCode) || p?.PackageCode === DAILY_CODE || String(p?.CapacityType) === SLICE) continue + const left = capacity(p?.CycleCapacityRemainPrecise ?? p?.CycleCapacityRemain) + const end = endOf(p) + if (!(left > 0) || end <= now) continue + if (!at || end < at) at = end, amount = left + else if (end === at) amount += left + } + return at ? { runsOutAt: new Date(at).toISOString(), runsOut: amount } : null +} + // ---- models ----------------------------------------------------------------- // variants are the reasoning levels as OpenCode gives them to the AI SDK. @@ -1166,7 +1236,17 @@ function makePlugin(site) { try { const a = await current(site, client, auth) // the meter has no /v2 prefix, on either site - return { ...usageOf(await meter(site, a, "/billing/meter/get-user-resource-summary"), auth.plan), signIn: "kept" } + const sum = await meter(site, a, "/billing/meter/get-user-resource-summary") + const out = usageOf(sum, auth.plan) + // when the credits left run out, for routing to spend them first; + // a list that can't be read leaves it unknown, the card stands + const credits = out.windows.find((w) => w.name === "Credits") + if (credits) { + try { + Object.assign(credits, runsOutOf(sum, await packagesOf(site, a)) ?? {}) + } catch {} + } + return { ...out, signIn: "kept" } } catch (e) { return { error: e?.message ?? String(e), signIn: "kept" } } @@ -1258,4 +1338,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf } +export const _internal = { runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 07ce287..941f2f7 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.13", + "version": "0.1.14", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs", diff --git a/packages/workbuddy/usage.test.mjs b/packages/workbuddy/usage.test.mjs index 5ec405a..ebaba32 100644 --- a/packages/workbuddy/usage.test.mjs +++ b/packages/workbuddy/usage.test.mjs @@ -185,3 +185,69 @@ test("each model's rate is its credits", async () => { expect(["x0.03", " X1.00 ", 1.5, "0"].map(creditsOf)).toEqual([0.03, 1, 1.5, 0]) for (const c of ["", null, undefined, "free", "x-1", "Infinity"]) expect(creditsOf(c)).toBeUndefined() }) + +// the detail lists as www.workbuddy.ai sent them for a Pro account on +// 2026-10-11 (ids left out): the Bonus Pack's 232.4 credits left end on +// 10-13, before Pro's on 10-29; the Free Plan's daily slice (CapacityType +// 4) isn't in the summary and ends at the same midnight on every account +const BONUS = "TCACA_code_006_DbXS0lrypC" +const AI_SUMMARY = { IsPaidUser: true, Packages: [ + { PackageCode: "TCACA_code_002_AkiJS3ZHF5", CycleTotalCapacity: "1000", CycleRemainCapacity: "1000", CycleUsedCapacity: "0" }, + { PackageCode: BONUS, CycleTotalCapacity: "250", CycleRemainCapacity: "232.4", CycleUsedCapacity: "17.6" }, + { PackageCode: "TCACA_code_037_WxOD3MpI2o", CycleTotalCapacity: "1000", CycleRemainCapacity: "1000", CycleUsedCapacity: "0" }, +] } +const AI_PAID = { TotalCount: 1, Accounts: [ + { PackageCode: "TCACA_code_002_AkiJS3ZHF5", PackageName: "Pro Monthly", CapacityType: 2, CycleCapacityRemainPrecise: "1000", CycleStartTime: "2026-09-29 00:40:52", CycleEndTime: "2026-10-29 00:40:52", DeductionEndTime: 1793205652000, ExpiredTime: "" }, +] } +const AI_FREE = { TotalCount: 3, Accounts: [ + { PackageCode: BONUS, PackageName: "Bonus Pack", CapacityType: 1, CycleCapacityRemainPrecise: "232.4", CycleStartTime: "2026-09-29 00:39:27", CycleEndTime: "2026-10-13 00:39:27", DeductionEndTime: 1791823167000, ExpiredTime: "" }, + { PackageCode: "TCACA_code_037_WxOD3MpI2o", PackageName: "Plan Bonus", CapacityType: 2, CycleCapacityRemainPrecise: "1000", CycleStartTime: "2026-09-29 00:40:52", CycleEndTime: "2026-10-29 00:40:52", DeductionEndTime: 1793205652000, ExpiredTime: "" }, + { PackageCode: "TCACA_code_035_ArVxJcGDsm", PackageName: "Free Plan", CapacityType: 4, CycleCapacityRemainPrecise: "100", CycleStartTime: "2026-10-01 00:00:00", CycleEndTime: "2026-10-31 23:59:59", DeductionEndTime: 2050936768000, ExpiredTime: "" }, +] } + +test("the credits that run out soonest, for routing to spend first (cdredfox on X)", async () => { + // the same lists ten years on, so the test still reads them as to come + const YEARS = 10, later10 = (d) => ({ ...d, Accounts: d.Accounts.map((p) => ({ ...p, DeductionEndTime: p.DeductionEndTime + Date.UTC(2036, 9, 1) - Date.UTC(2026, 9, 1), + CycleEndTime: String(Number(p.CycleEndTime.slice(0, 4)) + YEARS) + p.CycleEndTime.slice(4) })) }) + const bodies = {} + serve({ + "/billing/meter/get-user-resource-summary": () => ok(AI_SUMMARY), + "/billing/meter/get-user-resource-paid-packages": (init) => ((bodies.paid = JSON.parse(init.body)), ok(later10(AI_PAID))), + "/billing/meter/get-user-resource-free-packages": (init) => ((bodies.free = JSON.parse(init.body)), ok(later10(AI_FREE))), + }) + const auth = { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u" } + const u = await usageOf(WorkBuddyAIAuthPlugin, auth) + const w = u.windows.find((x) => x.name === "Credits") + expect(w.runsOutAt).toBe("2036-10-12T16:39:27.000Z") + expect(w.runsOut).toBe(232.4) + // the lists are asked for as WorkBuddy's client asks: without the codes + // the API answers 10001 "PackageCodes required" + expect(bodies.paid).toMatchObject({ PageNumber: 1, PageSize: 200, Status: [0, 3], NeedRenewInfo: true }) + expect(bodies.paid.PackageCodes).toContain("TCACA_code_002_AkiJS3ZHF5") + expect(bodies.free.PackageCodes).toContain(BONUS) + expect(bodies.free.SlicePeriodStartTime).toMatch(/^\d{4}-\d{2}-\d{2} 00:00:00$/) +}) + +test("runsOutOf: soonest end of credits left, by the summary's packages, never the daily slice", () => { + const now = Date.parse("2026-10-11T12:00:00Z") + expect(_internal.runsOutOf(AI_SUMMARY, [...AI_PAID.Accounts, ...AI_FREE.Accounts], now)).toEqual({ runsOutAt: "2026-10-12T16:39:27.000Z", runsOut: 232.4 }) + // the Bonus Pack spent: Pro and Plan Bonus end together, both count + const spent = AI_FREE.Accounts.map((p) => (p.PackageCode === BONUS ? { ...p, CycleCapacityRemainPrecise: "0" } : p)) + expect(_internal.runsOutOf(AI_SUMMARY, [...AI_PAID.Accounts, ...spent], now)).toEqual({ runsOutAt: "2026-10-28T16:40:52.000Z", runsOut: 2000 }) + // no DeductionEndTime: the cycle's end is read as UTC+8 + const plain = [{ ...AI_FREE.Accounts[0], DeductionEndTime: 0 }] + expect(_internal.runsOutOf(AI_SUMMARY, plain, now)).toEqual({ runsOutAt: "2026-10-12T16:39:27.000Z", runsOut: 232.4 }) + // only the daily slice, or a package already over: unknown + expect(_internal.runsOutOf(AI_SUMMARY, [AI_FREE.Accounts[2]], now)).toBeNull() + expect(_internal.runsOutOf(AI_SUMMARY, AI_FREE.Accounts, Date.parse("2026-11-01T00:00:00Z"))).toBeNull() +}) + +test("a detail list that can't be read leaves the card as it was", async () => { + serve({ + "/billing/meter/get-user-resource-summary": () => ok(AI_SUMMARY), + "/billing/meter/get-user-resource-paid-packages": () => new Response(JSON.stringify({ code: 10001, msg: "PackageCodes required" }), { status: 400 }), + }) + const u = await usageOf(WorkBuddyAIAuthPlugin, { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u" }) + expect(u.error).toBeUndefined() + expect(u.windows[0]).toEqual({ name: "Credits", used: 100 * 17.6 / 2250, display: "17.6 / 2250", amount: 17.6, limit: 2250, unit: "credits" }) +})