@magpie-community/opencode-zcode-auth 0.1.37 → 0.1.39

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 +49 -4
  2. package/index.mjs +214 -48
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -134,6 +134,44 @@ plan's own in-flight cap (3008/3009) does not: such a request is asked
134
134
  again instead (see [A few at once](#a-few-at-once)). A stream's body is
135
135
  never read or buffered on the way.
136
136
 
137
+ **Free first.** Picking `-Trial` by hand keeps the choice the user's,
138
+ but an agent that always asks the plain model never sees the gift.
139
+ `freeFirst` turns the preference around: the plain model spends the
140
+ account's own live gift first, and falls back to the coding plan when
141
+ the gift cannot serve it — a bucket that is spent, a model the gift
142
+ does not serve, no ZCode session, or the minute's rest a refusal just
143
+ earned. Turn it on for the whole plugin in magpie's Plugins › Options
144
+
145
+ ```json
146
+ { "freeFirst": true }
147
+ ```
148
+
149
+ or on the provider alone, under `provider.zcode.options` in the config
150
+ magpie hands its plugins — a key only `plugins.json`'s `config` carries,
151
+ so the plugin's own options are the ones magpie's Plugins › Options
152
+ edits. Where both say something, the provider's word stands. An account
153
+ with a coding plan and a gift spends the gift until it is spent, then
154
+ the plan; a gift-only account already goes to the gift by its plain
155
+ names, so the option changes nothing there. Across the accounts magpie
156
+ rotates, each spends its own gift before its own plan — which is the
157
+ point: free allowance is spent before subscribed quota, on every
158
+ account, with no per-account naming to keep up.
159
+
160
+ Two boundaries worth knowing. The gift is judged before the request is
161
+ sent, from the balance read the plugin keeps for ten minutes: a gift
162
+ that runs out between that read and the send has its refusal answered
163
+ from the plan in the same request — any gift failure is, its own
164
+ waited-out busy cap included, and the replay waits out the plan's busy
165
+ cap as any plan request does — and a spent answer or a block page rests
166
+ the model a minute and drops the route's balance read, so the requests
167
+ behind it go straight to the plan. A gift that cannot be asked at all —
168
+ the network, the host — is answered from the plan the same way, the
169
+ route read dropped for the next request, while a caller's own abort
170
+ stays an abort. The agent sees the plan's answer
171
+ either way. And the `-Trial` entries keep their own strict semantics —
172
+ asking one is still an explicit pick of the gift alone, never the plan;
173
+ a spent one answers 429 with freeFirst on, as it does without it.
174
+
137
175
  ## A few at once
138
176
 
139
177
  A plan serves one account a few requests at a time; past that, ZCode
@@ -195,8 +233,11 @@ left, shows no count.
195
233
  **Gift plans ZCode holds but has not granted.** ZCode hands out one-off
196
234
  trust-build / gift plans (a day's ZCode Trust Build, say) that are not
197
235
  on the account until the ZCode app claims them. The plugin reads the
198
- app's own list of them (`GET /api/v1/zcode-plan/billing/preview`) with
199
- the card and names them there — the window is named "Gift plans to
236
+ app's own lists of them with the card and names them there: its claim
237
+ banners' feed (`GET /api/v1/marketing/touch`, each delivery's
238
+ `claim_zcode_plan` button) and `GET /api/v1/zcode-plan/billing/preview`.
239
+ A banner plan (a weekend's ZCODE WEEKEND BUILD, 10-30) is in the feed
240
+ alone, never in the preview (#503) — the window is named "Gift plans to
200
241
  claim in the ZCode app" and the display shows "1 · ZCode Trust Build"
201
242
  — set aside, so the line stops nothing and routing, usage caps and the
202
243
  menu bar pass it over. The name is a fixed sentence magpie can
@@ -211,13 +252,17 @@ the next read shows it as an ordinary gift bucket.
211
252
  With ZCode turned on in magpie's Settings → Daily check-in (it is off
212
253
  until you turn it on), magpie has the plugin claim each account's gift
213
254
  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
255
+ reads both lists above (the banners' feed and the preview, each plan
256
+ once) and posts each plan to
215
257
  `POST /api/v1/zcode-plan/billing/claim` (`{"plan_id": …}`) with the
216
258
  account's ZCode session, as the app does. The answer is judged by the
217
259
  body's code, not the HTTP status:
218
260
 
219
261
  - nothing listed: *inactive* (ZCode answers an account with nothing to
220
- claim `{"code":0,"msg":""}`, with no list at all);
262
+ claim `{"code":0,"msg":""}`, with no list at all). A list that doesn't
263
+ read is *failed*, never nothing to claim. A plan just claimed may show
264
+ in neither `billing/preview` nor `billing/current` until its
265
+ `effective_at`, so neither list is read as "claimed or not";
221
266
  - code 0: *claimed* (the next request uses the plan);
222
267
  - code 1003 "target already exists" (HTTP 200): *done*, claimed before;
223
268
  - code 3007 "captcha verify failed": *captcha*, the plan is claimed in
package/index.mjs CHANGED
@@ -644,7 +644,8 @@ 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. The
647
+ // account but has not put on it: the app's banners (marketing/touch) and
648
+ // GET /billing/preview list them (toClaim). The
648
649
  // card only names them: they are claimed in the ZCode app, or by the
649
650
  // daily claim (claimDaily) when the user turned it on; on 10-06 a claim
650
651
  // without the app's Aliyun captcha attestation was refused (3007). A window, set aside (it is no
@@ -657,16 +658,10 @@ const CLAIM_HINT = "Gift plans to claim in the ZCode app"
657
658
  // own.
658
659
  async function claimHint(s) {
659
660
  if (!s.jwt || jwtExpired(s.jwt)) return null
660
- let d
661
- try {
662
- d = await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/preview?app_version=${APP_VERSION}&platform=${platform()}`, { auth: "Bearer " + s.jwt, device: s.device })
663
- } catch {
664
- return null
665
- }
666
- const plans = (previewPlans(d) ?? []).filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim())
661
+ const { plans } = await toClaim(s)
667
662
  if (!plans.length) return null
668
663
  const n = plans.length
669
- const plan = first(...plans.map((p) => (typeof p?.name === "string" ? p.name : "")), "ZCode gift plan")
664
+ const plan = first(...plans.map((p) => p.name), "ZCode gift plan")
670
665
  return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
671
666
  }
672
667
 
@@ -691,8 +686,8 @@ const zcodeHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform":
691
686
  // "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the
692
687
  // claim wants the app's captcha), else "failed" with why. Only a body
693
688
  // 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.
689
+ // JSON, is failed (unknown), never claimed. Only the code is read (#503
690
+ // has a real code 0 reply, "Plan claimed successfully.").
696
691
  async function claimOne(s, planID) {
697
692
  let res, text
698
693
  try {
@@ -732,41 +727,109 @@ function previewPlans(d) {
732
727
  return Array.isArray(d.plans) ? d.plans : null
733
728
  }
734
729
 
735
- // claimDaily claims every gift plan ZCode's preview lists for the account
736
- // (#503), as auth.checkin's answer: inactive when it lists none, claimed
737
- // when one was claimed now, done when each was claimed before, captcha
738
- // when ZCode wants the app's captcha for one (it is claimed in the ZCode
739
- // app), failed when the list or a claim can't be read. A failed one is
740
- // asked again later in the day, when a plan claimed now answers 1003.
730
+ // TOUCH is ZCode's marketing feed: the ZCode app's claim banners come
731
+ // from it, not from /billing/preview. A banner plan ("ZCODE WEEKEND
732
+ // BUILD", 10-30) is in neither /billing/preview nor /billing/current
733
+ // while the app shows its banner, and the app claims it through the same
734
+ // /billing/claim (#503's capture of 10-30, kongbai01203: GET
735
+ // /api/v1/marketing/touch?seq=<n, counting up from 0> with the session,
736
+ // X-Device-Mid, X-Client-Language and X-ZCode-App-Version, answered
737
+ // data.deliveries[].banner.buttons[].action = {"type":"claim_zcode_plan",
738
+ // "args":{"plan_id":…}} and the plan's name in
739
+ // banner.background.args.zcode_plan.name).
740
+ const TOUCH = "/api/v1/marketing/touch"
741
+ const CLAIM_ACTION = "claim_zcode_plan"
742
+ let touchSeq = 0
743
+ const clientLanguage = () => {
744
+ try {
745
+ return Intl.DateTimeFormat().resolvedOptions().locale || "en-US"
746
+ } catch {
747
+ return "en-US"
748
+ }
749
+ }
750
+
751
+ // touchPlans is the plans marketing/touch's deliveries offer to claim:
752
+ // [{plan_id, name}], [] for a feed with no deliveries, null for one that
753
+ // doesn't read. Each delivery is searched for its claim_zcode_plan
754
+ // actions and its zcode_plan's name, wherever the banner keeps them, so
755
+ // a button moved inside the banner is still found.
756
+ function touchPlans(d) {
757
+ if (d == null) return []
758
+ if (typeof d !== "object" || Array.isArray(d)) return null
759
+ if (d.deliveries == null) return []
760
+ if (!Array.isArray(d.deliveries)) return null
761
+ const out = []
762
+ for (const dv of d.deliveries) {
763
+ const ids = [], names = []
764
+ const walk = (v, depth) => {
765
+ if (!v || typeof v !== "object" || depth > 12) return
766
+ if (Array.isArray(v)) return v.forEach((x) => walk(x, depth + 1))
767
+ if (v.type === CLAIM_ACTION && typeof v.args?.plan_id === "string" && v.args.plan_id.trim()) ids.push(v.args.plan_id.trim())
768
+ if (v.zcode_plan && typeof v.zcode_plan === "object" && typeof v.zcode_plan.name === "string") names.push(v.zcode_plan.name)
769
+ for (const k of Object.keys(v)) walk(v[k], depth + 1)
770
+ }
771
+ walk(dv, 0)
772
+ for (const id of ids) out.push({ plan_id: id, name: first(names[0] ?? "", id) })
773
+ }
774
+ return out
775
+ }
776
+
777
+ // toClaim is every gift plan the account can claim: what the app's
778
+ // marketing feed offers (its banners) and what /billing/preview lists,
779
+ // once each by plan_id. unread names a list that didn't read: its
780
+ // plans are unknown, never none.
781
+ async function toClaim(s) {
782
+ const plans = [], unread = []
783
+ const add = (p) => {
784
+ if (!plans.some((q) => q.plan_id === p.plan_id)) plans.push(p)
785
+ }
786
+ const ask = async (what, url, headers, read) => {
787
+ let d
788
+ try {
789
+ d = await call("GET", url, { auth: "Bearer " + s.jwt, device: s.device, headers })
790
+ } catch (e) {
791
+ return unread.push(`${what}: ${e?.message ?? String(e)}`)
792
+ }
793
+ const got = read(d)
794
+ if (!got) return unread.push(`${what}: the plan list doesn't read`)
795
+ got.forEach(add)
796
+ }
797
+ await ask("gift plans to claim", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { "X-ZCode-App-Version": APP_VERSION, "X-Client-Language": clientLanguage() }, touchPlans)
798
+ await ask("gift plans to claim", `${ZCODE}/api/v1/zcode-plan/billing/preview?app_version=${APP_VERSION}&platform=${platform()}`, zcodeHeaders(), (d) => {
799
+ const l = previewPlans(d)
800
+ return l && l.filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim()).map((p) => ({ plan_id: p.plan_id.trim(), name: first(typeof p.name === "string" ? p.name : "", p.plan_id.trim()) }))
801
+ })
802
+ return { plans, unread }
803
+ }
804
+
805
+ // claimDaily claims every gift plan ZCode offers the account (#503:
806
+ // toClaim, the app's banners and its preview), as auth.checkin's answer:
807
+ // inactive when neither lists one, claimed when one was claimed now,
808
+ // done when each was claimed before, captcha when ZCode wants the app's
809
+ // captcha for one (it is claimed in the ZCode app), failed when a list
810
+ // or a claim can't be read. A failed one is asked again later in the
811
+ // day, when a plan claimed now answers 1003.
741
812
  // Nothing here marks the account: a failed claim keeps its sign-in.
742
813
  async function claimDaily(s) {
743
814
  if (!s?.jwt) return { outcome: "ineligible", message: "ZCode's gift plans are claimed with a ZCode sign-in; this account has none" }
744
815
  if (jwtExpired(s.jwt)) return { outcome: "failed", message: EXPIRED }
745
- let d
746
- try {
747
- 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() })
748
- } catch (e) {
749
- return { outcome: "failed", message: `gift plans to claim: ${e?.message ?? String(e)}` }
750
- }
751
- const listed = previewPlans(d)
752
- if (!listed) return { outcome: "failed", message: "gift plans to claim: the plan list doesn't read" }
753
- const plans = listed.filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim())
816
+ const { plans, unread } = await toClaim(s)
817
+ if (!plans.length && unread.length) return { outcome: "failed", message: unread.join("; ") }
754
818
  if (!plans.length) return { outcome: "inactive", message: "no ZCode gift plan to claim" }
755
819
  const got = []
756
- for (const p of plans) {
757
- const name = first(typeof p.name === "string" ? p.name : "", p.plan_id)
758
- got.push({ name, ...(await claimOne(s, p.plan_id.trim())) })
759
- }
820
+ for (const p of plans) got.push({ name: p.name, ...(await claimOne(s, p.plan_id)) })
760
821
  const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name)
761
822
  const claimed = named("claimed")
762
823
  const said = [
763
824
  claimed.length ? `claimed ${claimed.join(", ")}` : "",
764
825
  ...got.filter((g) => g.outcome === "captcha").map((g) => `${g.name}: claim it in the ZCode app (${g.why})`),
765
826
  ...got.filter((g) => g.outcome === "failed").map((g) => `${g.name}: ${g.why}`),
827
+ ...unread,
766
828
  ].filter(Boolean).join("; ")
767
829
  // a plan claimed now is used by the next request, not ten minutes on
768
830
  if (claimed.length) routes.delete(s.key + "\0" + s.jwt)
769
- if (got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said }
831
+ // a list that didn't read may hold a plan not claimed: asked again
832
+ if (unread.length || got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said }
770
833
  if (got.some((g) => g.outcome === "captcha")) return { outcome: "captcha", message: said }
771
834
  if (claimed.length) return { outcome: "claimed", message: said }
772
835
  return { outcome: "done", message: `already claimed: ${named("done").join(", ")}` }
@@ -1731,6 +1794,28 @@ function busyAnswer(res, text) {
1731
1794
  })
1732
1795
  }
1733
1796
 
1797
+ // askBusy asks once and, when the answer is the vendor's in-flight cap
1798
+ // (3008/3009, or its own words), asks again through BUSY_WAITS's waits, a
1799
+ // quarter of a second and longer — about ten seconds of them. Past that the
1800
+ // account is saturated rather than busy, and the cap goes back as
1801
+ // busyAnswer's 429. The plan path's patience, shared with free first's
1802
+ // replay, whose plan has a cap of its own.
1803
+ async function askBusy(u, o, hs) {
1804
+ let res = await fetch(u, { ...o, headers: hs })
1805
+ for (let i = 0; res.status === 429; i++) {
1806
+ const text = await res.text()
1807
+ const cap = busy(429, text)
1808
+ if (!cap || i >= BUSY_WAITS.length) {
1809
+ res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
1810
+ break
1811
+ }
1812
+ const w = BUSY_WAITS[i]
1813
+ await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
1814
+ res = await fetch(u, { ...o, headers: hs })
1815
+ }
1816
+ return res
1817
+ }
1818
+
1734
1819
  function model(m, url) {
1735
1820
  const e = entry(m)
1736
1821
  return {
@@ -2119,12 +2204,17 @@ function sessionOf(id, device) {
2119
2204
 
2120
2205
  // ---- the plugin ------------------------------------------------------------------
2121
2206
 
2122
- export async function ZCodeAuthPlugin({ client }) {
2207
+ export async function ZCodeAuthPlugin({ client }, options = {}) {
2123
2208
  const log = (message) => {
2124
2209
  try {
2125
2210
  client?.app?.log?.({ body: { service: "zcode-auth", level: "error", message } })
2126
2211
  } catch {}
2127
2212
  }
2213
+ // freeFirst reads the option from the provider config's options first,
2214
+ // and from the plugin's own (magpie's Plugins › Options) when the
2215
+ // provider carries no freeFirst of its own.
2216
+ const freeFirst = (providerOptions) =>
2217
+ providerOptions?.freeFirst !== undefined ? providerOptions.freeFirst === true : options?.freeFirst === true
2128
2218
  const oauth = (site) => ({
2129
2219
  type: "oauth",
2130
2220
  label: `ZCode: ${SITES[site].name}${site === "bigmodel" ? " (智谱)" : ""} GLM Coding Plan`,
@@ -2230,7 +2320,8 @@ export async function ZCodeAuthPlugin({ client }) {
2230
2320
  // a dual account's body is read ahead of sending, so a gift that
2231
2321
  // says it is spent can spend nothing and replay what was asked for
2232
2322
  let start = alone
2233
- let orig, forcedGift = false
2323
+ let orig, forcedGift = false, freeGift = false
2324
+ let asked = ""
2234
2325
  let renamed = false
2235
2326
  const done = (res) => (renamed ? searchNamed(res) : res)
2236
2327
  if (opts.body != null) {
@@ -2244,6 +2335,7 @@ export async function ZCodeAuthPlugin({ client }) {
2244
2335
  renamed = true
2245
2336
  }
2246
2337
  let m = modelOf(orig)
2338
+ asked = m
2247
2339
  if (m.toLowerCase().endsWith("-trial")) {
2248
2340
  gift ??= await startPlan(s.jwt, s.device).catch(() => null)
2249
2341
  const raw = giftModel(gift, m)
@@ -2255,8 +2347,21 @@ export async function ZCodeAuthPlugin({ client }) {
2255
2347
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: raw })
2256
2348
  m = raw
2257
2349
  forcedGift = true
2350
+ } else if (!alone && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m)) {
2351
+ // free first: the plain model spends the account's own live
2352
+ // gift before it spends the coding plan, under the name the
2353
+ // gift lists. The gift is the route's cache alone (a failed
2354
+ // read cached its why), so a gift that cannot be read keeps
2355
+ // the request on the plan with no read per request; a
2356
+ // gift-only account is already on the gift and is left as
2357
+ // it was. A refusal past this check is replayed on the plan
2358
+ // in the same request (replayOnPlan below).
2359
+ const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
2360
+ orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: raw })
2361
+ m = raw
2362
+ freeGift = true
2258
2363
  }
2259
- start = alone || forcedGift
2364
+ start = alone || forcedGift || freeGift
2260
2365
  }
2261
2366
  const swap = (base) => {
2262
2367
  for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
@@ -2267,8 +2372,41 @@ export async function ZCodeAuthPlugin({ client }) {
2267
2372
  }
2268
2373
  }
2269
2374
  let h = new Headers(opts.headers)
2375
+ const askedUrl = url
2270
2376
  const place = workPlace(h)
2271
2377
  const sid = sessionOf(h.get("x-session-id"), s.device)
2378
+ // restModel is the gift saying this model has nothing left: the
2379
+ // model rests a minute (blocked) and the route is dropped, so
2380
+ // the requests behind it re-read the balance and go straight to
2381
+ // the plan.
2382
+ const restModel = () => {
2383
+ for (const [k, until] of blocked) if (Date.now() >= until) blocked.delete(k)
2384
+ blocked.set(s.key + "\0" + s.jwt + "\0" + asked.toLowerCase(), Date.now() + 60_000)
2385
+ routes.delete(s.key + "\0" + s.jwt)
2386
+ }
2387
+ // replayOnPlan is free first's answer to a gift that refused
2388
+ // what its own balance read had promised: the model as the
2389
+ // agent sent it, the plan's headers, the plan's own patience
2390
+ // (askBusy).
2391
+ const replayOnPlan = async () => {
2392
+ let u = askedUrl
2393
+ for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
2394
+ if (u.startsWith(b)) {
2395
+ u = s.base + u.slice(b.length)
2396
+ break
2397
+ }
2398
+ }
2399
+ const h2 = new Headers(opts.headers)
2400
+ workPlace(h2)
2401
+ h2.set("x-session-id", sid)
2402
+ h2.delete("authorization")
2403
+ h2.set("x-api-key", key)
2404
+ h2.set("Authorization", "Bearer " + key)
2405
+ h2.delete("content-length")
2406
+ opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid)
2407
+ delete opts.duplex
2408
+ return askBusy(u, opts, h2)
2409
+ }
2272
2410
  if (start) {
2273
2411
  if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
2274
2412
  if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
@@ -2306,20 +2444,18 @@ export async function ZCodeAuthPlugin({ client }) {
2306
2444
  // magpie sends every agent's and every session's requests of this
2307
2445
  // computer through this one process, and its queue spaces them by
2308
2446
  // the number declared above
2309
- const ask = () => fetch(url, { ...opts, headers: h })
2310
- let res = await ask()
2311
- for (let i = 0; res.status === 429; i++) {
2312
- const text = await res.text()
2313
- const cap = busy(429, text)
2314
- if (!cap || i >= BUSY_WAITS.length) {
2315
- res = cap
2316
- ? busyAnswer(res, text)
2317
- : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
2318
- break
2319
- }
2320
- const w = BUSY_WAITS[i]
2321
- await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
2322
- res = await ask()
2447
+ let res
2448
+ try {
2449
+ res = await askBusy(url, opts, h)
2450
+ } catch (e) {
2451
+ // free first moved the request onto the gift, so a gift that
2452
+ // cannot be asked at all — the network, the host — is answered
2453
+ // from the plan; the route read is dropped, so the next
2454
+ // request learns whether the host is back. A caller's abort
2455
+ // stays an abort.
2456
+ if (!freeGift || opts.signal?.aborted || e?.name === "AbortError") throw e
2457
+ routes.delete(s.key + "\0" + s.jwt)
2458
+ res = await replayOnPlan()
2323
2459
  }
2324
2460
  // the Start Plan turning the request away says what to do about
2325
2461
  // it: the account blocked, or the network
@@ -2329,6 +2465,10 @@ export async function ZCodeAuthPlugin({ client }) {
2329
2465
  // a key account sent to the Start Plan (its plan list read
2330
2466
  // none) reads its plans again on the next request, so a
2331
2467
  // coding plan that is there after all is used (#369)
2468
+ if (freeGift) {
2469
+ restModel()
2470
+ return done(kept(await replayOnPlan()))
2471
+ }
2332
2472
  if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt)
2333
2473
  return kept(startBlocked(res, text))
2334
2474
  }
@@ -2361,6 +2501,32 @@ export async function ZCodeAuthPlugin({ client }) {
2361
2501
  return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text))
2362
2502
  }
2363
2503
  }
2504
+ // free first's gift answer: the choice was the plugin's, so the
2505
+ // plan answers what the gift would fail — a spent bucket and a
2506
+ // refusal like any other 4xx or 5xx among them, the gift's own
2507
+ // waited-out busy cap included, since the plan's cap is its own.
2508
+ // A spent answer or a block page rests the model a minute and
2509
+ // drops the route read; a 401/403 drops the read alone, so the
2510
+ // next request learns whether the session is gone. Anything
2511
+ // else — a 200 carrying the answer — goes on as it came. A
2512
+ // stream's body is never read here.
2513
+ else if (start && freeGift) {
2514
+ const json = (res.headers.get("content-type") ?? "").includes("application/json")
2515
+ if (res.status >= 400 || json) {
2516
+ const text = await res.text()
2517
+ const cap = busy(res.status, text)
2518
+ const spent = !cap && spentUp(text, res.status)
2519
+ if (spent) {
2520
+ restModel()
2521
+ return done(kept(await replayOnPlan()))
2522
+ }
2523
+ if (res.status >= 400) {
2524
+ if (!cap && (res.status === 401 || res.status === 403)) routes.delete(s.key + "\0" + s.jwt)
2525
+ return done(kept(await replayOnPlan()))
2526
+ }
2527
+ return done(kept(res, text))
2528
+ }
2529
+ }
2364
2530
  // the plan's answer goes on as it came, the account kept: the
2365
2531
  // built-in never marked a ZCode account lapsed nor cleared one
2366
2532
  return done(kept(res))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.37",
3
+ "version": "0.1.39",
4
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",