Skip to content

Commit 62866f3

Browse files
committed
Feat: Update to 3.10, added autoclaim for weekend plans
升级到3.10版本 根据客户端新功能的开放,添加了自动claim周末一个亿免费token活动的功能(默认五分钟轮询接口,可调) 抢到不会继续抢,避免无意义网络请求 双端首发兼容
1 parent 9cec45e commit 62866f3

21 files changed

Lines changed: 1852 additions & 104 deletions

‎Android-APP/app/src/main/assets/server_bundle/server.cjs‎

Lines changed: 609 additions & 95 deletions
Large diffs are not rendered by default.

‎README.md‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,32 @@ curl http://localhost:8080/async/v1/messages \
120120
}'
121121
```
122122

123+
### Weekend-Plan Auto-Claim (manualClaimPlan)
124+
125+
ZCode 3.10 exposes limited-quota trial plans (e.g. weekend packages) that are
126+
claimed first-come-first-served and activate at a future time. The proxy can
127+
grab them for you automatically — it polls the preview endpoint every 5 minutes
128+
and claims the highest-priority plan the moment the campaign endpoint goes live
129+
(a 404 before launch is the expected pre-campaign state). Requires
130+
`auth.mode: oauth` and `identity.appVersion >= 3.10.0`.
131+
132+
```yaml
133+
claim:
134+
enabled: true # start the auto-claim scheduler while serving
135+
# auto: true # set false to only use the CLI command
136+
# planId: "" # claim a specific plan; empty = highest priority
137+
```
138+
139+
One-shot usage:
140+
141+
```bash
142+
zcode-proxy claim list # show currently claimable plans
143+
zcode-proxy claim # claim now (highest priority, or claim.planId)
144+
```
145+
146+
Backoff: `already_claimed`/`quota_exhausted` wait for the server-provided next
147+
window; other failures use `claim.cooldownMs` (default 10 min).
148+
123149
## Usage Examples
124150

125151
### OpenAI Format
@@ -191,12 +217,13 @@ multi-session autosave (localStorage). Open Settings (⚙) to configure.
191217
| `provider` | `ZCODE_PROVIDER` | `zai` | Upstream provider |
192218
| `plan` | — | `coding-plan` | Plan tier: `coding-plan` (direct upstream) or `start-plan` (zcode.z.ai gateway + JWT + captcha) |
193219
| `providers.<p>.credential` | — | — | Per-provider credential override (else uses `auth.apiKey`) |
194-
| `identity.appVersion` | `ZCODE_APP_VERSION` | `3.9.1` | `User-Agent: ZCode/{version}` |
220+
| `identity.appVersion` | `ZCODE_APP_VERSION` | `3.10.0` | `User-Agent: ZCode/{version}` |
195221
| `identity.deviceMid` | `ZCODE_IDENTITY_DEVICE_MID` | auto-generated | Device identity (`X-Device-Mid`); UUIDv4 generated once at first `auth login` / config creation and reused forever |
196222
| `identity.sourceTitle` | `ZCODE_SOURCE_TITLE` | `cli` | `X-Title: Z Code@{title}` |
197223
| `identity.refererOrigin` | `ZCODE_REFERER_ORIGIN` | `https://zcode.z.ai` | `HTTP-Referer` URL |
198224
| `endpointRouting.enabled` | `ZCODE_ENDPOINT_ROUTING` | `true` | Server-controlled upstream URL remapping via `zcode.z.ai/api/v1/agent/configs` (mirrors ZCode's `ProviderEndpointRoutingService`; fail-open) |
199225
| `clientSigning.enabled` | `ZCODE_CLIENT_SIGNING` | `true` | Client request signing V4 (Ed25519 + proof-of-work, gate-driven; only activates when the server sets `codingPlanSignature.enable=true`; fail-open) |
226+
| `claim.enabled` | `ZCODE_CLAIM_ENABLED` | `false` | Weekend-plan auto-claim: poll `zcode.z.ai/api/v1/zcode-plan/billing/preview` and claim trial packages (oauth-only; see below) |
200227
| config file path | `ZCODE_PROXY_CONFIG` | `config.yaml` | Config file to load on `serve` |
201228

202229
Start-plan captcha tunables (env only): `ZCODE_CAPTCHA_RETRIES` (per-token solve retries), `CAPTCHA_POOL_MIN` / `CAPTCHA_POOL_MAX` (pre-solved token pool sizing).

‎config.example.yaml‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ models:
5858
identity:
5959
# Mirrors process.env.ZCODE_APP_VERSION in the ZCode bundle.
6060
# Must be printable ASCII; non-conforming values fall back to the default.
61-
# Default: "3.9.1" (current ZCode release). Override to match your real client.
62-
appVersion: "3.9.1"
61+
# Default: "3.10.0" (current ZCode release). Override to match your real client.
62+
appVersion: "3.10.0"
6363
# X-Title suffix → "Z Code@{sourceTitle}". Default "cli".
6464
sourceTitle: "cli"
6565
# HTTP-Referer URL. Default "https://zcode.z.ai".
@@ -128,6 +128,34 @@ async:
128128
# Optional model override; empty uses the request's `model`.
129129
defaultModel: ""
130130

131+
# Manual claim ("weekend plan") — mirrors the ZCode 3.10 desktop client's
132+
# manualClaimPlan feature. When enabled, the proxy periodically lists claimable
133+
# trial plans ({origin}/api/v1/zcode-plan/billing/preview) and auto-claims the
134+
# highest-priority one ({origin}/api/v1/zcode-plan/billing/claim) using the
135+
# OAuth JWT + an Aliyun captcha token (same solver as start-plan). Weekend
136+
# campaigns are quota-limited first-come-first-served; claimed plans activate
137+
# at the campaign's `starts_at` and land as Start-Plan quota.
138+
#
139+
# IMPORTANT: requires `auth.mode: oauth` (claim uses the JWT from login), and
140+
# identity.appVersion must be >= the campaign's minimum client version
141+
# (default 3.10.0) or the server rejects with `ineligible`.
142+
#
143+
# Env overrides: ZCODE_CLAIM_ENABLED, ZCODE_CLAIM_AUTO, ZCODE_CLAIM_ORIGIN,
144+
# ZCODE_CLAIM_POLL_INTERVAL_MS.
145+
claim:
146+
enabled: false
147+
# Auto-claim in the background while serving. `false` = CLI-only
148+
# (`zcode-proxy claim` still works when `enabled: true`).
149+
auto: true
150+
origin: "https://zcode.z.ai"
151+
# Preview poll cadence (5 min default).
152+
pollIntervalMs: 300000
153+
# Backoff after failed attempts (10 min default); quota_exhausted /
154+
# already_claimed back off to the server-provided next window instead.
155+
cooldownMs: 600000
156+
# Optional: claim a specific plan_id. Empty = highest-priority preview.
157+
planId: ""
158+
131159
# Server-controlled upstream URL remapping (mirrors the ZCode client's
132160
# ProviderEndpointRoutingService). The proxy periodically fetches
133161
# {origin}/api/v1/agent/configs and rewrites matching upstream URLs per the

‎src/claim/client.test.ts‎

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
/**
2+
* Tests for `src/claim/client.ts` — mock fetch asserts request shape (URL,
3+
* query params, headers incl. captcha/version/platform) and canned responses
4+
* verify preview parsing and the claim biz-code failure mapping.
5+
*/
6+
import { describe, it, expect, mock } from "bun:test";
7+
import { createClaimClient } from "./client.js";
8+
import type { ClaimFailureKind } from "./types.js";
9+
10+
function makeMockFetch(impl: (req: Request, init?: RequestInit) => Promise<Response>): typeof fetch {
11+
return mock((url: string | URL | Request, init?: RequestInit) => {
12+
const req = new Request(typeof url === "string" ? url : url.toString(), init);
13+
return impl(req, init);
14+
}) as unknown as typeof fetch;
15+
}
16+
17+
function jsonResp(body: unknown, status = 200): Response {
18+
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
19+
}
20+
21+
const PREVIEW_BODY = {
22+
code: 0,
23+
data: {
24+
plans: [
25+
{
26+
plan_id: "weekend-free-1024",
27+
name: "Weekend Free",
28+
description: "weekend trial",
29+
priority: 5,
30+
starts_at: 1783000000,
31+
ends_at: 1783200000,
32+
entitlements: [
33+
{
34+
entitlement_id: "ent-1",
35+
show_name: "GLM-5.2",
36+
meter: "token",
37+
unit_type: "tokens",
38+
capabilities: ["chat"],
39+
grant_units: 100000,
40+
period: "daily",
41+
priority: 1,
42+
effective_at: 1783000000,
43+
},
44+
{ no_id: "dropped" },
45+
],
46+
},
47+
{ name: "no plan_id — dropped" },
48+
],
49+
},
50+
};
51+
52+
describe("createClaimClient — getPreviews", () => {
53+
it("fetches preview with app_version + platform query and parses plans/entitlements", async () => {
54+
let capturedUrl = "";
55+
const fetchImpl = makeMockFetch((req) => {
56+
capturedUrl = req.url;
57+
return Promise.resolve(jsonResp(PREVIEW_BODY));
58+
});
59+
const client = createClaimClient({ origin: "https://zcode.z.ai/", jwt: "jwt-1", appVersion: "3.10.0", platform: "win32-x64", fetchImpl });
60+
61+
const plans = await client.getPreviews();
62+
63+
expect(capturedUrl).toBe("https://zcode.z.ai/api/v1/zcode-plan/billing/preview?app_version=3.10.0&platform=win32-x64");
64+
expect(plans).toHaveLength(1);
65+
const p = plans[0];
66+
expect(p.planId).toBe("weekend-free-1024");
67+
expect(p.name).toBe("Weekend Free");
68+
expect(p.priority).toBe(5);
69+
expect(p.startsAt).toBe(1783000000);
70+
expect(p.endsAt).toBe(1783200000);
71+
expect(p.entitlements).toHaveLength(1);
72+
expect(p.entitlements[0]).toEqual({
73+
entitlementId: "ent-1",
74+
showName: "GLM-5.2",
75+
meter: "token",
76+
unitType: "tokens",
77+
capabilities: ["chat"],
78+
grantUnits: 100000,
79+
period: "daily",
80+
priority: 1,
81+
effectiveAt: 1783000000,
82+
});
83+
});
84+
85+
it("sends Authorization only when jwt provided", async () => {
86+
const auths: (string | null)[] = [];
87+
const fetchImpl = makeMockFetch((req) => {
88+
auths.push(req.headers.get("authorization"));
89+
return Promise.resolve(jsonResp(PREVIEW_BODY));
90+
});
91+
const withJwt = createClaimClient({ origin: "https://zcode.z.ai", jwt: "jwt-1", appVersion: "3.10.0", platform: "win32-x64", fetchImpl });
92+
await withJwt.getPreviews();
93+
const anon = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.10.0", platform: "win32-x64", fetchImpl });
94+
await anon.getPreviews();
95+
expect(auths[0]).toBe("Bearer jwt-1");
96+
expect(auths[1]).toBeNull();
97+
});
98+
99+
it("throws on non-zero biz code and missing data", async () => {
100+
const fetchImpl = makeMockFetch(() => Promise.resolve(jsonResp({ code: 1002, msg: "campaign ended" })));
101+
const client = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.10.0", platform: "win32-x64", fetchImpl });
102+
await expect(client.getPreviews()).rejects.toThrow("1002");
103+
const fetchNoData = makeMockFetch(() => Promise.resolve(jsonResp({ code: 0 })));
104+
const client2 = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.10.0", platform: "win32-x64", fetchImpl: fetchNoData });
105+
await expect(client2.getPreviews()).rejects.toThrow("preview failed");
106+
});
107+
});
108+
109+
describe("createClaimClient — claim", () => {
110+
function capture(req: Request) {
111+
return {
112+
url: req.url,
113+
auth: req.headers.get("authorization"),
114+
captchaParam: req.headers.get("x-aliyun-captcha-verify-param"),
115+
captchaRegion: req.headers.get("x-aliyun-captcha-verify-region"),
116+
appVersion: req.headers.get("x-zcode-app-version"),
117+
platform: req.headers.get("x-platform"),
118+
contentType: req.headers.get("content-type"),
119+
};
120+
}
121+
122+
it("POSTs plan_id with jwt + captcha + version + platform headers", async () => {
123+
let cap: ReturnType<typeof capture> | undefined;
124+
let body = "";
125+
const fetchImpl = makeMockFetch(async (req) => {
126+
cap = capture(req);
127+
body = await req.text();
128+
return jsonResp({ code: 0, data: { plan: { starts_at: 1783000000, ends_at: 1783200000 } } });
129+
});
130+
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "jwt-1", appVersion: "3.10.0", platform: "linux-x64", fetchImpl });
131+
132+
const out = await client.claim("weekend-free-1024", { verifyParam: "cap-token", region: "cn-hangzhou" });
133+
134+
expect(cap!.url).toBe("https://zcode.z.ai/api/v1/zcode-plan/billing/claim");
135+
expect(cap!.auth).toBe("Bearer jwt-1");
136+
expect(cap!.captchaParam).toBe("cap-token");
137+
expect(cap!.captchaRegion).toBe("cn-hangzhou");
138+
expect(cap!.appVersion).toBe("3.10.0");
139+
expect(cap!.platform).toBe("linux-x64");
140+
expect(cap!.contentType).toBe("application/json");
141+
expect(JSON.parse(body)).toEqual({ plan_id: "weekend-free-1024" });
142+
expect(out).toEqual({ ok: true, planId: "weekend-free-1024", startsAt: 1783000000, endsAt: 1783200000 });
143+
});
144+
145+
it("omits region header when region missing/empty", async () => {
146+
let region: string | null = "sentinel";
147+
const fetchImpl = makeMockFetch((req) => {
148+
region = req.headers.get("x-aliyun-captcha-verify-region");
149+
return Promise.resolve(jsonResp({ code: 0, data: { plan: {} } }));
150+
});
151+
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "jwt-1", appVersion: "3.10.0", platform: "win32-x64", fetchImpl });
152+
await client.claim("p1", { verifyParam: "t" });
153+
expect(region).toBeNull();
154+
});
155+
156+
it("maps biz codes to failure kinds and surfaces failureEndsAt", async () => {
157+
const cases: Array<[number, ClaimFailureKind]> = [
158+
[1001, "not_found"],
159+
[1002, "unavailable"],
160+
[1003, "already_claimed"],
161+
[1004, "ineligible"],
162+
[1005, "quota_exhausted"],
163+
[3001, "invalid_request"],
164+
[3007, "captcha"],
165+
[9999, "unknown"],
166+
];
167+
for (const [code, kind] of cases) {
168+
const fetchImpl = makeMockFetch(() =>
169+
Promise.resolve(jsonResp({ code, msg: `biz ${code}`, data: { plan: { ends_at: 1783100000 } } })),
170+
);
171+
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "jwt-1", appVersion: "3.10.0", platform: "win32-x64", fetchImpl });
172+
const out = await client.claim("p1", { verifyParam: "t" });
173+
expect(out.ok).toBe(false);
174+
if (!out.ok) {
175+
expect(out.failureKind).toBe(kind);
176+
expect(out.code).toBe(code);
177+
expect(out.failureEndsAt).toBe(1783100000);
178+
}
179+
}
180+
});
181+
182+
it("derives http_error / login_required from HTTP status without biz code", async () => {
183+
const fetch500 = makeMockFetch(() => Promise.resolve(jsonResp({ msg: "boom" }, 500)));
184+
const c1 = createClaimClient({ origin: "https://zcode.z.ai", jwt: "j", appVersion: "3.10.0", platform: "p", fetchImpl: fetch500 });
185+
const out1 = await c1.claim("p1", { verifyParam: "t" });
186+
expect(out1.ok).toBe(false);
187+
if (!out1.ok) expect(out1.failureKind).toBe("http_error");
188+
189+
const fetch401 = makeMockFetch(() => Promise.resolve(new Response("", { status: 401 })));
190+
const c2 = createClaimClient({ origin: "https://zcode.z.ai", jwt: "j", appVersion: "3.10.0", platform: "p", fetchImpl: fetch401 });
191+
const out2 = await c2.claim("p1", { verifyParam: "t" });
192+
expect(out2.ok).toBe(false);
193+
if (!out2.ok) expect(out2.failureKind).toBe("login_required");
194+
});
195+
196+
it("returns login_required without HTTP call when jwt missing", async () => {
197+
const fetchImpl = makeMockFetch(() => {
198+
throw new Error("should not be called");
199+
});
200+
const client = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.10.0", platform: "p", fetchImpl });
201+
const out = await client.claim("p1", { verifyParam: "t" });
202+
expect(out.ok).toBe(false);
203+
if (!out.ok) expect(out.failureKind).toBe("login_required");
204+
});
205+
});

0 commit comments

Comments
 (0)