@magpie-community/opencode-qoder-auth 0.2.47 → 0.2.49

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 +15 -0
  2. package/index.mjs +113 -23
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -68,6 +68,21 @@ Refreshing:
68
68
  - Only one refresh runs at a time. A request that reads the sign-in before
69
69
  magpie saved a renewal uses the renewed pair, and a renewal handed a pair
70
70
  a request already spent gives what that request got.
71
+ - A job token's end is what Qoder says: `expire_time` or `expires_at` (a
72
+ date, or an epoch in seconds or milliseconds), then `expires_in`
73
+ (milliseconds), then a day.
74
+ - A chat Qoder answers 401 or 403 with no other code ("Login expired") is
75
+ sent again once: with the pair saved since, when another request, magpie
76
+ or another process renewed it meanwhile, else after one refresh, under the
77
+ same lock. A token renewed less than 5 minutes ago and refused again isn't
78
+ renewed again; the refusal is the answer.
79
+ - A model Qoder serves that the account's listing has off or leaves out is
80
+ asked for the same way: the job token is renewed once (or the pair saved
81
+ since is used) and the list read again, before the request is answered
82
+ `unknown or disabled model`. On a job token Qoder no longer honours in
83
+ full, the listing can have only the free models on (#484). The same
84
+ 5-minute rule holds, and an id Qoder has never served is said unknown at
85
+ once, with no renewal.
71
86
  - The device token, which reads usage, has no end on record: it is rotated
72
87
  when Qoder refuses it. On a [Qoder CN](#qoder-cn) device-token account it
73
88
  is the chat token too, and is renewed as above.
package/index.mjs CHANGED
@@ -56,6 +56,7 @@ const SIGN_IN_TIMEOUT = 15 * 60 * 1000
56
56
  const REFRESH_LEAD = 5 * 60 * 1000 // a chat token this close to its end is refreshed before a request
57
57
  const RENEW_LEAD = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh)
58
58
  const KEEP_SPENT_MS = 60 * 60 * 1000 // how long what a spent refresh token gave is remembered
59
+ const RELOGIN_GAP = 5 * 60 * 1000 // a token renewed this recently that Qoder refuses isn't renewed again
59
60
  const DAY = 24 * 60 * 60 * 1000
60
61
  const CHAT = "@ai-sdk/openai-compatible"
61
62
 
@@ -234,9 +235,33 @@ async function openapi(site, path, { method = "GET", token, body, query } = {})
234
235
  return { status: res.status, json, text }
235
236
  }
236
237
 
237
- // expiresAt is when a job token Qoder gave with expires_in (milliseconds)
238
- // runs out; a day when it said none.
239
- const expiresAt = (jt) => Date.now() + (jt.expires_in > 0 ? jt.expires_in : DAY)
238
+ // expiresAt is when a job token Qoder gave runs out, read as Qoder's own
239
+ // client reads it, for a refreshed token as for an exchanged PAT's: its
240
+ // expire_time or expires_at first (a date, or an epoch in seconds or
241
+ // milliseconds), then expires_in (milliseconds), then a day. A refreshed
242
+ // token was read for expires_in alone, so an end Qoder said as a date was
243
+ // put down as a day away, and renewed after it had run out (plugins#474).
244
+ // An end already past is no end said.
245
+ function expiresAt(jt) {
246
+ for (const k of ["expire_time", "expires_at"]) {
247
+ const at = whenSaid(jt?.[k])
248
+ if (at > Date.now()) return at
249
+ }
250
+ if (jt?.expires_in > 0) return Date.now() + jt.expires_in
251
+ return Date.now() + DAY
252
+ }
253
+
254
+ // whenSaid is the time a token's end field names, in milliseconds: a date,
255
+ // or an epoch in seconds or milliseconds; 0 for none (absent, 0, unreadable).
256
+ function whenSaid(v) {
257
+ if (typeof v === "number" || /^\d+$/.test(String(v ?? "").trim())) {
258
+ const n = Number(v)
259
+ if (!(n > 0)) return 0
260
+ return n < 1e12 ? n * 1000 : n
261
+ }
262
+ const at = Date.parse(String(v ?? "").trim())
263
+ return isNaN(at) ? 0 : at
264
+ }
240
265
 
241
266
  // deviceExpiry is when a device token used for chat runs out: its
242
267
  // expires_at (a date) or expires_in (seconds), as Qoder's CLI reads it; a
@@ -382,18 +407,6 @@ async function deviceSignIn(site) {
382
407
  }
383
408
  }
384
409
 
385
- // exchangeExpiry is when a job token from /api/v1/jobToken/exchange runs
386
- // out, as Qoder's own client reads it: expire_time or expires_at (a date)
387
- // first, then expires_in (milliseconds), then a day.
388
- function exchangeExpiry(jt) {
389
- for (const k of ["expire_time", "expires_at"]) {
390
- const at = Date.parse(String(jt?.[k] ?? "").trim())
391
- if (!isNaN(at)) return at
392
- }
393
- if (jt?.expires_in > 0) return Date.now() + jt.expires_in
394
- return Date.now() + DAY
395
- }
396
-
397
410
  // exchangeToken is the job token from an exchange response, as Qoder's
398
411
  // client reads it: token, device_token or access_token.
399
412
  function exchangeToken(jt) {
@@ -413,7 +426,7 @@ async function patSignIn(site, pat) {
413
426
  const token = exchangeToken(r.json)
414
427
  if (!token) throw new Error(`${site.name} PAT exchange: empty token in response`)
415
428
  const refresh = String(r.json?.refresh_token ?? r.json?.refreshToken ?? "").trim()
416
- const chat = { access: token, refresh, expires: exchangeExpiry(r.json) }
429
+ const chat = { access: token, refresh, expires: expiresAt(r.json) }
417
430
  let email = ""
418
431
  let name = ""
419
432
  let uid = ""
@@ -1185,9 +1198,11 @@ function failure(status, text) {
1185
1198
  // lapsed: only a refused refresh did (errorResponse says kept). Qoder's
1186
1199
  // own words go with it: a 401 right after signing in isn't a lapsed
1187
1200
  // sign-in, and its reason is what says what is (Yayoi_no_yume on X).
1201
+ // lapsed: the job token the call carried was refused, which the loader
1202
+ // renews once and asks again with (plugins#474) before it says so.
1188
1203
  if (status === 401 || status === 403) {
1189
1204
  const said = msg && msg !== STATUS_CODES[status] ? ` (Qoder said ${status}: ${msg.slice(0, 300)})` : ""
1190
- return { status: 401, message: "the sign-in lapsed — sign in again" + said }
1205
+ return { status: 401, message: "the sign-in lapsed — sign in again" + said, lapsed: true }
1191
1206
  }
1192
1207
  if (status === 429 || msg.toLowerCase().includes("quota")) return { status: 429, message: "usage limit reached: " + msg }
1193
1208
  return { status, message: msg }
@@ -2501,11 +2516,47 @@ const makePlugin = (site) => async ({ client }) => {
2501
2516
  return next
2502
2517
  })
2503
2518
 
2519
+ // relogin is the account to ask again with once Qoder refused the job
2520
+ // token refused (a chat's 401/403 "Login expired"), or undefined to say
2521
+ // the refusal as it is. Under the lock, as fresh: the sign-in as saved
2522
+ // now (another request, magpie's auth.refresh or another process may
2523
+ // have renewed it meanwhile, and then that is what is used, with no
2524
+ // refresh), else the job token renewed once and saved. Qoder has been
2525
+ // seen to refuse a job token it had put down as a day away for minutes
2526
+ // before magpie renewed it (plugins#474), and a request then failed
2527
+ // until the renewal came. A token this process renewed only minutes ago
2528
+ // that is refused too isn't renewed again: a refusal that isn't about the
2529
+ // token's end would otherwise spend a refresh token on every request.
2530
+ const relogin = (getAuth, refused) =>
2531
+ locked(async () => {
2532
+ const stored = await getAuth()
2533
+ if (stored?.type !== "oauth" || !stored.access || !stored.uid) throw new SignInGone(`${site.name}: not signed in`)
2534
+ siteOf(site, stored)
2535
+ const a = latest(stored)
2536
+ if (a.access !== refused) return a
2537
+ const now = Date.now()
2538
+ for (const v of spent.values()) if (v.got.access === refused && now - v.at < RELOGIN_GAP) return undefined
2539
+ const next = { ...a, ...(await renew(a)) }
2540
+ await client.auth.set({ path: { id: ID }, body: next })
2541
+ renewals.add(next)
2542
+ return next
2543
+ })
2544
+
2545
+ // the ids Qoder serves: the site's shipped list and every key a listing
2546
+ // has named, on or off
2547
+ const served = new Set(site.models.map((m) => m.id))
2548
+ const knows = (id) => served.has(id)
2504
2549
  const models = async (cred, again = false) => {
2505
2550
  const key = listingKey(cred)
2506
2551
  let l = listings.get(key)
2507
2552
  if (!l || again) {
2508
- l = modelInfos(await fetchListing(siteOf(site, cred), cred), siteOf(site, cred))
2553
+ const s = siteOf(site, cred)
2554
+ const listing = await fetchListing(s, cred)
2555
+ for (const m of s.modelScene ? (Array.isArray(listing?.[s.modelScene]) ? listing[s.modelScene] : []) : sceneModels(listing)) {
2556
+ const k = String(m?.key ?? "").trim()
2557
+ if (k) served.add(k)
2558
+ }
2559
+ l = modelInfos(listing, s)
2509
2560
  listings.set(key, l)
2510
2561
  }
2511
2562
  return l
@@ -2737,10 +2788,31 @@ const makePlugin = (site) => async ({ client }) => {
2737
2788
  })
2738
2789
 
2739
2790
  // ask is the answer to a chat completion on the live account cred.
2740
- const ask = async (chat, cred, init, named = "", fallback = false) => {
2791
+ // asked is what ask asked with: the account it ended on, which a refused
2792
+ // job token's renewal (relogin, given getAuth) changes.
2793
+ const ask = async (chat, cred, init, named = "", fallback = false, getAuth, asked = {}) => {
2794
+ asked.cred = cred
2741
2795
  let m
2796
+ let relogged = false
2797
+ const listed = (ms) => ms.find((x) => x.key === chat.model)
2742
2798
  try {
2743
- m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model)
2799
+ m = listed(await models(cred)) ?? listed(await models(cred, true))
2800
+ // A model Qoder serves that the account's listing leaves out, or has
2801
+ // off, on a job token Qoder no longer honours in full: the token is
2802
+ // renewed once (relogin, as for a refused chat) and the list asked
2803
+ // again. On an enterprise qoder.com account (plugins#484) the listing
2804
+ // had only the free dfmodel and qfmodel on while the job token was
2805
+ // stale, and every other model was answered 400 here, before a chat
2806
+ // could be refused and renew it. An id Qoder has never served is said
2807
+ // unknown at once, with no renewal spent on it.
2808
+ if (!m && getAuth && knows(chat.model)) {
2809
+ relogged = true
2810
+ const next = await relogin(getAuth, cred.access)
2811
+ if (next) {
2812
+ cred = asked.cred = next
2813
+ m = listed(await models(cred, true))
2814
+ }
2815
+ }
2744
2816
  } catch (e) {
2745
2817
  if (e instanceof SignInGone || e?.expired) return signedInError(e)
2746
2818
  return errorResponse({ status: 502, message: e?.message ?? String(e) })
@@ -2760,8 +2832,8 @@ const makePlugin = (site) => async ({ client }) => {
2760
2832
  // resend can be queued again before it is answered.
2761
2833
  const deadline = QUEUE.now() + QUEUE.budget
2762
2834
  const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key }
2763
- for (let waited = 0; ; waited++) {
2764
- if (waited) {
2835
+ for (let sent = 0, waited = 0; ; sent++) {
2836
+ if (sent) {
2765
2837
  body.request_id = body.chat_record_id = randomUUID()
2766
2838
  ask.requestId = body.request_id
2767
2839
  }
@@ -2781,6 +2853,21 @@ const makePlugin = (site) => async ({ client }) => {
2781
2853
  }
2782
2854
  const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
2783
2855
  if (f) call.abort()
2856
+ // a refused job token: renewed once (or the one renewed meanwhile)
2857
+ // and the request sent again, before the refusal is said
2858
+ if (f?.lapsed && getAuth && !relogged) {
2859
+ relogged = true
2860
+ let next
2861
+ try {
2862
+ next = await relogin(getAuth, cred.access)
2863
+ } catch (e) {
2864
+ return signedInError(e)
2865
+ }
2866
+ if (next) {
2867
+ cred = asked.cred = next
2868
+ continue
2869
+ }
2870
+ }
2784
2871
  // an answered call moves its task on, as Qoder's client moves it
2785
2872
  if (!f) task.answered = true
2786
2873
  // with another account, provider or group member after this one
@@ -2792,6 +2879,7 @@ const makePlugin = (site) => async ({ client }) => {
2792
2879
  } catch (e) {
2793
2880
  return errorResponse({ status: 502, message: e?.message ?? String(e) })
2794
2881
  }
2882
+ waited++
2795
2883
  }
2796
2884
  }
2797
2885
 
@@ -2860,7 +2948,9 @@ const makePlugin = (site) => async ({ client }) => {
2860
2948
  }
2861
2949
  const h = new Headers(input instanceof Request ? input.headers : undefined)
2862
2950
  new Headers(init.headers ?? {}).forEach((v, k) => h.set(k, v))
2863
- return signed(await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1"), renewed(cred))
2951
+ const asked = {}
2952
+ const res = await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1", getAuth, asked)
2953
+ return signed(res, renewed(cred) || (asked.cred !== cred && renewed(asked.cred)))
2864
2954
  },
2865
2955
  }
2866
2956
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.47",
3
+ "version": "0.2.49",
4
4
  "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",