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

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 +34 -7
  2. package/index.mjs +112 -10
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -166,9 +166,12 @@ and end. The card's plan and term stay the coding plan's. A gift read
166
166
  that fails leaves just the coding card — magpie hides a card's windows
167
167
  behind an error, so a gift hiccup must not black out a working Coding
168
168
  Plan. A gift that goes out of date while requests use it simply stops
169
- showing. Beside the coding plan's windows each gift bucket is named
170
- after its plan ("Start Plan · GLM-5.1-Trial"), one plan or several, so
171
- the two allowances can't be read as one.
169
+ showing. Beside the coding plan's windows each gift bucket is named by
170
+ its model first, as ZCode's own "Today's balance" lists it, then by its
171
+ plan ("GLM-5.1-Trial · Start Plan"), one plan or several, so the two
172
+ allowances can't be read as one. The model comes first because magpie's
173
+ ring and account row cut a long name short: "ZCODE GLOBAL BUI…" (the
174
+ Start Plan claimed on 10-29) said neither (#504).
172
175
 
173
176
  **Gift plans that start later.** A plan on the balance whose `starts_at`
174
177
  is still to come (a Start Plan taking effect at 23:00 today) serves
@@ -197,12 +200,36 @@ the card and names them there — the window is named "Gift plans to
197
200
  claim in the ZCode app" and the display shows "1 · ZCode Trust Build"
198
201
  — set aside, so the line stops nothing and routing, usage caps and the
199
202
  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);
203
+ translate; the count and the plan's own name are the display. Reading
204
+ the card never claims one. A preview that fails, or lists nothing, adds
205
+ no line at all, and a card that is an error keeps its error. Claim the
206
+ plan in the ZCode app (open it once), or let the daily claim below do it;
204
207
  the next read shows it as an ordinary gift bucket.
205
208
 
209
+ ## The daily claim
210
+
211
+ With ZCode turned on in magpie's Settings → Daily check-in (it is off
212
+ until you turn it on), magpie has the plugin claim each account's gift
213
+ plans once a day (`auth.checkin`; `magpie accounts checkin` asks now). It
214
+ reads the app's preview list and posts each plan it lists to
215
+ `POST /api/v1/zcode-plan/billing/claim` (`{"plan_id": …}`) with the
216
+ account's ZCode session, as the app does. The answer is judged by the
217
+ body's code, not the HTTP status:
218
+
219
+ - nothing listed: *inactive*;
220
+ - code 0: *claimed* (the next request uses the plan);
221
+ - code 1003 "target already exists" (HTTP 200): *done*, claimed before;
222
+ - code 3007 "captcha verify failed": *captcha*, the plan is claimed in
223
+ the ZCode app (on 10-06 ZCode wanted the app's Aliyun captcha for a
224
+ claim; whether it still does for a fresh plan is not known yet);
225
+ - anything else, an HTTP error without a code, or a reply that isn't
226
+ JSON: *failed*, which magpie asks again later that day. It is never
227
+ taken as claimed, and a failed claim leaves the account's sign-in
228
+ alone.
229
+
230
+ An account added with a GLM Coding Plan key has no ZCode session to claim
231
+ with (*ineligible*).
232
+
206
233
  **No ZCode session.** A card read with a key, or with a sign-in whose
207
234
  ZCode session has run out (it can't be renewed), sets aside a line named
208
235
  "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
@@ -713,7 +800,7 @@ async function startUsage(s) {
713
800
  return g
714
801
  }
715
802
 
716
- // byPlan names a bucket after its plan ("ZCode 1024 Dev Day · GLM-5.3")
803
+ // byPlan names a bucket after its plan ("GLM-5.3 · ZCode 1024 Dev Day")
717
804
  // when the gift's buckets come from more than one plan: two plans each
718
805
  // give a GLM-5.3, and named alike a spent one and a live one can't be
719
806
  // told apart (01huadalang, Discord: the new-user plan's spent GLM-5.3
@@ -721,7 +808,7 @@ async function startUsage(s) {
721
808
  // their own names, as the card's header names the plan.
722
809
  function byPlan(windows) {
723
810
  const several = new Set(windows.map((w) => w._plan || "")).size > 1
724
- return (name, plan) => (several && plan ? plan + " · " + name : name)
811
+ return (name, plan) => (several && plan ? name + " · " + plan : name)
725
812
  }
726
813
 
727
814
  // countedFirst puts the buckets a request spends before those set aside
@@ -782,9 +869,13 @@ async function dualUsage(s, out) {
782
869
  // Several buckets may serve one model: one spent sibling cannot block it.
783
870
  const best = bestBuckets(g.windows)
784
871
  // beside the Coding Plan's windows every gift bucket is named after
785
- // its plan, one plan or several: "Start Plan · GLM-5.1-Trial" can't
786
- // be read as the Coding Plan's own (windy, Discord)
787
- const label = (name, plan) => first(plan, "Start Plan") + " · " + name
872
+ // its plan, one plan or several: "GLM-5.1-Trial · Start Plan" can't
873
+ // be read as the Coding Plan's own (windy, Discord). The bucket's
874
+ // own name (ZCode's show_name, as its "Today's balance" lists it)
875
+ // comes first: magpie's ring and account row cut a long name short,
876
+ // and "ZCODE GLOBAL BUI…" said neither the model nor the plan's
877
+ // kind, so the Start Plan read as missing (Danbuth, plugins#504)
878
+ const label = (name, plan) => name + " · " + first(plan, "Start Plan")
788
879
  out.windows.push(...countedFirst(g.windows.map(({ _plan: p, _spent, ...w }, i) => {
789
880
  const selected = gift.allModels.filter((m) => best.get(m.toLowerCase()) === i)
790
881
  const models = selected.map(giftID)
@@ -2321,6 +2412,17 @@ export async function ZCodeAuthPlugin({ client }) {
2321
2412
  return saved({ error: e?.message ?? String(e) })
2322
2413
  }
2323
2414
  },
2415
+ // the daily claim of ZCode's gift plans (#503): magpie runs it once a
2416
+ // day per account while Settings' Daily check-in has ZCode on (off
2417
+ // until the user turns it on), and its Check in now button asks
2418
+ // right away. See claimDaily.
2419
+ async checkin(getAuth) {
2420
+ try {
2421
+ return await claimDaily(stateOf(await getAuth()))
2422
+ } catch (e) {
2423
+ return { outcome: "failed", message: e?.message ?? String(e) }
2424
+ }
2425
+ },
2324
2426
  methods: [
2325
2427
  oauth("zai"),
2326
2428
  oauth("bigmodel"),
@@ -2367,4 +2469,4 @@ export async function ZCodeAuthPlugin({ client }) {
2367
2469
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2368
2470
  // out of reach, undefined forgets it
2369
2471
  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 }
2472
+ 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.36",
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",