@magpie-community/opencode-zcode-auth 0.1.30 → 0.1.32

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 +37 -4
  2. package/index.mjs +226 -17
  3. package/package.json +4 -1
package/README.md CHANGED
@@ -30,7 +30,8 @@ over Anthropic's Messages API. Provider id: `zcode`.
30
30
  request, and the plan's endpoint keeps a prompt cache on the machine it
31
31
  picks by it, so without it the cache is mostly missed (#387). An
32
32
  account known only by its key gets a device id made from the key, the
33
- same on every start. zcode.z.ai also
33
+ same on every start. Every request also carries the `x-session-id`
34
+ header below. zcode.z.ai also
34
35
  answers 405 code 3012 to every request of an account its risk control
35
36
  blocked, ZCode's own app's included (plugins#348). That answer comes
36
37
  back as ZCode's words, then "ZCode's risk control blocked this account
@@ -40,6 +41,14 @@ over Anthropic's Messages API. Provider id: `zcode`.
40
41
  firewall says this network's address was blocked instead.
41
42
  - The Start Plan's token can't be refreshed. When it runs out, sign in
42
43
  again.
44
+ - Every request, on any plan, names its conversation in `x-session-id`,
45
+ as ZCode does: a bare UUID, the same on each turn. BigModel's prompt
46
+ cache follows it: without it a long conversation's turns hit the cache
47
+ about one time in twenty, with it nearly every turn (#387). The
48
+ agent's own session id (magpie tells it to the plugin) goes as it is
49
+ when it is a UUID, else as a UUID made from it, so the vendor sees
50
+ only ZCode's format; with none, a UUID made from the device. The same
51
+ id is `metadata.user_id`'s `session_id`, as in ZCode's requests.
43
52
  - **ZCode: a team's GLM Coding Plan**
44
53
  - For an account with a plan of its own and a seat on a team's plan
45
54
  (#285). The sign-ins above take the account's own plan, as ZCode does
@@ -119,9 +128,33 @@ coding plan; when the gift answers a trial entry with a quota error
119
128
  "exceed quota limit", which it can answer inside an HTTP 200) that too
120
129
  becomes a 429 and keeps the entry off for a minute. Any other gift
121
130
  answer (its 405, its 401, its 5xx) goes on as it came: the user picked
122
- the gift, so the coding plan is not spent behind their back. Every 429
123
- counts as spent, Z.ai's 1302/1303 rate limits among them. A stream's
124
- body is never read or buffered on the way.
131
+ the gift, so the coding plan is not spent behind their back. Every other
132
+ 429 counts as spent — Z.ai's 1302/1303 rate limits among them — while the
133
+ plan's own in-flight cap (3008/3009) does not: such a request is asked
134
+ again instead (see [A few at once](#a-few-at-once)). A stream's body is
135
+ never read or buffered on the way.
136
+
137
+ ## A few at once
138
+
139
+ A plan serves one account a few requests at a time; past that, ZCode
140
+ answers 429 with code 3008 "user concurrency limit exceeded", or 3009
141
+ "model concurrency limit exceeded". magpie funnels every agent's and every
142
+ session's requests of one computer through this one plugin process, so
143
+ magpie's own queue spaces an account's requests by the number this plugin
144
+ declares — `maxConcurrency` on the auth hook, and `magpie.maxConcurrency`
145
+ in its `package.json`, both three. A request the vendor refuses anyway
146
+ waits a moment (a quarter of a second, then longer — about ten seconds of
147
+ waits in all) and asks again, the same request byte for byte. A cap that
148
+ outlasts the waits goes on as it came, ZCode's words followed by what it
149
+ is, so magpie can move that request along instead of resting the account.
150
+
151
+ Three is a default, not a cap the plugin enforces. A plan's real cap
152
+ follows its tier — Z.ai serves a Max plan more at once than a Pro, and a
153
+ Lite fewer — and is higher off-peak
154
+ ([Z.ai's usage policy](https://docs.z.ai/devpack/usage-policy)), so a
155
+ number written into the plugin would hold a Max account to a Lite one's
156
+ with no way to raise it. A user who knows their plan's cap sets it on the
157
+ account or the provider in magpie, and magpie's queue follows that.
125
158
 
126
159
  ## The usage card
127
160
 
package/index.mjs CHANGED
@@ -50,12 +50,15 @@ const siteOf = (s) => (s === "bigmodel" ? "bigmodel" : "zai")
50
50
  const platform = () => `${process.platform}-${process.arch}` // darwin-arm64, win32-x64, linux-x64, as ZCode names them
51
51
  const uuid = () => crypto.randomUUID()
52
52
  const anyDevice = uuid() // X-Device-Mid for calls made signed out (the model list)
53
- // keyDevice is a device id for an account known only by its key: the same
54
- // key gives the same id on every start, as a sign-in's saved device does
55
- const keyDevice = (key) => {
56
- const h = createHash("sha256").update("zcode-device\0" + key).digest("hex")
53
+ // uuidOf is a version 4 shaped UUID made from a seed: the same seed gives
54
+ // the same UUID every time
55
+ const uuidOf = (seed) => {
56
+ const h = createHash("sha256").update(seed).digest("hex")
57
57
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h[16], 16) & 3) | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`
58
58
  }
59
+ // keyDevice is a device id for an account known only by its key: the same
60
+ // key gives the same id on every start, as a sign-in's saved device does
61
+ const keyDevice = (key) => uuidOf("zcode-device\0" + key)
59
62
  const first = (...ss) => ss.map((s) => (typeof s === "string" ? s.trim() : "")).find((s) => s) ?? ""
60
63
 
61
64
  // STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
@@ -262,9 +265,11 @@ const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) &&
262
265
 
263
266
  // spentUp is the gift saying it has nothing left to spend: its own no-
264
267
  // resource-package code 1113, its "exceed quota limit" 1005 — a spent gift
265
- // can answer a 200 with a JSON body carrying one of those codes. Every 429
266
- // counts as spent, Z.ai's 1302/1303 rate limits among them.
268
+ // can answer a 200 with a JSON body carrying one of those codes. Every other
269
+ // 429 counts as spent, Z.ai's 1302/1303 rate limits among them; the plan's
270
+ // own in-flight cap (3008/3009) does not, since it is a turn not yet come.
267
271
  function spentUp(text, status) {
272
+ if (busy(status, text)) return false
268
273
  if (status === 429) return true
269
274
  let b
270
275
  try { b = JSON.parse(text) } catch { return false }
@@ -1197,6 +1202,86 @@ function configKey(key) {
1197
1202
  return null
1198
1203
  }
1199
1204
 
1205
+ // ownLocation is where ZCode 3.16 finds the account's own coding plan key
1206
+ // when it keeps none: credentials.json's
1207
+ // project-key-location:v1:<[origin, family, accountId, team, 1, selection]>,
1208
+ // URI-encoded JSON, holds { organizationId, projectId, apiKeyId } (its
1209
+ // ProjectAccessTokenClient). ZCode trades that key for a short-lived
1210
+ // project token each time; here its secret is read (located), as a sign-in
1211
+ // here reads its own key's. The account's own (team null), of the family
1212
+ // ZCode is on first, else Z.ai's, as ZCode lists them; one of another
1213
+ // account the profile names is left alone (meraki7304, #410).
1214
+ const LOCATION = "project-key-location:v1:"
1215
+ function ownLocation(store, key) {
1216
+ const set = readJSON(join(settingDir(), "setting.json"))
1217
+ const fams = set?.providerFamilyDomain === "bigmodel" ? ["bigmodel", "zai"] : ["zai", "bigmodel"]
1218
+ const found = []
1219
+ for (const [name, v] of Object.entries(store)) {
1220
+ if (!name.startsWith(LOCATION)) continue
1221
+ let at
1222
+ try {
1223
+ at = JSON.parse(decodeURIComponent(name.slice(LOCATION.length)))
1224
+ } catch {
1225
+ continue
1226
+ }
1227
+ if (!Array.isArray(at) || at[3] !== null || String(at[4]) !== "1" || !fams.includes(at[1])) continue
1228
+ let loc
1229
+ try {
1230
+ loc = JSON.parse(decrypt(key, v) ?? "")
1231
+ } catch {}
1232
+ const org = first(loc?.organizationId), project = first(loc?.projectId), apiKeyId = first(loc?.apiKeyId)
1233
+ if (!org || !project || !apiKeyId) continue
1234
+ found.push({ site: at[1], origin: typeof at[0] === "string" ? at[0] : "", account: String(at[2] ?? ""), org, project, apiKeyId })
1235
+ }
1236
+ for (const site of fams) {
1237
+ const token = first(decrypt(key, store[`oauth:${site}:access_token`]))
1238
+ if (!token) continue
1239
+ let me = ""
1240
+ try {
1241
+ me = String(JSON.parse(decrypt(key, store[`oauth:${site}:user_info`]) ?? "{}")?.id ?? "")
1242
+ } catch {}
1243
+ const mine = found.filter((l) => l.site === site && (!me || l.account === me))
1244
+ if (!mine.length) continue
1245
+ const l = mine[0]
1246
+ // the origin ZCode asked, when it is the site's own; else the site's API
1247
+ let origin = SITES[site].api
1248
+ try {
1249
+ const u = new URL(l.origin)
1250
+ const h = u.host.toLowerCase()
1251
+ if (u.protocol === "https:" && (site === "zai" ? h === "z.ai" || h.endsWith(".z.ai") : h === "bigmodel.cn" || h.endsWith(".bigmodel.cn"))) origin = u.origin
1252
+ } catch {}
1253
+ return { site, base: SITES[site].base, token, loc: { origin, org: l.org, project: l.project, apiKeyId: l.apiKeyId } }
1254
+ }
1255
+ return null
1256
+ }
1257
+
1258
+ // located gives a sign-in that has only ZCode's key location (ownLocation)
1259
+ // its key: the secret of the key it names, read as ZCode lists the
1260
+ // project's keys (BigModel's token bare, Z.ai's as a Bearer). Nothing is
1261
+ // made: a location whose key is gone (404) leaves the sign-in keyless, as
1262
+ // before; any other failure is said. A key read is kept for the token.
1263
+ const locatedKeys = new Map()
1264
+ async function located(s) {
1265
+ if (!s || s.key || !s.loc || !s.token) return s
1266
+ const l = s.loc
1267
+ const id = [s.token, l.origin, l.org, l.project, l.apiKeyId].join("\0")
1268
+ let got = locatedKeys.get(id)
1269
+ if (!got || (got.err && Date.now() - got.at >= 60_000)) {
1270
+ const auth = s.site === "zai" ? "Bearer " + s.token : s.token
1271
+ try {
1272
+ const secret = first((await call("GET", `${keysURL(l.origin, l.org, l.project)}/copy/${encodeURIComponent(l.apiKeyId)}`, { auth }))?.secretKey)
1273
+ got = secret ? { key: `${l.apiKeyId}.${secret}` } : { err: new Error("no secret for the key") }
1274
+ } catch (e) {
1275
+ got = e?.status === 404 ? { key: "" } : { err: e }
1276
+ }
1277
+ got.at = Date.now()
1278
+ locatedKeys.set(id, got)
1279
+ }
1280
+ if (got.err) throw new Error(`ZCode's ${SITES[s.site].name} coding plan key: ${got.err.message} — sign in to ZCode again`)
1281
+ if (got.key) s.key = got.key
1282
+ return s
1283
+ }
1284
+
1200
1285
  // ownSignIn is what ZCode is signed in to now: the account, its coding
1201
1286
  // plan key, ZCode's session token (the Start Plan's key) and the team plan
1202
1287
  // it is switched to; null when it has none of them.
@@ -1217,6 +1302,8 @@ function ownSignIn() {
1217
1302
  // ZCode 3.15 keeps no plan key in its credentials; the one it uses sits
1218
1303
  // in config.json, the provider's options.apiKey (yetone/magpie#2130)
1219
1304
  if (!s.key) s = configKey(key) || s
1305
+ // ZCode 3.16 keeps neither: only where the key is (#410)
1306
+ if (!s.key) s = ownLocation(store, key) || s
1220
1307
  const jwt = first(first(decrypt(key, store.zcodejwttoken)).replace(/^Bearer /, ""))
1221
1308
  const team = ownTeam(store, key)
1222
1309
  if (team) s = { ...team, jwt }
@@ -1431,6 +1518,71 @@ function kept(res, text) {
1431
1518
  return new Response(text !== undefined ? text : res.body, { status: res.status, statusText: res.statusText, headers: h })
1432
1519
  }
1433
1520
 
1521
+ // ---- the plan's concurrency ------------------------------------------------------
1522
+ // ZCode serves one account a few requests at a time. Past that it answers 429
1523
+ // with code 3008, "user concurrency limit exceeded", or 3009, "model
1524
+ // concurrency limit exceeded": the request's turn has not come — not a plan
1525
+ // spent (1113/1005) and not a rate limit (1302/1303). magpie sends every
1526
+ // agent's and every session's requests of this computer through this one
1527
+ // process, and its own queue spaces an account's requests by the number
1528
+ // declared below (DEFAULT_CONCURRENCY, on the auth hook and in package.json);
1529
+ // a request the vendor refuses anyway waits a moment and asks again, the same
1530
+ // bytes. A refusal is immediate while a turn's answer is not, so a redundant
1531
+ // ask costs a round trip and no tokens.
1532
+ //
1533
+ // The plugin keeps no gate of its own: a plan's cap depends on its tier (Z.ai
1534
+ // serves Max more at once than Pro, and Lite fewer) and is higher off-peak
1535
+ // (https://docs.z.ai/devpack/usage-policy), so a number written here would
1536
+ // hold a Max account to a Lite one's, with no way for the user to raise it.
1537
+ const DEFAULT_CONCURRENCY = 3
1538
+ const BUSY_CODES = new Set(["3008", "3009"])
1539
+ // BUSY_WAITS are the waits between asks, longest last: about ten seconds of
1540
+ // them. Past that the account is saturated rather than busy, and magpie's
1541
+ // routing takes the request (or rests the account, as its 429 says).
1542
+ const BUSY_WAITS = [250, 500, 900, 1600, 2800, 4000]
1543
+ const BUSY_HINT =
1544
+ "ZCode serves one account a few requests at a time, and every agent and session of this computer asks through magpie; this request came behind the others, and the same request a moment later is served"
1545
+
1546
+ // busy says a 429 is that in-flight cap: its own code (3008, 3009), or its
1547
+ // own words when the envelope carries no code.
1548
+ function busy(status, text) {
1549
+ if (status !== 429) return false
1550
+ let b
1551
+ try {
1552
+ b = JSON.parse(text)
1553
+ } catch {
1554
+ return false
1555
+ }
1556
+ if (!b || typeof b !== "object") return false
1557
+ const say = (v) => (v == null || typeof v === "object" ? "" : String(v))
1558
+ if (BUSY_CODES.has(say(b.code) || say(b.error?.code))) return true
1559
+ return /concurrency limit exceeded/i.test(say(b.msg) + " " + say(b.message) + " " + say(b.error?.message) + " " + say(b.error))
1560
+ }
1561
+
1562
+ // busyAnswer is the vendor's cap refusal as the agent reads it: its words,
1563
+ // then what they are and what to do, as noPlanKey says why a key has no plan.
1564
+ function busyAnswer(res, text) {
1565
+ const h = new Headers(res.headers)
1566
+ h.set("content-type", "application/json")
1567
+ let v
1568
+ try {
1569
+ v = JSON.parse(text)
1570
+ } catch {}
1571
+ if (v && typeof v === "object") {
1572
+ const said = first(v.msg, v.message, v.error?.message, typeof v.error === "string" ? v.error : "", `${res.status}`)
1573
+ const code = v.code ?? v.error?.code
1574
+ const head = code != null && !said.includes(String(code)) ? `${said} (${res.status}, code ${code})` : said
1575
+ const message = `${head} — ${BUSY_HINT}`
1576
+ const out = v.error && typeof v.error === "object" ? { ...v, error: { ...v.error, message } } : { ...v, msg: message }
1577
+ return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h })
1578
+ }
1579
+ return new Response(JSON.stringify({ type: "error", error: { type: "rate_limit_error", message: `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText} — ${BUSY_HINT}`.trim() } }), {
1580
+ status: res.status,
1581
+ statusText: res.statusText,
1582
+ headers: h,
1583
+ })
1584
+ }
1585
+
1434
1586
  function model(m, url) {
1435
1587
  const e = entry(m)
1436
1588
  return {
@@ -1732,7 +1884,7 @@ function contextPrefix() {
1732
1884
  // sign-in's device. site names the powered-by line's provider, place where
1733
1885
  // the agent works (workPlace). A body that isn't a Messages request goes as
1734
1886
  // it is.
1735
- function dress(text, site, device, place) {
1887
+ function dress(text, site, device, place, session) {
1736
1888
  if (typeof text !== "string" || !text.includes("messages")) return text
1737
1889
  let b
1738
1890
  try {
@@ -1772,7 +1924,7 @@ function dress(text, site, device, place) {
1772
1924
  }
1773
1925
  if (Array.isArray(b.tools)) for (const t of b.tools) if (t && typeof t === "object") delete t.cache_control
1774
1926
  const meta = b.metadata && typeof b.metadata === "object" ? b.metadata : {}
1775
- b.metadata = { ...meta, user_id: userIdOf(device) }
1927
+ b.metadata = { ...meta, user_id: userIdOf(device, session) }
1776
1928
  return JSON.stringify(b)
1777
1929
  }
1778
1930
 
@@ -1780,13 +1932,14 @@ function dress(text, site, device, place) {
1780
1932
  // MLs and vWr) puts it on every Anthropic-format request, a coding plan's
1781
1933
  // too: the machine's device id, no account uuid. The plan's endpoint keeps
1782
1934
  // a prompt cache on the machine it picks by it, so a request without it
1783
- // lands anywhere and its cache is mostly missed (#387).
1784
- const userIdOf = (device) => JSON.stringify({ device_id: device, account_uuid: "", session_id: "" })
1935
+ // lands anywhere and its cache is mostly missed (#387). Its session_id is
1936
+ // the request's x-session-id (sessionOf), as ZCode's is.
1937
+ const userIdOf = (device, session = "") => JSON.stringify({ device_id: device, account_uuid: "", session_id: session })
1785
1938
 
1786
1939
  // marked is a coding plan's Messages request body with metadata.user_id
1787
1940
  // as ZCode sends it, when the agent sent none of its own. Anything else,
1788
1941
  // a body that isn't a Messages request among them, goes as it is.
1789
- function marked(text, device) {
1942
+ function marked(text, device, session) {
1790
1943
  if (typeof text !== "string" || !device || !text.includes("messages")) return text
1791
1944
  let b
1792
1945
  try {
@@ -1797,10 +1950,25 @@ function marked(text, device) {
1797
1950
  if (!b || typeof b !== "object" || Array.isArray(b) || !Array.isArray(b.messages)) return text
1798
1951
  const meta = b.metadata && typeof b.metadata === "object" && !Array.isArray(b.metadata) ? b.metadata : {}
1799
1952
  if (typeof meta.user_id === "string" && meta.user_id.trim()) return text
1800
- b.metadata = { ...meta, user_id: userIdOf(device) }
1953
+ b.metadata = { ...meta, user_id: userIdOf(device, session) }
1801
1954
  return JSON.stringify(b)
1802
1955
  }
1803
1956
 
1957
+ // sessionOf is the x-session-id a request goes with, as ZCode's client
1958
+ // (3.14.3, glm/zcode.cjs xst and Tst) sends it: a bare UUID, the same on
1959
+ // every turn of a conversation. BigModel keeps a prompt's cache for the
1960
+ // requests that name the same session and seldom for those that name none
1961
+ // (#387). The agent's session (chat.headers below) goes as it is when it is
1962
+ // a UUID, else as a UUID made from it, so the vendor sees only ZCode's
1963
+ // format, never magpie's or another agent's; with none, a UUID made from
1964
+ // the device.
1965
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
1966
+ function sessionOf(id, device) {
1967
+ const own = typeof id === "string" ? id.trim() : ""
1968
+ if (UUID.test(own)) return own.toLowerCase()
1969
+ return uuidOf(own ? "zcode-session\0" + own : "zcode-session-device\0" + (device ?? ""))
1970
+ }
1971
+
1804
1972
  // ---- the plugin ------------------------------------------------------------------
1805
1973
 
1806
1974
  export async function ZCodeAuthPlugin({ client }) {
@@ -1815,6 +1983,14 @@ export async function ZCodeAuthPlugin({ client }) {
1815
1983
  authorize: () => authorize(site, log),
1816
1984
  })
1817
1985
  return {
1986
+ // the agent's session, which magpie tells the plugins here and not
1987
+ // in the request, goes on as x-session-id (sessionOf)
1988
+ "chat.headers": async (input, output) => {
1989
+ const provider = input?.model?.providerID ?? input?.provider?.info?.id
1990
+ if (provider !== PROVIDER) return
1991
+ const id = input?.sessionID
1992
+ if (typeof id === "string" && id.trim()) output.headers["x-session-id"] = sessionOf(id)
1993
+ },
1818
1994
  config: async (cfg) => {
1819
1995
  cfg.provider ??= {}
1820
1996
  const was = cfg.provider[PROVIDER] ?? {}
@@ -1870,6 +2046,12 @@ export async function ZCodeAuthPlugin({ client }) {
1870
2046
  },
1871
2047
  auth: {
1872
2048
  provider: PROVIDER,
2049
+ // a plan serves one account a few requests at a time: magpie's own
2050
+ // field, so its queue spaces what the agents ask for before the vendor
2051
+ // sees it. This is a default, not a cap the plugin enforces — a plan's
2052
+ // own cap follows its tier (Max > Pro > Lite) and the time of day, and
2053
+ // a user who knows theirs can raise this on the account
2054
+ maxConcurrency: DEFAULT_CONCURRENCY,
1873
2055
  async loader(getAuth, provider) {
1874
2056
  const s0 = stateOf(await getAuth())
1875
2057
  if (!s0) return {}
@@ -1879,7 +2061,7 @@ export async function ZCodeAuthPlugin({ client }) {
1879
2061
  apiKey: s0.key || "zcode", // the fetch below puts the real one on
1880
2062
  async fetch(input, init) {
1881
2063
  const auth = await getAuth()
1882
- const s = stateOf(auth)
2064
+ const s = await located(stateOf(auth))
1883
2065
  if (!s) throw new Error("not signed in to ZCode")
1884
2066
  let url = input instanceof Request ? input.url : String(input)
1885
2067
  const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
@@ -1934,6 +2116,7 @@ export async function ZCodeAuthPlugin({ client }) {
1934
2116
  }
1935
2117
  let h = new Headers(opts.headers)
1936
2118
  const place = workPlace(h)
2119
+ const sid = sessionOf(h.get("x-session-id"), s.device)
1937
2120
  if (start) {
1938
2121
  if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
1939
2122
  if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
@@ -1941,9 +2124,10 @@ export async function ZCodeAuthPlugin({ client }) {
1941
2124
  // the Start Plan is served only to what looks like ZCode's own request
1942
2125
  url = startURL(url)
1943
2126
  h = startHeaders(h, s.jwt)
2127
+ h.set("x-session-id", sid)
1944
2128
  if (opts.body != null) {
1945
2129
  const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text())
1946
- opts.body = dress(text, s.site, s.device, place)
2130
+ opts.body = dress(text, s.site, s.device, place, sid)
1947
2131
  delete opts.duplex
1948
2132
  h.delete("content-length")
1949
2133
  }
@@ -1954,17 +2138,37 @@ export async function ZCodeAuthPlugin({ client }) {
1954
2138
  // count_tokens and other paths ZCode never sends go as they are
1955
2139
  if (opts.body != null && /\/v1\/messages$/.test(new URL(url).pathname)) {
1956
2140
  const text = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
1957
- const next = marked(text, s.device)
2141
+ const next = marked(text, s.device, sid)
1958
2142
  if (next !== text) h.delete("content-length")
1959
2143
  opts.body = next
1960
2144
  delete opts.duplex
1961
2145
  }
1962
2146
  if (renamed) h.delete("content-length")
2147
+ h.set("x-session-id", sid)
1963
2148
  h.delete("authorization")
1964
2149
  h.set("x-api-key", key)
1965
2150
  h.set("Authorization", "Bearer " + key)
1966
2151
  }
1967
- let res = await fetch(url, { ...opts, headers: h })
2152
+ // a refusal that is the account's or the model's own in-flight
2153
+ // cap is asked again a moment later (see the plan's concurrency):
2154
+ // magpie sends every agent's and every session's requests of this
2155
+ // computer through this one process, and its queue spaces them by
2156
+ // the number declared above
2157
+ const ask = () => fetch(url, { ...opts, headers: h })
2158
+ let res = await ask()
2159
+ for (let i = 0; res.status === 429; i++) {
2160
+ const text = await res.text()
2161
+ const cap = busy(429, text)
2162
+ if (!cap || i >= BUSY_WAITS.length) {
2163
+ res = cap
2164
+ ? busyAnswer(res, text)
2165
+ : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
2166
+ break
2167
+ }
2168
+ const w = BUSY_WAITS[i]
2169
+ await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
2170
+ res = await ask()
2171
+ }
1968
2172
  // the Start Plan turning the request away says what to do about
1969
2173
  // it: the account blocked, or the network
1970
2174
  if (start && res.status >= 400) {
@@ -2018,6 +2222,11 @@ export async function ZCodeAuthPlugin({ client }) {
2018
2222
  const auth = await getAuth()
2019
2223
  const s = stateOf(auth)
2020
2224
  if (!s) return { error: "not signed in", signIn: "kept" }
2225
+ try {
2226
+ await located(s)
2227
+ } catch (e) {
2228
+ return { error: e.message, signIn: "kept" }
2229
+ }
2021
2230
  // every card starts from the plan the sign-in saved, as magpie's
2022
2231
  // built-in did: a reply without a level, a team detail that
2023
2232
  // failed or an error keeps it
@@ -2112,4 +2321,4 @@ export async function ZCodeAuthPlugin({ client }) {
2112
2321
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2113
2322
  // out of reach, undefined forgets it
2114
2323
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
2115
- export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT, marked, keyDevice }
2324
+ export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.30",
3
+ "version": "0.1.32",
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",
@@ -12,5 +12,8 @@
12
12
  "type": "git",
13
13
  "url": "git+https://github.com/magpie-community/plugins.git",
14
14
  "directory": "packages/zcode"
15
+ },
16
+ "magpie": {
17
+ "maxConcurrency": 3
15
18
  }
16
19
  }