From 3f73907aacbd399cb6fe0b0c7237324c98f4a776 Mon Sep 17 00:00:00 2001 From: Euraxluo Date: Thu, 29 Oct 2026 21:46:35 +0800 Subject: [PATCH] workbuddy 0.2.0: WorkBuddy (China) daily check-in through the billing meter (#177) WorkBuddy (China) claims its daily check-in credits through the billing meter's /v2 activity status and daily-checkin. Outcomes are done, ineligible, inactive, claimed and failed, all of which magpie's host accepts. A request that gets no answer is thrown, for magpie's 1-minute backoff. The AI build has no hook. The review merged main (0.1.48) in, resolving the conflicts in meter, the hook list, _internal and README. It also made an API-key account ineligible without sending a request, and set the version to 0.2.0. Run at d66f51c on mote, with a temp HOME: - bun test packages/workbuddy: 253 pass, 0 fail - the whole repo: 3521 pass, 0 fail (3529 tests) - bun scripts/check.mjs workbuddy: ok Broken by hand, each red: - dropping the API-key line: its new test - the hook on the AI build: "WorkBuddy AI's plugin has no check-in" - an unreadable 200 not thrown: the usage test and the check-in test Not covered: main's own invalidToken flag on a refused meter reply has no test that fails without it. That gap is on main and was kept as it is. --- packages/workbuddy/README.md | 27 ++++- packages/workbuddy/checkin.test.mjs | 170 ++++++++++++++++++++++++++++ packages/workbuddy/index.mjs | 119 +++++++++++++++++-- packages/workbuddy/package.json | 2 +- packages/workbuddy/usage.test.mjs | 6 + 5 files changed, 307 insertions(+), 17 deletions(-) create mode 100644 packages/workbuddy/checkin.test.mjs diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 2635a83..604e8aa 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -397,11 +397,30 @@ entry. An already signed-in browser can simply renew another saved account. ## Not here -magpie's built-in WorkBuddy does more than this package: -- the daily check-in; -- the credits meter (`/billing/meter/get-user-resource-summary`); -- several accounts under one provider. +magpie's built-in WorkBuddy does more than this package: several accounts +under one provider. OpenCode's plugin API has no place for these. Credit multipliers accept the international catalog's `x0.34 credits` text as well as `x0.34`. An empty credits value (for example Auto) stays unknown, never free. + +## Daily check-in + +The account's daily credits are claimed through the billing meter. magpie +can run it once a day per account when its WorkBuddy check-in switch is on; +Settings → Usage → Plugins has that switch and a *Check in now* button. +The activity status is read first: inactive is `inactive`, a day already +checked in is `done`, and only an active unchecked day is claimed. A claim +that WorkBuddy answers 1001, 1002 or 1003 is `done`, `ineligible` or +`inactive`. A claim turned away 401 while the account's credits still read +is `ineligible`: that check-in takes WorkBuddy's own app. A transient +billing failure is retried twice before the card shows the failure. +Only WorkBuddy (China) checks in: the AI build has no claim endpoint, and +its plugin carries no check-in hook. +A request that gets no answer at all leaves the hook as a thrown error, so +magpie retries it on its 1-minute offline backoff rather than the 30-minute +one it gives a failed answer (#149). + +An `inactive` answer is kept for the whole Beijing day: the plugin host +gives it no recheck, and a manual refresh reads the kept one (tracked in +[yetone/magpie#2696](https://github.com/yetone/magpie/issues/2696)). diff --git a/packages/workbuddy/checkin.test.mjs b/packages/workbuddy/checkin.test.mjs new file mode 100644 index 0000000..8cd7be0 --- /dev/null +++ b/packages/workbuddy/checkin.test.mjs @@ -0,0 +1,170 @@ +// The daily check-in through the billing meter, with WorkBuddy's own path +// and idempotent answer. Everything stays on a local fake. +import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal +beforeAll(async () => { + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } = await import("./index.mjs")) +}) +const offline = async () => { throw new Error("no network in tests") } +const real = globalThis.fetch +globalThis.fetch = offline +afterAll(() => (globalThis.fetch = real)) +afterEach(() => { + globalThis.fetch = offline + _internal.renewing.clear() + _internal.renewed.clear() +}) + +const later = () => Date.now() + 3600_000 +const ok = (data = {}) => new Response(JSON.stringify({ code: 0, msg: "ok", data })) +const business = (code, msg) => new Response(JSON.stringify({ code, msg })) +const checkinOf = async (plugin, auth, client = {}) => (await plugin({ client })).auth.checkin(async () => auth) + +function serve(routes) { + const calls = [] + globalThis.fetch = async (url, init) => { + const u = new URL(String(url)) + calls.push({ url: u, init, headers: new Headers(init?.headers) }) + const r = routes[u.pathname] + return r ? r(init) : new Response("", { status: 404 }) + } + return calls +} + +test("China asks the activity status, then claims through /v2", async () => { + const calls = serve({ + "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, todayCheckedIn: false }), + "/v2/billing/meter/daily-checkin": () => ok(), + }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual({ outcome: "claimed" }) + expect(calls.map((c) => c.url.pathname)).toEqual(["/v2/billing/meter/checkin-activity-status", "/v2/billing/meter/daily-checkin"]) + const c = calls[1] + expect(c.init.method).toBe("POST") + expect(c.init.body).toBe("{}") + expect(c.headers.get("authorization")).toBe("Bearer at") + expect(c.headers.get("x-user-id")).toBe("u") + expect(c.headers.get("user-agent")).toBe("WorkBuddy/5.9.3") +}) + +test("the activity status already claimed is done without another claim", async () => { + const calls = serve({ "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, today_checked_in: true, daily_credit: 100 }) }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual({ outcome: "done", credit: 100 }) + expect(calls).toHaveLength(1) +}) + +test("the status code for an already checked day is done", async () => { + const calls = serve({ "/v2/billing/meter/checkin-activity-status": () => business(1001, "今天已签到,请明天再来") }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual({ outcome: "done" }) + expect(calls).toHaveLength(1) +}) + +test("an inactive activity is inactive", async () => { + const calls = serve({ "/v2/billing/meter/checkin-activity-status": () => ok({ active: false, todayCheckedIn: false }) }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual({ outcome: "inactive" }) + expect(calls).toHaveLength(1) +}) + +test("WorkBuddy's already, ineligible and ended codes are distinct", async () => { + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + for (const [code, expected] of [[1001, { outcome: "done" }], [1002, { outcome: "ineligible", message: "not eligible" }], [1003, { outcome: "inactive", message: "event over" }]]) { + serve({ + "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, todayCheckedIn: false }), + "/v2/billing/meter/daily-checkin": () => business(code, code === 1001 ? "already" : code === 1002 ? "not eligible" : "event over"), + }) + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual(expected) + } +}) + +test("a claim 401 while credits still read points to WorkBuddy's own app", async () => { + const calls = serve({ + "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, todayCheckedIn: false }), + "/v2/billing/meter/daily-checkin": () => new Response("", { status: 401 }), + "/billing/meter/get-user-resource-summary": () => ok({}), + }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual({ outcome: "ineligible", message: "WorkBuddy's check-in takes WorkBuddy's own app" }) + expect(calls).toHaveLength(3) +}) + +test("an unreadable reply is failed, never claimed", async () => { + serve({ + "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, todayCheckedIn: false }), + "/v2/billing/meter/daily-checkin": () => new Response(""), + }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + const out = await checkinOf(WorkBuddyAuthPlugin, auth) + expect(out.outcome).toBe("failed") + expect(out.message).toContain("unreadable") +}) + +test("a transient billing failure retries twice, then reports failure", async () => { + let calls = 0 + serve({ + "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, todayCheckedIn: false }), + "/v2/billing/meter/daily-checkin": () => { calls++; return business(10000, "API request failed with status code: 500") }, + }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + const out = await checkinOf(WorkBuddyAuthPlugin, auth) + expect(out.outcome).toBe("failed") + expect(calls).toBe(3) +}, 8000) + +test("a token near its end is renewed before the claim", async () => { + const sets = [] + const calls = serve({ + "/v2/plugin/auth/token/refresh": () => ok({ accessToken: "new", refreshToken: "r2", expiresIn: 3600 }), + "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, todayCheckedIn: false }), + "/v2/billing/meter/daily-checkin": () => ok(), + }) + const auth = { type: "oauth", access: "old", refresh: "r", expires: Date.now() + 60_000, uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth, { auth: { set: async (x) => sets.push(x) } })).toEqual({ outcome: "claimed" }) + expect(calls[0].url.pathname).toBe("/v2/plugin/auth/token/refresh") + expect(calls[1].headers.get("authorization")).toBe("Bearer new") + expect(sets).toHaveLength(1) +}) + +test("a day already in reports today's credit, the built-in's word for it", async () => { + serve({ "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, today_checked_in: true, today_credit: 30, daily_credit: 100 }) }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual({ outcome: "done", credit: 30 }) +}) + +test("the claim's credit, streak and message reach the card", async () => { + serve({ + "/v2/billing/meter/checkin-activity-status": () => ok({ active: true, todayCheckedIn: false }), + "/v2/billing/meter/daily-checkin": () => ok({ credit: 30, streak_days: 3, message: "签到成功,连续签到3天" }), + }) + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(await checkinOf(WorkBuddyAuthPlugin, auth)).toEqual({ outcome: "claimed", credit: 30, streak: 3, message: "签到成功,连续签到3天" }) +}) + +test("an unclassified failure leaves the hook as a throw, not a failed answer", async () => { + // magpie's wbCheckinFailed runs on a thrown error and keeps the offline + // words for its 1-minute backoff; a returned failed waits 30 minutes + globalThis.fetch = async () => { throw new Error("ECONNRESET: The socket connection was closed unexpectedly.") } + const auth = { type: "oauth", access: "at", refresh: "r", expires: later(), uid: "u", domain: "" } + expect(checkinOf(WorkBuddyAuthPlugin, auth)).rejects.toThrow("ECONNRESET") +}) + +test("WorkBuddy AI's plugin has no check-in", async () => { + // the meter is China's; the AI build has no claim endpoint (#47) + const hooks = await WorkBuddyAIAuthPlugin({ client: {} }) + expect(hooks.auth.checkin).toBeUndefined() +}) + +test("an API key account is ineligible, and nothing is asked", async () => { + // a key reads no credits, so a failed answer would only be asked again + // every 30 minutes all day + const calls = serve({}) + const got = await checkinOf(WorkBuddyAuthPlugin, { type: "api", key: "ck_test" }) + expect(got.outcome).toBe("ineligible") + expect(calls).toHaveLength(0) +}) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 9afb317..97bd442 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -1868,23 +1868,99 @@ function signedOut(site, a, why, expired, note) { // the same: WorkBuddy's message, else its code, else the HTTP status. async function meter(site, a, path, body = {}) { const res = await meterAsked(site, a, path, body) + const raw = await res.text() let env = {} + let parsed = true try { - env = JSON.parse(await res.text()) ?? {} - } catch {} - const code = Number.parseInt(env.code, 10) || 0 - if (!res.ok) { - // the status and whether the token itself was refused go with it, for - // usage's one renewal on a 401 (reissued) - const said = { status: res.status, invalidToken: invalidToken(res) } - if (code) throw Object.assign(new Error(env.msg || `error ${code}`), said) - if (env.msg) throw Object.assign(new Error(env.msg), said) - throw Object.assign(new Error(statusText(res.status)), said) + env = JSON.parse(raw) ?? {} + } catch { + parsed = false } - if (code) throw new Error(env.msg || `error ${code}`) + if (res.ok && !parsed) { + const unreadable = raw.trim().slice(0, 120) || "(empty)" + throw Object.assign(new Error(`unreadable reply ${unreadable}`), { status: res.status, code: 0, unreadable: true }) + } + const code = Number.parseInt(env.code, 10) || 0 + // the status, the code and whether the token itself was refused go with + // it, for usage's one renewal on a 401 (reissued) and check-in's outcomes + const said = { status: res.status, code } + if (!res.ok) said.invalidToken = invalidToken(res) + const err = (message) => Object.assign(new Error(message), said) + if (!res.ok) { + if (code) throw err(env.msg || `error ${code}`) + if (env.msg) throw err(env.msg) + throw err(statusText(res.status)) + } + if (code) throw err(env.msg || `error ${code}`) return env.data ?? null } +// checkinOf claims the account's daily credits. China has the /v2 meter; +// after the activity status names an active, unchecked day. Transient +// upstream failures are asked again twice (the bounded retry quota-hub +// observed on the billing endpoint; callers may shorten the waits for a +// test). +async function checkinOf(site, a, { waits = [0, 0] } = {}) { + let status + try { + status = await meter(site, a, "/v2/billing/meter/checkin-activity-status") + } catch (e) { + if (e?.code === 1001) return { outcome: "done" } + // a reply WorkBuddy sent is the day's failed answer; only a request + // that got no answer leaves as a throw, for magpie's offline backoff + if (e?.status !== undefined || e?.code !== undefined) return { outcome: "failed", message: e.message } + throw e + } + if (!status?.active) return { outcome: "inactive" } + if (status.today_checked_in ?? status.todayCheckedIn) { + // today_credit is what today actually gave, the built-in's word for a + // day already in; daily_credit is the day's grant + const credit = Number(status.today_credit ?? status.daily_credit) + return { outcome: "done", ...(Number.isFinite(credit) && credit > 0 ? { credit } : {}) } + } + const paths = ["/v2/billing/meter/daily-checkin"] + for (let attempt = 0; ; attempt++) { + let i = 0 + while (i < paths.length) { + try { + const got = await meter(site, a, paths[i++]) + // the claim's own answer, as the built-in hands it on: the credit + // and streak it granted and what it said, for the card + const credit = Number(got?.credit) + const streak = Number(got?.streak_days) + return { + outcome: "claimed", + ...(Number.isFinite(credit) && credit > 0 ? { credit } : {}), + ...(Number.isFinite(streak) && streak > 0 ? { streak } : {}), + ...(got?.message ? { message: String(got.message) } : {}), + } + } catch (e) { + if (e?.code === 1001) return { outcome: "done" } + if (e?.code === 1002) return { outcome: "ineligible", message: e.message } + if (e?.code === 1003) return { outcome: "inactive", message: e.message } + if (e?.status === 401) { + try { + await meter(site, a, "/billing/meter/get-user-resource-summary") + } catch { + throw e + } + return { outcome: "ineligible", message: "WorkBuddy's check-in takes WorkBuddy's own app" } + } + if (e?.unreadable) return { outcome: "failed", message: `check-in: ${e.message}` } + const transient = e?.status >= 500 || e?.code === 10000 + if (transient && attempt < waits.length) { + await new Promise((r) => setTimeout(r, waits[attempt])) + break + } + // a reply WorkBuddy sent is the day's failed answer; only a request + // that got no answer leaves as a throw, for magpie's offline backoff + if (e?.status !== undefined || e?.code !== undefined) return { outcome: "failed", message: e.message } + throw e + } + } + } +} + // capacity is a capacity the billing API sends, as a string ("438.88") // or now and then a number; empty is 0. function capacity(v) { @@ -3036,6 +3112,25 @@ function makePlugin(site) { // and is renewed as before. refreshLead: LEAD_MS, refresh: (auth) => refreshed(site, auth), + // the account's daily check-in: magpie can run it once a day per + // account, when its WorkBuddy check-in switch is on; the button in + // Settings asks right away. China's meter only: the AI build has no + // check-in (#47), so the hook stays off its plugin. Errors leave as + // throws, not as failed answers: host.js answers a throwing hook to + // magpie as an error, whose wbCheckinFailed keeps the offline words + // and magpie's 1-minute backoff, where a returned failed waits the + // full 30 minutes (magpie-community/plugins#149). checkinOf returns + // an outcome only for answers it read and classified. + ...(site.ai ? {} : { + async checkin(getAuth) { + const auth = await getAuth() + // an API key reads no credits (see usage), so it has no day to claim + if (auth?.type === "api") return { outcome: "ineligible", message: "check-in needs a signed-in account, not an API key" } + if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { outcome: "failed", message: "not signed in" } + const a = await current(site, client, auth) + return await checkinOf(site, a, { waits: [2000, 4000] }) + }, + }), options: [ { key: FREE_ONLY, @@ -3409,4 +3504,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { idFor, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +export const _internal = { idFor, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 9eac898..83e65f7 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.48", + "version": "0.2.0", "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 a007653..1d97411 100644 --- a/packages/workbuddy/usage.test.mjs +++ b/packages/workbuddy/usage.test.mjs @@ -131,6 +131,12 @@ test("any refused status is an error with words", async () => { } }) +test("a successful but unreadable usage reply is the card's error, not empty credits", async () => { + const auth = { type: "oauth", access: "a", expires: later(), uid: "u" } + serve({ "/billing/meter/get-user-resource-summary": () => new Response("gateway") }) + expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", error: "unreadable reply gateway" }) +}) + test("a token near its end is renewed and saved, as the loader does", async () => { const sets = [] const calls = serve({