@magpie-community/opencode-zcode-auth 0.1.27 → 0.1.29

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 +9 -1
  2. package/index.mjs +42 -19
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -44,6 +44,10 @@ over Anthropic's Messages API. Provider id: `zcode`.
44
44
  - It is kept as an account of its own, named `<email> (team)`, beside
45
45
  the account's own plan, so both can be used.
46
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.
47
51
  - **ZCode app's sign-in**
48
52
  - Uses the account the ZCode app on this computer is signed in to. For
49
53
  every request it reads ZCode's own credentials (`~/.zcode/v2`), so it
@@ -79,7 +83,11 @@ the ZCode app's sign-in (`refresh` then holds `"source": "zcode"`).
79
83
  ## How requests are routed
80
84
 
81
85
  Before each request, the plugin checks which plan the account is on, and
82
- 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:
83
91
 
84
92
  - If the key's account has a GLM Coding Plan
85
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)
@@ -995,6 +1001,10 @@ async function signedIn(site, token, jwt, device, onTeam = false) {
995
1001
  // TEAM marks a team seat's account name beside the account's own.
996
1002
  const TEAM = "team"
997
1003
  const who = (u) => first(String(u?.email ?? "").replace(/@phone\.local$/, ""), u?.name, u?.user_id, "ZCode")
1004
+ // uidOf is the account's user id, kept beside its name: magpie tells two
1005
+ // accounts of one name apart by it, a name being no one's own (wakkana on
1006
+ // Discord, WorkBuddy's)
1007
+ const uidOf = (u) => (u?.user_id === undefined || u?.user_id === null ? "" : String(u.user_id).trim())
998
1008
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
999
1009
 
1000
1010
  // authorize opens ZCode's sign-in flow on site; its callback polls it.
@@ -1053,6 +1063,7 @@ async function authorize(site, log, onTeam = false) {
1053
1063
  // the key doesn't run out; ZCode's token, when it is all there is, does
1054
1064
  expires: s.key || isTeam(s) ? 0 : jwtExpiry(s.jwt),
1055
1065
  accountId: onTeam ? `${who(got.user)} (${TEAM})` : who(got.user),
1066
+ ...(uidOf(got.user) ? { uid: uidOf(got.user) } : {}),
1056
1067
  }
1057
1068
  }
1058
1069
  },
@@ -1214,7 +1225,7 @@ function ownSignIn() {
1214
1225
  } catch {}
1215
1226
  }
1216
1227
  }
1217
- return { ...s, user: who(info) }
1228
+ return { ...s, user: who(info), uid: uidOf(info) }
1218
1229
  }
1219
1230
 
1220
1231
  // asZCode is the sign-in "as ZCode": what it reads is ZCode's own.
@@ -1226,9 +1237,9 @@ function asZCode() {
1226
1237
  async callback() {
1227
1238
  const own = ownSignIn()
1228
1239
  if (!own) return { type: "failed", error: "ZCode isn't signed in on this computer; sign in to ZCode, or sign in to Z.ai or BigModel here" }
1229
- const { user, ...s } = own
1240
+ const { user, uid, ...s } = own
1230
1241
  const state = { source: "zcode", device: anyDevice, ...s }
1231
- return { type: "success", refresh: JSON.stringify(state), access: s.key || s.jwt || "", expires: 0, accountId: user }
1242
+ return { type: "success", refresh: JSON.stringify(state), access: s.key || s.jwt || "", expires: 0, accountId: user, ...(uid ? { uid } : {}) }
1232
1243
  },
1233
1244
  }
1234
1245
  }
@@ -1247,8 +1258,9 @@ function stateOf(auth) {
1247
1258
  // send this account's requests as that one, and an expired session
1248
1259
  // says sign in again (EXPIRED) rather than borrowing another's.
1249
1260
  const own = ownSignIn()
1250
- if (own && own.user === String(auth.accountId ?? "")) {
1251
- const { user, ...now } = own
1261
+ // (by user id where both have one: another account may share the name)
1262
+ if (own && own.user === String(auth.accountId ?? "") && (!own.uid || !auth.uid || own.uid === String(auth.uid))) {
1263
+ const { user, uid: _uid, ...now } = own
1252
1264
  s = { source: "zcode", device: s.device, plan: s.plan, ...now }
1253
1265
  }
1254
1266
  }
@@ -1915,7 +1927,13 @@ export async function ZCodeAuthPlugin({ client }) {
1915
1927
  // it: the account blocked, or the network
1916
1928
  if (start && res.status >= 400) {
1917
1929
  const text = await res.text()
1918
- if (startRefused(res.status, text)) return kept(startBlocked(res, text))
1930
+ if (startRefused(res.status, text)) {
1931
+ // a key account sent to the Start Plan (its plan list read
1932
+ // none) reads its plans again on the next request, so a
1933
+ // coding plan that is there after all is used (#369)
1934
+ if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt)
1935
+ return kept(startBlocked(res, text))
1936
+ }
1919
1937
  res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
1920
1938
  }
1921
1939
  // a key with no plan behind it: what Z.ai said, and why a
@@ -1971,6 +1989,12 @@ export async function ZCodeAuthPlugin({ client }) {
1971
1989
  return out
1972
1990
  }
1973
1991
  try {
1992
+ // a card read is a fresh read: the route is read again with it,
1993
+ // so a plan bought, a gift claimed or a plan lapsed reaches the
1994
+ // requests when the card shows it, not ten minutes later (#379)
1995
+ routes.delete(s.key + "\0" + s.jwt)
1996
+ const { start, gift } = await plansOf(s)
1997
+ let card
1974
1998
  if (isTeam(s)) {
1975
1999
  let key = s.key
1976
2000
  if (!key) {
@@ -1980,10 +2004,9 @@ export async function ZCodeAuthPlugin({ client }) {
1980
2004
  await client?.auth?.set?.({ path: { id: provider?.id ?? PROVIDER }, body: next }).catch?.(() => {})
1981
2005
  }
1982
2006
  }
1983
- return saved(await teamUsage(s, key))
1984
- }
1985
- const { start, gift } = await plansOf(s)
1986
- const card = saved(start ? await startUsage(s) : gift ? await dualUsage(s) : await codingUsage(s))
2007
+ const team = await teamUsage(s, key)
2008
+ card = saved(gift ? await dualUsage(s, team) : team)
2009
+ } else card = saved(start ? await startUsage(s) : gift ? await dualUsage(s) : await codingUsage(s))
1987
2010
  // a gift plan ZCode holds for the account but has not put on it:
1988
2011
  // named on the card, claimed in the ZCode app (its claim needs
1989
2012
  // 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.27",
3
+ "version": "0.1.29",
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",