autoclaw 0.2.11: the points balance is a prepaid wallet window, and spend rides on local balance deltas (#445)

AutoClaw has no points ledger upstream (wallets.v2 is a balance only), so usage() now reports the balance as a prepaid wallet window, {name: "积分余额", balance, unit: "积分"} (magpie >= v0.1.1790, #3950), which routing reads as what is left; an empty wallet counts as used up. A display-only "本轮消耗" window (aside) is worked out from local balance deltas: any rise, from 0 too, opens a new cycle, and the Beijing day keeps its spent/gained sums. The ledger is keyed by signinAccountKey (#254), lives in $XDG_CONFIG_HOME/magpie/autoclaw-usage.json (temp file + rename, 30-day expiry), and a null/""/non-numeric total_balance is unknown and never recorded. The unsigned fallback reward reads 200 (was 400). Version 0.2.11, on top of main's 0.2.10 (#466, d8cfee3, whose FLAGGED rewrites are kept).

The reviewer pushed 6418906 on top of fb334b8: main merged in (no conflicts), version 0.2.10 -> 0.2.11, the README paragraph rewritten to match the code (it still described state in the package folder and a routing spend window), and an aside assertion on the spend window test.

Run at 6418906cb7387c5e6892f326c9a2d913cc252881, on mote (mote-run, HOME=$(mktemp -d)):
- bun test packages/autoclaw: 44 pass, 0 fail; nothing left in packages/autoclaw or $HOME/.config.
- bun scripts/check.mjs autoclaw: ok. Full bun test: 3050 pass, 8 skip, 0 fail (257 files).
- The merged tree's packages/autoclaw diff against main is exactly the PR's own diff plus the version line; FLAGGED's "CodeBuddy Code" entries are there.
- Broken by hand, one at a time, each red then restored: `last > 0` back in balanceObserve (balanceObserve test), the old key uid ?? accountId (same-name accounts test), the null guard dropped (unreadable balance test), `if (false)` for the spend window (two-reads test), aside removed (two-reads test, with the new assertion; it passed without it), the balance window removed (4 tests).
- npm pack 0.2.11 and imported the packed index.mjs (AutoclawAuthPlugin, AutoclawCnAuthPlugin, _internal).

Not tried: a real AutoClaw account (none here); the balance shapes and the routing order rest on the author's run with magpie v0.1.1876. Not known: whether an account at 0 积分 is still served (e.g. a member's GLM-5.3 allowance); magpie now benches it at 0.
This commit is contained in:
Yandre97
2026-10-28 23:46:06 +08:00
committed by GitHub
parent 4115073df3
commit f02894d3a0
4 changed files with 298 additions and 9 deletions
+14 -1
View File
@@ -35,7 +35,20 @@ OpenCode 同样可加载(`opencode auth login`)。登录信息保存在 magp
- 对话走 `POST {host}/autoclaw-proxy/proxy/autoclaw/v1/chat/completions`(`X-Authorization` 鉴权);
- token 过期前自动轮换(refresh token 一次一换,`auth.refresh` 钩子交给 magpie 串行化,不会双花);
- 积分余额通过 `auth.usage` 的 `balance` 显示(纯积分制,无总量上限,不做成额度窗口,细分钱包写在括号里);
- 积分余额通过 `auth.usage` 的 `balance` 显示(纯积分制,无总量上限,细分钱包写在括号里),
同时作为预付钱包窗口 `{ name: "积分余额", balance, unit: "积分" }` 上报(magpie ≥ v0.1.1790,
#3950):路由按真实余额认识和排位账号,不发明百分比,余额 0 算用完;更早的 magpie
不认识 `balance`,账号维持原状。
上游没有积分流水/用量接口(wallets.v2 只有余额),「本轮消耗」窗口**由本地余额差值算**:
每次 `usage()` 记下本轮峰值,`峰值 − 当前 = 本轮已消耗`,**任何上涨**(相对上次
观察到的余额,含从 0 回升——每日签到、礼包、兑换)都开新一轮,不等涨过旧峰值(签到常在花费
之后到)。因为每天签到都会开新一轮,「本轮」≈「自今天签到以来」。这个窗口带
`aside: true`,只展示、不参与路由:它的百分比是「自上次上涨以来花掉的比例」,不是池子剩余。
`total_balance` 为 null/空串/非数时按未知处理(「积分响应异常」),不记账。
状态按账号(键复用 `signinAccountKey`,#254:uid,没 uid 按 refresh token 哈希)存在
`$XDG_CONFIG_HOME/magpie/autoclaw-usage.json`(或 `~/.config/magpie/`,`AUTOCLAW_USAGE_STATE_FILE`
可改址),临时文件 + rename 写入,30 天没动的条目清走;插件更新不会丢。
测试可用 `_internal.setUsageStatePath` 把状态文件指到临时目录。
- **国际版登录是完整本地实现**:插件在 127.0.0.1 上取官方 TokenServer 端口池中的一个端口
(18432/19654/19723/53699,OAuth client 回调白名单;被占自动顺延)起临时服务器,内嵌引导页完成
阿里滑块验证(`AliyunCaptcha` SDK,`ali_captcha_verify_param` 回执)→ 获取授权页 →
+122 -5
View File
@@ -18,7 +18,8 @@
*/
import { createHash, randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { Buffer } from "node:buffer";
import * as http from "node:http";
@@ -430,6 +431,89 @@ function tokenFields(data, fallbackRefresh) {
// 签到与积分
// ---------------------------------------------------------------------------
// 上游没有积分流水/用量接口(wallets.v2 只有余额,task-list 只有签到),
// 「已用」只能用本地余额差值算:每次 usage() 观察一次余额,记下本轮峰值,
// 峰值 − 当前 = 本轮已消耗;任何上涨(相对上次余额,含从 0 回升——池子花光
// 后签到恰恰最常见)都开新一轮,峰值即当前、used 归零。
// 状态放 magpie 的配置目录(~/.config/magpie 或 $XDG_CONFIG_HOME/magpie,跟
// codearts 的台账一个思路):插件更新不会删掉它,CI 的 HOME=$(mktemp -d) 也
// 自然隔离;AUTOCLAW_USAGE_STATE_FILE 可改址。写入走临时文件 + rename,并发
// 写不会留下半份文件;30 天没动的条目顺手清走(没 uid 的账号键是 refresh
// 哈希,token 一刷新就换键,旧条目靠这个兜底)。北京日界另记当日 −消耗/+入账。
let usageStatePath;
function usageStatePathDefault() {
if (process.env.AUTOCLAW_USAGE_STATE_FILE) return process.env.AUTOCLAW_USAGE_STATE_FILE;
const cfgDir = process.env.XDG_CONFIG_HOME
? `${process.env.XDG_CONFIG_HOME}/magpie`
: `${process.env.HOME ?? ""}/.config/magpie`;
return `${cfgDir}/autoclaw-usage.json`;
}
let usageState;
/** 测试注入:指向临时目录,并丢掉内存缓存,测试之间互不沿用。 */
function setUsageStatePath(p) {
usageStatePath = p;
usageState = undefined;
}
function usageStateLoad() {
if (usageState) return usageState;
try {
usageState = JSON.parse(readFileSync(usageStatePath ?? usageStatePathDefault(), "utf8"));
if (!usageState || typeof usageState !== "object" || typeof usageState.accts !== "object") usageState = { accts: {} };
} catch {
usageState = { accts: {} };
}
return usageState;
}
const USAGE_STATE_TTL_MS = 30 * 86400 * 1000;
function usageStateSave() {
try {
const now = Date.now();
for (const [k, v] of Object.entries(usageState.accts)) {
const at = Date.parse(v?.at ?? "");
if (!Number.isFinite(at) || now - at > USAGE_STATE_TTL_MS) delete usageState.accts[k];
}
const path = usageStatePath ?? usageStatePathDefault();
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(usageState), { mode: 0o600 });
renameSync(tmp, path);
} catch {}
}
/** 北京日期(UTC+8)的 YYYY-MM-DD,签到/每日赠送的日界。 */
function beijingDayOf(d = new Date()) {
return new Date(d.getTime() + 8 * 3600 * 1000).toISOString().slice(0, 10);
}
/**
* 记一次余额观察,返回 { peak, used, daySpent, dayGained }。
* 任何上涨(total > 上次余额,含从 0 回升)都开新一轮:峰值即当前,used 归零——
* 不等涨过旧峰值(签到常在花费之后到),也不把 0 当「没见过」(池子花光再签到
* 恰恰是最常见的循环)。
* daySpent/dayGained:北京当日观察到的 −消耗/+入账 累计。
*/
function balanceObserve(key, total) {
const st = usageStateLoad();
const day = beijingDayOf();
const prev = st.accts[key] ?? {};
const last = Number(prev.balance);
const sameDay = prev.day === day;
let daySpent = sameDay ? Number(prev.daySpent) || 0 : 0;
let dayGained = sameDay ? Number(prev.dayGained) || 0 : 0;
let peak;
if (Number.isFinite(last) && total > last) {
// 上涨:开新一轮(README 承诺的「余额上涨即新一轮开始」)
dayGained += total - last;
peak = total;
} else {
peak = Number(prev.peak);
if (!Number.isFinite(peak) || peak <= 0 || total > peak) peak = total;
if (Number.isFinite(last) && total < last) daySpent += last - total;
}
const used = Math.max(0, peak - total);
st.accts[key] = { peak, balance: total, day, daySpent, dayGained, at: new Date().toISOString() };
usageStateSave();
return { peak, used, daySpent, dayGained };
}
async function fetchWallets(accessToken, hosts) {
for (const host of dedupe(hosts)) {
let payload;
@@ -842,8 +926,13 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
? signin
: (await signinStatus(token, hosts[0]).then((s) => s ?? signinStatus(token, hosts[1] ?? hosts[0])) ?? signin);
if (!data) return { error: "积分接口无数据(token 可能不属于该 host)", windows: [] };
const total = Number(data.total_balance);
if (!Number.isFinite(total)) return { error: "积分响应异常", windows: [] };
// total_balance 为 null/空串/非数时按「未知」处理,不记账:Number(null)===0
// 会把账号记成整池花光(used 100%),路由也会把它当成已耗尽。
const raw = data.total_balance;
if (raw == null || raw === "" || !Number.isFinite(Number(raw))) {
return { error: "积分响应异常", windows: [] };
}
const total = Number(raw);
const rows = Array.isArray(data.wallets) ? data.wallets : [];
const named = rows
@@ -860,18 +949,45 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
used: 0,
display: signinFinal.status === "completed"
? `今日已签 ✓${signinFinal.reward ? ` +${signinFinal.reward}` : ""}`
: `今日未签(+${signinFinal.reward || 400})`,
: `今日未签(+${signinFinal.reward || 200})`,
aside: true,
}]
: [];
// 本轮消耗窗口:上游没有用量/流水接口,用本地余额差值算
// (峰值 − 当前;任何上涨即新一轮)。首日只有一次观察时不出这行。
// 键复用 signinAccountKey(#254):显示名可以重复,没 uid 的旧账号按
// refresh token 哈希,同名的两个账号不能共用一本账。
const track = balanceObserve(signinAccountKey(providerId, auth), total);
// 预付余额窗口(magpie ≥ v0.1.1790,#3950):balance 是「还剩多少」的
// 一等读数,路由按它认识账号、不发明百分比——池子大的排前、花光的
// 垫底;旧宿主不认识这个字段,账号维持原状(未知),无副作用。
const windows = [...signinWindow, { name: "积分余额", balance: total, unit: "积分" }];
if (track.used > 0) {
const pct = track.peak > 0 ? Math.min(100, Math.round((track.used / track.peak) * 1000) / 10) : 0;
windows.unshift({
name: "本轮消耗",
// aside:只展示,不参与路由。这个百分比是「自上次上涨以来花掉的比例」,
// 不是「池子还剩多少」——路由的池子比较交给上面的 balance 窗口。
aside: true,
// used/remaining 是 0–100 的百分比;amount/limit 是原始积分
used: pct,
remaining: Math.max(0, 100 - pct),
amount: Math.round(track.used),
limit: Math.round(track.peak),
display: `${Math.round(track.used)} / ${Math.round(track.peak)} 积分`
+ (track.daySpent > 0 ? ` · 今日 -${Math.round(track.daySpent)}` : "")
+ (track.dayGained > 0 ? ` · +${Math.round(track.dayGained)}` : ""),
});
}
// 积分是纯余额,没有总量也没有已用量:只放在 balance 里。做成
// used: 0 的窗口,卡片会给它配上「剩余 100%」(#376)。细分钱包
// 一并写进 balance。
const parts = named.map((w) => `${w.name} ${Math.round(w.balance)}`);
return {
balance: `${Math.round(total)} 积分${parts.length ? `(${parts.join(" · ")})` : ""}`,
windows: signinWindow,
windows,
};
} catch (e) {
if (e?.banned) return { error: e.message, signIn: "kept", windows: [] };
@@ -1393,6 +1509,7 @@ export const _internal = {
makePluginForTest: makeAutoclawPlugin,
platformTm, md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId,
dailySignin, signinStatus, maybeSignin, signinAccountKey, signinConfig, checkinOutcome, refreshTokens,
balanceObserve, usageStatePath: () => usageStatePath ?? usageStatePathDefault(), setUsageStatePath, beijingDayOf,
fetchUserProfile, accountDeviceId, accountDisplayName, startLocalOAuth,
FLAGGED, unflagged, unflag, tidyBody, rewriteManagedBody, autoclawRewriteBody, explained, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT,
guidePageHtml, callbackPageHtml,
+161 -2
View File
@@ -2,7 +2,7 @@
// answer the upstream gives lands on one of its outcomes, and the plugin
// factory registers both providers with every hook check.mjs looks for.
import { expect, test } from "bun:test"
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AutoclawAuthPlugin, AutoclawCnAuthPlugin, _internal } from "./index.mjs"
@@ -627,6 +627,8 @@ test("signinOnUsage signs every account, also two with the same name", async ()
}
return Response.json({ code: 0, data: { total_balance: 1000, wallets: [] } })
}
const dir = mkdtempSync(join(tmpdir(), "autoclaw-usage-"))
_internal.setUsageStatePath(join(dir, ".usage-state.json"))
try {
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, { signin: true, signinOnUsage: true })
const accounts = [
@@ -644,6 +646,7 @@ test("signinOnUsage signs every account, also two with the same name", async ()
expect(_internal.signinAccountKey("autoclaw", accounts[2])).not.toBe(_internal.signinAccountKey("autoclaw", accounts[3]))
} finally {
globalThis.fetch = realFetch
rmSync(dir, { recursive: true, force: true })
}
})
@@ -658,13 +661,20 @@ test("usage: the credit balance and its wallets are the balance, never a window
] } })
return Response.json({ code: 0, data: null })
}
const dir = mkdtempSync(join(tmpdir(), "autoclaw-usage-"))
_internal.setUsageStatePath(join(dir, ".usage-state.json"))
try {
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } })
const u = await hooks.auth.usage(async () => ({ type: "oauth", access: "a1" }))
expect(u.balance).toBe("1234 积分(赠送积分 500 · 会员积分 734)")
expect(u.windows.filter((w) => w.name !== "每日签到")).toEqual([])
// the prepaid wallet reading (magpie #3950): the balance as told, in its
// unit, and no share invented - a first read has no spend window yet
expect(u.windows.filter((w) => w.name !== "每日签到")).toEqual([
{ name: "积分余额", balance: 1234.4, unit: "积分" },
])
} finally {
globalThis.fetch = realFetch
rmSync(dir, { recursive: true, force: true })
}
})
@@ -930,3 +940,152 @@ test("the shapes AutoClaw's gateway can't read go put right, on both channels (#
globalThis.fetch = realFetch
}
})
// The spend window rides on local balance deltas (the upstream has no points
// ledger): a drop is spend, and ANY rise over the last balance opens a new
// cycle - a check-in often lands after a spend, and waiting to pass the old
// peak would under-count the cycle. The Beijing-day sums keep the day's view.
test("balanceObserve: spend, top-up, and the day's sums", () => {
const { balanceObserve, setUsageStatePath, beijingDayOf } = _internal
const dir = mkdtempSync(join(tmpdir(), "autoclaw-usage-"))
setUsageStatePath(join(dir, ".usage-state.json"))
const K = "test-" + Math.random().toString(36).slice(2)
try {
// fresh sight: the peak is where tracking starts, nothing spent yet
expect(balanceObserve(K, 1000)).toEqual({ peak: 1000, used: 0, daySpent: 0, dayGained: 0 })
// a drop is spend against the peak
expect(balanceObserve(K, 900)).toEqual({ peak: 1000, used: 100, daySpent: 100, dayGained: 0 })
// a rise opens a new cycle: used resets, the gain adds up
expect(balanceObserve(K, 1100)).toEqual({ peak: 1100, used: 0, daySpent: 100, dayGained: 200 })
// further drops spend against the new peak
expect(balanceObserve(K, 1050)).toEqual({ peak: 1100, used: 50, daySpent: 150, dayGained: 200 })
// the review's case: spend 500, then a check-in +200 lands BELOW the old
// peak — the cycle still reopens (used 0), and the day keeps the 500
const K2 = K + "-2"
balanceObserve(K2, 1000)
balanceObserve(K2, 500)
expect(balanceObserve(K2, 700)).toEqual({ peak: 700, used: 0, daySpent: 500, dayGained: 200 })
// a drained pool is the most common cycle: 0 is a real reading, not
// "never seen" — the check-in that follows reopens the cycle from zero
const K3 = K + "-3"
balanceObserve(K3, 1000)
balanceObserve(K3, 0)
expect(balanceObserve(K3, 200)).toEqual({ peak: 200, used: 0, daySpent: 1000, dayGained: 200 })
expect(beijingDayOf()).toMatch(/^\d{4}-\d{2}-\d{2}$/)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// The window as the card sees it: nothing on a fresh sight, then the cycle's
// share with the day's sums; a check-in below the old peak reopens the cycle.
test("usage: the spend window across two reads, and a check-in that reopens the cycle", async () => {
const realFetch = globalThis.fetch
let balance = 20000
globalThis.fetch = async (input) => {
const u = String(input)
if (u.includes("wallets")) return Response.json({ code: 0, data: { total_balance: balance, wallets: [] } })
if (u.includes("autoclaw-task-list")) {
return Response.json({ code: 0, data: [{ task_id: "daily_signin", status: "completed", reward_points: 200 }] })
}
return Response.json({ code: 0, data: null })
}
const dir = mkdtempSync(join(tmpdir(), "autoclaw-usage-"))
_internal.setUsageStatePath(join(dir, ".usage-state.json"))
try {
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } })
const auth = { type: "oauth", access: "a1", refresh: "r1", uid: "spend-1" }
// fresh sight: the peak is set, no spend window yet, the wallet as told
const first = await hooks.auth.usage(async () => auth)
expect(first.windows.find((w) => w.name === "本轮消耗")).toBeUndefined()
expect(first.windows.find((w) => w.name === "积分余额")).toEqual({ name: "积分余额", balance: 20000, unit: "积分" })
// the pool drains 3123: the window carries the share and the day's spend
balance = 16877
const second = await hooks.auth.usage(async () => auth)
expect(second.windows.find((w) => w.name === "积分余额")?.balance).toBe(16877)
const w = second.windows.find((x) => x.name === "本轮消耗")
// display only: the share is spend since the last rise, not what is left
expect(w.aside).toBe(true)
expect(w.used).toBe(15.6)
expect(w.remaining).toBe(84.4)
expect(w.amount).toBe(3123)
expect(w.limit).toBe(20000)
expect(w.display).toBe("3123 / 20000 积分 · 今日 -3123")
// a check-in +200 lands below the old peak and still reopens the cycle
balance = 17077
const third = await hooks.auth.usage(async () => auth)
expect(third.windows.find((x) => x.name === "本轮消耗")).toBeUndefined()
} finally {
globalThis.fetch = realFetch
rmSync(dir, { recursive: true, force: true })
}
})
// Two accounts can carry the same display name (#254), so the ledger key is
// signinAccountKey - uid, or the refresh token when an old account has none -
// never the name. Both accounts here have NO uid on purpose: the pre-review
// key (uid ?? accountId ?? provider) fell back to the shared display name and
// read B's first sight as spend against A's peak; only the token-hash key
// keeps them apart.
test("usage: two same-name accounts keep separate ledgers", async () => {
const realFetch = globalThis.fetch
const balances = { a1: 1000, a2: 300 }
globalThis.fetch = async (input, init) => {
const u = String(input)
if (u.includes("wallets")) {
const who = new Headers(init?.headers).get("Authorization")
return Response.json({ code: 0, data: { total_balance: balances[who.slice(-2)], wallets: [] } })
}
return Response.json({ code: 0, data: [] })
}
const dir = mkdtempSync(join(tmpdir(), "autoclaw-usage-"))
_internal.setUsageStatePath(join(dir, ".usage-state.json"))
try {
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } })
const a = { type: "oauth", access: "a1", refresh: "r1", accountId: "AutoClaw用户" }
const b = { type: "oauth", access: "a2", refresh: "r2", accountId: "AutoClaw用户" }
await hooks.auth.usage(async () => a)
// B is a fresh sight of its own, not A's ledger: no window, not "used 700"
const u = await hooks.auth.usage(async () => b)
expect(u.windows.find((x) => x.name === "本轮消耗")).toBeUndefined()
expect(u.windows.find((x) => x.name === "积分余额")?.balance).toBe(300)
expect(u.balance).toBe("300 积分")
} finally {
globalThis.fetch = realFetch
rmSync(dir, { recursive: true, force: true })
}
})
// An unreadable total_balance (null / "" / not a number) is "unknown", never
// a drained pool: Number(null) is 0, which would record the whole cycle as
// spent and let routing shelve the account. The next good read starts clean.
test("usage: an unreadable total_balance is unknown, not a drained pool", async () => {
const realFetch = globalThis.fetch
let balance = null
globalThis.fetch = async (input) => {
const u = String(input)
if (u.includes("wallets")) return Response.json({ code: 0, data: { total_balance: balance, wallets: [] } })
return Response.json({ code: 0, data: [] })
}
const dir = mkdtempSync(join(tmpdir(), "autoclaw-usage-"))
_internal.setUsageStatePath(join(dir, ".usage-state.json"))
try {
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } })
const auth = { type: "oauth", access: "a1", refresh: "r1", uid: "null-1" }
const bad = await hooks.auth.usage(async () => auth)
expect(bad.error).toBe("积分响应异常")
expect(bad.windows).toEqual([])
// the ledger never saw the null: the next good read is a fresh sight
balance = 990
const good = await hooks.auth.usage(async () => auth)
expect(good.error).toBeUndefined()
expect(good.balance).toBe("990 积分")
expect(good.windows.find((x) => x.name === "本轮消耗")).toBeUndefined()
expect(good.windows.find((x) => x.name === "积分余额")?.balance).toBe(990)
} finally {
globalThis.fetch = realFetch
rmSync(dir, { recursive: true, force: true })
}
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-autoclaw-auth",
"version": "0.2.10",
"version": "0.2.11",
"description": "OpenCode provider plugin for AutoClaw (Zhipu OpenClaw): oversea web sign-in (Google/z.ai) and CN phone SMS, multi-account pool, credit balance and daily check-in",
"type": "module",
"main": "./index.mjs",