@magpie-community/opencode-zcode-auth 0.1.26 → 0.1.28

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 +17 -7
  2. package/index.mjs +64 -35
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -25,12 +25,14 @@ over Anthropic's Messages API. Provider id: `zcode`.
25
25
  agent's system prompt at the end of the third (a fourth block is
26
26
  refused, #343), the day in a `<system-reminder>` turn before the agent's
27
27
  turns, and the sign-in's device id in `metadata.user_id`. GLM Coding
28
- Plan and team requests go as the agent sent them. One it still turns
29
- away (a 405, the block page or code 3012) comes back with what to do
30
- about it, as magpie's built-in said: "ZCode's Start Plan still turned
31
- this request away, though magpie sends it as the ZCode app does; …
32
- Use an account with a GLM Coding Plan, or add another provider to this
33
- group".
28
+ Plan and team requests go as the agent sent them. zcode.z.ai also
29
+ answers 405 code 3012 to every request of an account its risk control
30
+ blocked, ZCode's own app's included (plugins#348). That answer comes
31
+ back as ZCode's words, then "ZCode's risk control blocked this account
32
+ for unusual activity (code 3012); …", which magpie reads as the account
33
+ restricted: it rests, and the group's other providers are used. Only
34
+ ZCode support lifts such a block. A block page from ZCode's edge
35
+ firewall says this network's address was blocked instead.
34
36
  - The Start Plan's token can't be refreshed. When it runs out, sign in
35
37
  again.
36
38
  - **ZCode: a team's GLM Coding Plan**
@@ -42,6 +44,10 @@ over Anthropic's Messages API. Provider id: `zcode`.
42
44
  - It is kept as an account of its own, named `<email> (team)`, beside
43
45
  the account's own plan, so both can be used.
44
46
  - With no seat on a team's plan, it says so and signs in to nothing.
47
+ - The same ZCode session also reads the person's gift plans. Their
48
+ `<model>-Trial` entries and gift buckets appear beside the team's
49
+ models and allowance. Plain models spend the team plan; trial entries
50
+ spend the personal gift, with no fallback to the team on refusal.
45
51
  - **ZCode app's sign-in**
46
52
  - Uses the account the ZCode app on this computer is signed in to. For
47
53
  every request it reads ZCode's own credentials (`~/.zcode/v2`), so it
@@ -77,7 +83,11 @@ the ZCode app's sign-in (`refresh` then holds `"source": "zcode"`).
77
83
  ## How requests are routed
78
84
 
79
85
  Before each request, the plugin checks which plan the account is on, and
80
- asks again every 10 minutes:
86
+ asks again every 10 minutes, and with every read of the usage card, so a
87
+ plan bought, a gift claimed or a plan lapsed reaches the requests when the
88
+ card shows it. A key whose plan list once reads no plan after reading one
89
+ is asked again after a minute, and a Start Plan refusal on such a key reads
90
+ the plans again on the next request:
81
91
 
82
92
  - If the key's account has a GLM Coding Plan
83
93
  (`/api/biz/subscription/list`), its requests go to that plan. A model
package/index.mjs CHANGED
@@ -194,8 +194,8 @@ async function startPlan(jwt, device) {
194
194
 
195
195
  // plansOf says where an account's requests go and what more it can spend:
196
196
  // {start, gift}. start is what onStart said: an account with no coding plan
197
- // sends every request to the gift and reads no balance to do it; a team's
198
- // seat, a sign-in with no ZCode token and a key whose plan-list read found
197
+ // sends every request to the gift and reads no balance to do it; a
198
+ // sign-in with no ZCode token and a key whose plan-list read found
199
199
  // no gift stay on the coding plan. gift is what a coding account also holds:
200
200
  // the gift plans ({models}), and its requests spend the gift for a model it
201
201
  // serves, until it says it is spent (see blocked). Asked again after 10
@@ -204,8 +204,8 @@ async function startPlan(jwt, device) {
204
204
  // ask).
205
205
  const routes = new Map()
206
206
  async function plansOf(s) {
207
- if (isTeam(s) || !s.jwt) return { start: false, gift: null }
208
- if (!s.key) return { start: true, gift: null }
207
+ if (!s.jwt) return { start: false, gift: null }
208
+ if (!s.key && !isTeam(s)) return { start: true, gift: null }
209
209
  const id = s.key + "\0" + s.jwt
210
210
  const r = routes.get(id)
211
211
  if (r && Date.now() - r.at < r.ttl) return r
@@ -213,7 +213,9 @@ async function plansOf(s) {
213
213
  let gift = null
214
214
  let sure = false
215
215
  try {
216
- if (!(await plan(s))) start = true
216
+ // A team seat stays on its team even when its personal plan list is
217
+ // empty. Its ZCode session still holds the person's gift plans.
218
+ if (!isTeam(s) && !(await plan(s))) start = true
217
219
  else {
218
220
  // a gift read that failed is unknown, not "no gift": asked again in
219
221
  // a minute, so its trial entries come back with the next list (an
@@ -222,7 +224,12 @@ async function plansOf(s) {
222
224
  gift = await startPlan(s.jwt, s.device).catch(() => ((failed = !jwtExpired(s.jwt)), null))
223
225
  sure = !failed
224
226
  }
225
- if (start) sure = true
227
+ // a key whose plan list read no plan, where the last read found one,
228
+ // is asked again in a minute rather than sent to the Start Plan for
229
+ // ten: one list without the plan (a renewal's boundary, a hiccup)
230
+ // turned a GLM Coding Plan account's every request into the Start
231
+ // Plan's 405 until the route was read again (#369)
232
+ if (start) sure = !(s.key && r && !r.start)
226
233
  } catch {
227
234
  // the plan list could not be read: a key account takes the dual route
228
235
  // (start stays false, the gift is kept, a minute's ttl), so a gift
@@ -632,7 +639,6 @@ async function claimHint(s) {
632
639
  // translate it; why goes in the display. Set aside: it stops nothing.
633
640
  const GIFT_SIGN_IN = "ZCode gift plans (-Trial models) need ZCode's sign-in"
634
641
  function giftSignIn(s, key) {
635
- if (isTeam(s)) return null
636
642
  if (!s.jwt) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: key ? "not read with an API key: add the account with a ZCode sign-in" : "this sign-in has no ZCode session: sign in again" }
637
643
  if (jwtExpired(s.jwt)) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "ZCode's sign-in has expired: sign in again" }
638
644
  return null
@@ -704,8 +710,8 @@ function bestBuckets(windows) {
704
710
  // Fresh usage also updates the request cache, so a replenished or spent
705
711
  // gift takes effect before its ten-minute route cache expires. A failed
706
712
  // gift read leaves the working Coding Plan's card and route alone.
707
- async function dualUsage(s) {
708
- const out = await codingUsage(s)
713
+ async function dualUsage(s, out) {
714
+ out ??= await codingUsage(s)
709
715
  const cached = routes.get(s.key + "\0" + s.jwt)
710
716
  try {
711
717
  const g = await giftOf(s)
@@ -1438,39 +1444,51 @@ function model(m, url) {
1438
1444
  }
1439
1445
 
1440
1446
  // ---- the Start Plan's requests ----------------------------------------------------
1441
- // zcode.z.ai serves the Start Plan only to what looks like ZCode's own
1442
- // request, and turns others away with 405 "request has been blocked due to
1443
- // unusual activity" (code 3012). A Start Plan request goes as the plugin
1447
+ // zcode.z.ai answers 405 "request has been blocked due to unusual
1448
+ // activity" (code 3012) to a request that doesn't look like ZCode's own
1449
+ // (#343: the agent's system prompt as a fourth block), and to every
1450
+ // request of an account its risk control blocked, ZCode's own app's too
1451
+ // (plugins#348). A Start Plan request goes as the plugin
1444
1452
  // the plan serves (ARNO's "Freeflow", provider zcode-start) sends it: its
1445
1453
  // headers (startHeaders) and its body (dress). The texts are prompt.mjs.
1446
1454
 
1447
- // START_BLOCKED is what the Start Plan still turning a request away means,
1448
- // word for word magpie's provider.ZCodeStartBlockedHint (#425), which
1449
- // magpie's Routing page knows and says in the user's language. It is put
1450
- // in place of the block page, whose words magpie would otherwise read as a
1451
- // network firewall's (provider.BlockedHint).
1452
- const START_BLOCKED = "ZCode's Start Plan still turned this request away, though magpie sends it as the ZCode app does; it can be a network block of this IP, or ZCode checking for something new. Use an account with a GLM Coding Plan, or add another provider to this group"
1453
- const EDGE_BLOCKED = /request has been blocked|errors\.aliyun\.com/i
1454
- const START_REFUSED = /unusual activity|"code"\s*:\s*"?3012\b/i
1455
-
1456
- // startRefused says a Start Plan answer is that refusal, as the built-in's
1457
- // zcodeStartExplain read it: a 405, a block page or code 3012.
1458
- const startRefused = (status, text) => status >= 400 && (status === 405 || EDGE_BLOCKED.test(text) || START_REFUSED.test(text))
1459
-
1460
- // startBlocked is the refusal's answer as the built-in passed it on: what
1461
- // the vendor said (its status for a block page), then START_BLOCKED.
1455
+ // START_RESTRICTED is what ZCode's 3012, "request has been blocked due to
1456
+ // unusual activity", means: ZCode's risk control blocked the account
1457
+ // (ZCode's support says so, and ZCode's own app gets the same 405 on such
1458
+ // an account, plugins#348), not that the request was sent wrong. Word for
1459
+ // word magpie's provider.ZCodeRestrictedHint: the gateway reads it as the
1460
+ // account restricted, rests it and asks the group's next member, and the
1461
+ // Routing page says it in the user's language.
1462
+ const START_RESTRICTED = "ZCode's risk control blocked this account for unusual activity (code 3012); it rests, and the group's other providers are used. If the ZCode app fails on this account too, only ZCode support can lift the block"
1463
+ // START_EDGE is what a block page from ZCode's edge firewall (Aliyun's)
1464
+ // means: this network's address, not the account. Word for word magpie's
1465
+ // provider.BlockedHint.
1466
+ const START_EDGE = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy"
1467
+ const EDGE_PAGE = /errors\.aliyun\.com|<html/i
1468
+ const START_REFUSED = /unusual activity|request has been blocked|"code"\s*:\s*"?3012\b/i
1469
+
1470
+ // startRefused says a Start Plan answer is a refusal: a 405, a block page
1471
+ // or code 3012.
1472
+ const startRefused = (status, text) => status >= 400 && (status === 405 || START_REFUSED.test(text))
1473
+
1474
+ // startBlocked is the refusal's answer: what the vendor said (its status
1475
+ // for a block page), then what it means. A block page is the network's;
1476
+ // anything else, ZCode's JSON 3012 or a bare 405, the account's.
1462
1477
  function startBlocked(res, text) {
1478
+ const page = EDGE_PAGE.test(text)
1463
1479
  let said = ""
1464
- if (!EDGE_BLOCKED.test(text)) {
1480
+ if (!page) {
1465
1481
  try {
1466
1482
  const v = JSON.parse(text)
1467
1483
  said = first(v?.error?.message, typeof v?.error === "string" ? v.error : "", v?.message, v?.msg)
1484
+ const code = v?.code ?? v?.error?.code
1485
+ if (said && code != null && !String(said).includes(String(code))) said = `${said} (${res.status}, code ${code})`
1468
1486
  } catch {}
1469
1487
  }
1470
1488
  said ||= `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText}`.trim()
1471
1489
  const h = new Headers(res.headers)
1472
1490
  h.set("content-type", "application/json")
1473
- const error = { type: "permission_error", message: `${said} — ${START_BLOCKED}` }
1491
+ const error = { type: "permission_error", message: `${said} — ${page ? START_EDGE : START_RESTRICTED}` }
1474
1492
  return new Response(JSON.stringify({ type: "error", error }), { status: res.status, statusText: res.statusText, headers: h })
1475
1493
  }
1476
1494
 
@@ -1900,10 +1918,16 @@ export async function ZCodeAuthPlugin({ client }) {
1900
1918
  }
1901
1919
  let res = await fetch(url, { ...opts, headers: h })
1902
1920
  // the Start Plan turning the request away says what to do about
1903
- // it, as the built-in's zcodeStartExplain did
1921
+ // it: the account blocked, or the network
1904
1922
  if (start && res.status >= 400) {
1905
1923
  const text = await res.text()
1906
- if (startRefused(res.status, text)) return kept(startBlocked(res, text))
1924
+ if (startRefused(res.status, text)) {
1925
+ // a key account sent to the Start Plan (its plan list read
1926
+ // none) reads its plans again on the next request, so a
1927
+ // coding plan that is there after all is used (#369)
1928
+ if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt)
1929
+ return kept(startBlocked(res, text))
1930
+ }
1907
1931
  res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
1908
1932
  }
1909
1933
  // a key with no plan behind it: what Z.ai said, and why a
@@ -1959,6 +1983,12 @@ export async function ZCodeAuthPlugin({ client }) {
1959
1983
  return out
1960
1984
  }
1961
1985
  try {
1986
+ // a card read is a fresh read: the route is read again with it,
1987
+ // so a plan bought, a gift claimed or a plan lapsed reaches the
1988
+ // requests when the card shows it, not ten minutes later (#379)
1989
+ routes.delete(s.key + "\0" + s.jwt)
1990
+ const { start, gift } = await plansOf(s)
1991
+ let card
1962
1992
  if (isTeam(s)) {
1963
1993
  let key = s.key
1964
1994
  if (!key) {
@@ -1968,10 +1998,9 @@ export async function ZCodeAuthPlugin({ client }) {
1968
1998
  await client?.auth?.set?.({ path: { id: provider?.id ?? PROVIDER }, body: next }).catch?.(() => {})
1969
1999
  }
1970
2000
  }
1971
- return saved(await teamUsage(s, key))
1972
- }
1973
- const { start, gift } = await plansOf(s)
1974
- const card = saved(start ? await startUsage(s) : gift ? await dualUsage(s) : await codingUsage(s))
2001
+ const team = await teamUsage(s, key)
2002
+ card = saved(gift ? await dualUsage(s, team) : team)
2003
+ } else card = saved(start ? await startUsage(s) : gift ? await dualUsage(s) : await codingUsage(s))
1975
2004
  // a gift plan ZCode holds for the account but has not put on it:
1976
2005
  // named on the card, claimed in the ZCode app (its claim needs
1977
2006
  // the app's captcha attestation, see claimHint). A card that is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
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",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",