@magpie-community/opencode-zcode-auth 0.1.37 → 0.1.38

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 +38 -0
  2. package/index.mjs +120 -17
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -134,6 +134,44 @@ plan's own in-flight cap (3008/3009) does not: such a request is asked
134
134
  again instead (see [A few at once](#a-few-at-once)). A stream's body is
135
135
  never read or buffered on the way.
136
136
 
137
+ **Free first.** Picking `-Trial` by hand keeps the choice the user's,
138
+ but an agent that always asks the plain model never sees the gift.
139
+ `freeFirst` turns the preference around: the plain model spends the
140
+ account's own live gift first, and falls back to the coding plan when
141
+ the gift cannot serve it — a bucket that is spent, a model the gift
142
+ does not serve, no ZCode session, or the minute's rest a refusal just
143
+ earned. Turn it on for the whole plugin in magpie's Plugins › Options
144
+
145
+ ```json
146
+ { "freeFirst": true }
147
+ ```
148
+
149
+ or on the provider alone, under `provider.zcode.options` in the config
150
+ magpie hands its plugins — a key only `plugins.json`'s `config` carries,
151
+ so the plugin's own options are the ones magpie's Plugins › Options
152
+ edits. Where both say something, the provider's word stands. An account
153
+ with a coding plan and a gift spends the gift until it is spent, then
154
+ the plan; a gift-only account already goes to the gift by its plain
155
+ names, so the option changes nothing there. Across the accounts magpie
156
+ rotates, each spends its own gift before its own plan — which is the
157
+ point: free allowance is spent before subscribed quota, on every
158
+ account, with no per-account naming to keep up.
159
+
160
+ Two boundaries worth knowing. The gift is judged before the request is
161
+ sent, from the balance read the plugin keeps for ten minutes: a gift
162
+ that runs out between that read and the send has its refusal answered
163
+ from the plan in the same request — any gift failure is, its own
164
+ waited-out busy cap included, and the replay waits out the plan's busy
165
+ cap as any plan request does — and a spent answer or a block page rests
166
+ the model a minute and drops the route's balance read, so the requests
167
+ behind it go straight to the plan. A gift that cannot be asked at all —
168
+ the network, the host — is answered from the plan the same way, the
169
+ route read dropped for the next request, while a caller's own abort
170
+ stays an abort. The agent sees the plan's answer
171
+ either way. And the `-Trial` entries keep their own strict semantics —
172
+ asking one is still an explicit pick of the gift alone, never the plan;
173
+ a spent one answers 429 with freeFirst on, as it does without it.
174
+
137
175
  ## A few at once
138
176
 
139
177
  A plan serves one account a few requests at a time; past that, ZCode
package/index.mjs CHANGED
@@ -1731,6 +1731,28 @@ function busyAnswer(res, text) {
1731
1731
  })
1732
1732
  }
1733
1733
 
1734
+ // askBusy asks once and, when the answer is the vendor's in-flight cap
1735
+ // (3008/3009, or its own words), asks again through BUSY_WAITS's waits, a
1736
+ // quarter of a second and longer — about ten seconds of them. Past that the
1737
+ // account is saturated rather than busy, and the cap goes back as
1738
+ // busyAnswer's 429. The plan path's patience, shared with free first's
1739
+ // replay, whose plan has a cap of its own.
1740
+ async function askBusy(u, o, hs) {
1741
+ let res = await fetch(u, { ...o, headers: hs })
1742
+ for (let i = 0; res.status === 429; i++) {
1743
+ const text = await res.text()
1744
+ const cap = busy(429, text)
1745
+ if (!cap || i >= BUSY_WAITS.length) {
1746
+ res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
1747
+ break
1748
+ }
1749
+ const w = BUSY_WAITS[i]
1750
+ await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
1751
+ res = await fetch(u, { ...o, headers: hs })
1752
+ }
1753
+ return res
1754
+ }
1755
+
1734
1756
  function model(m, url) {
1735
1757
  const e = entry(m)
1736
1758
  return {
@@ -2119,12 +2141,17 @@ function sessionOf(id, device) {
2119
2141
 
2120
2142
  // ---- the plugin ------------------------------------------------------------------
2121
2143
 
2122
- export async function ZCodeAuthPlugin({ client }) {
2144
+ export async function ZCodeAuthPlugin({ client }, options = {}) {
2123
2145
  const log = (message) => {
2124
2146
  try {
2125
2147
  client?.app?.log?.({ body: { service: "zcode-auth", level: "error", message } })
2126
2148
  } catch {}
2127
2149
  }
2150
+ // freeFirst reads the option from the provider config's options first,
2151
+ // and from the plugin's own (magpie's Plugins › Options) when the
2152
+ // provider carries no freeFirst of its own.
2153
+ const freeFirst = (providerOptions) =>
2154
+ providerOptions?.freeFirst !== undefined ? providerOptions.freeFirst === true : options?.freeFirst === true
2128
2155
  const oauth = (site) => ({
2129
2156
  type: "oauth",
2130
2157
  label: `ZCode: ${SITES[site].name}${site === "bigmodel" ? " (智谱)" : ""} GLM Coding Plan`,
@@ -2230,7 +2257,8 @@ export async function ZCodeAuthPlugin({ client }) {
2230
2257
  // a dual account's body is read ahead of sending, so a gift that
2231
2258
  // says it is spent can spend nothing and replay what was asked for
2232
2259
  let start = alone
2233
- let orig, forcedGift = false
2260
+ let orig, forcedGift = false, freeGift = false
2261
+ let asked = ""
2234
2262
  let renamed = false
2235
2263
  const done = (res) => (renamed ? searchNamed(res) : res)
2236
2264
  if (opts.body != null) {
@@ -2244,6 +2272,7 @@ export async function ZCodeAuthPlugin({ client }) {
2244
2272
  renamed = true
2245
2273
  }
2246
2274
  let m = modelOf(orig)
2275
+ asked = m
2247
2276
  if (m.toLowerCase().endsWith("-trial")) {
2248
2277
  gift ??= await startPlan(s.jwt, s.device).catch(() => null)
2249
2278
  const raw = giftModel(gift, m)
@@ -2255,8 +2284,21 @@ export async function ZCodeAuthPlugin({ client }) {
2255
2284
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: raw })
2256
2285
  m = raw
2257
2286
  forcedGift = true
2287
+ } else if (!alone && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m)) {
2288
+ // free first: the plain model spends the account's own live
2289
+ // gift before it spends the coding plan, under the name the
2290
+ // gift lists. The gift is the route's cache alone (a failed
2291
+ // read cached its why), so a gift that cannot be read keeps
2292
+ // the request on the plan with no read per request; a
2293
+ // gift-only account is already on the gift and is left as
2294
+ // it was. A refusal past this check is replayed on the plan
2295
+ // in the same request (replayOnPlan below).
2296
+ const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
2297
+ orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: raw })
2298
+ m = raw
2299
+ freeGift = true
2258
2300
  }
2259
- start = alone || forcedGift
2301
+ start = alone || forcedGift || freeGift
2260
2302
  }
2261
2303
  const swap = (base) => {
2262
2304
  for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
@@ -2267,8 +2309,41 @@ export async function ZCodeAuthPlugin({ client }) {
2267
2309
  }
2268
2310
  }
2269
2311
  let h = new Headers(opts.headers)
2312
+ const askedUrl = url
2270
2313
  const place = workPlace(h)
2271
2314
  const sid = sessionOf(h.get("x-session-id"), s.device)
2315
+ // restModel is the gift saying this model has nothing left: the
2316
+ // model rests a minute (blocked) and the route is dropped, so
2317
+ // the requests behind it re-read the balance and go straight to
2318
+ // the plan.
2319
+ const restModel = () => {
2320
+ for (const [k, until] of blocked) if (Date.now() >= until) blocked.delete(k)
2321
+ blocked.set(s.key + "\0" + s.jwt + "\0" + asked.toLowerCase(), Date.now() + 60_000)
2322
+ routes.delete(s.key + "\0" + s.jwt)
2323
+ }
2324
+ // replayOnPlan is free first's answer to a gift that refused
2325
+ // what its own balance read had promised: the model as the
2326
+ // agent sent it, the plan's headers, the plan's own patience
2327
+ // (askBusy).
2328
+ const replayOnPlan = async () => {
2329
+ let u = askedUrl
2330
+ for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
2331
+ if (u.startsWith(b)) {
2332
+ u = s.base + u.slice(b.length)
2333
+ break
2334
+ }
2335
+ }
2336
+ const h2 = new Headers(opts.headers)
2337
+ workPlace(h2)
2338
+ h2.set("x-session-id", sid)
2339
+ h2.delete("authorization")
2340
+ h2.set("x-api-key", key)
2341
+ h2.set("Authorization", "Bearer " + key)
2342
+ h2.delete("content-length")
2343
+ opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid)
2344
+ delete opts.duplex
2345
+ return askBusy(u, opts, h2)
2346
+ }
2272
2347
  if (start) {
2273
2348
  if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
2274
2349
  if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
@@ -2306,20 +2381,18 @@ export async function ZCodeAuthPlugin({ client }) {
2306
2381
  // magpie sends every agent's and every session's requests of this
2307
2382
  // computer through this one process, and its queue spaces them by
2308
2383
  // the number declared above
2309
- const ask = () => fetch(url, { ...opts, headers: h })
2310
- let res = await ask()
2311
- for (let i = 0; res.status === 429; i++) {
2312
- const text = await res.text()
2313
- const cap = busy(429, text)
2314
- if (!cap || i >= BUSY_WAITS.length) {
2315
- res = cap
2316
- ? busyAnswer(res, text)
2317
- : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
2318
- break
2319
- }
2320
- const w = BUSY_WAITS[i]
2321
- await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
2322
- res = await ask()
2384
+ let res
2385
+ try {
2386
+ res = await askBusy(url, opts, h)
2387
+ } catch (e) {
2388
+ // free first moved the request onto the gift, so a gift that
2389
+ // cannot be asked at all — the network, the host — is answered
2390
+ // from the plan; the route read is dropped, so the next
2391
+ // request learns whether the host is back. A caller's abort
2392
+ // stays an abort.
2393
+ if (!freeGift || opts.signal?.aborted || e?.name === "AbortError") throw e
2394
+ routes.delete(s.key + "\0" + s.jwt)
2395
+ res = await replayOnPlan()
2323
2396
  }
2324
2397
  // the Start Plan turning the request away says what to do about
2325
2398
  // it: the account blocked, or the network
@@ -2329,6 +2402,10 @@ export async function ZCodeAuthPlugin({ client }) {
2329
2402
  // a key account sent to the Start Plan (its plan list read
2330
2403
  // none) reads its plans again on the next request, so a
2331
2404
  // coding plan that is there after all is used (#369)
2405
+ if (freeGift) {
2406
+ restModel()
2407
+ return done(kept(await replayOnPlan()))
2408
+ }
2332
2409
  if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt)
2333
2410
  return kept(startBlocked(res, text))
2334
2411
  }
@@ -2361,6 +2438,32 @@ export async function ZCodeAuthPlugin({ client }) {
2361
2438
  return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text))
2362
2439
  }
2363
2440
  }
2441
+ // free first's gift answer: the choice was the plugin's, so the
2442
+ // plan answers what the gift would fail — a spent bucket and a
2443
+ // refusal like any other 4xx or 5xx among them, the gift's own
2444
+ // waited-out busy cap included, since the plan's cap is its own.
2445
+ // A spent answer or a block page rests the model a minute and
2446
+ // drops the route read; a 401/403 drops the read alone, so the
2447
+ // next request learns whether the session is gone. Anything
2448
+ // else — a 200 carrying the answer — goes on as it came. A
2449
+ // stream's body is never read here.
2450
+ else if (start && freeGift) {
2451
+ const json = (res.headers.get("content-type") ?? "").includes("application/json")
2452
+ if (res.status >= 400 || json) {
2453
+ const text = await res.text()
2454
+ const cap = busy(res.status, text)
2455
+ const spent = !cap && spentUp(text, res.status)
2456
+ if (spent) {
2457
+ restModel()
2458
+ return done(kept(await replayOnPlan()))
2459
+ }
2460
+ if (res.status >= 400) {
2461
+ if (!cap && (res.status === 401 || res.status === 403)) routes.delete(s.key + "\0" + s.jwt)
2462
+ return done(kept(await replayOnPlan()))
2463
+ }
2464
+ return done(kept(res, text))
2465
+ }
2466
+ }
2364
2467
  // the plan's answer goes on as it came, the account kept: the
2365
2468
  // built-in never marked a ZCode account lapsed nor cleared one
2366
2469
  return done(kept(res))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.37",
3
+ "version": "0.1.38",
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": "./index.mjs",