@magpie-community/opencode-zcode-auth 0.1.66 → 0.1.68

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 -12
  2. package/index.mjs +79 -20
  3. package/package.json +2 -3
package/README.md CHANGED
@@ -295,18 +295,23 @@ which it is answered here with the queue's 429. A request refused alone,
295
295
  or free first's gift (which goes to the coding plan), is answered as
296
296
  before.
297
297
 
298
- ## Two accounts at once
299
-
300
- Three ZCode accounts used at once from one address can get the address
301
- refused with a 405, where two are served (01huadalang on Discord). So the
302
- plugin declares `maxAccounts` two, on the auth hook and as
303
- `magpie.maxAccounts` in its `package.json`: magpie sends requests to the
304
- first two accounts of the user's list only, and holds the others in
305
- reserve. One that runs out or fails rests, and the first in reserve takes
306
- its place until it is back. A user changes the number on the provider in
307
- magpie (Advanced → Accounts at once, or `magpie provider at-once zcode
308
- <n>`), 0 for every account at once. A magpie older than the one that
309
- reads it uses every account, as before.
298
+ ## Every account, one address
299
+
300
+ The plugin declares no `maxAccounts`, so magpie sends requests to every
301
+ ZCode account of the user's: the routing chosen spreads them, and one
302
+ that runs out or fails rests while the others go on. A user who wants
303
+ fewer sets the number on the provider in magpie (Advanced → Accounts at
304
+ once, or `magpie provider at-once zcode <n>`).
305
+
306
+ What zcode.z.ai's firewall refuses an address for (405, for an hour or
307
+ two) is too many Start Plan requests in flight from it at once, whichever
308
+ accounts they are for. So besides each account's three, the Start Plan
309
+ is sent at most six requests at a time from this computer over all its
310
+ accounts; the rest wait their turn in the plugin, as an account's own do.
311
+ Six is what two accounts sent when 0.1.40 to 0.1.67 declared
312
+ `maxAccounts` two after a 405 with three (01huadalang on Discord), which
313
+ held a user's other accounts in reserve. The coding plan, on another
314
+ host, is held to none of it.
310
315
 
311
316
  ## The usage card
312
317
 
package/index.mjs CHANGED
@@ -1099,7 +1099,11 @@ async function claimDaily(s) {
1099
1099
  // translate it; why goes in the display. Set aside: it stops nothing.
1100
1100
  const GIFT_SIGN_IN = "ZCode gift plans (-Trial models) need ZCode's sign-in"
1101
1101
  function giftSignIn(s, key) {
1102
- 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" }
1102
+ if (!s.jwt) {
1103
+ if (key) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "not read with an API key: add the account with a ZCode sign-in" }
1104
+ if (s.source === "zcode" && ownStoreUnreadable()) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: UNREADABLE_SIGN_IN }
1105
+ return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "this sign-in has no ZCode session: sign in again" }
1106
+ }
1103
1107
  if (jwtExpired(s.jwt)) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "ZCode's sign-in has expired: sign in again" }
1104
1108
  return null
1105
1109
  }
@@ -1610,6 +1614,20 @@ function decrypt(key, v) {
1610
1614
  }
1611
1615
  }
1612
1616
 
1617
+ // UNREADABLE_SIGN_IN says why a sign-in "as ZCode" has no session to
1618
+ // read: ZCode 3.18 writes credentials.json's values as "enc:v2:os:…",
1619
+ // which looks bound to the system's own key store, and this plugin reads
1620
+ // enc:v1 alone (#1196).
1621
+ const UNREADABLE_SIGN_IN = "ZCode 3.18 keeps its sign-in in a new form this plugin can't read yet: add the account with a Z.ai or BigModel sign-in"
1622
+
1623
+ // ownStoreUnreadable says whether ZCode's credentials.json holds values
1624
+ // in a form decrypt can't read.
1625
+ function ownStoreUnreadable() {
1626
+ const store = readJSON(join(zcodeDir(), "credentials.json"))
1627
+ if (!store || typeof store !== "object") return false
1628
+ return Object.values(store).some((v) => typeof v === "string" && v.startsWith("enc:") && !v.startsWith("enc:v1:"))
1629
+ }
1630
+
1613
1631
  function readJSON(path) {
1614
1632
  try {
1615
1633
  return JSON.parse(readFileSync(path, "utf8"))
@@ -1876,7 +1894,7 @@ function asZCode() {
1876
1894
  method: "auto",
1877
1895
  async callback() {
1878
1896
  const own = ownSignIn()
1879
- 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" }
1897
+ if (!own) return { type: "failed", error: ownStoreUnreadable() ? UNREADABLE_SIGN_IN : "ZCode isn't signed in on this computer; sign in to ZCode, or sign in to Z.ai or BigModel here" }
1880
1898
  const { user, uid, ...s } = own
1881
1899
  const state = { source: "zcode", device: anyDevice, ...s }
1882
1900
  return { type: "success", refresh: JSON.stringify(state), access: s.key || s.jwt || "", expires: 0, accountId: user, ...(uid ? { uid } : {}) }
@@ -2106,13 +2124,16 @@ function kept(res, text) {
2106
2124
  // the number declared below (DEFAULT_CONCURRENCY, on the auth hook and in
2107
2125
  // package.json), which a user raises on the account.
2108
2126
  const DEFAULT_CONCURRENCY = 3
2109
- // DEFAULT_ACCOUNTS is how many of a user's ZCode accounts magpie sends
2110
- // requests to at the same time (maxAccounts, on the auth hook and in
2111
- // package.json): the first in the user's list, the next taking over once
2112
- // one runs out or fails. 01huadalang on Discord: three accounts used at
2113
- // once from one address got the address refused with a 405, two didn't. A
2114
- // user sets their own on the provider (Accounts at once), 0 for no limit.
2115
- const DEFAULT_ACCOUNTS = 2
2127
+ // No maxAccounts is declared: magpie sends requests to every ZCode account
2128
+ // of the user's, and a user still sets their own on the provider (Accounts
2129
+ // at once). 0.1.40 to 0.1.67 declared two, after 01huadalang's address was
2130
+ // refused with a 405 while three accounts took requests at once (Discord),
2131
+ // and the others sat in reserve until one ran out: a user with five gift
2132
+ // accounts saw two used (mathfournity on X). What the edge firewall counts
2133
+ // is this address's Start Plan requests in flight, not its accounts (see
2134
+ // busyHold), so that is what is held now, over every account (startGate's
2135
+ // address): as many as two accounts had in flight before, while a coding
2136
+ // plan account, on another host, is held to none of it.
2116
2137
  const BUSY_CODES = new Set(["3008", "3009", "3010"])
2117
2138
  // BUSY_WAITS are the waits before each ask again: ZCode's own client's,
2118
2139
  // 1s and 2s (kqo in its bundle). Past them the cap goes back to magpie,
@@ -2154,11 +2175,18 @@ const BUSY_HINT =
2154
2175
  // narrow is kept apart from lanes, which go when idle; now is its clock,
2155
2176
  // injectable for tests.
2156
2177
  const NARROW_FOR = 5 * 60_000
2157
- const startGate = { inflight: 3, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() }
2178
+ const startGate = { inflight: 3, address: 6, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() }
2179
+ // ADDRESS is the lane every account's Start Plan requests share as well as
2180
+ // their own: zcode.z.ai sees one address, and its firewall refused the whole
2181
+ // of it with 405 once ~10 were in flight (busyHold). startGate.address is
2182
+ // six, what two accounts of three each sent when the plugin declared
2183
+ // maxAccounts two, which no 405 followed. It is never narrowed.
2184
+ const ADDRESS = "\0address"
2158
2185
 
2159
2186
  // limitOf is how many of the account's Start Plan requests go at once: the
2160
2187
  // gate's number, or less while the account is narrowed.
2161
2188
  function limitOf(key) {
2189
+ if (key === ADDRESS) return startGate.address
2162
2190
  const n = startGate.narrow.get(key)
2163
2191
  if (!n) return startGate.inflight
2164
2192
  if (startGate.now() >= n.until) {
@@ -2238,6 +2266,34 @@ function startSlot(key, signal, { wait = startGate.wait, front = false } = {}) {
2238
2266
  })
2239
2267
  }
2240
2268
 
2269
+ // startSlots waits for a slot of the account's, then one of the address's
2270
+ // (ADDRESS), both within the one wait: { release } letting both go, or
2271
+ // { key } naming the lane whose wait ran out, nothing held. Every request
2272
+ // takes the account's first, so one holding the address's never waits for
2273
+ // an account's.
2274
+ async function startSlots(key, signal, { wait = startGate.wait, front = false } = {}) {
2275
+ const until = Date.now() + wait
2276
+ const mine = await startSlot(key, signal, { wait, front })
2277
+ if (!mine) return { key }
2278
+ let all
2279
+ try {
2280
+ all = await startSlot(ADDRESS, signal, { wait: until - Date.now(), front })
2281
+ } catch (e) {
2282
+ mine.release()
2283
+ throw e
2284
+ }
2285
+ if (!all) {
2286
+ mine.release()
2287
+ return { key: ADDRESS }
2288
+ }
2289
+ return {
2290
+ release() {
2291
+ all.release()
2292
+ mine.release()
2293
+ },
2294
+ }
2295
+ }
2296
+
2241
2297
  // released hands res on and lets its slot go once ZCode's answer has come
2242
2298
  // to its end, failed, or been given up on (the agent's abort, the reader's
2243
2299
  // cancel) — the request is in flight at ZCode until then. The answer is read
@@ -2281,9 +2337,12 @@ function released(res, slot, signal) {
2281
2337
  // so it tries the next account, and a short Retry-After.
2282
2338
  function startQueueAnswer(key) {
2283
2339
  const n = limitOf(key)
2340
+ const s = n === 1 ? "" : "s"
2284
2341
  const error = {
2285
2342
  type: "rate_limit_error",
2286
- message: `ZCode's free Start Plan serves this account ${n} request${n === 1 ? "" : "s"} at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`,
2343
+ message: key === ADDRESS
2344
+ ? `ZCode's free Start Plan is sent ${n} request${s} at a time from this computer, over all its accounts, as more get the address refused; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`
2345
+ : `ZCode's free Start Plan serves this account ${n} request${s} at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`,
2287
2346
  }
2288
2347
  return new Response(JSON.stringify({ type: "error", error }), {
2289
2348
  status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" },
@@ -3072,9 +3131,6 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3072
3131
  // of day, and a user who knows theirs can raise this on the account.
3073
3132
  // The Start Plan has the plugin's own gate below it (startGate)
3074
3133
  maxConcurrency: DEFAULT_CONCURRENCY,
3075
- // how many accounts take requests at once, the others in reserve
3076
- // (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all
3077
- maxAccounts: DEFAULT_ACCOUNTS,
3078
3134
  // magpie's own switches (OpenCode never reads auth.options), read at
3079
3135
  // each request through input.magpie
3080
3136
  options: [
@@ -3176,7 +3232,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3176
3232
  m = raw
3177
3233
  forcedGift = true
3178
3234
  giftName = giftID(raw)
3179
- } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
3235
+ } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && !startFull(ADDRESS) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
3180
3236
  // free first: the plain model spends the account's own live
3181
3237
  // gift before it spends the coding plan, under the name the
3182
3238
  // gift lists. The gift is the route's cache alone (a failed
@@ -3290,9 +3346,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3290
3346
  // the account's Start Plan slots (startGate): a request past them
3291
3347
  // waits here for one rather than being sent to be refused
3292
3348
  if (start) {
3293
- own.slot = await startSlot(gateKey, opts.signal)
3349
+ const got = await startSlots(gateKey, opts.signal)
3294
3350
  own.signal = opts.signal
3295
- if (!own.slot) return kept(startQueueAnswer(gateKey))
3351
+ if (!got.release) return kept(startQueueAnswer(got.key))
3352
+ own.slot = got
3296
3353
  // a hold may have armed while it waited
3297
3354
  if (edgeHeld()) return kept(edgeHeldAnswer())
3298
3355
  if (busyHeld()) return kept(busyHeldAnswer())
@@ -3355,8 +3412,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3355
3412
  const until = Date.now() + startGate.wait
3356
3413
  for (let turn = 0; res.requeue && !freeGift && turn < REQUEUE_MAX; turn++) {
3357
3414
  own.slot?.release()
3358
- own.slot = await startSlot(gateKey, opts.signal, { wait: until - Date.now(), front: true })
3359
- if (!own.slot) return kept(startQueueAnswer(gateKey))
3415
+ own.slot = null
3416
+ const got = await startSlots(gateKey, opts.signal, { wait: until - Date.now(), front: true })
3417
+ if (!got.release) return kept(startQueueAnswer(got.key))
3418
+ own.slot = got
3360
3419
  if (edgeHeld()) return kept(edgeHeldAnswer())
3361
3420
  if (busyHeld()) return kept(busyHeldAnswer())
3362
3421
  res = await askBusy(url, opts, h, () => busyCap(gateKey))
@@ -3570,4 +3629,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3570
3629
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
3571
3630
  // out of reach, undefined forgets it
3572
3631
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
3573
- export const _internal = { wallAnswer, unreached, planFull, notePlan, planFullUntil, locatedKeys, lastKeys, edge, EDGE_HOLD, busyHold, startGate, NARROW_FOR, limitOf, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, unclaimed, unclaimedSeen, aloneGift, aloneSeen, aloneNames, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
3632
+ export const _internal = { wallAnswer, unreached, planFull, notePlan, planFullUntil, locatedKeys, lastKeys, edge, EDGE_HOLD, busyHold, startGate, NARROW_FOR, limitOf, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, unclaimed, unclaimedSeen, aloneGift, aloneSeen, aloneNames, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, giftSignIn, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, ADDRESS, startSlots }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.66",
3
+ "version": "0.1.68",
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": "./opencode.mjs",
@@ -14,7 +14,6 @@
14
14
  "directory": "packages/zcode"
15
15
  },
16
16
  "magpie": {
17
- "maxConcurrency": 3,
18
- "maxAccounts": 2
17
+ "maxConcurrency": 3
19
18
  }
20
19
  }