@magpie-community/opencode-qoder-auth 0.2.62 → 0.2.64

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.
package/README.md CHANGED
@@ -189,9 +189,11 @@ itself.
189
189
  |---|---|
190
190
  | A refused sign-in (no code, or code 105) | 401 |
191
191
  | A quota (codes 110, 112–119, 122) | 429 |
192
+ | A model the account's listing has off while its usage says no credits are left (since 0.2.64, #880) | 429 usage limit reached, with the credits used and the model; a model off with credits left, or whose usage can't be read, stays 400 `unknown or disabled model`, and an id Qoder never served is that 400 at once |
192
193
  | Busy or queued for the model (code 10605) | Since 0.2.28 the request waits in Qoder's queue as Qoder's client does (below), then is sent again; since 0.2.62 a streamed request is answered 200 at once and kept alive with SSE comments for up to an hour, its outcome in the stream; past the wait, 503 with `Retry-After` from Qoder's `retryAfterSeconds` (30s when it gives none). Since 0.2.40, when magpie has another candidate after this request (`x-magpie-fallback: 1`), the 503 comes at once, saying the queue and how many are ahead, and magpie asks the next. The sign-in is untouched |
193
194
  | A refusal of the request itself (codes 406, 416, 430, 80411, 80412, 100400–100403) | 400, with Qoder's words |
194
195
  | "Error in upstream response", the model's own vendor behind Qoder failing, which Qoder sends as a 400 (since 0.2.24) | 502, so magpie asks again or another account; the sign-in is untouched |
196
+ | "Range of max_tokens should be [1, N]" behind "Error in upstream response" (since 0.2.63) | Asked again once with max_tokens N, which later requests for that model are sent from the start; refused again, 400 with Qoder's words, the sign-in untouched. QoDuck (`lmodel`) is never sent more than 131072, and a model whose listing entry names `max_output_tokens` never more than that; a smaller max_tokens goes as asked |
195
197
  | A failure before the answer starts | Qoder's status |
196
198
  | A failure after the answer has started | The stream ends with an error |
197
199
 
@@ -483,7 +485,8 @@ the account's credentials.
483
485
  (`Qoder.app` on macOS, `%LOCALAPPDATA%\Programs\Qoder` or, since
484
486
  0.2.26, `%ProgramFiles%\Qoder` on Windows, `/opt/Qoder` on Linux) or the runtime the CLI caches in `~/.qoder/.bin`
485
487
  (`runtime-info-<platform>-<arch>-*` on macOS and Linux,
486
- `umid-win32-x64-*\runtime-info.exe` on Windows; `QODER_CONFIG_DIR`,
488
+ `umid-win32-x64-*\runtime-info.exe` or, as qodercli 1.21.2 caches it
489
+ since 0.2.64, `runtime-info-win32-x64-*.exe` on Windows; `QODER_CONFIG_DIR`,
487
490
  `QODER_CLI_HOME` and `QODER_CONFIG_DIR_NAME` move it as they move the
488
491
  CLI's folder).
489
492
  - For another installation location, set `QODER_RUNTIME_INFO` to the
package/index.mjs CHANGED
@@ -1501,7 +1501,9 @@ function qoderBody(chat, m, named = "", task, site) {
1501
1501
  const sys = { type: "text", text: sysText }
1502
1502
  const budget = chat.max_completion_tokens || chat.max_tokens || 0
1503
1503
  const [thinking, effort] = effortFor(chat.reasoning_effort, m, typeof budget === "number" ? budget : 0)
1504
- const params = { enable_thinking: thinking, max_tokens: chat.max_completion_tokens || chat.max_tokens || 32000 }
1504
+ const asked = chat.max_completion_tokens || chat.max_tokens || 32000
1505
+ const cap = outputCap(m)
1506
+ const params = { enable_thinking: thinking, max_tokens: cap > 0 && asked > cap ? cap : asked }
1505
1507
  if (effort) params.reasoning_effort = effort
1506
1508
  const window = windowFor(chat, m, params.max_tokens)
1507
1509
  if (window > 0) params.context_length = window
@@ -1530,6 +1532,42 @@ function qoderBody(chat, m, named = "", task, site) {
1530
1532
  return body
1531
1533
  }
1532
1534
 
1535
+ // OUTPUT_CAPS are the largest max_tokens a model takes where its listing
1536
+ // entry names none: Qoder CN's QoDuck (lmodel) answers a larger one with a
1537
+ // 400 "Error in upstream response: Range of max_tokens should be [1,
1538
+ // 131072]", whatever the account (plugins#822, Gruu6y). A client asking
1539
+ // DeepSeek's 384K output was refused on every try, and each refusal rested
1540
+ // another account.
1541
+ const OUTPUT_CAPS = { lmodel: 131072 }
1542
+ // LEARNED_CAPS are the ceilings Qoder named in such a refusal, by model
1543
+ // key, for a model whose entry and OUTPUT_CAPS give none or a wrong one: the
1544
+ // refused request is asked again once at that ceiling, and later ones are
1545
+ // sent it from the start.
1546
+ const LEARNED_CAPS = new Map()
1547
+ // MAX_TOKENS_RANGE is that refusal's own words.
1548
+ const MAX_TOKENS_RANGE = /\brange of max_tokens should be \[\s*(\d+)\s*,\s*(\d+)\s*\]/i
1549
+
1550
+ // outputCap is the largest max_tokens model m takes, 0 when none is known:
1551
+ // what a refusal named, which is Qoder's own word, else its listing
1552
+ // entry's own (max_output_tokens), else OUTPUT_CAPS. A request's max_tokens is never sent above it, and one
1553
+ // asked lower is sent as asked.
1554
+ function outputCap(m) {
1555
+ const n = (v) => (Number.isInteger(v) && v > 0 ? v : 0)
1556
+ const raw = m?.config ?? {}
1557
+ return n(LEARNED_CAPS.get(m?.key)) || n(raw.max_output_tokens) || n(raw.maxOutputTokens) || n(OUTPUT_CAPS[m?.key])
1558
+ }
1559
+
1560
+ // reclamp is whether the request body was refused for a max_tokens above
1561
+ // model m's ceiling (failure's maxTokens), lowered to it if so: the
1562
+ // ceiling is remembered for the model, and the caller asks again once.
1563
+ function reclamp(f, body, m) {
1564
+ const cap = f?.maxTokens
1565
+ if (!(cap > 0) || !(body?.parameters?.max_tokens > cap)) return false
1566
+ if (m?.key) LEARNED_CAPS.set(m.key, cap)
1567
+ body.parameters.max_tokens = cap
1568
+ return true
1569
+ }
1570
+
1533
1571
  // failure is the status and message for a Qoder failure. Qoder's own code
1534
1572
  // says what it is, read as Qoder's client reads it (QoderErrorCode in the
1535
1573
  // app's qoder-agent-sdk worker): only 105 (loginExpired) is a lapsed
@@ -1598,6 +1636,11 @@ function failure(status, text) {
1598
1636
  }
1599
1637
  if (QUOTA_CODES.has(code)) return { status: 429, message: "usage limit reached: " + msg, signIn: "" }
1600
1638
  if (REQUEST_CODES.has(code)) return { status: 400, message: `Qoder refused the request (${code}): ${msg}`, signIn: "" }
1639
+ // a max_tokens above the model's ceiling, said behind "Error in upstream
1640
+ // response": the request's fault on every account, so a 400 that rests
1641
+ // none, with the ceiling for ask to send again at (plugins#822)
1642
+ const range = MAX_TOKENS_RANGE.exec(msg)
1643
+ if (range) return { status: 400, message: `Qoder refused the request's max_tokens: ${msg}`, signIn: "", maxTokens: Number(range[2]) }
1601
1644
  if (UPSTREAM_FAILED.test(msg)) return { status: 502, message: msg, signIn: "" }
1602
1645
  // a refused chat is the built-in's 401, which never marked the account
1603
1646
  // lapsed: only a refused refresh did (errorResponse says kept). Qoder's
@@ -2564,10 +2607,16 @@ async function campaignRuntime({ home = homedir(), platform = process.platform,
2564
2607
  const cache = join(config, ".bin")
2565
2608
  const entries = await readdir(cache, { withFileTypes: true }).catch(() => [])
2566
2609
  const found = []
2610
+ // qodercli 1.1.66 cached it on Windows as a folder umid-win32-<arch>-<hash>
2611
+ // holding runtime-info.exe and sgsdk.dll; qodercli 1.21.2 caches the file
2612
+ // itself, runtime-info-win32-<arch>-<hash>.exe, beside sgsdk.dll in .bin,
2613
+ // as elsewhere (plugins#879). Either is taken, the newest first.
2567
2614
  for (const d of entries) {
2568
2615
  let path
2569
- if (platform === "win32") {
2570
- if (d.isDirectory() && d.name.startsWith(`umid-win32-${arch}-`)) path = join(cache, d.name, name)
2616
+ if (platform === "win32" && d.isDirectory()) {
2617
+ if (d.name.startsWith(`umid-win32-${arch}-`)) path = join(cache, d.name, name)
2618
+ } else if (platform === "win32") {
2619
+ if (d.isFile() && d.name.startsWith(`runtime-info-win32-${arch}-`) && d.name.toLowerCase().endsWith(".exe")) path = join(cache, d.name)
2571
2620
  } else if (d.isFile() && d.name.startsWith(`runtime-info-${platform}-${arch}-`) && !d.name.endsWith(".tmp")) {
2572
2621
  path = join(cache, d.name)
2573
2622
  }
@@ -2768,6 +2817,31 @@ function when(v) {
2768
2817
  // account used up (magpie-community/plugins#454).
2769
2818
  const SPENT_IN_TURN = new Set(["Credits", "Add-on credits", "Shared credits"])
2770
2819
 
2820
+ // spentOf is the credits a usage envelope says the account has used of
2821
+ // what it has ("800 / 800 credits") when the pools spent in turn
2822
+ // (SPENT_IN_TURN) have none left together, and "" when they have some, or
2823
+ // when it says no pool at all. A free account's pools of 0 have none.
2824
+ function spentOf(env) {
2825
+ const u = env?.qoderUsage
2826
+ if (env?.displayMode !== "qoder" || !u || typeof u !== "object" || Array.isArray(u)) return ""
2827
+ let used = 0
2828
+ let total = 0
2829
+ let pools = 0
2830
+ for (const [a, b] of [["userQuota", "user_quota"], ["addOnQuota", "add_on_quota"], ["orgResourcePackage", "org_resource_package"]]) {
2831
+ const p = u[a] !== undefined ? u[a] : u[b]
2832
+ if (p === null || typeof p !== "object" || Array.isArray(p)) continue
2833
+ const t = p.total ?? p.cap
2834
+ if (typeof t !== "number" || !Number.isFinite(t) || t < 0) continue
2835
+ const n = typeof p.used === "number" ? p.used : typeof p.remaining === "number" ? t - p.remaining : NaN
2836
+ if (t > 0 && !Number.isFinite(n)) return ""
2837
+ pools++
2838
+ total += t
2839
+ used += t > 0 ? Math.min(Math.max(n, 0), t) : 0
2840
+ }
2841
+ if (!pools || used < total) return ""
2842
+ return `${gfmt(used)} / ${gfmt(total)} credits`
2843
+ }
2844
+
2771
2845
  // parseUsage is the plan and each pool of credits the envelope tells. When
2772
2846
  // more than one of the pools spent in turn holds credits, "Total credits"
2773
2847
  // is what they hold together, the one routing counts, and each pool is
@@ -3209,11 +3283,16 @@ const makePlugin = (site) => async ({ client }) => {
3209
3283
  if (!l || again) {
3210
3284
  const s = siteOf(site, cred)
3211
3285
  const listing = await fetchListing(s, cred)
3286
+ const off = new Set()
3212
3287
  for (const m of s.modelScene ? (Array.isArray(listing?.[s.modelScene]) ? listing[s.modelScene] : []) : sceneModels(listing)) {
3213
3288
  const k = String(m?.key ?? "").trim()
3214
3289
  if (k) served.add(k)
3290
+ if (k && !m.enable) off.add(k)
3215
3291
  }
3216
3292
  l = modelInfos(listing, s)
3293
+ // the keys this listing names and has off (ask tells a model off for
3294
+ // the credits apart by them)
3295
+ l.off = off
3217
3296
  if (!s.modelScene) l.freeView = freeView(sceneModels(listing))
3218
3297
  listings.set(key, l)
3219
3298
  }
@@ -3307,19 +3386,40 @@ const makePlugin = (site) => async ({ client }) => {
3307
3386
  const env = await fetchUsage(siteOf(site, cred), cred.access)
3308
3387
  return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who }
3309
3388
  }
3310
- let env
3311
- try {
3312
- env = await fetchUsage(siteOf(site, cred), cred.deviceToken)
3313
- } catch (e) {
3314
- if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
3315
- env = await fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken))
3316
- }
3317
- return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who }
3389
+ return { ...(await spareFree(cred, parseUsage(await usageEnv(getAuth, cred)))), signIn, ...who }
3318
3390
  } catch (e) {
3319
3391
  return { error: e?.message ?? String(e), signIn: e?.expired ? "expired" : signIn }
3320
3392
  }
3321
3393
  }
3322
3394
 
3395
+ // usageEnv is the account's usage envelope on its device token, rotated
3396
+ // once when refused, as usage reads it
3397
+ const usageEnv = async (getAuth, cred) => {
3398
+ try {
3399
+ return await fetchUsage(siteOf(site, cred), cred.deviceToken)
3400
+ } catch (e) {
3401
+ if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
3402
+ return fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken))
3403
+ }
3404
+ }
3405
+
3406
+ // creditsSpent is the credits the account has used of what it has
3407
+ // ("800 / 800 credits") when its usage says none are left (spentOf), and
3408
+ // "" when some are, or when it can't be read. Qoder and Qoder CN only:
3409
+ // QwenWork reads its usage elsewhere. A PAT account's is read on its job
3410
+ // token, as usage reads it.
3411
+ const creditsSpent = async (getAuth) => {
3412
+ if (site.usagePath) return ""
3413
+ try {
3414
+ const cred = await fresh(getAuth)
3415
+ if (cred.lingma) return ""
3416
+ if (cred.patAuth && !cred.deviceToken) return spentOf(await fetchUsage(siteOf(site, cred), cred.access))
3417
+ return spentOf(await usageEnv(getAuth, cred))
3418
+ } catch {
3419
+ return ""
3420
+ }
3421
+ }
3422
+
3323
3423
  // campaign is a campaigns page (the daily check-in) asked as the account:
3324
3424
  // a refused device token is rotated once, as usage does, and asked again
3325
3425
  const campaign = async (getAuth, input, url, init) => {
@@ -3458,6 +3558,7 @@ const makePlugin = (site) => async ({ client }) => {
3458
3558
  let m
3459
3559
  let relogged = false
3460
3560
  let renamed = false
3561
+ let reclamped = false
3461
3562
  const listed = (ms) => ms.find((x) => x.key === chat.model)
3462
3563
  try {
3463
3564
  m = listed(await models(cred)) ?? listed(await models(cred, true))
@@ -3470,6 +3571,26 @@ const makePlugin = (site) => async ({ client }) => {
3470
3571
  // could be refused and renew it. An id Qoder has never served is said
3471
3572
  // unknown at once, with no renewal spent on it.
3472
3573
  if (!m && getAuth && knows(chat.model)) {
3574
+ // Off because the credits are used up (plugins#880): on an
3575
+ // international personal_professional_trial account Qoder's listing
3576
+ // had dfmodel off once the 800 credits were spent, and on again
3577
+ // when the daily credits came back. That is the account's quota,
3578
+ // not the request's fault, so it is said as Qoder's own quota codes
3579
+ // are (429 usage limit reached), which a routing group fails over
3580
+ // on and rests the account for. Only a model the live listing names
3581
+ // and has off, on an account whose usage read says no credits are
3582
+ // left; a usage that can't be read says nothing, and the model goes
3583
+ // on to the renewal and the 400 below as before.
3584
+ if ((await models(cred)).off?.has(chat.model)) {
3585
+ const spent = await creditsSpent(getAuth)
3586
+ if (spent) {
3587
+ return errorResponse({
3588
+ status: 429,
3589
+ message: `usage limit reached: the account's credits are used up (${spent}), and Qoder lists "${chat.model}" off for it until they refresh`,
3590
+ signIn: "",
3591
+ })
3592
+ }
3593
+ }
3473
3594
  relogged = true
3474
3595
  const next = await relogin(getAuth, cred.access)
3475
3596
  if (next) {
@@ -3552,6 +3673,11 @@ const makePlugin = (site) => async ({ client }) => {
3552
3673
  renamed = true
3553
3674
  continue
3554
3675
  }
3676
+ // a max_tokens above the model's ceiling: asked again once at it
3677
+ if (!reclamped && reclamp(f, body, m)) {
3678
+ reclamped = true
3679
+ continue
3680
+ }
3555
3681
  // an answered call moves its task on, as Qoder's client moves it
3556
3682
  if (!f) task.answered = true
3557
3683
  // with another account, provider or group member after this one
@@ -3592,6 +3718,7 @@ const makePlugin = (site) => async ({ client }) => {
3592
3718
  const task = taskOf(sessionOf(chat, named), chat)
3593
3719
  const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : []
3594
3720
  let relogged = false
3721
+ let reclamped = false
3595
3722
  for (let i = 0; ; ) {
3596
3723
  const m = order[i]
3597
3724
  const s = siteOf(site, cred)
@@ -3630,6 +3757,10 @@ const makePlugin = (site) => async ({ client }) => {
3630
3757
  }
3631
3758
  return errorResponse({ status: 401, message: `the sign-in lapsed — open Qoder CN IDE so it signs in again (${String(f.message).slice(0, 300)})` })
3632
3759
  }
3760
+ if (!reclamped && reclamp(f, body, m)) {
3761
+ reclamped = true
3762
+ continue
3763
+ }
3633
3764
  if (f && LINGMA_NOT_HERE.test(f.message) && i + 1 < order.length) {
3634
3765
  console.warn(`qoder-cn: ${s.dedicated} doesn't serve ${m.key}; asking ${order[i + 1].key}`)
3635
3766
  i++
@@ -3945,4 +4076,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
3945
4076
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
3946
4077
 
3947
4078
  // for tests
3948
- export const _internal = { fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
4079
+ export const _internal = { spentOf, OUTPUT_CAPS, LEARNED_CAPS, outputCap, fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
package/opencode2.mjs CHANGED
@@ -85,8 +85,10 @@ export function fieldsOf(prompts) {
85
85
  if (p.placeholder) f.placeholder = String(p.placeholder)
86
86
  if (p.type === "select" && Array.isArray(p.options))
87
87
  f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
88
- // a prompt shown only when another answer says so can't be required
89
- if (!p.condition) f.required = true
88
+ // a prompt shown only when another answer says so can't be required, and
89
+ // neither can one whose own validate() accepts an empty answer (the
90
+ // browser sign-in's optional API key)
91
+ if (!p.condition && p.required !== false) f.required = true
90
92
  out.push(f)
91
93
  }
92
94
  return out.length ? out : undefined
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.62",
3
+ "version": "0.2.64",
4
4
  "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",