@magpie-community/opencode-qoder-auth 0.2.54 → 0.2.56

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 +46 -5
  2. package/index.mjs +310 -16
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -138,7 +138,10 @@ itself.
138
138
  - The model's own configuration from Qoder's list goes with it.
139
139
  - It picks the reasoning effort from the model's own levels:
140
140
  - The nearest level to the one asked, the higher one on a tie.
141
- - The model's default when none is asked.
141
+ - The model's default when none is asked, unless the request's
142
+ `max_tokens` is 1024 or less: that is asked as "none" (since 0.2.55,
143
+ plugins#643), since thinking would spend so small a budget on
144
+ reasoning alone.
142
145
  - The lowest level for "none", when the model can't turn thinking off.
143
146
  - It picks the context window (`context_length`) from the model's own
144
147
  windows (Qoder's Context setting: 200K, 400K, 1M): the default while the
@@ -338,10 +341,8 @@ Qoder IDE's settings: a host or an https address (a path is dropped).
338
341
  It follows Qoder IDE 1.38.0's own rules for that setting:
339
342
 
340
343
  - It first asks `GET <domain>/algo/api/v1/version`. A 404 means a legacy
341
- Lingma 1.0 (通义灵码) dedicated domain. Its sign-in goes through another
342
- protocol, which this plugin doesn't have yet, so the sign-in stops and
343
- says so. Any other answer means Qoder CN 2.0. A domain that doesn't answer
344
- is refused.
344
+ Lingma 1.0 (通义灵码) dedicated domain (see below). Any other answer means
345
+ Qoder CN 2.0. A domain that doesn't answer is refused.
345
346
  - A Qoder CN 2.0 domain uses the VPC protocol on hosts named the IDE's way:
346
347
  `-openapi` or `-gateway` after the host's first label. An IP or a host
347
348
  with no dot keeps its own origin. The sign-in uses the IDE's client id and
@@ -364,6 +365,46 @@ It follows Qoder IDE 1.38.0's own rules for that setting:
364
365
  The rules come from Qoder IDE's code. This plugin has not been tried with a
365
366
  dedicated account.
366
367
 
368
+ #### Lingma 1.0 dedicated domains (since 0.2.56)
369
+
370
+ A Lingma 1.0 domain has no device flow and takes no console PAT. Qoder CN
371
+ IDE signs in to it through its own language server. So the plugin uses the
372
+ account Qoder CN IDE is already signed in to on this computer:
373
+
374
+ 1. Sign in to the dedicated domain once in Qoder CN IDE (Settings →
375
+ 「企业版专属域登录」).
376
+ 2. In magpie, choose **Sign in with Qoder CN Enterprise dedicated domain
377
+ (企业版专属域)** and enter the same domain.
378
+
379
+ The plugin reads the IDE worker's cache, in its `SharedClientCache` folder:
380
+
381
+ | System | Folder |
382
+ |---|---|
383
+ | macOS | `~/Library/Application Support/QoderCN/SharedClientCache` |
384
+ | Windows | `%APPDATA%\QoderCN\SharedClientCache` |
385
+ | Linux | `$XDG_CONFIG_HOME/QoderCN/SharedClientCache` (`~/.config/...`) |
386
+
387
+ It also looks in `~/.config/Qoder CN/SharedClientCache` and `~/.lingma`, and
388
+ `QODERCN_COSY_HOME` names another folder. `cache/id` is the machine id, and
389
+ `cache/user` is the account, encrypted under that id.
390
+
391
+ - Every call goes to the domain itself, signed as the IDE's worker signs
392
+ it: `Cosy-ClientType` 0, version 2.5.18, the assistant scene.
393
+ - The models are the IDE's own: `qmodel_latest` (Qwen3.7-Max),
394
+ `dashscope_qmodel` (Qwen3.7-Plus) and `q36fmodel` (Qwen3.6-Flash). The
395
+ domain's own model list names keys its chat refuses. When the domain
396
+ answers "Model not exist" for a model, the next one is asked.
397
+ - The IDE renews its sign-in itself, and the plugin reads the cache again
398
+ near the token's end, or when the domain refuses it (105). When the IDE
399
+ holds nothing newer, the account is marked expired: open Qoder CN IDE so
400
+ it signs in again.
401
+ - Usage and the daily check-in are not read on such a domain.
402
+
403
+ The cache layout, the request shape and the models come from Milktea's
404
+ tests on a real Lingma dedicated domain. The folders and the model names
405
+ were checked against Qoder CN IDE 1.38.0. This plugin itself has not been
406
+ tried on one.
407
+
367
408
  ## The card's name
368
409
 
369
410
  An account signed in with a phone is shown by that phone — masked, `138****8000` — not by
package/index.mjs CHANGED
@@ -34,9 +34,9 @@
34
34
  // <instance>-openapi.vpc.qoder.com.cn, and gateway.qoder.com.cn becomes
35
35
  // <instance>-gateway.vpc.qoder.com.cn. The instance is kept on the account,
36
36
  // and an account with none is served as before.
37
- import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto"
37
+ import { createCipheriv, createDecipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto"
38
38
  import { execFile } from "node:child_process"
39
- import { readdir, stat } from "node:fs/promises"
39
+ import { readFile, readdir, stat } from "node:fs/promises"
40
40
  import { STATUS_CODES } from "node:http"
41
41
  import { homedir, hostname } from "node:os"
42
42
  import { join, resolve } from "node:path"
@@ -394,25 +394,217 @@ async function dedicatedProbe(origin) {
394
394
  }
395
395
 
396
396
  // dedicatedSignIn reads the domain as the IDE does and starts its device
397
- // sign-in. A legacy Lingma domain is refused with what it is: its sign-in
398
- // (cosy's login/generateUrl, a qoder-cn-ide:// callback) isn't served here.
399
- // The chat host is the gateway host when it answers at all, else the
400
- // domain's own origin, which answered the probe on the same /algo path; the
401
- // IDE leaves this to its language server, whose rule wasn't read (inferred).
397
+ // sign-in. A Lingma 1.0 domain (404 at the probe) is signed in to with the
398
+ // account Qoder CN IDE holds for it (lingmaSignIn). The chat host is the
399
+ // gateway host when it answers at all, else the domain's own origin, which
400
+ // answered the probe on the same /algo path; the IDE leaves this to its
401
+ // language server, whose rule wasn't read (inferred).
402
402
  async function dedicatedSignIn(site, input) {
403
403
  const origin = dedicatedOrigin(input)
404
404
  if (!origin) throw new Error(`Not a dedicated domain: ${String(input ?? "").slice(0, 100)}`)
405
405
  const status = await dedicatedProbe(origin)
406
406
  if (status === undefined) throw new Error(`${site.name}: ${origin} didn't answer (${DEDICATED_VERSION}); check the address and your network`)
407
- if (status === 404)
408
- throw new Error(
409
- `${site.name}: ${origin} is a Lingma 1.0 (通义灵码) dedicated domain, which this plugin can't sign in to yet; ${new URL(origin).host} answers 404 at ${DEDICATED_VERSION}, as Qoder IDE tells one apart`,
410
- )
407
+ if (status === 404) return lingmaSignIn(site, origin)
411
408
  const gateway = dedicatedHost(origin, "-gateway")
412
409
  const api = gateway !== origin && (await dedicatedProbe(gateway)) === undefined ? origin : undefined
413
410
  return deviceSignIn(dedicatedSite(site, origin, api))
414
411
  }
415
412
 
413
+ // ---- Lingma 1.0 dedicated domains (通义灵码专属版) ---------------------------
414
+ //
415
+ // A domain that answers 404 at the probe is a Lingma 1.0 deployment. Qoder
416
+ // CN IDE (1.38.0) signs in to one through its language server, not the
417
+ // device flow ("use extension 127 login", _loginWithExtension("dedicated")),
418
+ // and such a host serves none of the device flow: /device/selectAccounts and
419
+ // /api/v1/jobToken/exchange answer 404, a console PAT or the console's
420
+ // cookies are answered {"code":"105","message":"Login timeout"} at /algo,
421
+ // and /algo/api/v3/user/* "Request discarded" (all measured on Milktea's
422
+ // host). What works is the session the IDE's worker already holds once the
423
+ // user has signed in there, read from its cache as the worker writes it
424
+ // (Milktea's gist, plugins Discord 2026-11-03):
425
+ // <cosyHome>/cache/id the worker's machine id, a plain uuid (or <cosyHome>/id)
426
+ // <cosyHome>/cache/user base64(AES-128-CBC(JSON)), key = IV = the id's first 16 chars
427
+ // whose JSON has uid, organization_id, name, email, security_oauth_token,
428
+ // refresh_token and expire_time (ms). cosyHome is the IDE's userDataPath
429
+ // with SharedClientCache after it (its main.js; the worker is started with
430
+ // --workDir there): ~/Library/Application Support/QoderCN on macOS,
431
+ // %APPDATA%\QoderCN on Windows, $XDG_CONFIG_HOME (~/.config)/QoderCN on
432
+ // Linux. "Qoder CN" and ~/.lingma are the older layouts the gist found.
433
+ // The worker renews that session itself (its "CN 1.0 refresh"), so the
434
+ // account here is renewed by reading the cache again, never by a refresh
435
+ // call of its own: the host serves none that was found.
436
+ //
437
+ // Its chat is the same agent_chat_generation, signed with the COSY envelope
438
+ // as the worker signs it (the gist's capture): Cosy-ClientType 0, the
439
+ // worker's own version 2.5.18, no Cosy-Scene or Cosy-Business-*, and the
440
+ // assistant scene. Its model list names keys the chat refuses ("Model not
441
+ // exist"), so the models are the IDE's own (its modelSelector.item.* names):
442
+ // a key the domain refuses falls through to the next.
443
+ const LINGMA_VERSION = "2.5.18"
444
+ const LINGMA_LEAD = 5 * 60 * 1000
445
+ const LINGMA_MODELS = [
446
+ { key: "qmodel_latest", name: "Qwen3.7-Max" },
447
+ { key: "dashscope_qmodel", name: "Qwen3.7-Plus" },
448
+ { key: "q36fmodel", name: "Qwen3.6-Flash" },
449
+ ]
450
+ const LINGMA_LAPSED = /"code"\s*:\s*"?105"?|Login (?:expired|timeout)/i
451
+ const LINGMA_NOT_HERE = /model_not_found|Model not exist/i
452
+
453
+ // lingmaRoots is where Qoder CN IDE's worker keeps its cache on this
454
+ // system: QODERCN_COSY_HOME first, then the IDE's own folder, then the
455
+ // older layouts. HOME is read first, so a sandboxed HOME is the one
456
+ // looked in.
457
+ function lingmaRoots(env = process.env, platform = process.platform, home = env.HOME || env.USERPROFILE || homedir()) {
458
+ const roots = []
459
+ const add = (p) => p && !roots.includes(p) && roots.push(p)
460
+ add(String(env.QODERCN_COSY_HOME ?? "").trim())
461
+ if (platform === "darwin") add(join(home, "Library", "Application Support", "QoderCN", "SharedClientCache"))
462
+ else if (platform === "win32") add(join(env.APPDATA || join(home, "AppData", "Roaming"), "QoderCN", "SharedClientCache"))
463
+ else add(join(env.XDG_CONFIG_HOME || join(home, ".config"), "QoderCN", "SharedClientCache"))
464
+ add(join(home, ".config", "QoderCN", "SharedClientCache"))
465
+ add(join(home, ".config", "Qoder CN", "SharedClientCache"))
466
+ add(join(home, ".lingma"))
467
+ return roots
468
+ }
469
+
470
+ // lingmaDecode is the account one cosyHome holds, or why there is none.
471
+ async function lingmaDecode(root) {
472
+ const read = async (p) => (await readFile(p, "utf8").catch(() => "")).trim()
473
+ const id = (await read(join(root, "cache", "id"))) || (await read(join(root, "id")))
474
+ const blob = await read(join(root, "cache", "user"))
475
+ if (!id || !blob) return { root, reason: "no cache/id and cache/user" }
476
+ const key = Buffer.from(id.slice(0, 16), "utf8")
477
+ if (key.length !== 16) return { root, reason: "the machine id is too short" }
478
+ let a
479
+ try {
480
+ const d = createDecipheriv("aes-128-cbc", key, key)
481
+ a = JSON.parse(Buffer.concat([d.update(Buffer.from(blob, "base64")), d.final()]).toString("utf8"))
482
+ } catch {
483
+ return { root, reason: "cache/user doesn't open with the machine id" }
484
+ }
485
+ const access = String(a?.security_oauth_token ?? "").trim()
486
+ const uid = String(a?.uid ?? "").trim()
487
+ if (!access || !uid) return { root, reason: "cache/user names no signed-in account" }
488
+ const end = Number(a.expire_time)
489
+ return {
490
+ root,
491
+ machineId: id,
492
+ uid,
493
+ access,
494
+ email: String(a.email ?? ""),
495
+ name: String(a.name ?? ""),
496
+ orgId: String(a.organization_id ?? ""),
497
+ expires: Number.isFinite(end) && end > 0 ? end : 0,
498
+ }
499
+ }
500
+
501
+ // lingmaRead is the first account the IDE's caches hold, or an Error that
502
+ // says where it looked and what it found.
503
+ async function lingmaRead(site, roots = lingmaRoots()) {
504
+ const seen = []
505
+ for (const root of roots) {
506
+ const got = await lingmaDecode(root)
507
+ if (got.access) return got
508
+ seen.push(`${root}: ${got.reason}`)
509
+ }
510
+ return new SignInGone(
511
+ `${site.name}: no Qoder CN IDE sign-in found on this computer. Sign in to your dedicated domain once in Qoder CN IDE (Settings → 企业版专属域登录), then sign in here again. Looked in ${seen.join("; ")}`,
512
+ true,
513
+ )
514
+ }
515
+
516
+ const lingmaLive = (got, now = Date.now()) => !got.expires || got.expires - now > LINGMA_LEAD
517
+
518
+ // lingmaAccount is the account a read gives for the domain at origin.
519
+ function lingmaAccount(site, origin, got) {
520
+ const host = new URL(origin).host
521
+ return {
522
+ type: "success",
523
+ access: got.access,
524
+ // nothing here spends a refresh token: the IDE's worker renews it
525
+ refresh: "",
526
+ expires: got.expires || Date.now() + DAY,
527
+ accountId: `${got.email || got.uid} (${host})`,
528
+ cardName: `${got.email || got.name || got.uid} (${host})`,
529
+ uid: got.uid,
530
+ email: got.email,
531
+ name: got.name,
532
+ ...(got.orgId ? { orgId: got.orgId } : {}),
533
+ machineId: got.machineId,
534
+ deviceToken: "",
535
+ deviceRefresh: "",
536
+ dedicated: host,
537
+ lingma: true,
538
+ }
539
+ }
540
+
541
+ // lingmaSignIn signs in to a Lingma 1.0 domain with the account Qoder CN
542
+ // IDE holds, read when the sign-in is asked for so a missing or lapsed one
543
+ // is said at once.
544
+ async function lingmaSignIn(site, origin, roots) {
545
+ const got = await lingmaRead(site, roots)
546
+ if (got instanceof Error) throw got
547
+ if (!lingmaLive(got))
548
+ throw new SignInGone(
549
+ `${site.name}: Qoder CN IDE's sign-in (${got.email || got.uid}) ended ${new Date(got.expires).toISOString()}; open Qoder CN IDE so it signs in again, then sign in here again`,
550
+ true,
551
+ )
552
+ return {
553
+ url: origin,
554
+ instructions: `${new URL(origin).host} is a Lingma 1.0 (通义灵码) dedicated domain: using the account Qoder CN IDE is signed in to (${got.email || got.uid})`,
555
+ method: "auto",
556
+ async callback() {
557
+ return lingmaAccount(site, origin, got)
558
+ },
559
+ }
560
+ }
561
+
562
+ // lingmaRenew is a newer token for a, from the IDE's cache: what changed,
563
+ // or SignInGone (expired) when the IDE holds none newer that is live.
564
+ async function lingmaRenew(site, a, roots) {
565
+ const got = await lingmaRead(site, roots)
566
+ if (got instanceof Error) throw got
567
+ if (got.uid !== a.uid)
568
+ throw new SignInGone(`${site.name}: Qoder CN IDE is now signed in as another account (${got.email || got.uid}); sign in here again`, true)
569
+ if (got.access === a.access || !lingmaLive(got))
570
+ throw new SignInGone(`${site.name}: the sign-in lapsed and Qoder CN IDE holds none newer; open Qoder CN IDE so it signs in again`, true)
571
+ return { access: got.access, expires: got.expires || Date.now() + DAY, machineId: got.machineId }
572
+ }
573
+
574
+ // lingmaSite is site served from a Lingma 1.0 domain: every call on its
575
+ // own origin, signed as the IDE's worker signs them.
576
+ function lingmaSite(site, domain) {
577
+ const origin = dedicatedOrigin(domain)
578
+ if (!origin) return undefined
579
+ const host = new URL(origin).host
580
+ return {
581
+ ...site,
582
+ web: origin,
583
+ openapi: origin,
584
+ api: origin,
585
+ vpc: host,
586
+ dedicated: host,
587
+ lingma: true,
588
+ clientType: "0",
589
+ cosyVersion: LINGMA_VERSION,
590
+ modelScene: "assistant",
591
+ sessionType: "assistant",
592
+ }
593
+ }
594
+
595
+ // lingmaHeaders are a Lingma chat's headers, as the IDE's worker sent them
596
+ // (the gist's capture): the envelope with no scene or business headers.
597
+ function lingmaHeaders(url, u, body, site) {
598
+ const h = cosyHeaders(url, u, body, site)
599
+ delete h["Cosy-Scene"]
600
+ delete h["Cosy-Business-Product"]
601
+ delete h["Cosy-Business-Type"]
602
+ return { ...h, Accept: "text/event-stream", "Cache-Control": "no-cache", "x-request-id": randomUUID() }
603
+ }
604
+
605
+ // lingmaModel is a Lingma model as a request carries it
606
+ const lingmaModel = (m) => modelInfo({ key: m.key, display_name: m.name, format: "dashscope", source: "system", max_input_tokens: 180_000 })
607
+
416
608
  // siteOf is the site an account is served from: its VPC instance's when it
417
609
  // was signed in to one, else site. An instance on record that names none
418
610
  // is not read as "no VPC", which would send the enterprise's tokens to the
@@ -425,6 +617,11 @@ function siteOf(site, a) {
425
617
  const base = `https://${a.enterpriseHost}`
426
618
  return { ...site, web: base, openapi: base, api: base, vpc: a.enterpriseHost }
427
619
  }
620
+ if (a?.dedicated && a.lingma) {
621
+ const s = lingmaSite(site, a.dedicated)
622
+ if (!s) throw new SignInGone(`${site.name}: the account's dedicated domain "${a.dedicated}" isn't one; sign in again`)
623
+ return s
624
+ }
428
625
  if (a?.dedicated) {
429
626
  const s = dedicatedSite(site, a.dedicated, a.dedicatedApi)
430
627
  if (!s) throw new SignInGone(`${site.name}: the account's dedicated domain "${a.dedicated}" isn't one; sign in again`)
@@ -898,12 +1095,24 @@ function fitEffort(want, levels) {
898
1095
  return best
899
1096
  }
900
1097
 
1098
+ // SMALL_BUDGET is the largest max_tokens a request can name and still be
1099
+ // one no client meant to think in: Anthropic's API takes thinking only with
1100
+ // a budget of at least 1024 tokens and a max_tokens above it, and a client's
1101
+ // own short asks (a session title, a classification) name such budgets.
1102
+ // Thinking by default spends them on reasoning: on WorkBuddy, a title asked
1103
+ // at 64 tokens ended "length" with 64 reasoning tokens and no text
1104
+ // (plugins#643, itspig).
1105
+ const SMALL_BUDGET = 1024
1106
+
901
1107
  // effortFor is whether to think and at which of the model's efforts ("" for
902
1108
  // none): asked for none, a model that always thinks thinks at its lowest;
903
- // asked for nothing, or a level Qoder doesn't name, at its own default.
904
- function effortFor(asked, m) {
1109
+ // asked for nothing, or a level Qoder doesn't name, at its own default —
1110
+ // unless the request's own budget (max_tokens, 0 when it named none) is
1111
+ // SMALL_BUDGET or less, which is asked as none.
1112
+ function effortFor(asked, m, budget = 0) {
905
1113
  let want = String(asked ?? "").toLowerCase()
906
1114
  if (!EFFORT_RANK.includes(want)) want = ""
1115
+ if (want === "" && budget > 0 && budget <= SMALL_BUDGET) want = "none"
907
1116
  if (!m.thinks || (want === "none" && !m.alwaysThinks)) return [false, ""]
908
1117
  if (!m.efforts.length) return [true, ""]
909
1118
  if (want === "") return [true, m.defaultEffort]
@@ -1268,7 +1477,8 @@ function qoderBody(chat, m, named = "", task, site) {
1268
1477
  let sysText = system ? baseSystem + "\n\n" + system : baseSystem
1269
1478
  if (chat.tool_choice === "required" && tools.length) sysText += "\nYou must call an available function in this response."
1270
1479
  const sys = { type: "text", text: sysText }
1271
- const [thinking, effort] = effortFor(chat.reasoning_effort, m)
1480
+ const budget = chat.max_completion_tokens || chat.max_tokens || 0
1481
+ const [thinking, effort] = effortFor(chat.reasoning_effort, m, typeof budget === "number" ? budget : 0)
1272
1482
  const params = { enable_thinking: thinking, max_tokens: chat.max_completion_tokens || chat.max_tokens || 32000 }
1273
1483
  if (effort) params.reasoning_effort = effort
1274
1484
  const window = windowFor(chat, m, params.max_tokens)
@@ -1888,6 +2098,13 @@ async function* events(body, tools = []) {
1888
2098
  } catch {
1889
2099
  continue
1890
2100
  }
2101
+ // a refusal said inside an OK frame (a Lingma 1.0 domain's "Model not
2102
+ // exist" or 105): the turn's failure, not a chunk to read past into an
2103
+ // empty answer
2104
+ if (!Array.isArray(chunk?.choices) && (chunk?.error || (chunk?.code != null && chunk?.message))) {
2105
+ yield { error: failure(502, inner) }
2106
+ return
2107
+ }
1891
2108
  const delta = chunk?.choices?.[0]?.delta ?? {}
1892
2109
  if (delta.reasoning_content) {
1893
2110
  said = true
@@ -2720,6 +2937,8 @@ const makePlugin = (site) => async ({ client }) => {
2720
2937
  // exchanges the PAT again: the PAT lasts a year, the refresh two days.
2721
2938
  const renew = async (a) => {
2722
2939
  const s = siteOf(site, a)
2940
+ // a Lingma 1.0 account: the token Qoder CN IDE's worker renewed
2941
+ if (a.lingma) return lingmaRenew(s, a)
2723
2942
  if (a.deviceChat) {
2724
2943
  // the device token is the chat token: renewed as a device token,
2725
2944
  // both pairs being the one pair
@@ -2812,6 +3031,8 @@ const makePlugin = (site) => async ({ client }) => {
2812
3031
  const models = async (cred, again = false) => {
2813
3032
  const key = listingKey(cred)
2814
3033
  let l = listings.get(key)
3034
+ // a Lingma 1.0 domain's listing names keys its chat refuses: the IDE's own
3035
+ if (cred.lingma) return LINGMA_MODELS.map(lingmaModel)
2815
3036
  if (!l || again) {
2816
3037
  const s = siteOf(site, cred)
2817
3038
  const listing = await fetchListing(s, cred)
@@ -2871,6 +3092,8 @@ const makePlugin = (site) => async ({ client }) => {
2871
3092
  if (renewed(cred)) signIn = "renewed"
2872
3093
  // the card's name: magpie takes usage's `user` for it and never as a key
2873
3094
  const who = cred?.cardName ? { user: cred.cardName } : {}
3095
+ // a Lingma 1.0 domain serves no usage read that was found
3096
+ if (cred.lingma) return { windows: [], signIn, ...who }
2874
3097
  // a site with its own usage path (QwenWork's account-context, signed
2875
3098
  // like any other call and answered with its own envelope) is read
2876
3099
  // there; a 401 rotates the device token once, as the qoder path does
@@ -2960,6 +3183,7 @@ const makePlugin = (site) => async ({ client }) => {
2960
3183
  const checkin = async (getAuth) => {
2961
3184
  let cred
2962
3185
  try {
3186
+ if ((await getAuth())?.lingma) return { outcome: "inactive", message: "a Lingma 1.0 dedicated domain has no daily credits" }
2963
3187
  cred = await fresh(getAuth)
2964
3188
  } catch (e) {
2965
3189
  return { outcome: "failed", message: e?.message ?? String(e), ...(e?.expired ? { signIn: "expired" } : {}) }
@@ -3163,6 +3387,68 @@ const makePlugin = (site) => async ({ client }) => {
3163
3387
  }
3164
3388
  }
3165
3389
 
3390
+ // askLingma is ask for a Lingma 1.0 account: the IDE's models, signed as
3391
+ // its worker signs them, a model the domain refuses ("Model not exist",
3392
+ // said inside the stream) followed by the next, and a refused token (105)
3393
+ // asked again once with the token the IDE renewed meanwhile.
3394
+ const askLingma = async (chat, cred, init, named, getAuth, asked) => {
3395
+ asked.cred = cred
3396
+ const list = LINGMA_MODELS.map(lingmaModel)
3397
+ const want = list.find((x) => x.key === chat.model)
3398
+ if (!want) return errorResponse({ status: 400, message: `unknown model "${chat.model}"; this dedicated domain serves ${list.map((x) => x.key).join(", ")}` })
3399
+ const order = [want, ...list.filter((x) => x !== want)]
3400
+ const task = taskOf(sessionOf(chat, named), chat)
3401
+ const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : []
3402
+ let relogged = false
3403
+ for (let i = 0; ; ) {
3404
+ const m = order[i]
3405
+ const s = siteOf(site, cred)
3406
+ const url = s.api + CHAT_PATH
3407
+ let body
3408
+ try {
3409
+ body = qoderBody(chat, m, named, task, s)
3410
+ } catch (e) {
3411
+ return errorResponse({ status: 400, message: e?.message ?? String(e) })
3412
+ }
3413
+ const wire = encodeBody(JSON.stringify(body))
3414
+ const call = new AbortController()
3415
+ const signal = init.signal ? AbortSignal.any([init.signal, call.signal]) : call.signal
3416
+ let res, open
3417
+ try {
3418
+ res = await fetch(url, { method: "POST", headers: lingmaHeaders(url, cred, wire, s), body: wire, signal })
3419
+ if (res.ok) open = await opened(res, tools)
3420
+ } catch (e) {
3421
+ return errorResponse({ status: 502, message: e.message })
3422
+ }
3423
+ const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
3424
+ if (f) call.abort()
3425
+ if (f && (f.lapsed || LINGMA_LAPSED.test(f.message))) {
3426
+ if (getAuth && !relogged) {
3427
+ relogged = true
3428
+ let next
3429
+ try {
3430
+ next = await relogin(getAuth, cred.access)
3431
+ } catch (e) {
3432
+ return signedInError(e)
3433
+ }
3434
+ if (next) {
3435
+ cred = asked.cred = next
3436
+ continue
3437
+ }
3438
+ }
3439
+ return errorResponse({ status: 401, message: `the sign-in lapsed — open Qoder CN IDE so it signs in again (${String(f.message).slice(0, 300)})` })
3440
+ }
3441
+ if (f && LINGMA_NOT_HERE.test(f.message) && i + 1 < order.length) {
3442
+ console.warn(`qoder-cn: ${s.dedicated} doesn't serve ${m.key}; asking ${order[i + 1].key}`)
3443
+ i++
3444
+ continue
3445
+ }
3446
+ if (f) return errorResponse(f)
3447
+ task.answered = true
3448
+ return answer(open, chat, m.key === chat.model ? chat.model : m.key)
3449
+ }
3450
+ }
3451
+
3166
3452
  return {
3167
3453
  // the session the request is part of, for session_id and its task
3168
3454
  // (#330): magpie names it here (DSH's x-deepseek-harness-session-id
@@ -3183,6 +3469,13 @@ const makePlugin = (site) => async ({ client }) => {
3183
3469
  // end on record: usage rotates it once Qoder refuses it, as before.
3184
3470
  refreshLead: RENEW_LEAD,
3185
3471
  async refresh(auth) {
3472
+ // a Lingma 1.0 account: the IDE's newer token, when it has one;
3473
+ // nothing when it hasn't yet (fresh says so once it is needed)
3474
+ if (auth?.type === "oauth" && auth.lingma && auth.access && auth.uid) {
3475
+ const a = latest(auth)
3476
+ const next = await lingmaRenew(siteOf(site, a), a).catch(() => undefined)
3477
+ return next ? changed(auth, { ...a, ...next }) : undefined
3478
+ }
3186
3479
  if (auth?.type !== "oauth" || !auth.access || !auth.uid || !String(auth.refresh ?? "").trim()) return undefined
3187
3480
  const out = await locked(async () => {
3188
3481
  // a request renewed it meanwhile (or magpie hasn't saved this
@@ -3245,7 +3538,8 @@ const makePlugin = (site) => async ({ client }) => {
3245
3538
  const h = new Headers(input instanceof Request ? input.headers : undefined)
3246
3539
  new Headers(init.headers ?? {}).forEach((v, k) => h.set(k, v))
3247
3540
  const asked = {}
3248
- const res = await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1", getAuth, asked)
3541
+ const named = h.get(SESSION)?.trim().slice(0, 128) ?? ""
3542
+ const res = cred.lingma ? await askLingma(chat, cred, init, named, getAuth, asked) : await ask(chat, cred, init, named, h.get(FALLBACK) === "1", getAuth, asked)
3249
3543
  return signed(res, renewed(cred) || (asked.cred !== cred && renewed(asked.cred)))
3250
3544
  },
3251
3545
  }
@@ -3459,4 +3753,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
3459
3753
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
3460
3754
 
3461
3755
  // for tests
3462
- export const _internal = { freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
3756
+ export const _internal = { 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.54",
3
+ "version": "0.2.56",
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": "./index.mjs",