codearts 0.3.8: a window's runsOut is only credit its own remainder holds (#982)
usageFromStatistics took the bonus window's runsOutAt/runsOut from the soonest check-in batch while remaining/used were the whole bucket, and the total's from every non-basic batch whatever the buckets had left. So an account whose check-in was spent (bonus remaining 0) still had a total runsOut of 82.05 at tonight's midnight, and one with 2344.81 long-lived gift credits said 100 lapse in hours while the vendor's package_credit_expiring_amount was 0. magpie's routing reads a total's RunsOutAt as "what is left is lost then" (Allowance.Renewal), so these accounts were ranked ahead of ones that really lapse sooner. Now: - each bucket's lapse is its own batches' soonest, held to that bucket's package_credit_remain; an empty bucket has none; - the total's lapse is the soonest of the buckets' lapses (same Beijing day summed), never from batches of a bucket with nothing left; - the ledger fallback's batches are marked `estimated` (what was spent of a check-in isn't known): they say when, and how much is the vendor's own expiring amount, so with 0 or none said there is no lapse; the vendor's batch reads (with consumed/expired counts) are used as before; - each window carries the vendor's package_credit_expiring_amount as `expiring` when it is sent; - comments and README say the ledger keeps the date the claim names (a day on for today's check-ins); 30 days is only for a claim with none. Run (wsl-run, magpie-desktop, at this tree rebased on origin/main): bun test packages/codearts: 177 pass, 0 fail; bun scripts/check.mjs: ok. Fixtures are the issue's two accounts as filed (A: bonus 100 used, 0 left, total 82.05 left; B: 4100 / 2344.81 left, ledger grant 100 claimed 2026-11-10T16:01:04.916Z expiring 2026-11-11T16:01:03.812Z, expiring 0), clock held at 2026-11-11T10:00Z. Broken by hand: cap = Infinity in bucketLapse: the three #982 tests red (174 pass, 3 fail). cap = remain (no estimated gate): account B's test red alone (176 pass, 1 fail). Not tried: a real CodeArts account; the vendor's horizon for package_credit_expiring_amount isn't known, so vendor batch reads are not gated on it. A lagging vendor batch counter is bounded by the bucket's remainder only. Reported-by: KiMelody
This commit is contained in:
@@ -124,8 +124,14 @@ rate), shown as `DeepSeek-V4.1-Flash-1017`, not folded into `DeepSeek-V4.1-Flash
|
||||
- When each credit batch expires is read from the CodeArts console's own calls
|
||||
(`snap-manager/v1/package/credit/page`, `v1/ops/credit/*`); when those can't be read, the
|
||||
plugin falls back to a small ledger of the check-ins it claimed,
|
||||
`~/.config/magpie/codearts-checkins.json` (or `MAGPIE_CODEARTS_LEDGER`). This part is still
|
||||
being checked against more accounts — trust the CodeArts console where they differ.
|
||||
`~/.config/magpie/codearts-checkins.json` (or `MAGPIE_CODEARTS_LEDGER`), each check-in until
|
||||
the date its claim named. This part is still being checked against more accounts — trust the
|
||||
CodeArts console where they differ.
|
||||
- A window's `runsOutAt` / `runsOut` is only credit its own remainder holds: none when the bucket
|
||||
is empty, never more than it has left, and the total's is the buckets' own. The ledger can't
|
||||
tell what was spent of a check-in, so from it the amount is the vendor's own
|
||||
`package_credit_expiring_amount` (each window's `expiring`), and with none said there is no
|
||||
lapse.
|
||||
- `auth.checkin`: the client's 「限时福利 → 每日领取」 — `GET /v1/ops/delivery?channel=IDE`,
|
||||
`POST /v1/ops/claim`, then `POST /v1/ops/confirm` when the claim answers an id. A claim whose
|
||||
confirm failed is kept in that ledger for the day and confirmed at the next check-in; one the
|
||||
|
||||
+53
-14
@@ -105,7 +105,8 @@ const MAIN_AGENT_FALLBACK_ID = "a8bcb36232554267a5142361cc25a393"
|
||||
// Agents tried for a model list before giving up.
|
||||
const AGENT_DETAIL_TRIES = 3
|
||||
const AGENT_CENTER_HEADERS = { "Content-Type": "application/json", "Agent-Type": "AgentCenter", "X-Language": "zh-cn" }
|
||||
// Check-in credits are good for 30 days from when they are given.
|
||||
// How long check-in credits last when the claim names no date of its own. The
|
||||
// vendor's date wins: today's check-ins answer one about a day on (#982).
|
||||
const CHECKIN_CREDIT_DAYS = 30
|
||||
// Every credit batch with its own expiry, as the console's 「获取明细」 reads
|
||||
// them (its /portal/snap-manager and /portal/promptcenter calls are these):
|
||||
@@ -2059,14 +2060,34 @@ function soonestLapse(batches, now = Date.now()) {
|
||||
return { at, credit: live.filter((b) => beijingDay(b.expiresAt) === day).reduce((n, b) => n + b.left, 0) }
|
||||
}
|
||||
|
||||
/** The plugin's own check-in ledger as batches, for when the vendor's can't be read. */
|
||||
/**
|
||||
* The plugin's own check-in ledger as batches, for when the vendor's can't be
|
||||
* read. What was spent of each is not known, so `left` is only the grant and
|
||||
* the batch is `estimated`: it tells when, never how much is still in it (#982).
|
||||
*/
|
||||
const grantBatches = (grants) =>
|
||||
(grants ?? []).map((g) => ({ metric: PACKAGE_TYPE_METRICS.bonus, amount: num(g.credit), left: num(g.credit), expiresAt: vendorDate(g.expiresAt) }))
|
||||
(grants ?? []).map((g) => ({
|
||||
metric: PACKAGE_TYPE_METRICS.bonus, amount: num(g.credit), left: num(g.credit), expiresAt: vendorDate(g.expiresAt), estimated: true,
|
||||
}))
|
||||
|
||||
/**
|
||||
* What of one bucket lapses soonest, apart from a reset: its own batches'
|
||||
* soonest lapse, never more than the bucket has left (a batch's own counter
|
||||
* can lag the bucket's). Estimated batches say only when; how much is the
|
||||
* vendor's own expiring amount, so with none said nothing lapses (#982).
|
||||
*/
|
||||
function bucketLapse(batches, remain, expiring, now) {
|
||||
const lapse = soonestLapse(batches, now)
|
||||
if (!lapse) return undefined
|
||||
const cap = batches.some((b) => b.estimated) ? Math.min(remain, expiring ?? 0) : remain
|
||||
const credit = Math.min(lapse.credit, cap)
|
||||
return credit > 0 ? { at: lapse.at, credit } : undefined
|
||||
}
|
||||
|
||||
// ---- the check-in ledger -----------------------------------------------------
|
||||
//
|
||||
// CodeArts tells how many credits a bucket holds, never when each given batch
|
||||
// lapses; check-in credits are good for 30 days from their day. The plugin keeps
|
||||
// lapses; a check-in's claim says when its credits do. The plugin keeps
|
||||
// the claims it made, per account, so the usage card can say when the soonest
|
||||
// of them runs out. Best effort: a ledger that can't be read or written only
|
||||
// leaves that line out.
|
||||
@@ -2505,9 +2526,11 @@ function benefitWindow(raw, ids = BENEFIT_MODEL_FALLBACK) {
|
||||
* fetchCreditBatches): the plan's batch gives the month's reset to the second,
|
||||
* and the soonest of the rest to lapse is each bucket's (and the total's)
|
||||
* `runsOutAt`/`runsOut`. Without them, `grants` (the check-ins the plugin
|
||||
* claimed, 30 days each) stand in, and the reset is `end_date`.
|
||||
* claimed, each until the date its claim said) stand in, and the reset is
|
||||
* `end_date`. A window's `runsOut` is only credit its own remainder holds:
|
||||
* none when that is 0, or when nothing in it lapses (#982).
|
||||
*/
|
||||
function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds } = {}) {
|
||||
function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds, now = Date.now() } = {}) {
|
||||
let data = raw
|
||||
if (raw && typeof raw.code === "number") {
|
||||
if (raw.code !== 0) return { error: firstOf(raw.message, raw.msg, `CodeArts code ${raw.code}`), windows: [] }
|
||||
@@ -2517,7 +2540,6 @@ function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds } =
|
||||
const pkg = asRecord(data.package)
|
||||
const plan = firstOf(pkg.package_name_cn, pkg.package_name_en, pkg.spec_code)
|
||||
const metrics = Array.isArray(data.metrics) ? data.metrics : []
|
||||
const now = Date.now()
|
||||
const known = batches ?? grantBatches(grants)
|
||||
// The plan's own batch ends when the month's allowance comes back.
|
||||
const planEnds = known.filter((b) => b.metric === PACKAGE_TYPE_METRICS.basic && b.expiresAt > now).map((b) => b.expiresAt)
|
||||
@@ -2533,21 +2555,38 @@ function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds } =
|
||||
const limit = num(rec.package_credit_amount)
|
||||
const remain = num(rec.package_credit_remain)
|
||||
if (limit <= 0 && remain <= 0) continue // empty bucket, nothing to show
|
||||
const said = rec.package_credit_expiring_amount
|
||||
const w = creditWindow(name, limit, remain, {
|
||||
resetsAt: MONTHLY_CREDIT_METRICS.includes(rec.name) ? resetsAt : undefined,
|
||||
expiring: num(rec.package_credit_expiring_amount),
|
||||
expiring: num(said),
|
||||
})
|
||||
// The vendor's own count of what is about to lapse, as a field (#982).
|
||||
if (said !== undefined && said !== null && said !== "") w.expiring = num(said)
|
||||
metricOf.set(w, rec.name)
|
||||
windows.push(w)
|
||||
}
|
||||
|
||||
// What lapses soonest, apart from the month's reset: a bucket's own
|
||||
// batches; for the total, every batch but the plan's.
|
||||
// What lapses soonest, apart from the month's reset: each bucket's own
|
||||
// batches, held to what that bucket has left; for the total, the soonest
|
||||
// of the buckets' lapses, what lapses that Beijing day summed.
|
||||
const lapses = new Map()
|
||||
for (const item of metrics) {
|
||||
const rec = asRecord(item)
|
||||
if (rec.name === TOTAL_CREDIT_METRIC || rec.name === PACKAGE_TYPE_METRICS.basic || lapses.has(rec.name)) continue
|
||||
if (!Object.values(PACKAGE_TYPE_METRICS).includes(rec.name)) continue
|
||||
const said = rec.package_credit_expiring_amount
|
||||
const expiring = said === undefined || said === null || said === "" ? undefined : num(said)
|
||||
const lapse = bucketLapse(known.filter((b) => b.metric === rec.name), Math.max(0, num(rec.package_credit_remain)), expiring, now)
|
||||
if (lapse) lapses.set(rec.name, lapse)
|
||||
}
|
||||
const soonest = lapses.size ? Math.min(...[...lapses.values()].map((l) => l.at)) : undefined
|
||||
for (const w of windows) {
|
||||
const metric = metricOf.get(w)
|
||||
if (metric === PACKAGE_TYPE_METRICS.basic) continue
|
||||
const own = known.filter((b) => (metric === TOTAL_CREDIT_METRIC ? b.metric !== PACKAGE_TYPE_METRICS.basic : b.metric === metric))
|
||||
const lapse = soonestLapse(own, now)
|
||||
let lapse = lapses.get(metric)
|
||||
if (metric === TOTAL_CREDIT_METRIC && soonest !== undefined) {
|
||||
const day = beijingDay(soonest)
|
||||
lapse = { at: soonest, credit: [...lapses.values()].filter((l) => beijingDay(l.at) === day).reduce((n, l) => n + l.credit, 0) }
|
||||
}
|
||||
const left = Math.max(0, w.limit - w.amount)
|
||||
if (lapse && left > 0) {
|
||||
w.runsOutAt = new Date(lapse.at).toISOString()
|
||||
@@ -3024,7 +3063,7 @@ export const _internal = {
|
||||
BENEFIT_CLAIM_URL, AGENT_LIST_URL, AGENT_DETAIL_URL, CODE_AGENT_ID,
|
||||
canonicalQuery, beijingDay, nextBeijingMidnight, vendorDate, creditRateOf,
|
||||
claimBenefit, ensureBenefitClaimed, parseAgentModel, fetchAgentModels,
|
||||
readGrants, recordGrant, readUnconfirmed, recordUnconfirmed, grantExpiry, grantBatches, soonestLapse, fetchCreditBatches,
|
||||
readGrants, recordGrant, readUnconfirmed, recordUnconfirmed, grantExpiry, grantBatches, soonestLapse, bucketLapse, fetchCreditBatches,
|
||||
PACKAGE_CREDIT_PAGE_URL, OPS_CREDIT_OVERVIEW_URL, OPS_CREDIT_CAMPAIGN_URL,
|
||||
toBytes, isBenefitModel, prepareChatBody, signedFetch, signedGet,
|
||||
TOOL_NAME_LIMIT, cutToolName, shortenToolNames, restoreToolNames, restoreToolNamesInStream,
|
||||
|
||||
@@ -593,7 +593,7 @@ test("usageFromStatistics: the soonest check-in credits to lapse show on the bon
|
||||
const usage = x.usageFromStatistics({
|
||||
metrics: [
|
||||
{ name: "usageTotalPackageCredit", package_credit_amount: 7000, package_credit_remain: 6500 },
|
||||
{ name: "usageBonusPackageCredit", package_credit_amount: 2000, package_credit_remain: 1500 },
|
||||
{ name: "usageBonusPackageCredit", package_credit_amount: 2000, package_credit_remain: 1500, package_credit_expiring_amount: 1000 },
|
||||
],
|
||||
}, undefined, { grants })
|
||||
const bonus = usage.windows.find((w) => w.name === "赠送积分包")
|
||||
@@ -604,6 +604,84 @@ test("usageFromStatistics: the soonest check-in credits to lapse show on the bon
|
||||
assert.equal(x.soonestLapse(x.grantBatches([grants[0]])), undefined)
|
||||
})
|
||||
|
||||
// #982 (KiMelody), two accounts read 2026-11-11 in Beijing, the numbers as
|
||||
// filed. B's ledger grant is the last check-in to the millisecond; the vendor
|
||||
// said nothing is about to lapse on either.
|
||||
const NOW_982 = Date.parse("2026-11-11T10:00:00Z")
|
||||
const GRANT_982 = { at: "2026-11-10T16:01:04.916Z", credit: 100, expiresAt: "2026-11-11T16:01:03.812Z" }
|
||||
|
||||
test("a spent check-in leaves no lapse on the bucket or the total (#982, account A)", () => {
|
||||
const stats = {
|
||||
metrics: [
|
||||
{ name: "usageTotalPackageCredit", package_credit_amount: 600, package_credit_remain: 82.05, package_credit_expiring_amount: 0 },
|
||||
{ name: "usageBasicPackageCredit", package_credit_amount: 500, package_credit_remain: 82.05, package_credit_expiring_amount: 0 },
|
||||
{ name: "usageBonusPackageCredit", package_credit_amount: 100, package_credit_remain: 0, package_credit_expiring_amount: 0 },
|
||||
],
|
||||
}
|
||||
// The ledger's grant, and a vendor batch whose counter lags the bucket.
|
||||
const ghost = [{ metric: "usageBonusPackageCredit", amount: 100, left: 100, expiresAt: Date.parse(GRANT_982.expiresAt) }]
|
||||
for (const opts of [{ grants: [GRANT_982] }, { batches: ghost }]) {
|
||||
const usage = x.usageFromStatistics(stats, undefined, { ...opts, now: NOW_982 })
|
||||
const total = usage.windows.find((w) => w.name === "总积分")
|
||||
const bonus = usage.windows.find((w) => w.name === "赠送积分包")
|
||||
assert.equal(bonus.amount, 100)
|
||||
assert.equal(bonus.runsOutAt, undefined)
|
||||
assert.equal(total.runsOutAt, undefined, "the total has none of the bonus bucket's credits left to lose")
|
||||
assert.equal(total.runsOut, undefined)
|
||||
assert.equal(total.expiring, 0)
|
||||
}
|
||||
})
|
||||
|
||||
test("a check-in in the ledger is no lapse when the vendor says nothing expires (#982, account B)", () => {
|
||||
const stats = (expiring) => ({
|
||||
metrics: [
|
||||
{ name: "usageTotalPackageCredit", package_credit_amount: 4100, package_credit_remain: 2344.81, package_credit_expiring_amount: expiring },
|
||||
{ name: "usageBonusPackageCredit", package_credit_amount: 4100, package_credit_remain: 2344.81, package_credit_expiring_amount: expiring },
|
||||
],
|
||||
})
|
||||
const read = (expiring) => {
|
||||
const usage = x.usageFromStatistics(stats(expiring), undefined, { grants: [GRANT_982], now: NOW_982 })
|
||||
return [usage.windows.find((w) => w.name === "总积分"), usage.windows.find((w) => w.name === "赠送积分包")]
|
||||
}
|
||||
const [total, bonus] = read(0)
|
||||
assert.equal(bonus.amount, 1755.19)
|
||||
assert.equal(bonus.used.toFixed(2), "42.81")
|
||||
assert.equal(bonus.expiring, 0)
|
||||
assert.equal(bonus.runsOutAt, undefined, "the ledger can't say the grant wasn't spent")
|
||||
assert.equal(total.runsOutAt, undefined)
|
||||
// Said by the vendor, the ledger tells when, and only that much lapses.
|
||||
const [total2, bonus2] = read(40)
|
||||
assert.equal(bonus2.runsOutAt, GRANT_982.expiresAt)
|
||||
assert.equal(bonus2.runsOut, 40)
|
||||
assert.equal(total2.runsOutAt, GRANT_982.expiresAt)
|
||||
assert.equal(total2.runsOut, 40)
|
||||
// Without the vendor's field nothing is known.
|
||||
assert.equal(read(undefined)[1].runsOutAt, undefined)
|
||||
assert.equal(x.grantBatches([GRANT_982])[0].estimated, true)
|
||||
})
|
||||
|
||||
test("the total's lapse is the buckets' own, each held to what it has left (#982)", () => {
|
||||
const at = NOW_982 + 3 * 86_400_000
|
||||
const usage = x.usageFromStatistics({
|
||||
metrics: [
|
||||
{ name: "usageTotalPackageCredit", package_credit_amount: 3000, package_credit_remain: 2500 },
|
||||
{ name: "usageOnDemandPackageCredit", package_credit_amount: 2000, package_credit_remain: 2000 },
|
||||
{ name: "usageBonusPackageCredit", package_credit_amount: 1000, package_credit_remain: 30 },
|
||||
],
|
||||
}, undefined, {
|
||||
now: NOW_982,
|
||||
batches: [
|
||||
{ metric: "usageBonusPackageCredit", amount: 1000, left: 400, expiresAt: at },
|
||||
{ metric: "usageOnDemandPackageCredit", amount: 2000, left: 2000, expiresAt: at + 60 * 86_400_000 },
|
||||
],
|
||||
})
|
||||
const bonus = usage.windows.find((w) => w.name === "赠送积分包")
|
||||
const total = usage.windows.find((w) => w.name === "总积分")
|
||||
assert.equal(bonus.runsOut, 30, "never more than the bucket has")
|
||||
assert.equal(total.runsOutAt, iso(at))
|
||||
assert.equal(total.runsOut, 30)
|
||||
})
|
||||
|
||||
// Shaped as the console's own answers (personal-usage → 获取明细).
|
||||
const day = 86_400_000
|
||||
const iso = (ms) => new Date(ms).toISOString()
|
||||
@@ -2322,7 +2400,7 @@ test("a claimed check-in is kept, and the usage card says when those credits run
|
||||
return new Response(JSON.stringify({
|
||||
metrics: [
|
||||
{ name: "usageTotalPackageCredit", package_credit_amount: 6500, package_credit_remain: 6500 },
|
||||
{ name: "usageBonusPackageCredit", package_credit_amount: 1000, package_credit_remain: 1000 },
|
||||
{ name: "usageBonusPackageCredit", package_credit_amount: 1000, package_credit_remain: 1000, package_credit_expiring_amount: 1000 },
|
||||
],
|
||||
}), { status: 200 })
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-codearts-auth",
|
||||
"version": "0.3.7",
|
||||
"version": "0.3.8",
|
||||
"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",
|
||||
|
||||
Reference in New Issue
Block a user