@magpie-community/opencode-qoder-auth 0.2.55 → 0.2.57

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 +42 -4
  2. package/index.mjs +371 -21
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -341,10 +341,8 @@ Qoder IDE's settings: a host or an https address (a path is dropped).
341
341
  It follows Qoder IDE 1.38.0's own rules for that setting:
342
342
 
343
343
  - It first asks `GET <domain>/algo/api/v1/version`. A 404 means a legacy
344
- Lingma 1.0 (通义灵码) dedicated domain. Its sign-in goes through another
345
- protocol, which this plugin doesn't have yet, so the sign-in stops and
346
- says so. Any other answer means Qoder CN 2.0. A domain that doesn't answer
347
- 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.
348
346
  - A Qoder CN 2.0 domain uses the VPC protocol on hosts named the IDE's way:
349
347
  `-openapi` or `-gateway` after the host's first label. An IP or a host
350
348
  with no dot keeps its own origin. The sign-in uses the IDE's client id and
@@ -367,6 +365,46 @@ It follows Qoder IDE 1.38.0's own rules for that setting:
367
365
  The rules come from Qoder IDE's code. This plugin has not been tried with a
368
366
  dedicated account.
369
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
+
370
408
  ## The card's name
371
409
 
372
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"
@@ -223,7 +223,9 @@ const b64url = (buf) => buf.toString("base64url")
223
223
  async function openapi(site, path, { method = "GET", token, body, query } = {}) {
224
224
  const url = new URL(site.openapi + path)
225
225
  for (const [k, v] of Object.entries(query ?? {})) url.searchParams.set(k, v)
226
- const headers = { Accept: "application/json" }
226
+ // a site whose own client names itself on these calls (QwenWork) sends
227
+ // the same names
228
+ const headers = { Accept: "application/json", ...(site.clientHeaders?.() ?? {}) }
227
229
  if (body) headers["Content-Type"] = "application/json"
228
230
  if (token) headers.Authorization = `Bearer ${token}`
229
231
  const res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(20_000) })
@@ -394,25 +396,217 @@ async function dedicatedProbe(origin) {
394
396
  }
395
397
 
396
398
  // 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).
399
+ // sign-in. A Lingma 1.0 domain (404 at the probe) is signed in to with the
400
+ // account Qoder CN IDE holds for it (lingmaSignIn). The chat host is the
401
+ // gateway host when it answers at all, else the domain's own origin, which
402
+ // answered the probe on the same /algo path; the IDE leaves this to its
403
+ // language server, whose rule wasn't read (inferred).
402
404
  async function dedicatedSignIn(site, input) {
403
405
  const origin = dedicatedOrigin(input)
404
406
  if (!origin) throw new Error(`Not a dedicated domain: ${String(input ?? "").slice(0, 100)}`)
405
407
  const status = await dedicatedProbe(origin)
406
408
  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
- )
409
+ if (status === 404) return lingmaSignIn(site, origin)
411
410
  const gateway = dedicatedHost(origin, "-gateway")
412
411
  const api = gateway !== origin && (await dedicatedProbe(gateway)) === undefined ? origin : undefined
413
412
  return deviceSignIn(dedicatedSite(site, origin, api))
414
413
  }
415
414
 
415
+ // ---- Lingma 1.0 dedicated domains (通义灵码专属版) ---------------------------
416
+ //
417
+ // A domain that answers 404 at the probe is a Lingma 1.0 deployment. Qoder
418
+ // CN IDE (1.38.0) signs in to one through its language server, not the
419
+ // device flow ("use extension 127 login", _loginWithExtension("dedicated")),
420
+ // and such a host serves none of the device flow: /device/selectAccounts and
421
+ // /api/v1/jobToken/exchange answer 404, a console PAT or the console's
422
+ // cookies are answered {"code":"105","message":"Login timeout"} at /algo,
423
+ // and /algo/api/v3/user/* "Request discarded" (all measured on Milktea's
424
+ // host). What works is the session the IDE's worker already holds once the
425
+ // user has signed in there, read from its cache as the worker writes it
426
+ // (Milktea's gist, plugins Discord 2026-11-03):
427
+ // <cosyHome>/cache/id the worker's machine id, a plain uuid (or <cosyHome>/id)
428
+ // <cosyHome>/cache/user base64(AES-128-CBC(JSON)), key = IV = the id's first 16 chars
429
+ // whose JSON has uid, organization_id, name, email, security_oauth_token,
430
+ // refresh_token and expire_time (ms). cosyHome is the IDE's userDataPath
431
+ // with SharedClientCache after it (its main.js; the worker is started with
432
+ // --workDir there): ~/Library/Application Support/QoderCN on macOS,
433
+ // %APPDATA%\QoderCN on Windows, $XDG_CONFIG_HOME (~/.config)/QoderCN on
434
+ // Linux. "Qoder CN" and ~/.lingma are the older layouts the gist found.
435
+ // The worker renews that session itself (its "CN 1.0 refresh"), so the
436
+ // account here is renewed by reading the cache again, never by a refresh
437
+ // call of its own: the host serves none that was found.
438
+ //
439
+ // Its chat is the same agent_chat_generation, signed with the COSY envelope
440
+ // as the worker signs it (the gist's capture): Cosy-ClientType 0, the
441
+ // worker's own version 2.5.18, no Cosy-Scene or Cosy-Business-*, and the
442
+ // assistant scene. Its model list names keys the chat refuses ("Model not
443
+ // exist"), so the models are the IDE's own (its modelSelector.item.* names):
444
+ // a key the domain refuses falls through to the next.
445
+ const LINGMA_VERSION = "2.5.18"
446
+ const LINGMA_LEAD = 5 * 60 * 1000
447
+ const LINGMA_MODELS = [
448
+ { key: "qmodel_latest", name: "Qwen3.7-Max" },
449
+ { key: "dashscope_qmodel", name: "Qwen3.7-Plus" },
450
+ { key: "q36fmodel", name: "Qwen3.6-Flash" },
451
+ ]
452
+ const LINGMA_LAPSED = /"code"\s*:\s*"?105"?|Login (?:expired|timeout)/i
453
+ const LINGMA_NOT_HERE = /model_not_found|Model not exist/i
454
+
455
+ // lingmaRoots is where Qoder CN IDE's worker keeps its cache on this
456
+ // system: QODERCN_COSY_HOME first, then the IDE's own folder, then the
457
+ // older layouts. HOME is read first, so a sandboxed HOME is the one
458
+ // looked in.
459
+ function lingmaRoots(env = process.env, platform = process.platform, home = env.HOME || env.USERPROFILE || homedir()) {
460
+ const roots = []
461
+ const add = (p) => p && !roots.includes(p) && roots.push(p)
462
+ add(String(env.QODERCN_COSY_HOME ?? "").trim())
463
+ if (platform === "darwin") add(join(home, "Library", "Application Support", "QoderCN", "SharedClientCache"))
464
+ else if (platform === "win32") add(join(env.APPDATA || join(home, "AppData", "Roaming"), "QoderCN", "SharedClientCache"))
465
+ else add(join(env.XDG_CONFIG_HOME || join(home, ".config"), "QoderCN", "SharedClientCache"))
466
+ add(join(home, ".config", "QoderCN", "SharedClientCache"))
467
+ add(join(home, ".config", "Qoder CN", "SharedClientCache"))
468
+ add(join(home, ".lingma"))
469
+ return roots
470
+ }
471
+
472
+ // lingmaDecode is the account one cosyHome holds, or why there is none.
473
+ async function lingmaDecode(root) {
474
+ const read = async (p) => (await readFile(p, "utf8").catch(() => "")).trim()
475
+ const id = (await read(join(root, "cache", "id"))) || (await read(join(root, "id")))
476
+ const blob = await read(join(root, "cache", "user"))
477
+ if (!id || !blob) return { root, reason: "no cache/id and cache/user" }
478
+ const key = Buffer.from(id.slice(0, 16), "utf8")
479
+ if (key.length !== 16) return { root, reason: "the machine id is too short" }
480
+ let a
481
+ try {
482
+ const d = createDecipheriv("aes-128-cbc", key, key)
483
+ a = JSON.parse(Buffer.concat([d.update(Buffer.from(blob, "base64")), d.final()]).toString("utf8"))
484
+ } catch {
485
+ return { root, reason: "cache/user doesn't open with the machine id" }
486
+ }
487
+ const access = String(a?.security_oauth_token ?? "").trim()
488
+ const uid = String(a?.uid ?? "").trim()
489
+ if (!access || !uid) return { root, reason: "cache/user names no signed-in account" }
490
+ const end = Number(a.expire_time)
491
+ return {
492
+ root,
493
+ machineId: id,
494
+ uid,
495
+ access,
496
+ email: String(a.email ?? ""),
497
+ name: String(a.name ?? ""),
498
+ orgId: String(a.organization_id ?? ""),
499
+ expires: Number.isFinite(end) && end > 0 ? end : 0,
500
+ }
501
+ }
502
+
503
+ // lingmaRead is the first account the IDE's caches hold, or an Error that
504
+ // says where it looked and what it found.
505
+ async function lingmaRead(site, roots = lingmaRoots()) {
506
+ const seen = []
507
+ for (const root of roots) {
508
+ const got = await lingmaDecode(root)
509
+ if (got.access) return got
510
+ seen.push(`${root}: ${got.reason}`)
511
+ }
512
+ return new SignInGone(
513
+ `${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("; ")}`,
514
+ true,
515
+ )
516
+ }
517
+
518
+ const lingmaLive = (got, now = Date.now()) => !got.expires || got.expires - now > LINGMA_LEAD
519
+
520
+ // lingmaAccount is the account a read gives for the domain at origin.
521
+ function lingmaAccount(site, origin, got) {
522
+ const host = new URL(origin).host
523
+ return {
524
+ type: "success",
525
+ access: got.access,
526
+ // nothing here spends a refresh token: the IDE's worker renews it
527
+ refresh: "",
528
+ expires: got.expires || Date.now() + DAY,
529
+ accountId: `${got.email || got.uid} (${host})`,
530
+ cardName: `${got.email || got.name || got.uid} (${host})`,
531
+ uid: got.uid,
532
+ email: got.email,
533
+ name: got.name,
534
+ ...(got.orgId ? { orgId: got.orgId } : {}),
535
+ machineId: got.machineId,
536
+ deviceToken: "",
537
+ deviceRefresh: "",
538
+ dedicated: host,
539
+ lingma: true,
540
+ }
541
+ }
542
+
543
+ // lingmaSignIn signs in to a Lingma 1.0 domain with the account Qoder CN
544
+ // IDE holds, read when the sign-in is asked for so a missing or lapsed one
545
+ // is said at once.
546
+ async function lingmaSignIn(site, origin, roots) {
547
+ const got = await lingmaRead(site, roots)
548
+ if (got instanceof Error) throw got
549
+ if (!lingmaLive(got))
550
+ throw new SignInGone(
551
+ `${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`,
552
+ true,
553
+ )
554
+ return {
555
+ url: origin,
556
+ 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})`,
557
+ method: "auto",
558
+ async callback() {
559
+ return lingmaAccount(site, origin, got)
560
+ },
561
+ }
562
+ }
563
+
564
+ // lingmaRenew is a newer token for a, from the IDE's cache: what changed,
565
+ // or SignInGone (expired) when the IDE holds none newer that is live.
566
+ async function lingmaRenew(site, a, roots) {
567
+ const got = await lingmaRead(site, roots)
568
+ if (got instanceof Error) throw got
569
+ if (got.uid !== a.uid)
570
+ throw new SignInGone(`${site.name}: Qoder CN IDE is now signed in as another account (${got.email || got.uid}); sign in here again`, true)
571
+ if (got.access === a.access || !lingmaLive(got))
572
+ 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)
573
+ return { access: got.access, expires: got.expires || Date.now() + DAY, machineId: got.machineId }
574
+ }
575
+
576
+ // lingmaSite is site served from a Lingma 1.0 domain: every call on its
577
+ // own origin, signed as the IDE's worker signs them.
578
+ function lingmaSite(site, domain) {
579
+ const origin = dedicatedOrigin(domain)
580
+ if (!origin) return undefined
581
+ const host = new URL(origin).host
582
+ return {
583
+ ...site,
584
+ web: origin,
585
+ openapi: origin,
586
+ api: origin,
587
+ vpc: host,
588
+ dedicated: host,
589
+ lingma: true,
590
+ clientType: "0",
591
+ cosyVersion: LINGMA_VERSION,
592
+ modelScene: "assistant",
593
+ sessionType: "assistant",
594
+ }
595
+ }
596
+
597
+ // lingmaHeaders are a Lingma chat's headers, as the IDE's worker sent them
598
+ // (the gist's capture): the envelope with no scene or business headers.
599
+ function lingmaHeaders(url, u, body, site) {
600
+ const h = cosyHeaders(url, u, body, site)
601
+ delete h["Cosy-Scene"]
602
+ delete h["Cosy-Business-Product"]
603
+ delete h["Cosy-Business-Type"]
604
+ return { ...h, Accept: "text/event-stream", "Cache-Control": "no-cache", "x-request-id": randomUUID() }
605
+ }
606
+
607
+ // lingmaModel is a Lingma model as a request carries it
608
+ const lingmaModel = (m) => modelInfo({ key: m.key, display_name: m.name, format: "dashscope", source: "system", max_input_tokens: 180_000 })
609
+
416
610
  // siteOf is the site an account is served from: its VPC instance's when it
417
611
  // was signed in to one, else site. An instance on record that names none
418
612
  // is not read as "no VPC", which would send the enterprise's tokens to the
@@ -423,7 +617,13 @@ function siteOf(site, a) {
423
617
  // enterpriseHost, not the site's vpcDomain (Qoder CN's VPC suffix rule)
424
618
  if (a?.enterpriseHost) {
425
619
  const base = `https://${a.enterpriseHost}`
426
- return { ...site, web: base, openapi: base, api: base, vpc: a.enterpriseHost }
620
+ // and with no redirect_uri, as its sign-in had none
621
+ return { ...site, web: base, openapi: base, api: base, vpc: a.enterpriseHost, redirect: "" }
622
+ }
623
+ if (a?.dedicated && a.lingma) {
624
+ const s = lingmaSite(site, a.dedicated)
625
+ if (!s) throw new SignInGone(`${site.name}: the account's dedicated domain "${a.dedicated}" isn't one; sign in again`)
626
+ return s
427
627
  }
428
628
  if (a?.dedicated) {
429
629
  const s = dedicatedSite(site, a.dedicated, a.dedicatedApi)
@@ -479,10 +679,12 @@ async function deviceSignIn(site) {
479
679
  let name = ""
480
680
  let uid = dt.user_id
481
681
  let user = null
682
+ let identity = {}
482
683
  try {
483
684
  const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: dt.token })
484
685
  if (ui.status >= 200 && ui.status < 300) {
485
686
  user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
687
+ if (site.deviceRefreshTarget) identity = accountIdentity(ui.json)
486
688
  ;[email, name] = [user?.email ?? "", user?.name ?? ""]
487
689
  if (site.deviceOnly) uid = String(user?.id ?? user?.user_id ?? user?.uid ?? uid ?? "") || undefined
488
690
  // a VPC poll may give the token alone: the user is then the one
@@ -519,6 +721,7 @@ async function deviceSignIn(site) {
519
721
  machineId,
520
722
  deviceToken: dt.token,
521
723
  deviceRefresh: dt.refresh_token ?? "",
724
+ ...identity,
522
725
  ...(site.vpc ? { vpc: site.vpc } : {}),
523
726
  ...(site.enterpriseDomain ? { vpc: site.enterpriseDomain, enterpriseHost: site.enterpriseDomain } : {}),
524
727
  ...(site.dedicated ? { dedicated: site.dedicated, ...(site.api !== dedicatedHost(site.web, "-gateway") ? { dedicatedApi: site.api } : {}) } : {}),
@@ -822,7 +1025,14 @@ async function fetchListing(site, cred) {
822
1025
  // flagship answers 503 "Model catalog is unavailable") falls back to
823
1026
  // the list its site ships
824
1027
  if (res.status === 503 && site.fallbackModels) return site.fallbackModels
825
- throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}`)
1028
+ // QwenWork's "User identity could not be verified" (tnt1223 on
1029
+ // Discord): before 0.2.57 a biz account's token was refreshed as
1030
+ // personal, and no gateway call named the client. A sign-in records
1031
+ // the account's identity, which the refresh then asks for.
1032
+ const again = res.status === 403 && site.deviceRefreshTarget && /identity could not be verified/i.test(text)
1033
+ ? ` — ${site.name} didn't recognise this sign-in's identity; sign in to the account again`
1034
+ : ""
1035
+ throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}${again}`)
826
1036
  }
827
1037
  return JSON.parse(text)
828
1038
  }
@@ -1901,6 +2111,13 @@ async function* events(body, tools = []) {
1901
2111
  } catch {
1902
2112
  continue
1903
2113
  }
2114
+ // a refusal said inside an OK frame (a Lingma 1.0 domain's "Model not
2115
+ // exist" or 105): the turn's failure, not a chunk to read past into an
2116
+ // empty answer
2117
+ if (!Array.isArray(chunk?.choices) && (chunk?.error || (chunk?.code != null && chunk?.message))) {
2118
+ yield { error: failure(502, inner) }
2119
+ return
2120
+ }
1904
2121
  const delta = chunk?.choices?.[0]?.delta ?? {}
1905
2122
  if (delta.reasoning_content) {
1906
2123
  said = true
@@ -2349,16 +2566,30 @@ async function campaignCall(url, method, body, deviceToken, machine, signal) {
2349
2566
  })
2350
2567
  }
2351
2568
 
2569
+ // deviceRefreshBody is what the device token's refresh is asked with. A
2570
+ // site with a refresh target (QwenWork) asks as its client does
2571
+ // (refreshDeviceToken): a biz account for its own team, any other for
2572
+ // "c", and with the client id and redirect_uri when the site signs in with
2573
+ // that pair. Asked for "c", a biz account's token was rotated to its
2574
+ // personal identity.
2575
+ function deviceRefreshBody(site, refresh, a = {}) {
2576
+ if (!site.deviceRefreshTarget) return { refresh_token: refresh }
2577
+ const body = a?.identity === "biz" && a?.teamId
2578
+ ? { refresh_token: refresh, target: "biz", team_id: a.teamId }
2579
+ : { refresh_token: refresh, target: site.deviceRefreshTarget }
2580
+ return site.clientId && site.redirect ? { ...body, client_id: site.clientId, redirect_uri: site.redirect } : body
2581
+ }
2582
+
2352
2583
  // refreshDevice trades the device refresh token for a new pair; it rotates
2353
2584
  // too, so the caller saves it.
2354
- async function refreshDevice(site, refresh, chat = false) {
2585
+ async function refreshDevice(site, refresh, chat = false, a = {}) {
2355
2586
  if (!String(refresh ?? "").trim()) {
2356
2587
  if (chat) throw new SignInGone(`${site.name}: the sign-in lapsed; sign in again`)
2357
2588
  throw new Error("qoder device token refresh: missing refresh token; sign in again")
2358
2589
  }
2359
2590
  let r
2360
2591
  try {
2361
- r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh, ...(site.deviceRefreshTarget ? { target: site.deviceRefreshTarget } : {}) } })
2592
+ r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: deviceRefreshBody(site, refresh, a) })
2362
2593
  } catch (e) {
2363
2594
  throw new Error(`qoder device token refresh: request failed: ${e?.message ?? e}`)
2364
2595
  }
@@ -2576,6 +2807,47 @@ const parseAccountContext = (ctx, wallets) => {
2576
2807
  return out
2577
2808
  }
2578
2809
 
2810
+ // QWENWORK_APP is the QwenWork desktop release these calls name, as
2811
+ // QwenWorkCN.app 1.2.1's package.json has it (version, and
2812
+ // qoderworkUpgradeVersion for the release and its build).
2813
+ const QWENWORK_APP = { version: "1.2.1", release: "1.2.1-26092107" }
2814
+
2815
+ // qwenworkClientHeaders are the names QwenWork's own client puts on every
2816
+ // gateway call it makes outside a chat (openApiJsonRequest: buildUserAgent,
2817
+ // a fresh X-Request-Id and getQwenWorkClientHeaders): the sign-in poll, the
2818
+ // account-context, the device token's refresh. Without them every such
2819
+ // call went out as no client at all.
2820
+ const qwenworkClientHeaders = () => ({
2821
+ "User-Agent": `qoderwork/${QWENWORK_APP.version}`,
2822
+ "X-Request-Id": randomUUID(),
2823
+ "X-QwenWork-Version": QWENWORK_APP.version,
2824
+ "X-QwenWork-Release-Version": QWENWORK_APP.release,
2825
+ "X-QwenWork-Build": QWENWORK_APP.release.split("-")[1],
2826
+ "X-QwenWork-Platform": process.platform,
2827
+ "X-QwenWork-Arch": process.arch,
2828
+ "X-QwenWork-Channel": "stable",
2829
+ })
2830
+
2831
+ // accountIdentity is the identity QwenWork's client reads off the
2832
+ // account-context (fetchUserInfo over normalizeAccountContext: the
2833
+ // envelope's data with data.user spread over it; getIdentityFromUser): a
2834
+ // biz account names its team, which the device token's refresh is asked
2835
+ // for; anything else is the personal "c" identity, and gives nothing.
2836
+ function accountIdentity(v) {
2837
+ const e = v?.data ?? v
2838
+ if (!e || typeof e !== "object") return {}
2839
+ const u = e.user && typeof e.user === "object" && !Array.isArray(e.user) ? { ...e, ...e.user } : e
2840
+ const str = (o, keys) => {
2841
+ for (const k of keys) if (typeof o?.[k] === "string" && o[k].length > 0) return o[k]
2842
+ return null
2843
+ }
2844
+ const org = u.organization && typeof u.organization === "object" ? u.organization : null
2845
+ const isBiz = typeof u.is_biz === "boolean" ? u.is_biz : u.isBiz === true
2846
+ const orgId = str(u, ["orgId", "organization_id", "organizationId"]) ?? str(org, ["org_id", "orgId", "id"])
2847
+ const teamId = str(u, ["team_id", "teamId"]) ?? str(org, ["team_id", "teamId"])
2848
+ return isBiz && orgId && teamId ? { identity: "biz", teamId } : {}
2849
+ }
2850
+
2579
2851
  const QWENWORK_COMMON = {
2580
2852
  clientId: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb", // the desktop client's
2581
2853
  rsaKey: QWENWORK_RSA_KEY,
@@ -2585,6 +2857,7 @@ const QWENWORK_COMMON = {
2585
2857
  redirect: "qwenwork-cn://",
2586
2858
  deviceOnly: true, // the device token is itself the chat token
2587
2859
  deviceRefreshTarget: "c",
2860
+ clientHeaders: qwenworkClientHeaders,
2588
2861
  modelScene: "qwork", listAllModels: true,
2589
2862
  clientType: "6", businessProduct: "qoder_work", sessionType: "qoder_work",
2590
2863
  userInfoPath: "/api/v1/adapter/user/account-context?include=user,plan,quota,page,data_sharing",
@@ -2733,10 +3006,12 @@ const makePlugin = (site) => async ({ client }) => {
2733
3006
  // exchanges the PAT again: the PAT lasts a year, the refresh two days.
2734
3007
  const renew = async (a) => {
2735
3008
  const s = siteOf(site, a)
3009
+ // a Lingma 1.0 account: the token Qoder CN IDE's worker renewed
3010
+ if (a.lingma) return lingmaRenew(s, a)
2736
3011
  if (a.deviceChat) {
2737
3012
  // the device token is the chat token: renewed as a device token,
2738
3013
  // both pairs being the one pair
2739
- const dt = await refreshDevice(s, a.refresh, true)
3014
+ const dt = await refreshDevice(s, a.refresh, true, a)
2740
3015
  return spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh })
2741
3016
  }
2742
3017
  let jt
@@ -2825,6 +3100,8 @@ const makePlugin = (site) => async ({ client }) => {
2825
3100
  const models = async (cred, again = false) => {
2826
3101
  const key = listingKey(cred)
2827
3102
  let l = listings.get(key)
3103
+ // a Lingma 1.0 domain's listing names keys its chat refuses: the IDE's own
3104
+ if (cred.lingma) return LINGMA_MODELS.map(lingmaModel)
2828
3105
  if (!l || again) {
2829
3106
  const s = siteOf(site, cred)
2830
3107
  const listing = await fetchListing(s, cred)
@@ -2845,7 +3122,7 @@ const makePlugin = (site) => async ({ client }) => {
2845
3122
  locked(async () => {
2846
3123
  const a = latest(await getAuth())
2847
3124
  if (a?.deviceToken !== attempted) return a?.deviceToken
2848
- const dt = await refreshDevice(siteOf(site, a), a.deviceRefresh, !!a.deviceChat)
3125
+ const dt = await refreshDevice(siteOf(site, a), a.deviceRefresh, !!a.deviceChat, a)
2849
3126
  const next = { ...a, deviceToken: dt.token, deviceRefresh: dt.refresh }
2850
3127
  // the pair it spent was the chat pair too
2851
3128
  if (a.deviceChat) Object.assign(next, spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh }))
@@ -2884,6 +3161,8 @@ const makePlugin = (site) => async ({ client }) => {
2884
3161
  if (renewed(cred)) signIn = "renewed"
2885
3162
  // the card's name: magpie takes usage's `user` for it and never as a key
2886
3163
  const who = cred?.cardName ? { user: cred.cardName } : {}
3164
+ // a Lingma 1.0 domain serves no usage read that was found
3165
+ if (cred.lingma) return { windows: [], signIn, ...who }
2887
3166
  // a site with its own usage path (QwenWork's account-context, signed
2888
3167
  // like any other call and answered with its own envelope) is read
2889
3168
  // there; a 401 rotates the device token once, as the qoder path does
@@ -2891,7 +3170,7 @@ const makePlugin = (site) => async ({ client }) => {
2891
3170
  const read = async (token, path = site.usagePath) => {
2892
3171
  const s = siteOf(site, cred)
2893
3172
  const res = await fetch(`${s.openapi}${path}`, {
2894
- headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
3173
+ headers: { Accept: "application/json", ...(s.clientHeaders?.() ?? {}), Authorization: `Bearer ${token}` },
2895
3174
  signal: AbortSignal.timeout(20_000),
2896
3175
  })
2897
3176
  if (res.status !== 200) throw new UsageStatus(res.status)
@@ -2973,6 +3252,7 @@ const makePlugin = (site) => async ({ client }) => {
2973
3252
  const checkin = async (getAuth) => {
2974
3253
  let cred
2975
3254
  try {
3255
+ if ((await getAuth())?.lingma) return { outcome: "inactive", message: "a Lingma 1.0 dedicated domain has no daily credits" }
2976
3256
  cred = await fresh(getAuth)
2977
3257
  } catch (e) {
2978
3258
  return { outcome: "failed", message: e?.message ?? String(e), ...(e?.expired ? { signIn: "expired" } : {}) }
@@ -3176,6 +3456,68 @@ const makePlugin = (site) => async ({ client }) => {
3176
3456
  }
3177
3457
  }
3178
3458
 
3459
+ // askLingma is ask for a Lingma 1.0 account: the IDE's models, signed as
3460
+ // its worker signs them, a model the domain refuses ("Model not exist",
3461
+ // said inside the stream) followed by the next, and a refused token (105)
3462
+ // asked again once with the token the IDE renewed meanwhile.
3463
+ const askLingma = async (chat, cred, init, named, getAuth, asked) => {
3464
+ asked.cred = cred
3465
+ const list = LINGMA_MODELS.map(lingmaModel)
3466
+ const want = list.find((x) => x.key === chat.model)
3467
+ if (!want) return errorResponse({ status: 400, message: `unknown model "${chat.model}"; this dedicated domain serves ${list.map((x) => x.key).join(", ")}` })
3468
+ const order = [want, ...list.filter((x) => x !== want)]
3469
+ const task = taskOf(sessionOf(chat, named), chat)
3470
+ const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : []
3471
+ let relogged = false
3472
+ for (let i = 0; ; ) {
3473
+ const m = order[i]
3474
+ const s = siteOf(site, cred)
3475
+ const url = s.api + CHAT_PATH
3476
+ let body
3477
+ try {
3478
+ body = qoderBody(chat, m, named, task, s)
3479
+ } catch (e) {
3480
+ return errorResponse({ status: 400, message: e?.message ?? String(e) })
3481
+ }
3482
+ const wire = encodeBody(JSON.stringify(body))
3483
+ const call = new AbortController()
3484
+ const signal = init.signal ? AbortSignal.any([init.signal, call.signal]) : call.signal
3485
+ let res, open
3486
+ try {
3487
+ res = await fetch(url, { method: "POST", headers: lingmaHeaders(url, cred, wire, s), body: wire, signal })
3488
+ if (res.ok) open = await opened(res, tools)
3489
+ } catch (e) {
3490
+ return errorResponse({ status: 502, message: e.message })
3491
+ }
3492
+ const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
3493
+ if (f) call.abort()
3494
+ if (f && (f.lapsed || LINGMA_LAPSED.test(f.message))) {
3495
+ if (getAuth && !relogged) {
3496
+ relogged = true
3497
+ let next
3498
+ try {
3499
+ next = await relogin(getAuth, cred.access)
3500
+ } catch (e) {
3501
+ return signedInError(e)
3502
+ }
3503
+ if (next) {
3504
+ cred = asked.cred = next
3505
+ continue
3506
+ }
3507
+ }
3508
+ return errorResponse({ status: 401, message: `the sign-in lapsed — open Qoder CN IDE so it signs in again (${String(f.message).slice(0, 300)})` })
3509
+ }
3510
+ if (f && LINGMA_NOT_HERE.test(f.message) && i + 1 < order.length) {
3511
+ console.warn(`qoder-cn: ${s.dedicated} doesn't serve ${m.key}; asking ${order[i + 1].key}`)
3512
+ i++
3513
+ continue
3514
+ }
3515
+ if (f) return errorResponse(f)
3516
+ task.answered = true
3517
+ return answer(open, chat, m.key === chat.model ? chat.model : m.key)
3518
+ }
3519
+ }
3520
+
3179
3521
  return {
3180
3522
  // the session the request is part of, for session_id and its task
3181
3523
  // (#330): magpie names it here (DSH's x-deepseek-harness-session-id
@@ -3196,6 +3538,13 @@ const makePlugin = (site) => async ({ client }) => {
3196
3538
  // end on record: usage rotates it once Qoder refuses it, as before.
3197
3539
  refreshLead: RENEW_LEAD,
3198
3540
  async refresh(auth) {
3541
+ // a Lingma 1.0 account: the IDE's newer token, when it has one;
3542
+ // nothing when it hasn't yet (fresh says so once it is needed)
3543
+ if (auth?.type === "oauth" && auth.lingma && auth.access && auth.uid) {
3544
+ const a = latest(auth)
3545
+ const next = await lingmaRenew(siteOf(site, a), a).catch(() => undefined)
3546
+ return next ? changed(auth, { ...a, ...next }) : undefined
3547
+ }
3199
3548
  if (auth?.type !== "oauth" || !auth.access || !auth.uid || !String(auth.refresh ?? "").trim()) return undefined
3200
3549
  const out = await locked(async () => {
3201
3550
  // a request renewed it meanwhile (or magpie hasn't saved this
@@ -3258,7 +3607,8 @@ const makePlugin = (site) => async ({ client }) => {
3258
3607
  const h = new Headers(input instanceof Request ? input.headers : undefined)
3259
3608
  new Headers(init.headers ?? {}).forEach((v, k) => h.set(k, v))
3260
3609
  const asked = {}
3261
- const res = await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1", getAuth, asked)
3610
+ const named = h.get(SESSION)?.trim().slice(0, 128) ?? ""
3611
+ const res = cred.lingma ? await askLingma(chat, cred, init, named, getAuth, asked) : await ask(chat, cred, init, named, h.get(FALLBACK) === "1", getAuth, asked)
3262
3612
  return signed(res, renewed(cred) || (asked.cred !== cred && renewed(asked.cred)))
3263
3613
  },
3264
3614
  }
@@ -3472,4 +3822,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
3472
3822
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
3473
3823
 
3474
3824
  // for tests
3475
- 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 }
3825
+ 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 }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.55",
3
+ "version": "0.2.57",
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",