diff --git a/packages/codearts/README.md b/packages/codearts/README.md index d520ac9..d1f2024 100644 --- a/packages/codearts/README.md +++ b/packages/codearts/README.md @@ -223,10 +223,14 @@ naming the Basic pair) renews the credential once and sends it again — but onl changed the pair; the same pair would get the same refusal. An account that signed in without opening MaaS gets a `400` saying so, not an empty Basic header sent upstream. -**Usage and check-in.** `GET {subscription}/v1/subscription`: plan buckets (`skus[].quotas`) and -activity bonuses (`bonus_skus`) become magpie windows; a `.trial` bucket carries no expiry and -gets none invented; an expired bucket is folded away (`aside`) and takes no part in routing. The -check-in is `POST {subscription}/v1/subscription/bonus/claim` once a Beijing day: a 2xx with no +**Usage and check-in.** `GET {subscription}/v1/subscription`: the total of all unexpired plan +buckets (`skus[].quotas`) and activity bonuses (`bonus_skus`) is the one routing window; each +bucket remains visible as an `aside` detail. A `.trial` bucket carries no expiry and gets none +invented; an expired bucket is folded away and takes no part in the active total. The total's +`runsOutAt` is the soonest still-funded bucket to expire, and `runsOut` is the remaining credit +that expires on that Beijing day. When every bucket has expired, a used-up total remains so the +account is paused instead of being routed without a limit. The check-in is +`POST {subscription}/v1/subscription/bonus/claim` once a Beijing day: a 2xx with no `bonus_skus` is 「今日已无新增可领」 (`done`), not a failure. Turn on *Auto check-in* for OfficeAce under **Settings → Usage → Plugins**. @@ -338,8 +342,10 @@ measurements and code of [HuHong-Tao](https://github.com/yuweihao17/codearts/pul 去掉 `officeace/` 前缀,发到凭据里自带的 MaaS 地址(为空时用官方直连)。`401`(或 4xx 但报文点名这对 Basic 凭据) 会先续期一次再重发,**但只有续期真的换了这对凭据时才重发**。已登录但没开通 MaaS 的账号会得到一条说清原因的 `400`, 不会把空的 Basic 头发给上游。 -- **OfficeAce 的用量与签到**:`/v1/subscription` 的套餐桶(`skus[].quotas`)与活动桶(`bonus_skus`)转成 magpie 的窗口; - `.trial` 桶没有到期时间就不显示;已过期的桶收进折叠区(`aside`)且不参与路由。签到是每个北京自然日一次 +- **OfficeAce 的用量与签到**:`/v1/subscription` 中所有未过期套餐桶(`skus[].quotas`)和活动桶(`bonus_skus`) + 汇总成唯一参与路由的「总积分」窗口,各桶只作为 `aside` 明细展示;`.trial` 桶没有到期时间就不显示; + 已过期的桶收进折叠区且不参与有效余额汇总。「总积分」用仍有余额的桶里最早到期者作为 `runsOutAt`, + 并把同一北京自然日到期的余额合为 `runsOut`;如果所有桶都已过期,仍保留一个已用尽的总积分窗口来暂停账号。签到是每个北京自然日一次 `POST /v1/subscription/bonus/claim`:2xx 但 `bonus_skus` 为空是「今日已无新增可领」(`done`),不是失败。 - **已知限制**:STS 的 refresh_token 只能用一次。本包的每张卡各自登录、各自持有一条记录与一个 token,所以两张卡 互不影响;**续期只写被续的那条记录**,因此用户删掉的账号永远不会被写回来(无论它此前有没有被列出/使用过、 diff --git a/packages/codearts/index.mjs b/packages/codearts/index.mjs index fd9ca05..92fcd1b 100644 --- a/packages/codearts/index.mjs +++ b/packages/codearts/index.mjs @@ -3941,17 +3941,18 @@ function officeAceLiveModels(rows, baseUrl, rates) { * One usage window. * * An expired bucket is folded away (`aside`) and carries no amount/limit: its - * own total would become the denominator and read as "100% left". It takes no - * part in routing either, so the fold is all it needs to say. + * own total would become the denominator and read as "100% left". Active + * package details keep their numbers but are also `aside`; only the aggregate + * window may pause the account. */ -function officeAceWindow({ name, used, display, unit, resetsAt = "", expired = false, amount = 0, limit = 0 }) { +function officeAceWindow({ name, used, display, unit, resetsAt = "", expired = false, aside = false, amount = 0, limit = 0 }) { return { name, used, display, unit, ...(resetsAt ? { resetsAt } : {}), - ...(expired ? { aside: true } : { amount, limit, span: 0 }), + ...(expired ? { aside: true } : { amount, limit, span: 0, ...(aside ? { aside: true } : {}) }), } } @@ -3960,8 +3961,9 @@ function officeAceWindow({ name, used, display, unit, resetsAt = "", expired = f * * Two kinds of bucket: `skus[].quotas[]` (`sku_attr_code === 'officeace_points'`) * and `bonus_skus[]`. A `.trial` sku carries no expiry (the trial never - * expires — show it as it is, never guess a date); an expired bucket is marked - * `aside` so the card folds it away instead of letting it hold the top slot. + * expires — show it as it is, never guess a date). Only the aggregate of + * unexpired buckets participates in routing; package details are `aside`, and + * expired buckets are folded away without routing amounts. */ async function fetchOfficeAceUsage(cred, fetcher = fetch) { const r = await officeAceSigned(cred, `${OA_SUBSCRIPTION_BASE}${OA_SUBSCRIPTION_PATH}`, "GET", undefined, fetcher) @@ -3977,9 +3979,18 @@ async function fetchOfficeAceUsage(cred, fetcher = fetch) { } const round = (n) => Math.round(n * 100) / 100 + const expiryOf = (value, ignored = false) => { + if (ignored || typeof value !== "string" || value.length === 0) return undefined + const at = Date.parse(value) + return Number.isFinite(at) ? at : undefined + } const windows = [] const nowMs = Date.now() let plan = "" + let aggregateAmount = 0 + let aggregateLimit = 0 + let expiredLimit = 0 + const aggregateBatches = [] for (const sku of Array.isArray(j?.skus) ? j.skus : []) { for (const q of Array.isArray(sku?.quotas) ? sku.quotas : []) { @@ -3988,19 +3999,28 @@ async function fetchOfficeAceUsage(cred, fetcher = fetch) { const used = Number(q.current_value) if (!Number.isFinite(total) || total <= 0) continue const isTrial = String(sku.sku_code ?? "").endsWith(".trial") - const expiresAt = typeof q.expired_time === "string" && q.expired_time.length > 0 ? q.expired_time : null - const remaining = Math.max(0, total - used) - const expired = expiresAt !== null && !isTrial && new Date(expiresAt).getTime() <= nowMs + const expiresAt = expiryOf(q.expired_time, isTrial) + const amount = Math.min(total, Math.max(0, Number.isFinite(used) ? used : 0)) + const remaining = total - amount + const expired = expiresAt !== undefined && expiresAt <= nowMs if (!plan && typeof sku.sku_name === "string") plan = sku.sku_name + if (expired) { + expiredLimit += total + } else { + aggregateAmount += amount + aggregateLimit += total + if (remaining > 0 && expiresAt !== undefined) aggregateBatches.push({ left: remaining, expiresAt }) + } windows.push(officeAceWindow({ name: `${sku.sku_name ?? "套餐"} · 剩 ${round(remaining)}`, - used: Math.min(100, Math.max(0, Math.round((used / total) * 100))), + used: Math.min(100, Math.max(0, Math.round((amount / total) * 100))), // a `.trial` sku carries no expiry: nothing to invent - resetsAt: isTrial || expiresAt === null ? "" : new Date(expiresAt).toISOString(), + resetsAt: expiresAt === undefined ? "" : new Date(expiresAt).toISOString(), display: `${round(remaining)} / ${round(total)}`, unit: "积分", expired, - amount: used, + aside: true, + amount, limit: total, })) } @@ -4010,21 +4030,61 @@ async function fetchOfficeAceUsage(cred, fetcher = fetch) { const points = Number(bonus?.points) if (!Number.isFinite(points) || points <= 0) continue const used = Number(bonus.current_value) - const remaining = Math.max(0, points - (Number.isFinite(used) ? used : 0)) - const expiresAt = typeof bonus.expired_time === "string" ? bonus.expired_time : null - const expired = expiresAt !== null && new Date(expiresAt).getTime() <= nowMs + const amount = Math.min(points, Math.max(0, Number.isFinite(used) ? used : 0)) + const remaining = points - amount + const expiresAt = expiryOf(bonus.expired_time) + const expired = expiresAt !== undefined && expiresAt <= nowMs + if (expired) { + expiredLimit += points + } else { + aggregateAmount += amount + aggregateLimit += points + if (remaining > 0 && expiresAt !== undefined) aggregateBatches.push({ left: remaining, expiresAt }) + } windows.push(officeAceWindow({ name: `${bonus.activity_name ?? "活动奖励"} · 剩 ${round(remaining)}`, - used: Math.min(100, Math.round(((points - remaining) / points) * 100)), - resetsAt: expiresAt === null ? "" : new Date(expiresAt).toISOString(), + used: Math.min(100, Math.round((amount / points) * 100)), + resetsAt: expiresAt === undefined ? "" : new Date(expiresAt).toISOString(), display: `${round(remaining)} / ${round(points)}`, unit: "积分", expired, - amount: points - remaining, + aside: true, + amount, limit: points, })) } + // An account whose every bucket expired still needs one used-up routing + // window. Without it every detail is aside and magpie would keep routing. + const active = aggregateLimit > 0 + const rawLimit = active ? aggregateLimit : expiredLimit + if (rawLimit > 0) { + const rawAmount = active ? Math.min(rawLimit, aggregateAmount) : rawLimit + const rawRemaining = Math.max(0, rawLimit - rawAmount) + const roundedLimit = round(rawLimit) + // Keep sub-half-cent values instead of turning the routing denominator + // into zero. Normal credit values remain rounded to two decimals. + const keepRaw = roundedLimit === 0 + const limit = keepRaw ? rawLimit : roundedLimit + const amount = keepRaw ? rawAmount : Math.min(limit, round(rawAmount)) + const remaining = keepRaw ? rawRemaining : round(Math.max(0, limit - amount)) + const total = officeAceWindow({ + name: `总积分 · 剩 ${remaining}`, + used: Math.min(100, Math.max(0, Math.round((rawAmount / rawLimit) * 100))), + display: `${remaining} / ${limit}`, + unit: "积分", + amount, + limit, + }) + const lapse = active ? soonestLapse(aggregateBatches, nowMs) : undefined + if (lapse && rawRemaining > 0) { + const runsOut = Math.min(lapse.credit, rawRemaining) + total.runsOutAt = new Date(lapse.at).toISOString() + total.runsOut = round(runsOut) || runsOut + } + windows.unshift(total) + } + return { plan, windows } } diff --git a/packages/codearts/index.test.mjs b/packages/codearts/index.test.mjs index 2e3033a..e666a49 100644 --- a/packages/codearts/index.test.mjs +++ b/packages/codearts/index.test.mjs @@ -2949,7 +2949,7 @@ test("an account signed in through officeace-auth is read as it is, no second si const usage = await plugin.auth.usage(async () => record) assert.equal(usage.plan, "个人体验版") assert.equal(usage.user, "189****8051") - assert.equal(usage.windows.length, 4) + assert.equal(usage.windows.length, 5) assert.match( seen[0].headers.get("authorization"), /^V11-HMAC-SHA256 Credential=HSTAOZ3JN3WWYF3L\/\d{8}\/cn-southwest-2\/apic, SignedHeaders=/, @@ -3003,10 +3003,19 @@ test("usage reads plan, trial and bonus buckets apart, and folds an expired one const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) const { windows } = await plugin.auth.usage(async () => record) + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "4940 / 8500") + assert.equal(total.amount, 3560) + assert.equal(total.limit, 8500) + assert.equal(total.runsOutAt, "2031-01-01T00:00:00.000Z") + assert.equal(total.runsOut, 4440) + assert.equal("aside" in total, false) + const trial = windows.find((w) => w.name.startsWith("个人体验版")) assert.equal(trial.display, "500 / 500") assert.equal(trial.amount, 0) assert.equal(trial.limit, 500) + assert.equal(trial.aside, true) // a `.trial` sku carries no expiry: the window must not invent one assert.equal("resetsAt" in trial, false) @@ -3016,6 +3025,7 @@ test("usage reads plan, trial and bonus buckets apart, and folds an expired one assert.equal(plan.limit, 4000) assert.equal(plan.used, 45) assert.equal(plan.resetsAt, "2031-01-01T00:00:00.000Z") + assert.equal(plan.aside, true) const old = windows.find((w) => w.name.startsWith("旧套餐")) assert.equal(old.aside, true) @@ -3027,6 +3037,179 @@ test("usage reads plan, trial and bonus buckets apart, and folds an expired one const bonus = windows.find((w) => w.name.startsWith("新用户专属福利")) assert.equal(bonus.display, "2220 / 4000") assert.equal(bonus.used, 45) + assert.equal(bonus.aside, true) +}) + +test("a spent OfficeAce daily bonus does not pause credits left in other buckets", async () => { + const { record } = await officeAceAuthRecord() + const body = { + skus: [{ + sku_code: "officeace_personal_trial.trial", + sku_name: "个人体验版", + quotas: [{ sku_attr_code: "officeace_points", sku_value: 500, current_value: 0, expired_time: "" }], + }], + bonus_skus: [ + { activity_name: "新用户专属福利", points: 4000, current_value: 294.78, expired_time: "2031-02-05T23:25:23.515Z" }, + { activity_name: "每日签到有礼", points: 100, current_value: 100, expired_time: "2030-11-11T15:59:59Z" }, + ], + } + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(body), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "4205.22 / 4600") + assert.equal(total.amount, 394.78) + assert.equal(total.limit, 4600) + assert.equal(total.runsOutAt, "2031-02-05T23:25:23.515Z") + assert.equal(total.runsOut, 3705.22) + assert.equal("aside" in total, false) + + const daily = windows.find((w) => w.name.startsWith("每日签到有礼")) + assert.equal(daily.display, "0 / 100") + assert.equal(daily.amount, 100) + assert.equal(daily.limit, 100) + assert.equal(daily.aside, true) + assert.equal(windows.filter((w) => !w.aside).length, 1) +}) + +test("the aggregate expires with the soonest funded OfficeAce bonus", async () => { + const { record } = await officeAceAuthRecord() + const body = { + skus: [], + bonus_skus: [ + { activity_name: "Bonus A", points: 4000, current_value: 100, expired_time: "2031-02-05T23:25:23.515Z" }, + { activity_name: "Bonus B", points: 60, current_value: 10, expired_time: "2030-11-11T15:59:59Z" }, + { activity_name: "Bonus C", points: 40, current_value: 0, expired_time: "2030-11-11T15:59:59Z" }, + ], + } + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(body), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "3990 / 4100") + assert.equal(total.amount, 110) + assert.equal(total.runsOutAt, "2030-11-11T15:59:59.000Z") + assert.equal(total.runsOut, 90) +}) + +test("OfficeAce aggregate excludes an expired bonus", async () => { + const { record } = await officeAceAuthRecord() + const body = { + skus: [], + bonus_skus: [ + { activity_name: "Active", points: 100, current_value: 10, expired_time: "2031-01-01T00:00:00Z" }, + { activity_name: "Expired", points: 1000, current_value: 0, expired_time: "2020-01-01T00:00:00Z" }, + ], + } + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(body), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "90 / 100") + assert.equal(total.amount, 10) + assert.equal(total.limit, 100) + const expired = windows.find((w) => w.name.startsWith("Expired")) + assert.equal(expired.aside, true) + assert.equal(expired.amount, undefined) + assert.equal(expired.limit, undefined) +}) + +test("OfficeAce aggregate rounds a floating-point sum to two decimals", async () => { + const { record } = await officeAceAuthRecord() + const body = { + skus: [], + bonus_skus: [ + { activity_name: "A", points: 400, current_value: 294.67, expired_time: "" }, + { activity_name: "B", points: 200, current_value: 100.11, expired_time: "" }, + ], + } + assert.notEqual(body.bonus_skus[0].current_value + body.bonus_skus[1].current_value, 394.78) + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(body), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "205.22 / 600") + assert.equal(total.amount, 394.78) + const detail = windows.find((w) => w.name.startsWith("A")) + assert.equal("resetsAt" in detail, false) +}) + +test("OfficeAce caps overspent buckets and their aggregate at the available credit", async () => { + const { record } = await officeAceAuthRecord() + const body = { + skus: [{ + sku_code: "officeace_personal_monthly", + sku_name: "Plan", + quotas: [{ sku_attr_code: "officeace_points", sku_value: 10, current_value: 11, expired_time: "" }], + }], + bonus_skus: [{ activity_name: "Bonus", points: 20, current_value: 21, expired_time: "" }], + } + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(body), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "0 / 30") + assert.equal(total.amount, 30) + assert.equal(total.limit, 30) + assert.equal(total.used, 100) + assert.equal(windows.find((w) => w.name.startsWith("Plan")).amount, 10) + assert.equal(windows.find((w) => w.name.startsWith("Bonus")).amount, 20) +}) + +test("an OfficeAce account with only expired buckets keeps a used-up routing total", async () => { + const { record } = await officeAceAuthRecord() + const body = { + skus: [], + bonus_skus: [{ activity_name: "Expired", points: 100, current_value: 0, expired_time: "2020-01-01T00:00:00Z" }], + } + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(body), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "0 / 100") + assert.equal(total.amount, 100) + assert.equal(total.limit, 100) + assert.equal(total.used, 100) + assert.equal("aside" in total, false) + assert.equal(windows.filter((w) => !w.aside).length, 1) +}) + +test("a sub-half-cent OfficeAce total stays finite and routable", async () => { + const { record } = await officeAceAuthRecord() + const body = { + skus: [], + bonus_skus: [{ activity_name: "Tiny", points: 0.004, current_value: 0.002, expired_time: "" }], + } + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(body), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const total = windows.find((w) => w.name.startsWith("总积分")) + assert.equal(total.display, "0.002 / 0.004") + assert.equal(total.amount, 0.002) + assert.equal(total.limit, 0.004) + assert.equal(total.used, 50) + assert.equal(Number.isFinite(total.used), true) }) test("a failed usage read is said, never shown as an empty account", async () => { diff --git a/packages/codearts/package.json b/packages/codearts/package.json index e160fb6..d7c9d93 100644 --- a/packages/codearts/package.json +++ b/packages/codearts/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-codearts-auth", - "version": "0.3.10", + "version": "0.3.11", "description": "Huawei Cloud in OpenCode and magpie: CodeArts (码道) and OfficeAce (AgentArts), each from its own Huawei Cloud OAuth sign-in — models, credit rates, credit usage and the daily check-in (unofficial)", "type": "module", "main": "./opencode.mjs",