autoclaw 0.2.18: the README reads like a manual, and the sign-in's non-2xx guard gets its tests (#836)

autoclaw 0.2.18 (yunwang2442-creator, #836): the README is rewritten around
what a user does, with an English README.en.md shipped in `files`, and
dailySignin's non-2xx guard gets three tests. No change to index.mjs.

Reviewed at 699e545112c77938c4274368ef505017ed902e2e, merged onto main
b8100001 (mote, Bun 1.4.2, temp HOME):
- packages/autoclaw `bun test`: 103 pass, 0 fail
- `bun scripts/check.mjs autoclaw` and `bun scripts/check.mjs`: ok
- repo root `bun test`: 6820 pass, 20 skip, 0 fail (496 files)
- broken by hand (at 2ac00cee, same test file): removing
  `if (!res.ok) return null` turns exactly the three new tests red
- README facts checked against index.mjs (CHAT_PATH, X-Authorization,
  refreshShared's 60 s share and rotatedMemo, recordBalance's any-rise cycle)
- CI run 42378290789 green
Not tried: a real AutoClaw sign-in; the README in magpie's Plugins page.
This commit is contained in:
我是一条没有名字的区
2026-11-07 22:06:16 +08:00
committed by GitHub
parent b81000019f
commit 1df427773b
4 changed files with 230 additions and 51 deletions
+138
View File
@@ -0,0 +1,138 @@
# @magpie-community/opencode-autoclaw-auth
[中文](README.md) | English
An [OpenCode](https://opencode.ai) / [magpie](https://usemagpie.ai) provider plugin for **AutoClaw (Zhipu's OpenClaw cloud account system)**. Talks straight to the upstream cloud API: one sign-in brings both **model calls** and **credit balance**, with multi-account pools, failover, token rotation and daily check-in.
## What this plugin covers
One package registers two providers, split by where the account lives:
| Provider id | Sign-in | Upstream host | Model refs |
|---|---|---|---|
| `autoclaw` | Google / z.ai web OAuth | `autoglm-api.autoglm.ai` | `autoclaw/zai_auto` etc. |
| `autoclaw-cn` | Phone SMS (+86) | `autoglm-api.zhipuai.cn` | `autoclaw-cn/zai_auto` etc. |
Both providers support magpie's multi-account pools, failover, automatic token rotation and credit balance display. 4 online models verified working, as prefixed routeModelIds (`zai_` Zhipu / `zaicoding_` coding plan):
- `zai_auto` / `zai_auto-fast` (auto-routing, reasoning variants: low / high / max)
- `zai_glm-5.3-flash` (fast reasoning, reasoning variants)
- `zaicoding_glm-5.3` (GLM-5.3 coding, reasoning variants)
> Note: the old `zai_glm-5-turbo` and the Doubao DeepSeek mappings `tdpsk_deepseek-v4-flash-202605` / `tdpsk_deepseek-v4-pro-202606` were taken offline upstream (every call returns `400 illegal model`) and have been removed from the model list.
## Signing in
```sh
magpie plugin add @magpie-community/opencode-autoclaw-auth
magpie plugin login autoclaw # Google / z.ai web sign-in
magpie plugin login autoclaw-cn # phone SMS
magpie provider test autoclaw zai_auto
magpie quota # credit balance
```
OpenCode works the same way (`opencode auth login`). Sign-ins are kept in magpie's `plugin-auth.json` (mode 600) or OpenCode's `auth.json`.
**The chat endpoint**: `POST {host}/autoclaw-proxy/proxy/autoclaw/v1/chat/completions`, authenticated with `X-Authorization: Bearer <access token>` (separate from the headers the sign-in/credit endpoints use). Access tokens rotate before they expire — the refresh token is one-time, the `auth.refresh` hook is serialized by magpie, in-flight refreshes for the same token are shared (reused within 60 s), so **a refresh token is never spent twice**; every rotation lands in an in-memory fallback, so a failed write-back loses nothing.
**What the credit line means**: points only, no cap; the wallet breakdown (gift / membership) rides inside the balance string as brackets (`余额行(赠送积分 500 · 会员积分 734)`), never as its own window. The **current-spend** window's percentage is the **share spent since the last rise** (peak − current), not the pool's remainder; a new cycle opens on **any rise** over the last observed balance (including a rise from 0 — check-ins, gifts, redemptions), **without waiting to pass the old peak** (a check-in often lands after spending). Since the daily check-in opens one every day, "current" ≈ "since today's check-in".
**The international sign-in is fully local**: the plugin takes one port from the official TokenServer pool on 127.0.0.1 (18432/19654/19723/53699, the OAuth client's callback whitelist; taken ports roll over), serves a built-in guide page that runs Alibaba's slider captcha (`AliyunCaptcha`, `ali_captcha_verify_param` receipt), opens the authorization page, forwards to Google/z.ai, and captures the callback code automatically — all in the browser, nothing to paste. The server closes when sign-in finishes (or after 10 minutes if abandoned, releasing the port). A callback code must match the `state` the authorization page issued; anything else is rejected (anti-forgery). The local server's write endpoints only accept 127.0.0.1/localhost origins.
## Credits on the card
`magpie quota` / a GUI refresh shows, on every AutoClaw card:
- **Credit balance** (prepaid wallet window `{ name: "积分余额", balance, unit: "积分" }`, magpie ≥ v0.1.1790, #3950): routing knows and ranks accounts by their real balance, invents no percentages, and treats 0 as spent out; older magpie builds ignore `balance` and leave the account as-is.
- **Daily check-in** status row (今日已签 ✓ / 今日未签(+N)).
- **Current spend** (aside, display-only, never routed): the upstream has no per-model credit ledger (wallets.v2 carries balances only), so it is computed from local balance deltas — each `usage()` records the cycle peak, `peak − current = spent this cycle`; **any rise** (relative to the last seen balance, including a rise from 0 — check-ins, gifts, redemptions) opens a new cycle. Since a daily check-in opens one every day, "current" ≈ "since today's check-in".
- **Campaign points** (aside): when the account has campaign ledger activity, one extra row at the end — see [Daily check-in](#daily-check-in) below.
- A `total_balance` that is null / empty / non-numeric is treated as unknown ("积分响应异常") and not recorded.
State is kept per account (keyed by `signinAccountKey`, #254: uid, or a hash of the refresh token when there is none) as JSON. Address precedence: `AUTOCLAW_USAGE_STATE_FILE` (explicit override) → `$XDG_CONFIG_HOME/magpie/` → `$HOME/.config/magpie/` (on Windows HOME is usually unset, so `USERPROFILE` next, `os.homedir()` last — never the drive root `C:\.config\magpie`) → file name `autoclaw-usage.json`. Writes go through a temp file + rename; entries untouched for 30 days are pruned; plugin updates do not lose it. Tests can point it elsewhere with `_internal.setUsageStatePath`.
## Daily check-in
Two ways; the native one is recommended:
**① magpie native check-in (magpie ≥ v0.1.1083, recommended)**: the plugin implements the `auth.checkin` hook on magpie's unified schedule — Settings → Usage → Plugins has a **Daily check-in** switch per provider (default off); when on, each account is signed once a day (Beijing time; first check 2 minutes after start, polling every 30 minutes, failures retried 30 minutes later). The account's Usage card shows the result, and **Check in now** signs manually.
**② Legacy auto-sign-in (default off)**: quota reads (`magpie quota`, GUI refresh) and token refreshes sign the account in when it is not yet signed (idempotent upstream, deduped locally by Beijing day; failures are not throttled — the next quota read or refresh retries). For older magpie/OpenCode hosts, or users who prefer this behavior, turn on `signinOnUsage`.
> **"Sign-in for points" campaign rewards**: the server only records an `autoclaw_user_active` event for a `POST /userapi/v1/user-info` that carries the full official desktop business headers (`X-Channel: AutoClaw20`, `X-Version: 2.2.0`, UA `AutoClaw/2.2.0 (win-x64)`, `X-Tm: win-x64`, `X-Product`, …; every platform reports this Windows fingerprint) — without that call, such campaigns pay nothing (yetone/magpie#3681). Measured payouts: international "AutoClaw Weekly Perks" +4000, CN "AutoClaw 用户登录奖励" +5000.
>
> **Only ① the native check-in path calls `user-info`**: with the current access token, refreshed and retried only when the upstream refuses it. `user-info` itself does not complete the daily check-in — that stays with `task-complete`; the two are independent. ② the legacy path, and hosts that never run the `checkin` hook (OpenCode 1.x/2.x), do not earn campaign rewards.
### The campaign points row
When the account has campaign ledger activity (credits, spends or expiries), `usage()` appends one row:
```text
剩 4,000(AutoClaw Weekly Perks) · 已领 14,000 · 过期 7,711(近期)
```
- **Source**: `GET /agent-assetmgr/api/v1/ledgers_std?biz_app_id=autoclaw&page_size=200&wallet_scope=campaign`. The server opens one wallet instance per activity (`wallet_id`), and credit / debit / expire entries all carry `wallet_scope=campaign`; the server may ignore the filter, so entries are re-filtered client-side.
- **How 剩 is computed**: per instance, `credit − debit − expire`, clamped at 0. An instance whose credit fell out of the window counts 0 (its expiry still lands in 过期) — **remaining never over-states**, but out-of-window credits do not participate.
- **已领 / 过期** are window sums (the newest ~151 entries ≈ 18 days; pagination is inert), hence (近期).
- **Caching**: per account key (`signinAccountKey`), 10 minutes; invalidated the moment check-in's `user-info` reaches the server (a grant may have just landed); a failed read is not cached (the next `usage()` retries); a protocol change (entries not an array) is treated as unknown and cached for 10 minutes. Any read failure only omits the row — balance and check-in rows are never affected.
- **The row never carries `balance`**: magpie (≥ v0.1.1790) treats a window's `balance` as a prepaid routing pool (#3950) and would double-count it.
- **Numbers are grouped in threes** (`fmtPoints`, locale-independent); the wallet breakdown inside the balance line is not (yet).
## Options
The legacy path has **two switches** (plugin options first, config file fallback; the native check-in switch lives only in the GUI's Settings):
```sh
# Channel 1: plugin options (magpie CLI)
magpie plugin options @magpie-community/opencode-autoclaw-auth '{"signin": false}' # master off
magpie plugin options @magpie-community/opencode-autoclaw-auth '{"signinHour": 8}' # only 8:00–8:59
magpie plugin options @magpie-community/opencode-autoclaw-auth '{"signinOnUsage": true}' # sign on quota reads / refreshes
# Channel 2: config file ~/.config/magpie/autoclaw.json (hot-read)
cat > ~/.config/magpie/autoclaw.json <<'EOF'
{ "signin": true, "signinHour": null, "signinOnUsage": true }
EOF
```
| Option | Default | Meaning |
|---|---|---|
| `signin` | `true` | legacy auto-sign-in master switch (does not affect native check-in) |
| `signinOnUsage` | `false` | sign in on quota reads / refreshes (default off, left to the native switch) |
| `signinHour` | `null` | restrict the sign-in hour: `8` = only when local time is 8:00–8:59; `null` = no restriction |
| `dump406` | `false` | master switch for the 406 dump (boolean; the string `"false"` does not count as on). Writes to `~/.config/magpie/autoclaw-406/`; the `AUTOCLAW_406_DUMP_DIR` env var overrides the address and turns it on by itself (takes precedence over this option) |
## The chat gateway and request shaping
AutoClaw's chat gateway enforces a strict request shape; missing any item returns an empty-body `406 Not Acceptable`:
- **Official system prefix**: must start with `You are AutoClaw. Answer the user directly and concisely.` (the plugin merges it into the caller's system messages, or adds a minimal one when there is none)
- **max_tokens removed**: the gateway refuses `max_tokens` / `max_completion_tokens`; the plugin strips them before sending
- **No X-Harness-Type**: the upstream 406s on that header; the legacy header is deleted
- **External harness identity lines rewritten**: the upstream intercepts system messages that announce an external agent identity ("You are Codex", "You are Claude Code", …); the plugin's `unflag` rewrites them into compatible wording
- **Official client fingerprint (international chat)**: international chat requests carry the full header set of the official AutoClaw 2.0.3 desktop client (`official` channel), taken from its AppImage's `dist/main.cjs`: `X-Channel: official`, `X-Version: 2.0.3`, `X-Lang: en`, `X-Client-Type: pc`, `X-Product: autoclaw`, `x_trace_id: autoclaw-desktop`, `X-Auth-Appid/X-Auth-TimeStamp/X-Auth-Sign` (`md5("100003&<second timestamp>&<appKey>")`, the same signature as sign-in and credits), `X-Request-Id` = `X-Trace-Id` (one UUID per request), `X-Session-Id` (a UUID constant per conversation, derived from the first message), OpenAI SDK 6.26.0's `User-Agent` and `X-Stainless-*`. `X-Tm` follows the official `managedPlatform()`: macOS `mac`, Windows `win`, Linux `linux` (x64/arm64 alike). Next to a **non-official** fingerprint the gateway refuses `X-Tm: linux` (403 `forbidden`, #367); the `linux-x64` sent by 0.2.7–0.2.11 was a workaround, not the official value.
The CN build `autoclaw-cn` goes through AutoClaw 2.1.0's managed gateway (`autoglm-acceleration-api.zhipuai.cn`); the international `autoclaw` goes through the overseas direct gateway (`autoglm-api.autoglm.ai`). Both verified with real calls and inference.
### The 406 dump (off by default)
A 406's upstream body is empty and magpie keeps only token counts — diagnosing a sentence the FLAGGED list misses needs the refused request's own text. When enabled (the `AUTOCLAW_406_DUMP_DIR` env var, or the plugin option `"dump406": true`), every 406 writes the **rewritten, actually-sent** system/developer messages (plus the `model` field; never user/assistant/tool content) as one JSON: file mode 0600, directory 0700, the newest 10 kept (rotated by write time; only files matching `autoclaw-406-*.json` are ever touched).
**Privacy note**: system prompts are not free of personal data — harnesses put the working directory, git status, project instruction files, sometimes the user's email there. This is a local 0600 diagnostic file, off by default; know that before turning it on. `AUTOCLAW_406_DUMP_DIR` may point at any existing directory (rotation only deletes the dump's own files); the default directory falls back `HOME` → `USERPROFILE` → `os.homedir()` on Windows GUI processes (which usually have no `HOME`).
## Known behavior
- Phone-number accounts only ever use the CN host (managed gateway; 401/403 mark the sign-in expired); z.ai/Google accounts only the international host (401/403 retries the other side, both refusing marks it expired).
- An exhausted quota is not a signed-out account: a `403` + `{"code":810000,"message":"GLM-5.3 免费额度已用完,…"}` answer (or a 403 body about quotas/balances) becomes a `429` carrying the upstream's own words, the sign-in is kept (`X-Magpie-Sign-In: kept`), and the international side stops host-hopping (plugins#274).
- A banned account is not a signed-out account: a `403` + `{"code":410004,"message":"The account has been banned"}` answer (or code/message fields saying banned / 封禁 / 账号异常 / 账号被冻结) flows through on chat, refresh, credits and check-in with the upstream's own words; chat becomes a `403 permission_error`, the sign-in is kept, no host-hopping. Other 401/403s still mark the sign-in expired.
- The upstream model whitelist changes with versions; a retired model returns `400 illegal model` (the error message passes through).
- Refresh tokens are **mutually evicting** with the AutoClaw desktop app (both rotate) — do not stay signed in on desktop with the same account.
- When the upstream changes protocols, `CLIENT_VERSION` / endpoint paths may need to follow the official client.
### Local sign-in page ownership
The plugin waits for the loopback listener before returning its guide URL. Magpie/OpenCode opens that URL; the callback does not launch a second browser through a shell. Cancelled or expired sessions release their port; begin a new sign-in rather than reusing the old URL.
The guide distinguishes an intentional authorization redirect from the user closing the page. The redirect must keep the loopback callback alive; closing a guide before authorization still cancels it. The guide reports a disconnected or expired session explicitly.
## Disclaimer
This is an **unofficial** community plugin, unaffiliated with Zhipu AI / OpenClaw / AutoClaw. It is built on reverse-engineering and live testing of the official client's behavior, for personal study only; account risks are the user's own. Upstream protocol changes can break it at any time.
+34 -49
View File
@@ -1,6 +1,10 @@
# @magpie-community/opencode-autoclaw-auth
[OpenCode](https://opencode.ai) / [magpie](https://usemagpie.ai) provider 插件:**AutoClaw(智谱澳龙 / OpenClaw 云端账号体系)**。
中文 | [English](README.en.md)
[OpenCode](https://opencode.ai) / [magpie](https://usemagpie.ai) provider 插件:**AutoClaw(智谱澳龙 / OpenClaw 云端账号体系)**。直连上游云 API,一次登录同时拿到**模型调用**与**积分额度**,支持多账号、故障切换、token 自动轮换与每日签到。
## 这个插件管什么
一个包注册两个供应商,按账号所在地分开登录、分开记额度:
@@ -17,7 +21,7 @@
> 注:旧版中的 `zai_glm-5-turbo` 以及豆包 DeepSeek 映射 `tdpsk_deepseek-v4-flash-202605`、`tdpsk_deepseek-v4-pro-202606` 已被上游下线(调用均返回 `400 非法模型`),本版本已从模型列表中移除。
## 安装
## 怎么登录
```sh
magpie plugin add @magpie-community/opencode-autoclaw-auth
@@ -29,34 +33,23 @@ magpie quota # 积分余额
OpenCode 同样可加载(`opencode auth login`)。登录信息保存在 magpie 的 `plugin-auth.json`(600 权限)/ OpenCode 的 `auth.json`。
## 直连说明(不经本地网关)
**对话端点**:`POST {host}/autoclaw-proxy/proxy/autoclaw/v1/chat/completions`,`X-Authorization: Bearer <access token>` 鉴权(与登录/积分接口各自的头分开)。token 过期前自动轮换——refresh token 一次一换,`auth.refresh` 钩子交给 magpie 串行化,同一令牌的刷新在途共享(60 秒内复用),**不会双花**;轮换结果记入内存兜底,写回失败也不丢。
插件**直连上游云 API**,登录/对话/刷新/积分全部自行完成:
**积分显示的口径**:纯积分制,无总量上限,细分钱包(赠送/会员等)以 `余额行(赠送积分 500 · 会员积分 734)` 的括号形式附在 balance 字符串里,不单独成窗口。「本轮消耗」窗口的百分比是**「自上次上涨以来花掉的比例」**(峰值 − 当前),不是池子剩余;开新一轮的条件是**余额出现任何上涨**(相对上次观察值,含从 0 回升——签到、礼包、兑换),**不等涨过旧峰值**(签到常在花费之后到)。每日签到恰好每天开一轮,所以「本轮」≈「自今天签到以来」。
- 对话走 `POST {host}/autoclaw-proxy/proxy/autoclaw/v1/chat/completions`(`X-Authorization` 鉴权);
- token 过期前自动轮换(refresh token 一次一换,`auth.refresh` 钩子交给 magpie 串行化,不会双花);
- 积分余额通过 `auth.usage` 的 `balance` 显示(纯积分制,无总量上限,细分钱包写在括号里),
同时作为预付钱包窗口 `{ name: "积分余额", balance, unit: "积分" }` 上报(magpie ≥ v0.1.1790,
#3950):路由按真实余额认识和排位账号,不发明百分比,余额 0 算用完;更早的 magpie
不认识 `balance`,账号维持原状。
上游没有按模型的积分流水接口(wallets.v2 只有余额)。「本轮消耗」窗口**由本地余额差值算**——
活动行另从 `ledgers_std` 拉取(见下文「每日签到」一节)。
每次 `usage()` 记下本轮峰值,`峰值 − 当前 = 本轮已消耗`,**任何上涨**(相对上次
观察到的余额,含从 0 回升——每日签到、礼包、兑换)都开新一轮,不等涨过旧峰值(签到常在花费
之后到)。因为每天签到都会开新一轮,「本轮」≈「自今天签到以来」。这个窗口带
`aside: true`,只展示、不参与路由:它的百分比是「自上次上涨以来花掉的比例」,不是池子剩余。
`total_balance` 为 null/空串/非数时按未知处理(「积分响应异常」),不记账。
状态按账号(键复用 `signinAccountKey`,#254:uid,没 uid 按 refresh token 哈希)存 JSON,
地址优先级:`AUTOCLAW_USAGE_STATE_FILE`(显式覆盖)→ `$XDG_CONFIG_HOME/magpie/` →
`$HOME/.config/magpie/`(Windows 上 HOME 常未设,改用 `USERPROFILE`,再兜底 `os.homedir()`,
绝不落在盘根 `C:\.config\magpie`)→ 文件名 `autoclaw-usage.json`。写入走临时文件 + rename,
30 天没动的条目清走;插件更新不会丢。测试可用 `_internal.setUsageStatePath` 指到临时目录。
- **国际版登录是完整本地实现**:插件在 127.0.0.1 上取官方 TokenServer 端口池中的一个端口
(18432/19654/19723/53699,OAuth client 回调白名单;被占自动顺延)起临时服务器,内嵌引导页完成
阿里滑块验证(`AliyunCaptcha` SDK,`ali_captcha_verify_param` 回执)→ 获取授权页 →
自动跳转 Google/z.ai → 回调自动捕获 code,全程浏览器完成、无需粘贴;登录结束服务器即关
(未完成时 10 分钟后自动关闭释放端口)。回调 code 必须匹配授权页下发的 `state`,其余一律拒收
(防伪造回调劫持登录);本地服务器的写接口仅接受 127.0.0.1/localhost 来源。
**国际版登录是完整本地实现**:插件在 127.0.0.1 上取官方 TokenServer 端口池中的一个端口(18432/19654/19723/53699,OAuth client 回调白名单;被占自动顺延)起临时服务器,内嵌引导页完成阿里滑块验证(`AliyunCaptcha` SDK,`ali_captcha_verify_param` 回执)→ 获取授权页 → 自动跳转 Google/z.ai → 回调自动捕获 code,全程浏览器完成、无需粘贴;登录结束服务器即关(未完成时 10 分钟后自动关闭释放端口)。回调 code 必须匹配授权页下发的 `state`,其余一律拒收(防伪造回调劫持登录);本地服务器的写接口仅接受 127.0.0.1/localhost 来源。
## 积分在卡片上怎么显示
`magpie quota` / GUI 刷新时,每张 AutoClaw 卡片显示:
- **积分余额**(预付钱包窗口 `{ name: "积分余额", balance, unit: "积分" }`,magpie ≥ v0.1.1790,#3950):路由按真实余额认识和排位账号,不发明百分比,余额 0 算用完;更早的 magpie 不认识 `balance`,账号维持原状。
- **每日签到**状态行(今日已签 ✓ / 今日未签(+N))。
- **本轮消耗**(aside,只展示、不参与路由):上游没有按模型的积分流水接口(wallets.v2 只有余额),所以由本地余额差值算——每次 `usage()` 记下本轮峰值,`峰值 − 当前 = 本轮已消耗`;**任何上涨**(相对上次余额,含从 0 回升——签到、礼包、兑换)都开新一轮。因为每天签到都会开新一轮,「本轮」≈「自今天签到以来」。
- **活动积分**(aside):账号有活动流水时末尾多一行,见下文[「每日签到」](#每日签到)一节。
- `total_balance` 为 null/空串/非数时按未知处理(「积分响应异常」),不记账。
状态按账号(键复用 `signinAccountKey`,#254:uid,没 uid 按 refresh token 哈希)存 JSON,地址优先级:`AUTOCLAW_USAGE_STATE_FILE`(显式覆盖)→ `$XDG_CONFIG_HOME/magpie/` → `$HOME/.config/magpie/`(Windows 上 HOME 常未设,改用 `USERPROFILE`,再兜底 `os.homedir()`,绝不落在盘根 `C:\.config\magpie`)→ 文件名 `autoclaw-usage.json`。写入走临时文件 + rename,30 天没动的条目清走;插件更新不会丢。测试可用 `_internal.setUsageStatePath` 指到临时目录。
## 每日签到
@@ -66,13 +59,11 @@ OpenCode 同样可加载(`opencode auth login`)。登录信息保存在 magp
**② 旧链路自动补签(默认关)**:查额度(`magpie quota`、GUI 刷新)与 token 刷新时发现未签就补签(服务端幂等,本地按北京日去重;失败无节流——下次查额度或刷新时立即重试)。旧版 magpie / OpenCode 宿主或偏好该行为的用户开启 `signinOnUsage`。
`magpie quota` 的额度窗口在查询成功时显示**每日签到**状态行(今日已签 ✓ / 今日未签(+N))。
> **「登录领积分」类活动奖励**:服务端只为带整套官方桌面端业务头(`X-Channel: AutoClaw20`、`X-Version: 2.2.0`、UA `AutoClaw/2.2.0 (win-x64)`、`X-Tm: win-x64`、`X-Product` 等;所有平台都按这套 Windows 指纹上报)的 `POST /userapi/v1/user-info` 记录 `autoclaw_user_active` 活跃事件——没有这次调用,这类活动就领不到(yetone/magpie#3681)。本次实测到账:国际「AutoClaw Weekly Perks」+4000、国内「AutoClaw 用户登录奖励」+5000。
>
> **只有 ① 原生签到链路会调用 `user-info`**:用当前 access token 直接请求,access token 被上游拒绝时才刷新重试;`user-info` 本身不完成每日签到,每日签到仍由 `task-complete` 完成,两者相互独立。② 旧链路补签与不执行 `checkin` 钩子的宿主(OpenCode 1.x/2.x)不会领取活动奖励。
### 活动余额行(活动积分)
### 活动积分行
账号有活动流水时(领过、花过或失效过活动积分),`usage()` 返回的窗口列表末尾多一行:
@@ -80,20 +71,15 @@ OpenCode 同样可加载(`opencode auth login`)。登录信息保存在 magp
剩 4,000(AutoClaw Weekly Perks) · 已领 14,000 · 过期 7,711(近期)
```
- **数据来源**:`GET /agent-assetmgr/api/v1/ledgers_std?biz_app_id=autoclaw&page_size=200&wallet_scope=campaign`。
服务端给每个活动开独立的 `wallet` 实例(`wallet_id`),credit / debit / expire 三种流水
都带 `wallet_scope=campaign`;服务端可能忽略过滤参数,客户端按 scope 再过滤一遍。
- **剩 的算法**:按实例 `credit − debit − expire`(截 0)。入账掉出窗口的旧实例按 0 计
(其失效额仍计入「过期」)——**「剩」永远不会虚高**,但窗口外的旧入账不参与计算。
- **数据来源**:`GET /agent-assetmgr/api/v1/ledgers_std?biz_app_id=autoclaw&page_size=200&wallet_scope=campaign`。服务端给每个活动开独立的 `wallet` 实例(`wallet_id`),credit / debit / expire 三种流水都带 `wallet_scope=campaign`;服务端可能忽略过滤参数,客户端按 scope 再过滤一遍。
- **剩 的算法**:按实例 `credit − debit − expire`(截 0)。入账掉出窗口的旧实例按 0 计(其失效额仍计入「过期」)——**「剩」永远不会虚高**,但窗口外的旧入账不参与计算。
- **已领 / 过期**是窗口内(最近 ~151 条、约 18 天,翻页参数无效)的合计,标注(近期)。
- **缓存**:按账号键(`signinAccountKey`)10 分钟;`checkin` 的 user-info 到达服务端时
立即失效(活动可能刚到账);读取失败不缓存(下次 `usage()` 立即重试);协议变更
(entries 非数组)按未知处理、缓存 10 分钟不重试。任何读取失败只省略该行,
绝不影响余额与签到行。
- **活动行不携带 `balance`**:窗口的 `balance` 会被 magpie(≥ v0.1.1790)当作预付路由池
(#3950)重复计入路由。
- **缓存**:按账号键(`signinAccountKey`)10 分钟;`checkin` 的 user-info 到达服务端时立即失效(活动可能刚到账);读取失败不缓存(下次 `usage()` 立即重试);协议变更(entries 非数组)按未知处理、缓存 10 分钟不重试。任何读取失败只省略该行,绝不影响余额与签到行。
- **活动行不携带 `balance`**:窗口的 `balance` 会被 magpie(≥ v0.1.1790)当作预付路由池(#3950)重复计入路由。
- **数字三位分组**(`fmtPoints`,不依赖 locale);余额行里的细分钱包数值暂不分组。
## 配置项
旧链路的开关有**两个通道**(插件 options 优先,配置文件兜底;原生签到开关只在 GUI 的 Settings 里):
```sh
@@ -122,7 +108,6 @@ AutoClaw 对话网关对请求形状有硬性要求,缺任一条都回 `406 No
- **删除 max_tokens**:网关拒收 `max_tokens` / `max_completion_tokens`,插件会在发送前自动剔除
- **不发送 X-Harness-Type**:上游收到 `X-Harness-Type` 即报 406,已删除该残留请求头
- **改写外部 Harness 身份声明**:上游拦截 system 中包含的外部 agent 身份句(如 `You are Codex`、`You are Claude Code` 等),插件的 `unflag` 会自动将其替换为兼容措辞,避免 406 拦截
- **官方客户端指纹(国际版对话)**:国际版对话请求带官方 AutoClaw 2.0.3 桌面端(`official` 渠道)的整套请求头,取自其 AppImage 的 `dist/main.cjs`:`X-Channel: official`、`X-Version: 2.0.3`、`X-Lang: en`、`X-Client-Type: pc`、`X-Product: autoclaw`、`x_trace_id: autoclaw-desktop`、`X-Auth-Appid/X-Auth-TimeStamp/X-Auth-Sign`(`md5("100003&<秒级时间戳>&<appKey>")`,与登录/积分接口同一签名)、`X-Request-Id` = `X-Trace-Id`(每次请求一个 UUID)、`X-Session-Id`(同一对话不变的 UUID,插件由对话首条消息导出)、OpenAI SDK 6.26.0 的 `User-Agent` 与 `X-Stainless-*`。`X-Tm` 与官方 `managedPlatform()` 一致:macOS `mac`、Windows `win`、Linux `linux`(x64/arm64 相同)。网关只在**非官方指纹**旁拒收 `X-Tm: linux`(403 `forbidden`,#367);0.2.7–0.2.11 发的 `linux-x64` 只是绕过,不是官方值。
国内版 `autoclaw-cn` 走 AutoClaw 2.1.0 managed gateway(`autoglm-acceleration-api.zhipuai.cn`);国际版 `autoclaw` 走海外直连网关(`autoglm-api.autoglm.ai`)。两者均已通过真实调用与推理验证。
@@ -142,12 +127,12 @@ AutoClaw 对话网关对请求形状有硬性要求,缺任一条都回 `406 No
- refresh token 与 AutoClaw 桌面端**共用会互踢**(双方都轮换),插件账号请勿同时在桌面端登录。
- 上游偶发改协议时,`CLIENT_VERSION` / 端点路径可能需要随官方客户端更新。
## 本地登录页的所有权(Local sign-in page ownership)
插件先在回环端口上就绪,再返回引导页 URL。magpie/OpenCode 打开这个 URL;回调不会通过 shell 再拉起第二个浏览器。已取消或已过期的会话会释放端口——请重新发起登录,不要复用旧 URL。
引导页会区分「用户主动完成授权跳转」与「用户直接关闭页面」:授权跳转必须保持回环回调存活;在授权完成前关闭引导页同样视为取消。会话断开或过期时,引导页会明确提示。
## 免责声明
本包为**非官方**社区插件,与智谱 AI / OpenClaw / AutoClaw 无任何关联。实现基于对官方客户端行为的逆向分析与实测,仅供个人学习研究;使用产生的账号风险由使用者自行承担。上游协议变更可能导致插件随时失效。
### Local sign-in page ownership
The plugin waits for the loopback listener before returning its guide URL. Magpie/OpenCode opens that URL; the callback does not launch a second browser through a shell. Cancelled or expired sessions release their port; begin a new sign-in rather than reusing the old URL.
The guide distinguishes an intentional authorization redirect from the user closing the page. The redirect must keep the loopback callback alive; closing a guide before authorization still cancels it. The guide reports a disconnected or expired session explicitly.
+55
View File
@@ -2789,3 +2789,58 @@ test("maintainer: the fake clock never leaks into the rest of the suite", async
await Bun.sleep(60)
expect(Date.now() - t0).toBeGreaterThanOrEqual(40)
})
// 维护者最终 review 点名的缺口:dailySignin 的「HTTP 非 2xx 一律返回 null」
// 没有专属测试。最险的形状是「HTTP 500 但 body 里写着 success:true」——
// 谁要是把 `if (!res.ok) return null` 删了(或改成先读 body),这条必须红。
test("0.2.18: a 500 with success:true in the body is a failure, not a claimed sign-in", async () => {
const realFetch = globalThis.fetch
globalThis.fetch = async () => new Response(
String.raw`{"code":0,"data":{"success":true,"reward_points":400}}`,
{ status: 500 },
)
try {
// 直测 dailySignin:非 2xx → null(body 里写什么都一样)
const r = await _internal.dailySignin("at-x", "https://autoglm-api.autoglm.ai")
expect(r).toBeNull()
// 经 checkinOutcome 的完整链路:null → failed,绝不落成 claimed
expect(_internal.checkinOutcome(r).outcome).toBe("failed")
} finally {
globalThis.fetch = realFetch
}
})
// 同族守卫:403 + success:true 同样必须失败(和维护者举的 500 是同一条 if 守住的)。
test("0.2.18: a 403 with success:true in the body is a failure too", async () => {
const realFetch = globalThis.fetch
globalThis.fetch = async () => new Response(
String.raw`{"code":0,"data":{"success":true,"reward_points":400}}`,
{ status: 403 },
)
try {
expect(await _internal.dailySignin("at-x", "https://autoglm-api.autoglm.ai")).toBeNull()
} finally {
globalThis.fetch = realFetch
}
})
// 经 checkin 的端到端:task-list 正常返回任务,task-complete 回 500+success:true,
// 当天必须落成 failed(30 分钟后重试),绝不能记成已签。
test("0.2.18: a checkin whose task-complete answers 500 with success:true ends the day as failed", async () => {
const realFetch = globalThis.fetch
globalThis.fetch = campFetch({
total: 4000,
ledger: [],
signin: () => pendingTask(),
complete: () => new Response(String.raw`{"code":0,"data":{"success":true,"reward_points":400}}`, { status: 500 }),
})
try {
const hooks = await campHooks()
const r = await hooks.auth.checkin(async () => campAuth("nonok500"))
expect(r.outcome).toBe("failed")
expect(r.credit).toBeUndefined()
expect(r.message).toBe("签到接口无响应")
} finally {
campCleanup(realFetch)
}
})
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-autoclaw-auth",
"version": "0.2.17",
"version": "0.2.18",
"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": "./opencode.mjs",
@@ -9,7 +9,8 @@
"index.mjs",
"opencode.mjs",
"opencode2.mjs",
"README.md"
"README.md",
"README.en.md"
],
"keywords": [
"opencode",