catpaw 0.2.1: the credits' refresh time is the window's reset, so Smart routing ranks the account (#867)

The 可用积分 window was always aside with no reset, so Smart routing never
ranked catpaw accounts by it. The credit/balance response the plugin
already reads carries userPlan.nextRefreshTime, a ms epoch string
("1796054400000"), when the plan's credits refresh. It is now the
window's resetsAt; magpie's Allowance.Renewal ranks by it, soonest first.

Why resetsAt and not runsOutAt (the issue's suggestion): 重置 is the
window's renewal; runsOutAt is for credits lost apart from a reset, and
with runsOut set the GUI would say "N credits expire", which nobody has
checked. Routing ranks both the same (Renewal takes the sooner).

used stays 0 and there is no limit: the vendor gives only the balance,
and a difference of balances would be made up. The GUI's rendering of
the window is unchanged (aside is not sent to it); it now shows the
reset line. A credit of 0 is not read as used 100: catpaw has free
models that may still answer.

No reason for aside was recorded (eeb344f1, PR #174); it read as "no
reset known". nextRefreshTime missing, empty, not 13+ digits (a
seconds value, a date string, a fraction, negative) or an object keeps
the window aside, as before: a failed read is unknown. A past refresh
time is kept as read; magpie treats a passed reset as not known.

Run at this tree on mote (mote-run):
- packages/catpaw bun test: 64 pass, 0 fail (13 new)
- bun scripts/check.mjs catpaw: exit 0
- repo-root bun test under a mktemp HOME: 6904 pass, 0 fail, 501 files
  (without an isolated HOME, 21 fail: zcode/devin tests that refuse a
  real HOME by design)

Broken by hand, then restored:
- window always aside again: 2 fail (reporter's string shape, numeric)
- any non-empty value accepted: 3 fail (seconds, negative, fraction)

Not tried: a real catpaw account (none here); the reporter's balance
shape is taken from the issue. Not tried in a running magpie's Routing
page.

Reported-by: orinsid
This commit is contained in:
yetone
2026-11-08 20:56:34 +08:00
parent 9b41df1507
commit 46fef953c8
5 changed files with 73 additions and 3 deletions
+1
View File
@@ -24,6 +24,7 @@ magpie plugin login catpaw # 选「网页登录」/「妙手桌面端登录
- **余额(usage)**:`GET https://catx.nocode.cn/api/gateway/credit/balance`,鉴权头是 **`X-Auth-Token: <accessToken>`**。
- ⚠️ 这个接口与聊天网关**不是同一个鉴权头**:它只认 `X-Auth-Token`,把聊天用的 `Cookie: X-Passport-Token` 发到这里会稳定 401(body `code 4010`)。magpie 把 usage 的 401 当作「登录态失效」,所以鉴权头必须分开核对。
- 读成功后**不带 `signIn` 字段**:magpie 以此把「已退出登录」的标记撤掉。
- 「可用积分」窗口:上游只给余额(`availableCredits`),不给总额与累计用量,所以 `used` 恒为 0、不伪造。`userPlan.nextRefreshTime`(毫秒时间戳)作为窗口的 `resetsAt`,magpie 的 Smart 路由据此先用积分先刷新的账号(plugins#867);该字段缺失或无法解析时窗口保持 `aside`,不参与排序。
- **无签到**:CatPaw 没有每日签到活动。
## 协议细节
+3 -1
View File
@@ -31,6 +31,7 @@ export function fakeCatPaw() {
disabledSources: new Set(["CatPawCLI"]),
turnBodies: [],
balanceCalls: 0,
balancePlan: null, // extra userPlan fields a test sets (nextRefreshTime)
// POST /api/agent/maas/model-types, the list the desktop client asks for
// (items as its renderer reads them: modelTypeId, modelTypeName, provider,
// supportImage). The ids here are the table's own, plus one the table has
@@ -54,6 +55,7 @@ export function fakeCatPaw() {
state.disabledSources = new Set(["CatPawCLI"])
state.turnBodies = []
state.balanceCalls = 0
state.balancePlan = null
state.modelTypes = defaultModelTypes()
state.modelTypeCalls = []
state.modelTypesFail = false
@@ -77,7 +79,7 @@ export function fakeCatPaw() {
return json(200, {
code: 0,
message: "success",
data: { availableCredits: "1134.67", userPlan: { planId: "plan_free", planName: "体验版", pro: false, status: "active" } },
data: { availableCredits: "1134.67", userPlan: { planId: "plan_free", planName: "体验版", pro: false, status: "active", ...state.balancePlan } },
errorCode: null,
})
}
+24 -1
View File
@@ -21,6 +21,29 @@ const ORIGIN = "https://ai.catpaw.meituan.com"
// usage() — sending the cookie here marks the account signed out).
const balanceUrl = () => process.env.CATPAW_BALANCE_URL || "https://catx.nocode.cn/api/gateway/credit/balance"
// refreshAt reads the balance's `userPlan.nextRefreshTime`, when the plan's
// credits are next refreshed: a ms epoch, as a string ("1796054400000") or
// a number. Anything else — missing, empty, not all digits, or too small
// to be ms (a seconds value would land in 1970) — is not known: null.
function refreshAt(v) {
const s = typeof v === "number" ? String(v) : typeof v === "string" ? v.trim() : ""
if (!/^\d{13,}$/.test(s)) return null
const t = new Date(Number(s))
return Number.isNaN(t.getTime()) ? null : t
}
// creditWindow is the balance as magpie's window. The vendor gives what is
// left, not what was spent or the plan's size, so `used` stays 0 (a
// difference of balances would be made up). With the refresh time known it
// is the window's reset, and Smart routing spends the account whose credits
// refresh first (plugins#867); without it the window stays aside, as
// nothing about it can rank the account.
function creditWindow(credit, nextRefreshTime) {
const w = { name: "可用积分", used: 0, display: `${credit} credit` }
const at = refreshAt(nextRefreshTime)
return at ? { ...w, resetsAt: at.toISOString() } : { ...w, aside: true }
}
// the passport domain the web sign-in runs on (login-config / poll-token /
// current-user, none of them authenticated; the vendor serves them from
// catx.nocode.cn while the conversation gateway is ai.catpaw.meituan.com)
@@ -990,7 +1013,7 @@ export async function CatPawAuthPlugin({ client } = {}) {
return {
plan: plan.planName || (plan.pro ? "妙手 CatPaw Pro" : NAME),
user: a?.type === "oauth" && a.source !== "desktop" ? a.name || a.accountId || "妙手网页登录" : authAccount(),
windows: [{ name: "可用积分", used: 0, display: `${credit} credit`, aside: true }],
windows: [creditWindow(credit, plan.nextRefreshTime)],
}
},
// CatPaw has no check-in (confirmed: no such activity in its client)
+44
View File
@@ -727,6 +727,50 @@ describe("usage", () => {
expect(fake.state.balanceCalls).toBe(1)
})
// plugins#867 (orinsid): the same response carries userPlan.nextRefreshTime,
// a ms epoch as a string, when the credits refresh. It is the window's
// reset, so Smart routing can rank the account by it.
test("the credits' refresh time is the window's reset (reporter's shape)", async () => {
fake.state.balancePlan = { nextRefreshTime: "1796054400000" }
const usage = await plugin.auth.usage(getAuth)
const w = usage.windows[0]
expect(w.aside).toBeUndefined()
expect(w.resetsAt).toBe("2026-11-30T16:00:00.000Z")
expect(new Date(w.resetsAt).getTime()).toBe(1796054400000)
expect(w.used).toBe(0) // the vendor gives no total: nothing to count spent against
expect(w.limit).toBeUndefined()
expect(w.display).toBe("1134.67 credit")
})
test("a numeric refresh time reads the same", async () => {
fake.state.balancePlan = { nextRefreshTime: 1796054400000 }
const usage = await plugin.auth.usage(getAuth)
expect(usage.windows[0].resetsAt).toBe("2026-11-30T16:00:00.000Z")
expect(usage.windows[0].aside).toBeUndefined()
})
// a refresh time that can't be read is not known: the window stays aside,
// as before, rather than ranking the account by a made-up date
for (const [label, v] of [
["missing", undefined],
["null", null],
["empty", ""],
["garbage", "soon"],
["seconds, not ms", "1796054400"],
["a date string", "2026-12-01"],
["negative", "-1796054400000"],
["a fraction", "1796054400000.5"],
["an object", { at: "1796054400000" }],
]) {
test(`a refresh time that is ${label} keeps the window aside`, async () => {
fake.state.balancePlan = v === undefined ? {} : { nextRefreshTime: v }
const usage = await plugin.auth.usage(getAuth)
expect(usage.error).toBeUndefined()
expect(usage.windows[0].aside).toBe(true)
expect(usage.windows[0].resetsAt).toBeUndefined()
})
}
test("a refused token says the sign-in expired", async () => {
saved = { type: "oauth", access: "not-the-token", expires: 0, source: "manual" }
const usage = await plugin.auth.usage(getAuth)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-catpaw-auth",
"version": "0.2.0",
"version": "0.2.1",
"description": "OpenCode & Magpie provider plugin for Meituan's 妙手 CatPaw (ai.catpaw.meituan.com): web sign-in or the desktop client's saved credentials, chat through the round/event/turn protocol, models and credit balance",
"type": "module",
"main": "./opencode.mjs",