@magpie-community/opencode-zcode-auth 0.1.33 → 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 +41 -5
  2. package/index.mjs +160 -20
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -166,7 +166,19 @@ 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.
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.
172
+
173
+ **Gift plans that start later.** A plan on the balance whose `starts_at`
174
+ is still to come (a Start Plan taking effect at 23:00 today) serves
175
+ nothing yet: no request goes to it and its buckets don't count. The card
176
+ names it in a line set aside, "ZCode gift plan not started yet", with
177
+ the plan's name and its start in this computer's time as the display
178
+ ("Start Plan · 2026-10-29 23:00"), soonest first. An account whose only
179
+ gift plan starts later gets a card with that line, not "ended or never
180
+ started". The status ZCode gives such a plan has not been seen, so any
181
+ status but `expired` is taken; `starts_at` decides it.
170
182
 
171
183
  **Resets.** A GLM Coding Plan of the account's own, and a team seat,
172
184
  show the resets the vendor's usage page lists
@@ -185,12 +197,36 @@ the card and names them there — the window is named "Gift plans to
185
197
  claim in the ZCode app" and the display shows "1 · ZCode Trust Build"
186
198
  — set aside, so the line stops nothing and routing, usage caps and the
187
199
  menu bar pass it over. The name is a fixed sentence magpie can
188
- translate; the count and the plan's own name are the display. The plugin never claims one: the claim needs the
189
- Aliyun captcha attestation only the app's renderer can make. A preview
190
- that fails, or lists nothing, adds no line at all, and a card that is an
191
- 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;
192
204
  the next read shows it as an ordinary gift bucket.
193
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
+
194
230
  **No ZCode session.** A card read with a key, or with a sign-in whose
195
231
  ZCode session has run out (it can't be renewed), sets aside a line named
196
232
  "ZCode gift plans (-Trial models) need ZCode's sign-in", with why in its
package/index.mjs CHANGED
@@ -182,7 +182,7 @@ async function startPlan(jwt, device) {
182
182
  for (const p of plans) {
183
183
  const st = String(p?.status ?? "").trim().toLowerCase()
184
184
  const end = num(p?.ends_at)
185
- if (st !== "active" || (end > 0 && end <= now)) continue
185
+ if (st !== "active" || (end > 0 && end <= now) || notStarted(p, now)) continue
186
186
  any = true
187
187
  if (end > 0) ttl = Math.min(ttl, (end - now) * 1000)
188
188
  if (!name) name = String(p?.name ?? "").trim()
@@ -520,6 +520,28 @@ function startNum(v) {
520
520
  return undefined
521
521
  }
522
522
 
523
+ // notStarted is a plan whose starts_at is still to come (a Start Plan
524
+ // that takes effect at 23:00 today, windy on Discord): it serves nothing
525
+ // yet, so no request is routed to it and its buckets don't count, but the
526
+ // card names it with its start. ZCode's balance gives every plan a
527
+ // starts_at in Unix seconds; which status a plan not started yet carries
528
+ // is not known, so any but "expired" is taken.
529
+ function notStarted(p, now) {
530
+ const at = startNum(p?.starts_at)
531
+ return at > now && String(p?.status ?? "").trim().toLowerCase() !== "expired"
532
+ }
533
+
534
+ // PENDING is the card's line for a gift plan that has not started yet: a
535
+ // fixed sentence, so magpie translates it; the plan's name and its start,
536
+ // in this computer's time, are the display. Set aside: it stops nothing.
537
+ const PENDING = "ZCode gift plan not started yet"
538
+ const two = (n) => String(n).padStart(2, "0")
539
+ const localTime = (sec) => {
540
+ const d = new Date(Math.trunc(sec) * 1000)
541
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`
542
+ }
543
+ const pendingLines = (g) => (g?.pending ?? []).map((p) => ({ name: PENDING, used: 0, aside: true, display: `${p.name} · ${localTime(p.start)}` }))
544
+
523
545
  // giftOf reads the balance and returns the gift's card fields: its plans and
524
546
  // windows. Several plans can be active at once, so every live plan's buckets
525
547
  // show, each keeping its own models and end; the plan and end put on the
@@ -551,21 +573,28 @@ async function giftOf(s) {
551
573
  return keep
552
574
  })
553
575
 
576
+ // a plan not started yet is named with its start, soonest first; its
577
+ // buckets, if the balance lists any, wait for it
578
+ const pending = plans.filter((p) => notStarted(p, now))
579
+ .map((p) => ({ name: first(str(p.name), "Start Plan"), start: startNum(p.starts_at) }))
580
+ .sort((a, b) => a.start - b.start)
581
+
554
582
  // every live plan counts as the gift: no plan-name filter decides it,
555
583
  // the balance says what the session can spend
556
584
  let active = null
557
585
  for (const p of plans) {
558
- if (p.status.trim().toLowerCase() !== "active") continue
586
+ if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) continue
559
587
  const end = startNum(p.ends_at)
560
588
  if (end > 0 && end <= now) continue
561
589
  if (active && !(end > 0 && (!startNum(active.end) || end < startNum(active.end)))) continue
562
590
  active = { name: first(str(p.name), "Start Plan"), end, until: end > 0 ? new Date(Math.trunc(end) * 1000).toISOString() : "" }
563
591
  }
564
- if (!active) return null
565
- const out = { plan: active.name, windows: [] }
566
- if (active.until) Object.assign(out, { until: active.until, renew: "off" })
592
+ if (!active && !pending.length) return null
593
+ // with no live plan, the one starting soonest names the card
594
+ const out = { plan: active?.name ?? pending[0].name, windows: [], live: !!active, pending }
595
+ if (active?.until) Object.assign(out, { until: active.until, renew: "off" })
567
596
  const live = plans.filter((p) => {
568
- if (p.status.trim().toLowerCase() !== "active") return false
597
+ if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) return false
569
598
  const end = startNum(p.ends_at)
570
599
  return !(end > 0 && end <= now)
571
600
  })
@@ -615,10 +644,10 @@ async function giftOf(s) {
615
644
  const CLAIM_HINT = "Gift plans to claim in the ZCode app"
616
645
 
617
646
  // claimHint is the card's line for gift plans ZCode is holding for the
618
- // account but has not put on it: GET /billing/preview lists them, and
619
- // only the ZCode app claims one — its claim takes the Aliyun captcha
620
- // attestation the app's own renderer makes, so the plugin reads the list
621
- // 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
622
651
  // allowance: using it up stops nothing), so the card shows it and
623
652
  // routing, caps and the menu bar pass it over. The window's name is a
624
653
  // fixed sentence, so magpie can translate it (a display is shown as it
@@ -641,6 +670,93 @@ async function claimHint(s) {
641
670
  return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
642
671
  }
643
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
+
644
760
  // GIFT_SIGN_IN is the card's line for an account whose gift plans can't
645
761
  // be read: ZCode's gift plans (the Start Plan, ZCode 1024 Dev Day, ZCode
646
762
  // Trust Build) are served by zcode.z.ai to ZCode's own session alone, so
@@ -678,6 +794,9 @@ async function startUsage(s) {
678
794
  }
679
795
  return { ...w, models: [...models, ...models.map(giftID)] }
680
796
  }))
797
+ g.windows.push(...pendingLines(g))
798
+ delete g.live
799
+ delete g.pending
681
800
  return g
682
801
  }
683
802
 
@@ -715,6 +834,12 @@ function bestBuckets(windows) {
715
834
  return best
716
835
  }
717
836
 
837
+ // giftReadable: ZCode's session can read the gift beside a coding plan,
838
+ // so the card asks for it even when no gift is live for requests: a plan
839
+ // that starts later is named on the card (windy, Discord), not left out
840
+ // because nothing could be spent yet.
841
+ const giftReadable = (s) => !!s.jwt && !jwtExpired(s.jwt)
842
+
718
843
  // dualUsage shows both pools but only the pool a request can use counts
719
844
  // for its model. Live gift models don't spend the Coding windows; spent
720
845
  // or blocked gift buckets stay visible without holding up the Coding Plan.
@@ -726,29 +851,32 @@ async function dualUsage(s, out) {
726
851
  const cached = routes.get(s.key + "\0" + s.jwt)
727
852
  try {
728
853
  const g = await giftOf(s)
729
- const gift = g ? { name: g.plan, models: [...new Set(g.windows.filter((w) => !w._spent)
854
+ const gift = g?.live ? { name: g.plan, models: [...new Set(g.windows.filter((w) => !w._spent)
730
855
  .flatMap((w) => w.models ?? []).map((m) => m.toLowerCase()))],
731
856
  allModels: uniqueModels(g.windows.flatMap((w) => w.models ?? [])) } : null
732
857
  if (cached) {
733
858
  cached.gift = gift
734
- const ends = g ? [g.until, ...g.windows.map((w) => w.resetsAt)].map((t) => Date.parse(t)).filter(Number.isFinite) : []
859
+ // a plan that starts later is read again when it starts
860
+ const ends = g ? [g.until, ...g.windows.map((w) => w.resetsAt)].map((t) => Date.parse(t))
861
+ .concat(g.pending.map((p) => p.start * 1000)).filter(Number.isFinite) : []
735
862
  if (ends.length) cached.ttl = Math.min(cached.ttl, Math.max(0, Math.min(...ends) - cached.at))
736
863
  }
737
- if (g) {
864
+ if (g?.live) {
738
865
  // the gift's models are its trial entries alone: a plain model stays
739
866
  // on the coding plan, and the user picks the gift by its entry
740
867
  const notModels = gift.allModels.map((m) => giftID(m).toLowerCase())
741
868
  if (notModels.length) out.windows = out.windows.map((w) => w.aside ? w : { ...w, notModels })
742
869
  // Several buckets may serve one model: one spent sibling cannot block it.
743
870
  const best = bestBuckets(g.windows)
744
- const label = byPlan(g.windows)
871
+ // beside the Coding Plan's windows every gift bucket is named after
872
+ // its plan, one plan or several: "Start Plan · GLM-5.1-Trial" can't
873
+ // be read as the Coding Plan's own (windy, Discord)
874
+ const label = (name, plan) => first(plan, "Start Plan") + " · " + name
745
875
  out.windows.push(...countedFirst(g.windows.map(({ _plan: p, _spent, ...w }, i) => {
746
876
  const selected = gift.allModels.filter((m) => best.get(m.toLowerCase()) === i)
747
877
  const models = selected.map(giftID)
748
878
  const scoped = models.length ? { ...w, models } : { ...w, aside: true }
749
- // the card names a bucket's model as the picker does (GLM-5.3-Flash-Trial);
750
- // no plan prefix while one plan gives them all — the card's section
751
- // header already says the account; with several, byPlan names each
879
+ // the card names a bucket's model as the picker does (GLM-5.3-Flash-Trial)
752
880
  let name = w.name
753
881
  for (const m of selected) {
754
882
  const at = name.toLowerCase().indexOf(m.toLowerCase())
@@ -757,6 +885,7 @@ async function dualUsage(s, out) {
757
885
  return { ...scoped, name: label(name, p) }
758
886
  })))
759
887
  }
888
+ if (g) out.windows.push(...pendingLines(g))
760
889
  } catch {
761
890
  if (cached) {
762
891
  cached.gift = null
@@ -2260,8 +2389,8 @@ export async function ZCodeAuthPlugin({ client }) {
2260
2389
  }
2261
2390
  }
2262
2391
  const team = await teamUsage(s, key)
2263
- card = saved(gift ? await dualUsage(s, team) : team)
2264
- } else card = saved(start ? await startUsage(s) : gift ? await dualUsage(s) : await codingUsage(s))
2392
+ card = saved(gift || giftReadable(s) ? await dualUsage(s, team) : team)
2393
+ } else card = saved(start ? await startUsage(s) : gift || giftReadable(s) ? await dualUsage(s) : await codingUsage(s))
2265
2394
  // a gift plan ZCode holds for the account but has not put on it:
2266
2395
  // named on the card, claimed in the ZCode app (its claim needs
2267
2396
  // the app's captcha attestation, see claimHint). A card that is
@@ -2279,6 +2408,17 @@ export async function ZCodeAuthPlugin({ client }) {
2279
2408
  return saved({ error: e?.message ?? String(e) })
2280
2409
  }
2281
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
+ },
2282
2422
  methods: [
2283
2423
  oauth("zai"),
2284
2424
  oauth("bigmodel"),
@@ -2325,4 +2465,4 @@ export async function ZCodeAuthPlugin({ client }) {
2325
2465
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2326
2466
  // out of reach, undefined forgets it
2327
2467
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
2328
- 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.33",
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",