From 735e83e62101b7620ebbc13d57fcfac14004d0d6 Mon Sep 17 00:00:00 2001 From: R227BOUT <235274933+R227BOUT@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:43:54 +0800 Subject: [PATCH] raccoon 0.1.13: the daily pool is its own window (#1178) The raccoon card shows the daily pool (`daily_points`: 300 credits a day, each lasting 7 days) as its own "Daily pool" window, read as used / limit with a limit of max(2,100, daily_points, the unexpired daily grants in bills), along with its next expiry. When the pool is shown, routing weighs it and the aggregate Credits window becomes display-only (`aside`). The `setting_info` fallback and accounts with a daily pool of 0 keep Credits as the only weighted window. Version 0.1.13. Run at 7d2bbf94 on mote (rebased on d123d540): - `bun test packages/raccoon`: 58 pass, 0 fail. - `bun scripts/check.mjs raccoon`: ok. Broken by hand: with main's index.mjs under the PR's tests, 3 fail (the daily pool's used / limit, a daily_points over 2,100, and Credits when the bills cover every grant). The other 47 pass. Not tried: a real Raccoon account. The window values come from the author's account data. Co-authored-by: R227BOUT <235274933+R227BOUT@users.noreply.github.com> --- packages/raccoon/README.md | 4 +- packages/raccoon/index.mjs | 102 ++++++++++++++++++++++++----- packages/raccoon/package.json | 2 +- packages/raccoon/raccoon.test.mjs | 105 +++++++++++++++++++++++++++++- 4 files changed, 192 insertions(+), 21 deletions(-) diff --git a/packages/raccoon/README.md b/packages/raccoon/README.md index 8399430..d2c628b 100644 --- a/packages/raccoon/README.md +++ b/packages/raccoon/README.md @@ -10,7 +10,7 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia 3. Raccoon desktop live session reuse (strictly read-only, reading the `auth.json` the desktop app keeps — `/agent/config/auth.json` in current builds, where the profile is `~/Library/Application Support/office-raccoon` on macOS and `%USERPROFILE%\.office-raccoon` on Windows, and `~/.box-agent/config/auth.json` in older ones — without writing or spending desktop refresh tokens). A desktop seat keeps the token it was signed in with on its own record, so it is never answered with, and never reports, another account's credentials or credits; once its own token is refused or runs out it asks to be signed in again. The app's own refresh token is still never spent. - **Token renewal**: single-flight proactive refresh 5 minutes before expiration for browser logins. - **Dynamic model catalog & credit rates**: real-time synchronization from `/api/web/llm/v2/model_catalog` with context window, output limit, vision/reasoning tags, credit multipliers, and limited-free markers. -- **Usage & allowances**: reports available credits, unexpired grant bills, daily expiration timestamps, and Pro/Free subscription plans. +- **Usage & allowances**: reports available credits, unexpired grant bills, daily expiration timestamps, and Pro/Free subscription plans. The **Daily pool** window (`daily_points`: 300 credits granted per day, each slice lasting 7 days, so 2,100 at most) reads used / limit like every other window (`144 / 2,100`) and carries the next expiry date. It is the only balance that lapses, so it is what routing weighs; the aggregate Credits window beside it is display-only (`aside`). When `/points/v1/balance` answers 403 and the balance comes from `setting_info`, there is no `daily_points` there: the card then shows Credits alone, still carrying the routing weight. - **Daily check-in & desktop onboarding grant**: supports Magpie automatic daily check-in (`+300` credits/day) and one-time desktop onboarding grant (`+3000` credits). - **SSE model rewrite**: transparently rewrites internal upstream model names back to requested downstream models for client compatibility. - **The card's name**: the account's own phone number (`138****8000`), read once per token from `/api/web/auth/v1/user_info` with the JWT the sign-in holds. `accountId` stays the account's identity (the JWT's `Raccoon-pu-`, or the desktop app's name) — magpie keys the user's own name for the account, its proxy, model picks and a gateway key's list by it, so it never changes. The card shows usage's `user`, which is the phone once a sign-in or renewal has read it. A failed read changes nothing and never costs a sign-in. @@ -27,7 +27,7 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia 3. 直接只读复用本机商汤小浣熊客户端实时登录态(客户端保存的 `auth.json`:新版在客户端配置目录下的 `agent/config/auth.json`(macOS 为 `~/Library/Application Support/office-raccoon`,Windows 为 `%USERPROFILE%\.office-raccoon`),旧版在 `~/.box-agent/config/auth.json`)。桌面端席位会把登录时读到的 token 保存在自己的账号记录里,因此它不会拿到、也不会**上报**另一个账号的凭据或积分;一旦自己的 token 被拒或用尽,就提示重新登录(客户端自身的 refresh token 依旧不会被动用)。 - **Token 自动续期**:浏览器登录账号过期前 5 分钟自动单飞刷新。 - **动态模型目录与积分倍率**:实时同步 `/api/web/llm/v2/model_catalog`,展示模型上下文、最大输出、视觉/思考能力、积分倍率与限免(`Free`)标识。 -- **积分余额与套餐查询**:展示可用积分、未过期发放额度、每日积分过期时间与 Pro/Free 套餐状态。积分余额接口 `/api/web/points/v1/balance` 拒绝时(403),改从 `/api/web/office/v3/setting_info` 读可用积分;套餐接口读不到时不显示套餐,而不是当作 Free。余额比账单里未过期的发放额度略多时(10% 以内),以这批发放下见过的最高余额作总额,之后用掉的积分记为已用;有新的发放或发放过期时重新计。 +- **积分余额与套餐查询**:展示可用积分、未过期发放额度、每日积分过期时间与 Pro/Free 套餐状态。**每日池**(`Daily pool` 窗口,`daily_points`,每天 300 分、每份存 7 天,上限 2,100)与其余窗口同向显示「已用 / 上限」(`144 / 2100`)并附最近一次过期时间。它是唯一会作废的余额,所以由它承担路由权重;旁边的聚合 Credits 窗口标 `aside` 只显示不参与路由。积分余额接口 `/api/web/points/v1/balance` 拒绝时(403),改从 `/api/web/office/v3/setting_info` 读可用积分——这里读不到 `daily_points`,此时卡片只显示 Credits 且照常参与路由。套餐接口读不到时不显示套餐,而不是当作 Free。余额比账单里未过期的发放额度略多时(10% 以内),以这批发放下见过的最高余额作总额,之后用掉的积分记为已用;有新的发放或发放过期时重新计。 - **每日签到与桌面端登录奖励**:支持 Magpie 每日自动签到(`+300` 积分/天)及首次桌面端 `+3000` 积分登录奖励领取。 - **SSE 模型名重写**:将上游响应中的内部模型名重写为下游请求的 `model`,确保 Claude Code / Codex / OpenCode 等客户端兼容。 diff --git a/packages/raccoon/index.mjs b/packages/raccoon/index.mjs index 4d7571c..0a88502 100644 --- a/packages/raccoon/index.mjs +++ b/packages/raccoon/index.mjs @@ -645,7 +645,14 @@ async function availablePoints(token) { try { const points = await apiGetJson("/api/web/points/v1/balance", token) const n = Number(points?.available_points) - if (Number.isFinite(n)) return Math.floor(n) + if (Number.isFinite(n)) { + // daily_points is the daily-grant pool the vendor keeps itself (300/day, + // each grant lasting 7 days). It includes remainders of grants already + // past expire_at but not swept yet, so it is the authoritative "free + // credits still left"; the bills only say when the next slice expires. + const d = Number(points?.daily_points) + return { avail: Math.floor(n), daily: Number.isFinite(d) ? Math.floor(d) : null } + } first = new Error("balance has no available_points") } catch (e) { if (e?.signIn === "expired") throw e @@ -660,7 +667,7 @@ async function availablePoints(token) { } const n = Number(info?.available_points) if (!Number.isFinite(n)) throw first - return Math.floor(n) + return { avail: Math.floor(n), daily: null } } // topBalance holds, per account and per set of grants, the highest balance @@ -709,13 +716,23 @@ function saveTop(account, grants, top) { } catch {} } +// The daily pool: 300 credits granted per day, each slice lasting 7 days, so +// the ceiling the vendor's own rule implies is 2,100. This is only the window's +// limit; the remaining side always comes from the vendor's daily_points, never +// from this arithmetic. A vendor that grants more per day still reads right, +// because the bills' unexpired daily grants are summed too and the limit takes +// whichever is larger. +const DAILY_POOL_CAP = 2100 + async function queryUsage(token, account = "") { - const [avail, entitlement, bills] = await Promise.all([ + const [pool, entitlement, bills] = await Promise.all([ availablePoints(token), apiGetJson("/api/web/auth/v1/entitlement_info", token).catch(() => null), allBills(token).catch(() => null), ]) + const avail = pool.avail + // entitlement_info answers 403 too (plugins #520): an unread plan is // left unsaid, not read as Free. const office = entitlement?.office ?? entitlement?.code ?? {} @@ -729,6 +746,12 @@ async function queryUsage(token, account = "") { let grantedFromBills = 0 let soonestExpMs = 0 let expiringPts = 0 + // The daily pool's own slice: what will expire inside the vendor's 7-day + // window, and when. Kept apart from the aggregate so the card can show it + // on its own line (300/day, 7 days deep). + let dailyUnexpired = 0 + let dailySoonestMs = 0 + let dailySoonestPts = 0 const expired = [] const grantKeys = [] const now = Date.now() @@ -743,6 +766,15 @@ async function queryUsage(token, account = "") { continue } grantedFromBills += pts + if (String(item?.biz_type ?? "") === "daily_grant" && expMs > now) { + dailyUnexpired += pts + if (!dailySoonestMs || expMs < dailySoonestMs) { + dailySoonestMs = expMs + dailySoonestPts = pts + } else if (expMs === dailySoonestMs) { + dailySoonestPts += pts + } + } if (expMs > now) { if (!soonestExpMs || expMs < soonestExpMs) { soonestExpMs = expMs @@ -779,30 +811,66 @@ async function queryUsage(token, account = "") { const runsOutAt = soonestExpMs ? new Date(soonestExpMs).toISOString() : null const runsOut = soonestExpMs ? Math.min(avail, expiringPts) : 0 + // The daily pool comes first when the vendor reports it: 300 credits a day, + // each slice good for 7 days, so what will lapse is the vendor's + // daily_points - not the aggregate. Same reading direction as the aggregate + // (used / limit), so the card reads one way. The aggregate is display-only + // beside it: it also holds reward/top-up credits that never lapse, and the + // pool that expires is what routing should weigh. When the vendor says no + // daily_points (the setting_info fallback), the aggregate stays the only + // window and keeps its routing weight - nothing is left unweighed. + const windows = [] + // A pool of 0 shows nothing: the account may have no daily grants at all, + // and a "2,100 / 2,100 used" line would read the whole account as spent. + // Credits then keeps its routing weight. + const dailyRemain = typeof pool.daily === "number" && pool.daily > 0 ? Math.floor(pool.daily) : null + if (dailyRemain !== null) { + // The limit is the vendor's 300/day x 7 days, but never less than what it + // says is left or than the unexpired daily grants in bills already add up + // to - so a larger grant schedule reads as "0% used" instead of a negative + // one, and the percentage stays honest. + const limit = Math.max(DAILY_POOL_CAP, dailyRemain, dailyUnexpired) + const usedPts = Math.max(0, limit - dailyRemain) + const dailySoonestAt = dailySoonestMs ? new Date(dailySoonestMs).toISOString() : null + windows.push({ + name: "Daily pool", + used: limit > 0 ? (100 * usedPts) / limit : 0, + display: `${usedPts} / ${limit}`, + amount: usedPts, + limit, + unit: "credits", + ...(dailySoonestAt ? { runsOutAt: dailySoonestAt, runsOut: Math.min(dailyRemain, dailySoonestPts || dailyRemain) } : {}), + }) + } + if (grantedFromBills > 0 && grantedFromBills >= avail) { const used = grantedFromBills - avail + windows.push({ + name: "Credits", + used: (100 * used) / grantedFromBills, + display: `${used} / ${grantedFromBills}`, + amount: used, + limit: grantedFromBills, + unit: "credits", + // Display-only only while the daily pool is on the card too; alone it + // is the window routing weighs. + ...(dailyRemain !== null ? { aside: true } : {}), + ...(runsOutAt ? { runsOutAt, runsOut } : {}), + }) + } + + if (windows.length === 0) { return { ...(plan ? { plan } : {}), ...(proEnable && expireAt ? { until: new Date(expireAt).toISOString() } : {}), - windows: [ - { - name: "Credits", - used: (100 * used) / grantedFromBills, - display: `${used} / ${grantedFromBills}`, - amount: used, - limit: grantedFromBills, - unit: "credits", - ...(runsOutAt ? { runsOutAt, runsOut } : {}), - }, - ], + balance: `${avail} credits`, + windows, } } - return { ...(plan ? { plan } : {}), ...(proEnable && expireAt ? { until: new Date(expireAt).toISOString() } : {}), - balance: `${avail} credits`, - windows: [], + windows, } } diff --git a/packages/raccoon/package.json b/packages/raccoon/package.json index 1d471ee..35f9dbd 100644 --- a/packages/raccoon/package.json +++ b/packages/raccoon/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-raccoon-auth", - "version": "0.1.12", + "version": "0.1.13", "description": "OpenCode & Magpie provider plugin for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com)", "type": "module", "main": "./opencode.mjs", diff --git a/packages/raccoon/raccoon.test.mjs b/packages/raccoon/raccoon.test.mjs index 19b4fa0..9c3b83f 100644 --- a/packages/raccoon/raccoon.test.mjs +++ b/packages/raccoon/raccoon.test.mjs @@ -351,13 +351,25 @@ test("usage reports Credits window when unexpired bills account for total grante expires: Date.now() + 3600_000, })) expect(u.balance).toBeUndefined() - expect(u.windows.length).toBe(1) + // the daily pool (daily_points: 519) is reported on its own line first, + // the aggregate beside it, display-only + expect(u.windows.length).toBe(2) expect(u.windows[0]).toMatchObject({ + name: "Daily pool", + amount: 1581, + limit: 2100, + display: "1581 / 2100", + unit: "credits", + runsOutAt: "2029-10-17T15:59:59.000Z", + runsOut: 300, + }) + expect(u.windows[1]).toMatchObject({ name: "Credits", amount: 81, limit: 9600, display: "81 / 9600", unit: "credits", + aside: true, runsOutAt: "2029-10-17T15:59:59.000Z", runsOut: 300, }) @@ -391,6 +403,93 @@ test("usage asks for income bills so a busy account keeps its Credits window", a expect(asked).toEqual([{ type: "income", limit: 200 }]) }) +test("the daily pool reads used / limit like the aggregate, and a swept-late grant shows in it", async () => { + const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) + const now = Date.now() + startServer({ + // daily_points (1,956) also holds remainders of grants past expire_at + // that the vendor has not swept yet; the bills only know about the live ones + "GET /api/web/points/v1/balance": () => + Response.json({ + code: 0, + data: { available_points: 9500, daily_points: 1956, reward_points: 9000, monthly_points: 0, topup_points: 0 }, + }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => + Response.json({ + code: 0, + data: { + items: [ + { bill_id: "d2", biz_type: "daily_grant", points: 300, expire_at: iso(now + day) }, + { bill_id: "d1", biz_type: "daily_grant", points: 300, expire_at: iso(now - day) }, + { bill_id: "r1", biz_type: "reward_grant", points: 9000 }, + ], + }, + }), + }) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => ({ type: "oauth", access: validTok, refresh: "rt1", expires: Date.now() + 3600_000 })) + // remaining 1,956 of 2,100: 144 used, same direction as the Credits line + expect(u.windows[0]).toMatchObject({ + name: "Daily pool", + amount: 144, + limit: 2100, + display: "144 / 2100", + unit: "credits", + runsOutAt: new Date(Date.parse(iso(now + day))).toISOString(), + runsOut: 300, + }) +}) + +test("a daily_points over 2,100 raises the pool's limit instead of reading negative", async () => { + const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) + startServer({ + // a vendor granting 500/day (2,500 after 5 days) would break a hard 2,100 + "GET /api/web/points/v1/balance": () => + Response.json({ + code: 0, + data: { available_points: 9500, daily_points: 2500, reward_points: 9000, monthly_points: 0, topup_points: 0 }, + }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => + Response.json({ + code: 0, + data: { + items: [ + { bill_id: "d1", biz_type: "daily_grant", points: 500, expire_at: iso(Date.now() + day) }, + { bill_id: "r1", biz_type: "reward_grant", points: 9000 }, + ], + }, + }), + }) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => ({ type: "oauth", access: validTok, refresh: "rt1", expires: Date.now() + 3600_000 })) + expect(u.windows[0]).toMatchObject({ + name: "Daily pool", + amount: 0, + limit: 2500, + display: "0 / 2500", + }) +}) + +test("no daily_points in the balance keeps the card as it was (Credits only, no aside)", async () => { + const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) + startServer({ + "GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 9519 } }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => + Response.json({ + code: 0, + data: { items: [{ bill_id: "r1", biz_type: "reward_grant", points: 9600 }] }, + }), + }) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => ({ type: "oauth", access: validTok, refresh: "rt1", expires: Date.now() + 3600_000 })) + expect(u.windows.length).toBe(1) + expect(u.windows[0]).toMatchObject({ name: "Credits", amount: 81, limit: 9600 }) + expect(u.windows[0].aside).toBeUndefined() +}) + test("usage falls back to paged bills when the vendor refuses type=income (plugins #223)", async () => { const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) // newest first, as the endpoint answers: 1200 spends, then the grants @@ -454,7 +553,11 @@ test("setting_info's balance fills the Credits window the bills account for (plu const hooks = await RaccoonAuthPlugin({ client: {} }) const u = await hooks.auth.usage(async () => ({ type: "oauth", access: validTok, refresh: "rt1", expires: Date.now() + 3600_000 })) expect(u.plan).toBe("Free") + // the fallback path has no daily_points: Credits stays the only window and + // keeps its routing weight (no aside) + expect(u.windows.length).toBe(1) expect(u.windows[0]).toMatchObject({ name: "Credits", amount: 81, limit: 9600 }) + expect(u.windows[0].aside).toBeUndefined() }) // The balance in plugins #936's screenshot (9,623 credits) is more than the