@jianmu-plugins/opencode-zcode-auth 0.1.61 → 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 +45 -16
  2. package/index.mjs +213 -39
  3. package/package.json +6 -28
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @magpie-community/opencode-zcode-auth
1
+ # @jianmu-plugins/opencode-zcode-auth
2
2
 
3
3
  Signs in to Z.ai's GLM Coding Plan, or BigModel's (智谱). It does this the
4
4
  way [ZCode](https://zcode.z.ai) does, and serves the plan's GLM models
@@ -117,7 +117,14 @@ the plans again on the next request:
117
117
  (`/api/biz/subscription/list`), its requests go to that plan. A model
118
118
  the account's gift plans also serve is listed again as
119
119
  `<model>-Trial`; asking that entry spends the gift (see below).
120
- - Otherwise they go to the gift plans.
120
+ - Otherwise they go to the gift plans. A model the gift plans' balance
121
+ doesn't name (an agent left on GLM-5.2 while the gift serves only
122
+ GLM-5.3-Flash) would spend none of the free quota, so it is answered
123
+ with the models the balance names and not sent. The balance is the one
124
+ the model list read; a model it doesn't name has it read again first.
125
+ When the plan list can't be read, an account whose last read found no
126
+ plan stays on the gift plans rather than sending its key to the coding
127
+ plan's host, which bills a key with no plan pay-as-you-go.
121
128
 
122
129
  Every request carries the key as both `x-api-key` and
123
130
  `Authorization: Bearer`.
@@ -275,18 +282,36 @@ the slots. An account whose slots are taken elsewhere is narrowed to one
275
282
  within a few refusals and then refused alone, so the firewall hold still
276
283
  comes before the 405.
277
284
 
278
- ## Two accounts at once
279
-
280
- Three ZCode accounts used at once from one address can get the address
281
- refused with a 405, where two are served (01huadalang on Discord). So the
282
- plugin declares `maxAccounts` two, on the auth hook and as
283
- `magpie.maxAccounts` in its `package.json`: magpie sends requests to the
284
- first two accounts of the user's list only, and holds the others in
285
- reserve. One that runs out or fails rests, and the first in reserve takes
286
- its place until it is back. A user changes the number on the provider in
287
- magpie (Advanced → Accounts at once, or `magpie provider at-once zcode
288
- <n>`), 0 for every account at once. A magpie older than the one that
289
- reads it uses every account, as before.
285
+ Since 0.1.64 the request that brought about such a narrowing is not
286
+ failed either. Up to 0.1.63 it went back to magpie as a 429 after its
287
+ re-asks, so two sessions on an account served one at a time showed a 429
288
+ every time the narrowing ran out (JJLIN070414 on X), and with one account
289
+ the agent was told it. Now it gives its slot back at once, without the 2s
290
+ re-ask, and waits at the head of the queue until one of the account's
291
+ other requests has ended, then is sent again, as ZCode's own client
292
+ (its dynamic-workflow governor) cuts its cap and queues a capped request
293
+ rather than failing it. The waits share the gate's two minutes, after
294
+ which it is answered here with the queue's 429. A request refused alone,
295
+ or free first's gift (which goes to the coding plan), is answered as
296
+ before.
297
+
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.
290
315
 
291
316
  ## The usage card
292
317
 
@@ -337,8 +362,12 @@ menu bar pass it over. The name is a fixed sentence magpie can
337
362
  translate; the count and the plan's own name are the display. Reading
338
363
  the card never claims one. A preview that fails, or lists nothing, adds
339
364
  no line at all, and a card that is an error keeps its error. Claim the
340
- plan in the ZCode app (open it once), or let the daily claim below do it;
341
- the next read shows it as an ordinary gift bucket.
365
+ plan in the ZCode app (open it once); while ZCode asks its security check
366
+ for a claim, as it does now, the daily claim below posts none. The next
367
+ read shows it as an ordinary gift bucket: its `-Trial` entry is listed and
368
+ free first spends it. Until then a `-Trial` pick that finds no gift is
369
+ refused with the held plan's name and "claim it in the ZCode app", not
370
+ only "no active limited quota" (heduian and bg5eau on X, 11-14).
342
371
 
343
372
  ## The daily claim
344
373
 
package/index.mjs CHANGED
@@ -263,13 +263,20 @@ async function plansOf(s) {
263
263
  // Plan's 405 until the route was read again (#369)
264
264
  if (start) sure = !(s.key && r && !r.start)
265
265
  } catch {
266
- // the plan list could not be read: a key account takes the dual route
267
- // (start stays false, the gift is kept, a minute's ttl), so a gift
268
- // refusal still replays to the coding plan rather than blacking out
269
- try {
270
- gift = await startPlan(s.jwt, s.device)
271
- sure = false
272
- } catch {}
266
+ // the plan list could not be read. An account the last read found with
267
+ // no coding plan stays on the Start Plan for the minute: the dual route
268
+ // would send its key to the coding plan's host, which bills a key with
269
+ // no plan pay-as-you-go while the free quota sits unspent (bg5eau on
270
+ // X). Any other key account takes the dual route (start stays false,
271
+ // the gift is kept, a minute's ttl), so a gift refusal still replays to
272
+ // the coding plan rather than blacking out
273
+ if (r?.start) start = true
274
+ else {
275
+ try {
276
+ gift = await startPlan(s.jwt, s.device)
277
+ } catch {}
278
+ }
279
+ sure = false
273
280
  }
274
281
  const out = { start, gift, at: Date.now(), ttl: Math.min(sure ? 600_000 : 60_000, gift?.ttl ?? 600_000) }
275
282
  routes.set(id, out)
@@ -715,6 +722,48 @@ async function claimHint(s) {
715
722
  return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
716
723
  }
717
724
 
725
+ // unclaimed names the gift plans ZCode holds for the account but has not
726
+ // put on it (toClaim), for a -Trial pick that finds no gift: the weekend
727
+ // plan (ZCODE WEEKEND BUILD) comes only by a claim, and the claim needs
728
+ // the ZCode app's captcha (claimDaily posts none), so until it is
729
+ // claimed in the app the pick's quota does not exist yet (heduian and
730
+ // bg5eau on X, 11-14). The refusal says where the quota is rather than
731
+ // only that there is none. Kept ten minutes per session, so an agent
732
+ // retrying the pick doesn't read the feed each time; a read that fails
733
+ // names none and is not kept.
734
+ // aloneSeen is a gift-only account's balance as last read (the model list
735
+ // reads it), kept ten minutes. A request reads no balance on its own: only
736
+ // a model the kept balance doesn't name has it read again (aloneGift), so
737
+ // a gift claimed since is not refused. A read that fails is not kept.
738
+ const aloneSeen = new Map()
739
+ const aloneNames = (s) => {
740
+ const c = aloneSeen.get(s.jwt)
741
+ return c && Date.now() - c.at < 600_000 ? giftNames(c.gift) : []
742
+ }
743
+ async function aloneGift(s) {
744
+ let gift
745
+ try {
746
+ gift = await startPlan(s.jwt, s.device)
747
+ } catch {
748
+ return null
749
+ }
750
+ aloneSeen.set(s.jwt, { at: Date.now(), gift })
751
+ return gift
752
+ }
753
+
754
+ const unclaimedSeen = new Map()
755
+ async function unclaimed(s) {
756
+ if (!s.jwt || jwtExpired(s.jwt)) return []
757
+ const k = s.jwt
758
+ const c = unclaimedSeen.get(k)
759
+ if (c && Date.now() - c.at < 600_000) return c.names
760
+ const got = await toClaim(s).catch(() => null)
761
+ if (!got || got.unread.length) return []
762
+ const names = uniqueModels(got.plans.map((p) => first(p.name, p.plan_id)).filter(Boolean))
763
+ unclaimedSeen.set(k, { at: Date.now(), names })
764
+ return names
765
+ }
766
+
718
767
  // ---- the daily claim ---------------------------------------------------------------
719
768
 
720
769
  // CLAIMED_ALREADY is /billing/claim's body code for a plan the account
@@ -1050,7 +1099,11 @@ async function claimDaily(s) {
1050
1099
  // translate it; why goes in the display. Set aside: it stops nothing.
1051
1100
  const GIFT_SIGN_IN = "ZCode gift plans (-Trial models) need ZCode's sign-in"
1052
1101
  function giftSignIn(s, key) {
1053
- 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
+ }
1054
1107
  if (jwtExpired(s.jwt)) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "ZCode's sign-in has expired: sign in again" }
1055
1108
  return null
1056
1109
  }
@@ -1561,6 +1614,20 @@ function decrypt(key, v) {
1561
1614
  }
1562
1615
  }
1563
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
+
1564
1631
  function readJSON(path) {
1565
1632
  try {
1566
1633
  return JSON.parse(readFileSync(path, "utf8"))
@@ -1804,7 +1871,11 @@ function ownSignIn() {
1804
1871
  else s = { ...s, jwt, base: s.base || ZAI_BASE, site: s.base === BIGMODEL_BASE ? "bigmodel" : "zai" }
1805
1872
  if (!s.key && !s.jwt && !isTeam(s)) return null
1806
1873
  let info = {}
1807
- for (const name of ["oauth:zai:user_info", "oauth:bigmodel:user_info"]) {
1874
+ // The JWT belongs to the app's active sign-in. Cached profiles from
1875
+ // another provider must not name it, and 3.18's China sign-in is zai_cn.
1876
+ const active = decrypt(key, store["oauth:active_provider"])
1877
+ const families = [...new Set([active, "zai", "zai_cn", "bigmodel"].filter((x) => ["zai", "zai_cn", "bigmodel"].includes(x)))]
1878
+ for (const name of families.map((x) => `oauth:${x}:user_info`)) {
1808
1879
  const v = decrypt(key, store[name])
1809
1880
  if (v && !first(info.email, info.name, info.user_id)) {
1810
1881
  try {
@@ -1823,7 +1894,7 @@ function asZCode() {
1823
1894
  method: "auto",
1824
1895
  async callback() {
1825
1896
  const own = ownSignIn()
1826
- 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" }
1827
1898
  const { user, uid, ...s } = own
1828
1899
  const state = { source: "zcode", device: anyDevice, ...s }
1829
1900
  return { type: "success", refresh: JSON.stringify(state), access: s.key || s.jwt || "", expires: 0, accountId: user, ...(uid ? { uid } : {}) }
@@ -2040,7 +2111,11 @@ function kept(res, text) {
2040
2111
  // this computer through this one process, so the plugin does what that
2041
2112
  // client does: the Start Plan gets a few requests of an account in flight at
2042
2113
  // once (startGate), the rest wait their turn here instead of being sent to be
2043
- // refused, and a refusal anyway is asked again twice (BUSY_WAITS).
2114
+ // refused, and a refusal anyway is asked again twice (BUSY_WAITS). A refusal
2115
+ // of a request sent beside others of the same account lowers that account's
2116
+ // gate and waits its turn again (askBusy's requeue), as ZCode's own
2117
+ // dynamic-workflow governor cuts its cap and queues a capped subagent
2118
+ // request rather than failing it.
2044
2119
  //
2045
2120
  // The coding plan keeps no gate of the plugin's: its cap depends on its tier
2046
2121
  // (Z.ai serves Max more at once than Pro, and Lite fewer) and is higher
@@ -2049,13 +2124,16 @@ function kept(res, text) {
2049
2124
  // the number declared below (DEFAULT_CONCURRENCY, on the auth hook and in
2050
2125
  // package.json), which a user raises on the account.
2051
2126
  const DEFAULT_CONCURRENCY = 3
2052
- // DEFAULT_ACCOUNTS is how many of a user's ZCode accounts magpie sends
2053
- // requests to at the same time (maxAccounts, on the auth hook and in
2054
- // package.json): the first in the user's list, the next taking over once
2055
- // one runs out or fails. 01huadalang on Discord: three accounts used at
2056
- // once from one address got the address refused with a 405, two didn't. A
2057
- // user sets their own on the provider (Accounts at once), 0 for no limit.
2058
- 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.
2059
2137
  const BUSY_CODES = new Set(["3008", "3009", "3010"])
2060
2138
  // BUSY_WAITS are the waits before each ask again: ZCode's own client's,
2061
2139
  // 1s and 2s (kqo in its bundle). Past them the cap goes back to magpie,
@@ -2064,6 +2142,10 @@ const BUSY_CODES = new Set(["3008", "3009", "3010"])
2064
2142
  // requests a capped account could serve on the wire, and the agents' own
2065
2143
  // retries came on top.
2066
2144
  const BUSY_WAITS = [1000, 2000]
2145
+ // REQUEUE_MAX bounds how often one request is handed back to the gate by a
2146
+ // narrowing (askBusy): each narrowing lowers the gate, three to one at most
2147
+ // takes two, so more is a fault of the count, not ZCode.
2148
+ const REQUEUE_MAX = 4
2067
2149
  // The hint names neither "plan" nor "limit": after the vendor's "…limit
2068
2150
  // exceeded" either would read to magpie as a plan used up.
2069
2151
  const BUSY_HINT =
@@ -2093,11 +2175,18 @@ const BUSY_HINT =
2093
2175
  // narrow is kept apart from lanes, which go when idle; now is its clock,
2094
2176
  // injectable for tests.
2095
2177
  const NARROW_FOR = 5 * 60_000
2096
- 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"
2097
2185
 
2098
2186
  // limitOf is how many of the account's Start Plan requests go at once: the
2099
2187
  // gate's number, or less while the account is narrowed.
2100
2188
  function limitOf(key) {
2189
+ if (key === ADDRESS) return startGate.address
2101
2190
  const n = startGate.narrow.get(key)
2102
2191
  if (!n) return startGate.inflight
2103
2192
  if (startGate.now() >= n.until) {
@@ -2125,8 +2214,10 @@ const startFull = (key) => {
2125
2214
  }
2126
2215
 
2127
2216
  // startSlot waits for one of the account's Start Plan slots: { release },
2128
- // null when startGate.wait ran out first, or the agent's abort thrown.
2129
- function startSlot(key, signal) {
2217
+ // null when the wait (startGate.wait unless given) ran out first, or the
2218
+ // agent's abort thrown. A request handed back by a narrowing (requeued) was
2219
+ // first in line already, so it waits at the head of the queue.
2220
+ function startSlot(key, signal, { wait = startGate.wait, front = false } = {}) {
2130
2221
  const lanes = startGate.lanes
2131
2222
  let l = lanes.get(key)
2132
2223
  if (!l) lanes.set(key, (l = { busy: 0, queue: [] }))
@@ -2168,12 +2259,41 @@ function startSlot(key, signal) {
2168
2259
  leave()
2169
2260
  next()
2170
2261
  resolve(null)
2171
- }, startGate.wait)
2262
+ }, Math.max(0, wait))
2172
2263
  signal?.addEventListener?.("abort", aborted, { once: true })
2173
- l.queue.push(go)
2264
+ if (front) l.queue.unshift(go)
2265
+ else l.queue.push(go)
2174
2266
  })
2175
2267
  }
2176
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
+
2177
2297
  // released hands res on and lets its slot go once ZCode's answer has come
2178
2298
  // to its end, failed, or been given up on (the agent's abort, the reader's
2179
2299
  // cancel) — the request is in flight at ZCode until then. The answer is read
@@ -2217,9 +2337,12 @@ function released(res, slot, signal) {
2217
2337
  // so it tries the next account, and a short Retry-After.
2218
2338
  function startQueueAnswer(key) {
2219
2339
  const n = limitOf(key)
2340
+ const s = n === 1 ? "" : "s"
2220
2341
  const error = {
2221
2342
  type: "rate_limit_error",
2222
- 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`,
2223
2346
  }
2224
2347
  return new Response(JSON.stringify({ type: "error", error }), {
2225
2348
  status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" },
@@ -2266,10 +2389,12 @@ const busyHeld = () => busyHold.now() < busyHold.until
2266
2389
  // busyCap records one sustained concurrency cap of a Start Plan request.
2267
2390
  // Only a run arms a hold; the window is cleared on arming, and a cap that
2268
2391
  // lands while the hold is on counts toward nothing — the hold's own 429s and
2269
- // the first caps after it cannot keep re-arming it.
2392
+ // the first caps after it cannot keep re-arming it. It says true when the
2393
+ // cap narrowed the account instead: the request is then requeued, not
2394
+ // failed (see askBusy).
2270
2395
  function busyCap(key) {
2271
- if (key != null && narrowed(key)) return
2272
- if (busyHeld()) return
2396
+ if (key != null && narrowed(key)) return true
2397
+ if (busyHeld()) return false
2273
2398
  const now = busyHold.now()
2274
2399
  busyHold.hits.push(now)
2275
2400
  while (busyHold.hits.length && now - busyHold.hits[0] > BUSY_WINDOW) busyHold.hits.shift()
@@ -2277,6 +2402,7 @@ function busyCap(key) {
2277
2402
  busyHold.until = now + BUSY_HOLD
2278
2403
  busyHold.hits.length = 0
2279
2404
  }
2405
+ return false
2280
2406
  }
2281
2407
 
2282
2408
  // BUSY_HOLD_MARK marks an answer the hold made up: a request the gate or the
@@ -2345,8 +2471,13 @@ function busyAnswer(res, text) {
2345
2471
  // 1s and then 2s, as ZCode's own client does. Past them the cap goes back as
2346
2472
  // busyAnswer's 429. A request refused again at its 1s re-ask is a sustained
2347
2473
  // cap, told to onCap once (the firewall hold's count); one the re-ask got
2348
- // past is not. The plan path's patience, shared with free first's replay,
2349
- // whose plan has a cap of its own.
2474
+ // past is not. When onCap says the cap narrowed the account (others of this
2475
+ // computer were in flight on it), asking again in 2s would only be refused
2476
+ // beside them again: the busyAnswer goes back at once marked `requeue`, and
2477
+ // the Start Plan path waits for one of those others to end and sends it
2478
+ // again (JJLIN070414 on X: two sessions on one account, each pair's second
2479
+ // request failed 429 where ZCode's own client queues it). The plan path's
2480
+ // patience, shared with free first's replay, whose plan has a cap of its own.
2350
2481
  async function askBusy(u, o, hs, onCap) {
2351
2482
  let res = await fetch(u, { ...o, headers: hs })
2352
2483
  let caps = 0
@@ -2354,7 +2485,11 @@ async function askBusy(u, o, hs, onCap) {
2354
2485
  const text = await res.text()
2355
2486
  const cap = busy(429, text)
2356
2487
  // one request's refusals are one saturation signal, not one per ask
2357
- if (cap && ++caps === 2) onCap?.()
2488
+ if (cap && ++caps === 2 && onCap?.() === true) {
2489
+ res = busyAnswer(res, text)
2490
+ res.requeue = true
2491
+ break
2492
+ }
2358
2493
  // the hold armed: a request already in flight stops asking too. The
2359
2494
  // second check catches the asks that capped before the hold armed and
2360
2495
  // woke from their wait after it. Keying on onCap keeps the coding plan
@@ -2943,7 +3078,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2943
3078
  const s = await located(stateOf(auth))
2944
3079
  if (!s) return provider.models
2945
3080
  const { start, gift: known } = await plansOf(s).catch(() => ({ start: false, gift: null }))
2946
- const gift = start ? await startPlan(s.jwt, s.device).catch(() => null) : known
3081
+ const gift = start ? await aloneGift(s) : known
2947
3082
  const base = start ? START_BASE : s.base
2948
3083
  const cfg = await zcodeConfig().catch(() => null)
2949
3084
  let ms = modelsOf(cfg, planID(base))
@@ -2996,9 +3131,6 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2996
3131
  // of day, and a user who knows theirs can raise this on the account.
2997
3132
  // The Start Plan has the plugin's own gate below it (startGate)
2998
3133
  maxConcurrency: DEFAULT_CONCURRENCY,
2999
- // how many accounts take requests at once, the others in reserve
3000
- // (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all
3001
- maxAccounts: DEFAULT_ACCOUNTS,
3002
3134
  // magpie's own switches (OpenCode never reads auth.options), read at
3003
3135
  // each request through input.magpie
3004
3136
  options: [
@@ -3092,14 +3224,15 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3092
3224
  const raw = giftModel(gift, m)
3093
3225
  const available = raw && giftUsable(s, gift, raw)
3094
3226
  if (!available) {
3095
- const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}` }
3227
+ const held = raw ? [] : await unclaimed(s)
3228
+ const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}${held.length ? `. ZCode holds ${held.join(", ")} for this account unclaimed: claim it in the ZCode app (its claim needs the app's security check), and ${m} spends it` : ""}` }
3096
3229
  return kept(new Response(JSON.stringify({ type: "error", error }), { status: raw ? 429 : 400, headers: { "content-type": "application/json" } }))
3097
3230
  }
3098
3231
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
3099
3232
  m = raw
3100
3233
  forcedGift = true
3101
3234
  giftName = giftID(raw)
3102
- } 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)) {
3103
3236
  // free first: the plain model spends the account's own live
3104
3237
  // gift before it spends the coding plan, under the name the
3105
3238
  // gift lists. The gift is the route's cache alone (a failed
@@ -3119,6 +3252,25 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3119
3252
  m = raw
3120
3253
  freeGift = true
3121
3254
  giftName = giftID(raw)
3255
+ } else if (alone && /\/v1\/messages$/.test(new URL(url).pathname)) {
3256
+ // a gift-only account's Start Plan serves the models its
3257
+ // balance names, and ZCode's app offers only those
3258
+ // (resolveStartPlanBalanceAvailability). Any other model
3259
+ // spends none of the free quota, so it is not sent: an
3260
+ // agent left on another model would be billed while the
3261
+ // gift stayed unspent (bg5eau on X). The balance is the
3262
+ // one the model list read (aloneSeen); a model it doesn't
3263
+ // name has it read again before the refusal. One not read
3264
+ // yet, one that fails, or one naming none leaves the
3265
+ // request as it was.
3266
+ const named = (ns) => ns.some((x) => x.toLowerCase() === m.toLowerCase())
3267
+ const kept0 = aloneNames(s)
3268
+ const names = kept0.length && !named(kept0) ? giftNames(await aloneGift(s)) : []
3269
+ if (names.length && !named(names)) {
3270
+ const shown = uniqueModels(names.map(wireModel))
3271
+ const error = { type: "invalid_request_error", message: `ZCode's Start Plan on this account serves ${shown.join(", ")}; ${m} is not among them and would spend none of its free quota, so it was not sent. Pick ${shown.length > 1 ? "one of those" : shown[0]} for this account` }
3272
+ return kept(new Response(JSON.stringify({ type: "error", error }), { status: 400, headers: { "content-type": "application/json" } }))
3273
+ }
3122
3274
  }
3123
3275
  start = alone || forcedGift || freeGift
3124
3276
  }
@@ -3194,9 +3346,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3194
3346
  // the account's Start Plan slots (startGate): a request past them
3195
3347
  // waits here for one rather than being sent to be refused
3196
3348
  if (start) {
3197
- own.slot = await startSlot(gateKey, opts.signal)
3349
+ const got = await startSlots(gateKey, opts.signal)
3198
3350
  own.signal = opts.signal
3199
- if (!own.slot) return kept(startQueueAnswer(gateKey))
3351
+ if (!got.release) return kept(startQueueAnswer(got.key))
3352
+ own.slot = got
3200
3353
  // a hold may have armed while it waited
3201
3354
  if (edgeHeld()) return kept(edgeHeldAnswer())
3202
3355
  if (busyHeld()) return kept(busyHeldAnswer())
@@ -3246,6 +3399,27 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3246
3399
  // coding plan is served by another host and was never refused
3247
3400
  // with the IP's 405.
3248
3401
  res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined)
3402
+ // a cap this computer brought on itself, with others of the
3403
+ // account in flight beside it, narrowed the account's gate:
3404
+ // the request gives its slot back and waits, first in line,
3405
+ // until one of those others has ended, then is sent again —
3406
+ // queued, as ZCode's own client queues its subagents' caps,
3407
+ // not failed. Free first's gift goes to the plan instead,
3408
+ // which serves it now. The waits share one startGate.wait;
3409
+ // each turn the gate is lower or the request is alone, where
3410
+ // a cap is ZCode's or another client's and goes back as it
3411
+ // did.
3412
+ const until = Date.now() + startGate.wait
3413
+ for (let turn = 0; res.requeue && !freeGift && turn < REQUEUE_MAX; turn++) {
3414
+ own.slot?.release()
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
3419
+ if (edgeHeld()) return kept(edgeHeldAnswer())
3420
+ if (busyHeld()) return kept(busyHeldAnswer())
3421
+ res = await askBusy(url, opts, h, () => busyCap(gateKey))
3422
+ }
3249
3423
  } catch (e) {
3250
3424
  // free first moved the request onto the gift, so a gift that
3251
3425
  // cannot be asked at all — the network, the host — is answered
@@ -3455,4 +3629,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3455
3629
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
3456
3630
  // out of reach, undefined forgets it
3457
3631
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
3458
- 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, 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,41 +1,19 @@
1
1
  {
2
2
  "name": "@jianmu-plugins/opencode-zcode-auth",
3
- "version": "0.1.61",
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",
7
- "exports": {
8
- ".": "./opencode2.mjs"
9
- },
10
- "files": [
11
- "index.mjs",
12
- "opencode.mjs",
13
- "opencode2.mjs",
14
- "prompt.mjs",
15
- "README.md"
16
- ],
17
- "keywords": [
18
- "opencode",
19
- "opencode-plugin",
20
- "magpie",
21
- "zcode",
22
- "z.ai",
23
- "bigmodel",
24
- "glm",
25
- "coding-plan"
26
- ],
7
+ "exports": { ".": "./opencode2.mjs" },
8
+ "files": ["index.mjs", "opencode.mjs", "opencode2.mjs", "prompt.mjs", "README.md"],
9
+ "keywords": ["opencode", "opencode-plugin", "magpie", "zcode", "z.ai", "bigmodel", "glm", "coding-plan"],
27
10
  "license": "MIT",
28
11
  "repository": {
29
12
  "type": "git",
30
- "url": "git+https://github.com/TopoReduce/plugins.git",
13
+ "url": "git+https://github.com/magpie-community/plugins.git",
31
14
  "directory": "packages/zcode"
32
15
  },
33
16
  "magpie": {
34
- "maxConcurrency": 3,
35
- "maxAccounts": 2
36
- },
37
- "jianmu": {
38
- "maxConcurrency": 3,
39
- "maxAccounts": 2
17
+ "maxConcurrency": 3
40
18
  }
41
19
  }