@magpie-community/opencode-zcode-auth 0.1.34 → 0.1.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +28 -4
  2. package/index.mjs +103 -5
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -197,12 +197,36 @@ the card and names them there — the window is named "Gift plans to
197
197
  claim in the ZCode app" and the display shows "1 · ZCode Trust Build"
198
198
  — set aside, so the line stops nothing and routing, usage caps and the
199
199
  menu bar pass it over. The name is a fixed sentence magpie can
200
- translate; the count and the plan's own name are the display. The plugin never claims one: the claim needs the
201
- Aliyun captcha attestation only the app's renderer can make. A preview
202
- that fails, or lists nothing, adds no line at all, and a card that is an
203
- error keeps its error. Claim the plan in the ZCode app (open it once);
200
+ translate; the count and the plan's own name are the display. Reading
201
+ the card never claims one. A preview that fails, or lists nothing, adds
202
+ no line at all, and a card that is an error keeps its error. Claim the
203
+ plan in the ZCode app (open it once), or let the daily claim below do it;
204
204
  the next read shows it as an ordinary gift bucket.
205
205
 
206
+ ## The daily claim
207
+
208
+ With ZCode turned on in magpie's Settings → Daily check-in (it is off
209
+ until you turn it on), magpie has the plugin claim each account's gift
210
+ plans once a day (`auth.checkin`; `magpie accounts checkin` asks now). It
211
+ reads the app's preview list and posts each plan it lists to
212
+ `POST /api/v1/zcode-plan/billing/claim` (`{"plan_id": …}`) with the
213
+ account's ZCode session, as the app does. The answer is judged by the
214
+ body's code, not the HTTP status:
215
+
216
+ - nothing listed: *inactive*;
217
+ - code 0: *claimed* (the next request uses the plan);
218
+ - code 1003 "target already exists" (HTTP 200): *done*, claimed before;
219
+ - code 3007 "captcha verify failed": *captcha*, the plan is claimed in
220
+ the ZCode app (on 10-06 ZCode wanted the app's Aliyun captcha for a
221
+ claim; whether it still does for a fresh plan is not known yet);
222
+ - anything else, an HTTP error without a code, or a reply that isn't
223
+ JSON: *failed*, which magpie asks again later that day. It is never
224
+ taken as claimed, and a failed claim leaves the account's sign-in
225
+ alone.
226
+
227
+ An account added with a GLM Coding Plan key has no ZCode session to claim
228
+ with (*ineligible*).
229
+
206
230
  **No ZCode session.** A card read with a key, or with a sign-in whose
207
231
  ZCode session has run out (it can't be renewed), sets aside a line named
208
232
  "ZCode gift plans (-Trial models) need ZCode's sign-in", with why in its
package/index.mjs CHANGED
@@ -644,10 +644,10 @@ async function giftOf(s) {
644
644
  const CLAIM_HINT = "Gift plans to claim in the ZCode app"
645
645
 
646
646
  // claimHint is the card's line for gift plans ZCode is holding for the
647
- // account but has not put on it: GET /billing/preview lists them, and
648
- // only the ZCode app claims one — its claim takes the Aliyun captcha
649
- // attestation the app's own renderer makes, so the plugin reads the list
650
- // and asks the user to claim it there. A window, set aside (it is no
647
+ // account but has not put on it: GET /billing/preview lists them. The
648
+ // card only names them: they are claimed in the ZCode app, or by the
649
+ // daily claim (claimDaily) when the user turned it on; on 10-06 a claim
650
+ // without the app's Aliyun captcha attestation was refused (3007). A window, set aside (it is no
651
651
  // allowance: using it up stops nothing), so the card shows it and
652
652
  // routing, caps and the menu bar pass it over. The window's name is a
653
653
  // fixed sentence, so magpie can translate it (a display is shown as it
@@ -670,6 +670,93 @@ async function claimHint(s) {
670
670
  return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
671
671
  }
672
672
 
673
+ // ---- the daily claim ---------------------------------------------------------------
674
+
675
+ // CLAIMED_ALREADY is /billing/claim's body code for a plan the account
676
+ // has claimed before: HTTP 200 {"code":1003,"msg":"target already
677
+ // exists"} (magpie-community/plugins#503, a real reply), the desktop
678
+ // app's manualClaimPlan.claim.failure.alreadyClaimed. CAPTCHA is its
679
+ // answer to a claim without the Aliyun captcha attestation the ZCode app's
680
+ // renderer makes: HTTP 400 {"code":3007,"msg":"captcha verify failed"}
681
+ // (seen 10-06, #30).
682
+ const CLAIMED_ALREADY = 1003
683
+ const CAPTCHA = 3007
684
+ const CAPTCHA_WORDS = /captcha/i
685
+
686
+ // zcodeHeaders are what the ZCode app sends on its billing calls beside
687
+ // the session (#503's capture): its version and platform.
688
+ const zcodeHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform": platform() })
689
+
690
+ // claimOne asks /billing/claim for one plan and says what its body says:
691
+ // "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the
692
+ // claim wants the app's captcha), else "failed" with why. Only a body
693
+ // that reads decides: an HTTP error without one, or text that isn't
694
+ // JSON, is failed (unknown), never claimed. The code 0 body hasn't been
695
+ // seen yet, so nothing but its code is read.
696
+ async function claimOne(s, planID) {
697
+ let res, text
698
+ try {
699
+ res = await fetch(`${ZCODE}/api/v1/zcode-plan/billing/claim`, {
700
+ method: "POST",
701
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA, Authorization: "Bearer " + s.jwt, "X-Device-Mid": s.device || anyDevice, ...zcodeHeaders() },
702
+ body: JSON.stringify({ plan_id: planID }),
703
+ })
704
+ text = await res.text()
705
+ } catch (e) {
706
+ return { outcome: "failed", why: e?.message ?? String(e) }
707
+ }
708
+ let env
709
+ try {
710
+ env = JSON.parse(text)
711
+ } catch {}
712
+ const code = env && typeof env === "object" && env.code != null && String(env.code).trim() !== "" ? Number(env.code) : NaN
713
+ const msg = typeof env?.msg === "string" ? env.msg : ""
714
+ if (code === CAPTCHA || CAPTCHA_WORDS.test(msg)) return { outcome: "captcha", why: msg || `code ${code}` }
715
+ if (code === CLAIMED_ALREADY) return { outcome: "done" }
716
+ if (code === 0 && res.ok) return { outcome: "claimed" }
717
+ if (!Number.isFinite(code)) return { outcome: "failed", why: `HTTP ${res.status}, unreadable reply ${String(text ?? "").trim().slice(0, 120) || "(empty)"}` }
718
+ return { outcome: "failed", why: `${msg || "error"} (HTTP ${res.status}, code ${code})` }
719
+ }
720
+
721
+ // claimDaily claims every gift plan ZCode's preview lists for the account
722
+ // (#503), as auth.checkin's answer: inactive when it lists none, claimed
723
+ // when one was claimed now, done when each was claimed before, captcha
724
+ // when ZCode wants the app's captcha for one (it is claimed in the ZCode
725
+ // app), failed when the list or a claim can't be read. A failed one is
726
+ // asked again later in the day, when a plan claimed now answers 1003.
727
+ // Nothing here marks the account: a failed claim keeps its sign-in.
728
+ async function claimDaily(s) {
729
+ if (!s?.jwt) return { outcome: "ineligible", message: "ZCode's gift plans are claimed with a ZCode sign-in; this account has none" }
730
+ if (jwtExpired(s.jwt)) return { outcome: "failed", message: EXPIRED }
731
+ let d
732
+ try {
733
+ d = await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/preview?app_version=${APP_VERSION}&platform=${platform()}`, { auth: "Bearer " + s.jwt, device: s.device, headers: zcodeHeaders() })
734
+ } catch (e) {
735
+ return { outcome: "failed", message: `gift plans to claim: ${e?.message ?? String(e)}` }
736
+ }
737
+ if (!Array.isArray(d?.plans)) return { outcome: "failed", message: "gift plans to claim: no plan list in the reply" }
738
+ const plans = d.plans.filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim())
739
+ if (!plans.length) return { outcome: "inactive", message: "no ZCode gift plan to claim" }
740
+ const got = []
741
+ for (const p of plans) {
742
+ const name = first(typeof p.name === "string" ? p.name : "", p.plan_id)
743
+ got.push({ name, ...(await claimOne(s, p.plan_id.trim())) })
744
+ }
745
+ const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name)
746
+ const claimed = named("claimed")
747
+ const said = [
748
+ claimed.length ? `claimed ${claimed.join(", ")}` : "",
749
+ ...got.filter((g) => g.outcome === "captcha").map((g) => `${g.name}: claim it in the ZCode app (${g.why})`),
750
+ ...got.filter((g) => g.outcome === "failed").map((g) => `${g.name}: ${g.why}`),
751
+ ].filter(Boolean).join("; ")
752
+ // a plan claimed now is used by the next request, not ten minutes on
753
+ if (claimed.length) routes.delete(s.key + "\0" + s.jwt)
754
+ if (got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said }
755
+ if (got.some((g) => g.outcome === "captcha")) return { outcome: "captcha", message: said }
756
+ if (claimed.length) return { outcome: "claimed", message: said }
757
+ return { outcome: "done", message: `already claimed: ${named("done").join(", ")}` }
758
+ }
759
+
673
760
  // GIFT_SIGN_IN is the card's line for an account whose gift plans can't
674
761
  // be read: ZCode's gift plans (the Start Plan, ZCode 1024 Dev Day, ZCode
675
762
  // Trust Build) are served by zcode.z.ai to ZCode's own session alone, so
@@ -2321,6 +2408,17 @@ export async function ZCodeAuthPlugin({ client }) {
2321
2408
  return saved({ error: e?.message ?? String(e) })
2322
2409
  }
2323
2410
  },
2411
+ // the daily claim of ZCode's gift plans (#503): magpie runs it once a
2412
+ // day per account while Settings' Daily check-in has ZCode on (off
2413
+ // until the user turns it on), and its Check in now button asks
2414
+ // right away. See claimDaily.
2415
+ async checkin(getAuth) {
2416
+ try {
2417
+ return await claimDaily(stateOf(await getAuth()))
2418
+ } catch (e) {
2419
+ return { outcome: "failed", message: e?.message ?? String(e) }
2420
+ }
2421
+ },
2324
2422
  methods: [
2325
2423
  oauth("zai"),
2326
2424
  oauth("bigmodel"),
@@ -2367,4 +2465,4 @@ export async function ZCodeAuthPlugin({ client }) {
2367
2465
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2368
2466
  // out of reach, undefined forgets it
2369
2467
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
2370
- export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY }
2468
+ export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.34",
4
- "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan",
3
+ "version": "0.1.35",
4
+ "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan, and claims its gift plans daily",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": "./index.mjs",