From a16adb3025b9414ffeab5e22abbcaa6b8972d343 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 09:33:06 +0800 Subject: [PATCH] qoder 0.2.56: Qoder CN signs in to a Lingma 1.0 dedicated domain with Qoder CN IDE's account (Milktea) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Milktea (Discord) said the plugin still can't sign in to their Qoder CN IDE enterprise dedicated domain (企业专属域). Their domain answers 404 at /algo/api/v1/version, so Qoder IDE 1.38.0 counts it as Lingma 1.0 (dedicated_lingma; the IDE then logs "use extension 127 login" and leaves the sign-in to its language server). 0.2.53 refused such a domain. Milktea measured these on that host (their gist): - /device/selectAccounts and /api/v1/jobToken/exchange answer 404. - A console PAT or the console's cookies get 105 "Login timeout" at /algo. - /algo/api/v3/user/* answers "Request discarded". What works is the session the IDE's worker keeps: - /cache/id holds the machine id (or /id). - /cache/user is base64(AES-128-CBC(JSON)), with key = IV = the id's first 16 chars. The JSON has uid, organization_id, email, security_oauth_token (pt-), refresh_token and expire_time. What changed: - The dedicated method's 404 branch now reads that cache (lingmaSignIn). The account it saves has lingma: true, the domain, the IDE's token and its machine id, and is named (). With no cache, or a lapsed one, the sign-in says so and lists the folders it looked in. - cosyHome comes from the CN IDE's main.js: /SharedClientCache. That is ~/Library/Application Support/QoderCN on macOS, %APPDATA%\QoderCN on Windows and $XDG_CONFIG_HOME (~/.config)/QoderCN on Linux. The gist's Linux-only folders, ~/.lingma and QODERCN_COSY_HOME are read too. - Every call goes to the domain itself (lingmaSite). The chat is signed as the gist captured the worker signing it: Cosy-ClientType 0, version 2.5.18, no Cosy-Scene or Cosy-Business-*, the assistant scene, and model_config format dashscope. - The models are the IDE's own keys: qmodel_latest, dashscope_qmodel and q36fmodel, all modelSelector.item.* names in the CN IDE's workbench. The domain's own list names keys its chat refuses. A "Model not exist" said in the stream falls through to the next key. - Renewal reads the cache again; the worker renews its own token ("CN 1.0 refresh" in its strings). This happens near the token's end, in auth.refresh, and once after a 105. With nothing newer, the account gets a 401 marked expired that says to open Qoder CN IDE. - Usage reads nothing, and the check-in is inactive. - events: a frame with no choices that holds an error, or a code and a message, is now the turn's failure. Before, it was read past, which gave an empty answer. This is the only change outside the Lingma path. - README: a section on Lingma 1.0 domains. Run (mote, bun 1.4.2): packages/qoder `bun test`, 375 pass, 0 fail. The new lingma.test.mjs has 11 tests, with fixtures in the gist's literal shapes. fetch is stubbed and HOME is a sandbox. On 0.2.55 all 11 are red. `bun scripts/check.mjs` passes. dedicated.test.mjs lost its "Lingma is refused" test, which lingma.test.mjs now covers. Broken by hand: with Cosy-Scene and Cosy-Business-* kept, and with the events error frame off, 2 of the 11 went red (the chat's headers, and the fall-through on an error said in an OK frame). Not tried: - Any real Lingma dedicated domain or real Qoder CN IDE cache. Milktea's gist was run against one; this code wasn't. - The cache's AES key, the SSE wrapper, the version 2.5.18 and the missing headers come from the gist's capture, not from the IDE's code. - Whether the cached account belongs to the domain entered isn't checked (the cache doesn't name a domain). - The Remote-SSH layout (/SharedClientCache). --- packages/qoder/README.md | 46 ++++- packages/qoder/dedicated.test.mjs | 10 +- packages/qoder/index.mjs | 307 ++++++++++++++++++++++++++++-- packages/qoder/lingma.test.mjs | 274 ++++++++++++++++++++++++++ packages/qoder/package.json | 2 +- 5 files changed, 613 insertions(+), 26 deletions(-) create mode 100644 packages/qoder/lingma.test.mjs diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 668d195..a1d25c8 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -341,10 +341,8 @@ Qoder IDE's settings: a host or an https address (a path is dropped). It follows Qoder IDE 1.38.0's own rules for that setting: - It first asks `GET /algo/api/v1/version`. A 404 means a legacy - Lingma 1.0 (通义灵码) dedicated domain. Its sign-in goes through another - protocol, which this plugin doesn't have yet, so the sign-in stops and - says so. Any other answer means Qoder CN 2.0. A domain that doesn't answer - is refused. + Lingma 1.0 (通义灵码) dedicated domain (see below). Any other answer means + Qoder CN 2.0. A domain that doesn't answer is refused. - A Qoder CN 2.0 domain uses the VPC protocol on hosts named the IDE's way: `-openapi` or `-gateway` after the host's first label. An IP or a host 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: The rules come from Qoder IDE's code. This plugin has not been tried with a dedicated account. +#### Lingma 1.0 dedicated domains (since 0.2.56) + +A Lingma 1.0 domain has no device flow and takes no console PAT. Qoder CN +IDE signs in to it through its own language server. So the plugin uses the +account Qoder CN IDE is already signed in to on this computer: + +1. Sign in to the dedicated domain once in Qoder CN IDE (Settings → + 「企业版专属域登录」). +2. In magpie, choose **Sign in with Qoder CN Enterprise dedicated domain + (企业版专属域)** and enter the same domain. + +The plugin reads the IDE worker's cache, in its `SharedClientCache` folder: + +| System | Folder | +|---|---| +| macOS | `~/Library/Application Support/QoderCN/SharedClientCache` | +| Windows | `%APPDATA%\QoderCN\SharedClientCache` | +| Linux | `$XDG_CONFIG_HOME/QoderCN/SharedClientCache` (`~/.config/...`) | + +It also looks in `~/.config/Qoder CN/SharedClientCache` and `~/.lingma`, and +`QODERCN_COSY_HOME` names another folder. `cache/id` is the machine id, and +`cache/user` is the account, encrypted under that id. + +- Every call goes to the domain itself, signed as the IDE's worker signs + it: `Cosy-ClientType` 0, version 2.5.18, the assistant scene. +- The models are the IDE's own: `qmodel_latest` (Qwen3.7-Max), + `dashscope_qmodel` (Qwen3.7-Plus) and `q36fmodel` (Qwen3.6-Flash). The + domain's own model list names keys its chat refuses. When the domain + answers "Model not exist" for a model, the next one is asked. +- The IDE renews its sign-in itself, and the plugin reads the cache again + near the token's end, or when the domain refuses it (105). When the IDE + holds nothing newer, the account is marked expired: open Qoder CN IDE so + it signs in again. +- Usage and the daily check-in are not read on such a domain. + +The cache layout, the request shape and the models come from Milktea's +tests on a real Lingma dedicated domain. The folders and the model names +were checked against Qoder CN IDE 1.38.0. This plugin itself has not been +tried on one. + ## The card's name An account signed in with a phone is shown by that phone — masked, `138****8000` — not by diff --git a/packages/qoder/dedicated.test.mjs b/packages/qoder/dedicated.test.mjs index a9608ed..e72107c 100644 --- a/packages/qoder/dedicated.test.mjs +++ b/packages/qoder/dedicated.test.mjs @@ -3,7 +3,7 @@ // Nothing here comes from a real dedicated account: the rules are read from // Qoder IDE 1.38.0's workbench (config.general.dedicatedUrl): // - its probe GETs /algo/api/v1/version; 404 is a Lingma 1.0 -// dedicated domain, any other status Qoder CN 2.0; +// dedicated domain (lingma.test.mjs), any other status Qoder CN 2.0; // - a 2.0 domain signs in at /device/selectAccounts with the IDE's // client id and no redirect_uri, and polls and reads the user on the host // named with "-openapi" after its first label ("-gateway" for its gateway); @@ -147,13 +147,7 @@ test("a Qoder CN 2.0 dedicated sign-in probes, opens the domain's page and polls expect(hostsOf()).toEqual([WEB, GATEWAY, OPENAPI]) }, 10_000) -test("a domain that answers 404 at /algo/api/v1/version is Lingma 1.0 and is refused before any sign-in", async () => { - toServer() - route = () => new Response("", { status: 404 }) - const m = dedicatedMethod(await QoderCNAuthPlugin({ client: store().client })) - await expect(m.authorize({ dedicated: WEB })).rejects.toThrow("Lingma 1.0") - expect(seen.map((s) => s.host + s.path)).toEqual([WEB + "/algo/api/v1/version"]) -}) +// a domain that answers 404 at the probe is Lingma 1.0: lingma.test.mjs test("a domain that doesn't answer is refused, never read as either kind", async () => { toServer() diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index d2b91ce..75f3a64 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -34,9 +34,9 @@ // -openapi.vpc.qoder.com.cn, and gateway.qoder.com.cn becomes // -gateway.vpc.qoder.com.cn. The instance is kept on the account, // and an account with none is served as before. -import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto" +import { createCipheriv, createDecipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto" import { execFile } from "node:child_process" -import { readdir, stat } from "node:fs/promises" +import { readFile, readdir, stat } from "node:fs/promises" import { STATUS_CODES } from "node:http" import { homedir, hostname } from "node:os" import { join, resolve } from "node:path" @@ -394,25 +394,217 @@ async function dedicatedProbe(origin) { } // dedicatedSignIn reads the domain as the IDE does and starts its device -// sign-in. A legacy Lingma domain is refused with what it is: its sign-in -// (cosy's login/generateUrl, a qoder-cn-ide:// callback) isn't served here. -// The chat host is the gateway host when it answers at all, else the -// domain's own origin, which answered the probe on the same /algo path; the -// IDE leaves this to its language server, whose rule wasn't read (inferred). +// sign-in. A Lingma 1.0 domain (404 at the probe) is signed in to with the +// account Qoder CN IDE holds for it (lingmaSignIn). The chat host is the +// gateway host when it answers at all, else the domain's own origin, which +// answered the probe on the same /algo path; the IDE leaves this to its +// language server, whose rule wasn't read (inferred). async function dedicatedSignIn(site, input) { const origin = dedicatedOrigin(input) if (!origin) throw new Error(`Not a dedicated domain: ${String(input ?? "").slice(0, 100)}`) const status = await dedicatedProbe(origin) if (status === undefined) throw new Error(`${site.name}: ${origin} didn't answer (${DEDICATED_VERSION}); check the address and your network`) - if (status === 404) - throw new Error( - `${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`, - ) + if (status === 404) return lingmaSignIn(site, origin) const gateway = dedicatedHost(origin, "-gateway") const api = gateway !== origin && (await dedicatedProbe(gateway)) === undefined ? origin : undefined return deviceSignIn(dedicatedSite(site, origin, api)) } +// ---- Lingma 1.0 dedicated domains (通义灵码专属版) --------------------------- +// +// A domain that answers 404 at the probe is a Lingma 1.0 deployment. Qoder +// CN IDE (1.38.0) signs in to one through its language server, not the +// device flow ("use extension 127 login", _loginWithExtension("dedicated")), +// and such a host serves none of the device flow: /device/selectAccounts and +// /api/v1/jobToken/exchange answer 404, a console PAT or the console's +// cookies are answered {"code":"105","message":"Login timeout"} at /algo, +// and /algo/api/v3/user/* "Request discarded" (all measured on Milktea's +// host). What works is the session the IDE's worker already holds once the +// user has signed in there, read from its cache as the worker writes it +// (Milktea's gist, plugins Discord 2026-11-03): +// /cache/id the worker's machine id, a plain uuid (or /id) +// /cache/user base64(AES-128-CBC(JSON)), key = IV = the id's first 16 chars +// whose JSON has uid, organization_id, name, email, security_oauth_token, +// refresh_token and expire_time (ms). cosyHome is the IDE's userDataPath +// with SharedClientCache after it (its main.js; the worker is started with +// --workDir there): ~/Library/Application Support/QoderCN on macOS, +// %APPDATA%\QoderCN on Windows, $XDG_CONFIG_HOME (~/.config)/QoderCN on +// Linux. "Qoder CN" and ~/.lingma are the older layouts the gist found. +// The worker renews that session itself (its "CN 1.0 refresh"), so the +// account here is renewed by reading the cache again, never by a refresh +// call of its own: the host serves none that was found. +// +// Its chat is the same agent_chat_generation, signed with the COSY envelope +// as the worker signs it (the gist's capture): Cosy-ClientType 0, the +// worker's own version 2.5.18, no Cosy-Scene or Cosy-Business-*, and the +// assistant scene. Its model list names keys the chat refuses ("Model not +// exist"), so the models are the IDE's own (its modelSelector.item.* names): +// a key the domain refuses falls through to the next. +const LINGMA_VERSION = "2.5.18" +const LINGMA_LEAD = 5 * 60 * 1000 +const LINGMA_MODELS = [ + { key: "qmodel_latest", name: "Qwen3.7-Max" }, + { key: "dashscope_qmodel", name: "Qwen3.7-Plus" }, + { key: "q36fmodel", name: "Qwen3.6-Flash" }, +] +const LINGMA_LAPSED = /"code"\s*:\s*"?105"?|Login (?:expired|timeout)/i +const LINGMA_NOT_HERE = /model_not_found|Model not exist/i + +// lingmaRoots is where Qoder CN IDE's worker keeps its cache on this +// system: QODERCN_COSY_HOME first, then the IDE's own folder, then the +// older layouts. HOME is read first, so a sandboxed HOME is the one +// looked in. +function lingmaRoots(env = process.env, platform = process.platform, home = env.HOME || env.USERPROFILE || homedir()) { + const roots = [] + const add = (p) => p && !roots.includes(p) && roots.push(p) + add(String(env.QODERCN_COSY_HOME ?? "").trim()) + if (platform === "darwin") add(join(home, "Library", "Application Support", "QoderCN", "SharedClientCache")) + else if (platform === "win32") add(join(env.APPDATA || join(home, "AppData", "Roaming"), "QoderCN", "SharedClientCache")) + else add(join(env.XDG_CONFIG_HOME || join(home, ".config"), "QoderCN", "SharedClientCache")) + add(join(home, ".config", "QoderCN", "SharedClientCache")) + add(join(home, ".config", "Qoder CN", "SharedClientCache")) + add(join(home, ".lingma")) + return roots +} + +// lingmaDecode is the account one cosyHome holds, or why there is none. +async function lingmaDecode(root) { + const read = async (p) => (await readFile(p, "utf8").catch(() => "")).trim() + const id = (await read(join(root, "cache", "id"))) || (await read(join(root, "id"))) + const blob = await read(join(root, "cache", "user")) + if (!id || !blob) return { root, reason: "no cache/id and cache/user" } + const key = Buffer.from(id.slice(0, 16), "utf8") + if (key.length !== 16) return { root, reason: "the machine id is too short" } + let a + try { + const d = createDecipheriv("aes-128-cbc", key, key) + a = JSON.parse(Buffer.concat([d.update(Buffer.from(blob, "base64")), d.final()]).toString("utf8")) + } catch { + return { root, reason: "cache/user doesn't open with the machine id" } + } + const access = String(a?.security_oauth_token ?? "").trim() + const uid = String(a?.uid ?? "").trim() + if (!access || !uid) return { root, reason: "cache/user names no signed-in account" } + const end = Number(a.expire_time) + return { + root, + machineId: id, + uid, + access, + email: String(a.email ?? ""), + name: String(a.name ?? ""), + orgId: String(a.organization_id ?? ""), + expires: Number.isFinite(end) && end > 0 ? end : 0, + } +} + +// lingmaRead is the first account the IDE's caches hold, or an Error that +// says where it looked and what it found. +async function lingmaRead(site, roots = lingmaRoots()) { + const seen = [] + for (const root of roots) { + const got = await lingmaDecode(root) + if (got.access) return got + seen.push(`${root}: ${got.reason}`) + } + return new SignInGone( + `${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("; ")}`, + true, + ) +} + +const lingmaLive = (got, now = Date.now()) => !got.expires || got.expires - now > LINGMA_LEAD + +// lingmaAccount is the account a read gives for the domain at origin. +function lingmaAccount(site, origin, got) { + const host = new URL(origin).host + return { + type: "success", + access: got.access, + // nothing here spends a refresh token: the IDE's worker renews it + refresh: "", + expires: got.expires || Date.now() + DAY, + accountId: `${got.email || got.uid} (${host})`, + cardName: `${got.email || got.name || got.uid} (${host})`, + uid: got.uid, + email: got.email, + name: got.name, + ...(got.orgId ? { orgId: got.orgId } : {}), + machineId: got.machineId, + deviceToken: "", + deviceRefresh: "", + dedicated: host, + lingma: true, + } +} + +// lingmaSignIn signs in to a Lingma 1.0 domain with the account Qoder CN +// IDE holds, read when the sign-in is asked for so a missing or lapsed one +// is said at once. +async function lingmaSignIn(site, origin, roots) { + const got = await lingmaRead(site, roots) + if (got instanceof Error) throw got + if (!lingmaLive(got)) + throw new SignInGone( + `${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`, + true, + ) + return { + url: origin, + 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})`, + method: "auto", + async callback() { + return lingmaAccount(site, origin, got) + }, + } +} + +// lingmaRenew is a newer token for a, from the IDE's cache: what changed, +// or SignInGone (expired) when the IDE holds none newer that is live. +async function lingmaRenew(site, a, roots) { + const got = await lingmaRead(site, roots) + if (got instanceof Error) throw got + if (got.uid !== a.uid) + throw new SignInGone(`${site.name}: Qoder CN IDE is now signed in as another account (${got.email || got.uid}); sign in here again`, true) + if (got.access === a.access || !lingmaLive(got)) + 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) + return { access: got.access, expires: got.expires || Date.now() + DAY, machineId: got.machineId } +} + +// lingmaSite is site served from a Lingma 1.0 domain: every call on its +// own origin, signed as the IDE's worker signs them. +function lingmaSite(site, domain) { + const origin = dedicatedOrigin(domain) + if (!origin) return undefined + const host = new URL(origin).host + return { + ...site, + web: origin, + openapi: origin, + api: origin, + vpc: host, + dedicated: host, + lingma: true, + clientType: "0", + cosyVersion: LINGMA_VERSION, + modelScene: "assistant", + sessionType: "assistant", + } +} + +// lingmaHeaders are a Lingma chat's headers, as the IDE's worker sent them +// (the gist's capture): the envelope with no scene or business headers. +function lingmaHeaders(url, u, body, site) { + const h = cosyHeaders(url, u, body, site) + delete h["Cosy-Scene"] + delete h["Cosy-Business-Product"] + delete h["Cosy-Business-Type"] + return { ...h, Accept: "text/event-stream", "Cache-Control": "no-cache", "x-request-id": randomUUID() } +} + +// lingmaModel is a Lingma model as a request carries it +const lingmaModel = (m) => modelInfo({ key: m.key, display_name: m.name, format: "dashscope", source: "system", max_input_tokens: 180_000 }) + // siteOf is the site an account is served from: its VPC instance's when it // was signed in to one, else site. An instance on record that names none // is not read as "no VPC", which would send the enterprise's tokens to the @@ -425,6 +617,11 @@ function siteOf(site, a) { const base = `https://${a.enterpriseHost}` return { ...site, web: base, openapi: base, api: base, vpc: a.enterpriseHost } } + if (a?.dedicated && a.lingma) { + const s = lingmaSite(site, a.dedicated) + if (!s) throw new SignInGone(`${site.name}: the account's dedicated domain "${a.dedicated}" isn't one; sign in again`) + return s + } if (a?.dedicated) { const s = dedicatedSite(site, a.dedicated, a.dedicatedApi) if (!s) throw new SignInGone(`${site.name}: the account's dedicated domain "${a.dedicated}" isn't one; sign in again`) @@ -1901,6 +2098,13 @@ async function* events(body, tools = []) { } catch { continue } + // a refusal said inside an OK frame (a Lingma 1.0 domain's "Model not + // exist" or 105): the turn's failure, not a chunk to read past into an + // empty answer + if (!Array.isArray(chunk?.choices) && (chunk?.error || (chunk?.code != null && chunk?.message))) { + yield { error: failure(502, inner) } + return + } const delta = chunk?.choices?.[0]?.delta ?? {} if (delta.reasoning_content) { said = true @@ -2733,6 +2937,8 @@ const makePlugin = (site) => async ({ client }) => { // exchanges the PAT again: the PAT lasts a year, the refresh two days. const renew = async (a) => { const s = siteOf(site, a) + // a Lingma 1.0 account: the token Qoder CN IDE's worker renewed + if (a.lingma) return lingmaRenew(s, a) if (a.deviceChat) { // the device token is the chat token: renewed as a device token, // both pairs being the one pair @@ -2825,6 +3031,8 @@ const makePlugin = (site) => async ({ client }) => { const models = async (cred, again = false) => { const key = listingKey(cred) let l = listings.get(key) + // a Lingma 1.0 domain's listing names keys its chat refuses: the IDE's own + if (cred.lingma) return LINGMA_MODELS.map(lingmaModel) if (!l || again) { const s = siteOf(site, cred) const listing = await fetchListing(s, cred) @@ -2884,6 +3092,8 @@ const makePlugin = (site) => async ({ client }) => { if (renewed(cred)) signIn = "renewed" // the card's name: magpie takes usage's `user` for it and never as a key const who = cred?.cardName ? { user: cred.cardName } : {} + // a Lingma 1.0 domain serves no usage read that was found + if (cred.lingma) return { windows: [], signIn, ...who } // a site with its own usage path (QwenWork's account-context, signed // like any other call and answered with its own envelope) is read // there; a 401 rotates the device token once, as the qoder path does @@ -2973,6 +3183,7 @@ const makePlugin = (site) => async ({ client }) => { const checkin = async (getAuth) => { let cred try { + if ((await getAuth())?.lingma) return { outcome: "inactive", message: "a Lingma 1.0 dedicated domain has no daily credits" } cred = await fresh(getAuth) } catch (e) { return { outcome: "failed", message: e?.message ?? String(e), ...(e?.expired ? { signIn: "expired" } : {}) } @@ -3176,6 +3387,68 @@ const makePlugin = (site) => async ({ client }) => { } } + // askLingma is ask for a Lingma 1.0 account: the IDE's models, signed as + // its worker signs them, a model the domain refuses ("Model not exist", + // said inside the stream) followed by the next, and a refused token (105) + // asked again once with the token the IDE renewed meanwhile. + const askLingma = async (chat, cred, init, named, getAuth, asked) => { + asked.cred = cred + const list = LINGMA_MODELS.map(lingmaModel) + const want = list.find((x) => x.key === chat.model) + if (!want) return errorResponse({ status: 400, message: `unknown model "${chat.model}"; this dedicated domain serves ${list.map((x) => x.key).join(", ")}` }) + const order = [want, ...list.filter((x) => x !== want)] + const task = taskOf(sessionOf(chat, named), chat) + const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : [] + let relogged = false + for (let i = 0; ; ) { + const m = order[i] + const s = siteOf(site, cred) + const url = s.api + CHAT_PATH + let body + try { + body = qoderBody(chat, m, named, task, s) + } catch (e) { + return errorResponse({ status: 400, message: e?.message ?? String(e) }) + } + const wire = encodeBody(JSON.stringify(body)) + const call = new AbortController() + const signal = init.signal ? AbortSignal.any([init.signal, call.signal]) : call.signal + let res, open + try { + res = await fetch(url, { method: "POST", headers: lingmaHeaders(url, cred, wire, s), body: wire, signal }) + if (res.ok) open = await opened(res, tools) + } catch (e) { + return errorResponse({ status: 502, message: e.message }) + } + const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error + if (f) call.abort() + if (f && (f.lapsed || LINGMA_LAPSED.test(f.message))) { + if (getAuth && !relogged) { + relogged = true + let next + try { + next = await relogin(getAuth, cred.access) + } catch (e) { + return signedInError(e) + } + if (next) { + cred = asked.cred = next + continue + } + } + return errorResponse({ status: 401, message: `the sign-in lapsed — open Qoder CN IDE so it signs in again (${String(f.message).slice(0, 300)})` }) + } + if (f && LINGMA_NOT_HERE.test(f.message) && i + 1 < order.length) { + console.warn(`qoder-cn: ${s.dedicated} doesn't serve ${m.key}; asking ${order[i + 1].key}`) + i++ + continue + } + if (f) return errorResponse(f) + task.answered = true + return answer(open, chat, m.key === chat.model ? chat.model : m.key) + } + } + return { // the session the request is part of, for session_id and its task // (#330): magpie names it here (DSH's x-deepseek-harness-session-id @@ -3196,6 +3469,13 @@ const makePlugin = (site) => async ({ client }) => { // end on record: usage rotates it once Qoder refuses it, as before. refreshLead: RENEW_LEAD, async refresh(auth) { + // a Lingma 1.0 account: the IDE's newer token, when it has one; + // nothing when it hasn't yet (fresh says so once it is needed) + if (auth?.type === "oauth" && auth.lingma && auth.access && auth.uid) { + const a = latest(auth) + const next = await lingmaRenew(siteOf(site, a), a).catch(() => undefined) + return next ? changed(auth, { ...a, ...next }) : undefined + } if (auth?.type !== "oauth" || !auth.access || !auth.uid || !String(auth.refresh ?? "").trim()) return undefined const out = await locked(async () => { // a request renewed it meanwhile (or magpie hasn't saved this @@ -3258,7 +3538,8 @@ const makePlugin = (site) => async ({ client }) => { const h = new Headers(input instanceof Request ? input.headers : undefined) new Headers(init.headers ?? {}).forEach((v, k) => h.set(k, v)) const asked = {} - const res = await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1", getAuth, asked) + const named = h.get(SESSION)?.trim().slice(0, 128) ?? "" + const res = cred.lingma ? await askLingma(chat, cred, init, named, getAuth, asked) : await ask(chat, cred, init, named, h.get(FALLBACK) === "1", getAuth, asked) return signed(res, renewed(cred) || (asked.cred !== cred && renewed(asked.cred))) }, } @@ -3472,4 +3753,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) { export const protocol = { makePlugin, deviceSignIn, openapi, siteOf } // for tests -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 } +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 } diff --git a/packages/qoder/lingma.test.mjs b/packages/qoder/lingma.test.mjs new file mode 100644 index 0000000..9a3b822 --- /dev/null +++ b/packages/qoder/lingma.test.mjs @@ -0,0 +1,274 @@ +// Qoder CN Lingma 1.0 (通义灵码) dedicated domains: a domain that answers 404 +// at /algo/api/v1/version, as Qoder IDE 1.38.0's probe tells one apart, and +// whose sign-in is the session Qoder CN IDE's worker holds. The shapes are +// Milktea's (plugins Discord 2026-11-03, the redacted gist that was tested on +// a real dedicated host): +// - /cache/id is the machine id (or /id), cache/user is +// base64(AES-128-CBC(JSON)) under key = IV = the id's first 16 chars, and +// the JSON is { uid, yx_uid, organization_id, organization_name, name, +// email, security_oauth_token, refresh_token, expire_time, user_type }; +// - each SSE event is {"headers":…,"body":"","statusCodeValue":…}; +// - "Model not exist" (model_not_found) and 105 "Login timeout" are said +// inside the stream. +// Nothing here reaches the network: fetch is answered in-process. +import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test" +import { createCipheriv } from "node:crypto" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { QoderCNAuthPlugin, _internal } from "./index.mjs" + +const HOST = "corp.rdc.aliyuncs.com" +const ORIGIN = "https://" + HOST +const CHAT = "/algo/api/v2/service/pro/sse/agent_chat_generation" +const MACHINE = "3f2b9c1e-7a4d-4e8f-9b21-6c0d5e4a1f37" + +const real = globalThis.fetch +const saved = {} +let sandbox, cosy, seen, route + +beforeAll(() => { + for (const k of ["HOME", "USERPROFILE", "APPDATA", "XDG_CONFIG_HOME", "QODERCN_COSY_HOME"]) saved[k] = process.env[k] +}) +afterAll(() => { + for (const [k, v] of Object.entries(saved)) v === undefined ? delete process.env[k] : (process.env[k] = v) +}) +beforeEach(() => { + sandbox = mkdtempSync(join(tmpdir(), "qoder-lingma-")) + // every layout the reader knows sits under the sandbox: none of this + // machine's own is read + process.env.HOME = process.env.USERPROFILE = sandbox + process.env.APPDATA = join(sandbox, "AppData", "Roaming") + process.env.XDG_CONFIG_HOME = join(sandbox, ".config") + cosy = join(sandbox, "cosy") + process.env.QODERCN_COSY_HOME = cosy + seen = [] + route = () => new Response("", { status: 404 }) + globalThis.fetch = async (input, init = {}) => { + const u = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url) + const body = typeof init.body === "string" ? init.body : "" + seen.push({ host: u.host, path: u.pathname, search: u.search, headers: new Headers(init.headers), body }) + return route(u.host + u.pathname, { body, headers: new Headers(init.headers) }) + } +}) +afterEach(() => { + globalThis.fetch = real + rmSync(sandbox, { recursive: true, force: true }) +}) + +// ideCache writes the account the IDE's worker caches, as the gist read it +function ideCache(root, account, { idAtRoot = false, id = MACHINE } = {}) { + mkdirSync(join(root, "cache"), { recursive: true }) + writeFileSync(join(root, ...(idAtRoot ? ["id"] : ["cache", "id"])), id + "\n") + const key = Buffer.from(id.slice(0, 16), "utf8") + const c = createCipheriv("aes-128-cbc", key, key) + writeFileSync(join(root, "cache", "user"), Buffer.concat([c.update(JSON.stringify(account), "utf8"), c.final()]).toString("base64")) +} +const ACCOUNT = (over = {}) => ({ + uid: "1234567890123456", + yx_uid: "1234567890123456", + organization_id: "65f0c1d2e3a4b5c6d7e8f901", + organization_name: "Corp", + name: "陈", + email: "milk@corp.example", + security_oauth_token: "pt-AbCdEfGhIjKlMnOpQrStUvW", + refresh_token: "rt-ZyXwVuTsRqPoNmLkJiHgFeD", + expire_time: Date.now() + 6 * 3600_000, + user_type: "enterprise_professional", + ...over, +}) + +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) +const frame = (inner, status = 200) => "data:" + JSON.stringify({ headers: { "Content-Type": ["application/json"] }, body: JSON.stringify(inner), statusCodeValue: status }) + "\n\n" +const sse = (...frames) => new Response(frames.join(""), { headers: { "Content-Type": "text/event-stream" } }) +const OK = frame({ choices: [{ index: 0, delta: { content: "OK" }, finish_reason: "stop" }], model: "qmodel_latest" }) +const NOT_HERE = frame({ error: { message: "Model not exist.", code: "model_not_found" } }, 400) +const LAPSED = frame({ code: "105", message: "Login timeout" }, 403) + +function store(initial) { + let auth = initial + return { client: { auth: { set: async ({ body }) => (auth = body) } }, get: async () => auth, auth: () => auth } +} +const lingmaMethod = (hooks) => hooks.auth.methods.find((m) => m.prompts?.some((p) => p.key === "dedicated")) +const signedIn = (over = {}) => ({ + type: "oauth", + access: "pt-AbCdEfGhIjKlMnOpQrStUvW", + refresh: "", + expires: Date.now() + 3_600_000, + accountId: `milk@corp.example (${HOST})`, + uid: "1234567890123456", + email: "milk@corp.example", + name: "陈", + machineId: MACHINE, + deviceToken: "", + deviceRefresh: "", + dedicated: HOST, + lingma: true, + ...over, +}) +const ask = { model: "qmodel_latest", messages: [{ role: "user", content: "hi" }] } +const chats = () => seen.filter((s) => s.path === CHAT) +const sentModel = (s) => JSON.parse(_internal.decodeBody(s.body)).model_config.key + +test("the IDE's cache is looked for where Qoder CN IDE keeps it on each system, the override first", () => { + const home = "/h" + expect(_internal.lingmaRoots({ QODERCN_COSY_HOME: "/o" }, "darwin", home).slice(0, 2)).toEqual(["/o", join(home, "Library", "Application Support", "QoderCN", "SharedClientCache")]) + expect(_internal.lingmaRoots({ APPDATA: "C:/Users/m/AppData/Roaming" }, "win32", home)[0]).toBe(join("C:/Users/m/AppData/Roaming", "QoderCN", "SharedClientCache")) + expect(_internal.lingmaRoots({}, "win32", home)[0]).toBe(join(home, "AppData", "Roaming", "QoderCN", "SharedClientCache")) + expect(_internal.lingmaRoots({ XDG_CONFIG_HOME: "/x" }, "linux", home)[0]).toBe(join("/x", "QoderCN", "SharedClientCache")) + const linux = _internal.lingmaRoots({}, "linux", home) + expect(linux).toEqual([join(home, ".config", "QoderCN", "SharedClientCache"), join(home, ".config", "Qoder CN", "SharedClientCache"), join(home, ".lingma")]) +}) + +test("the worker's cache/user opens under its machine id, beside it or at the root", async () => { + ideCache(join(sandbox, "a"), ACCOUNT()) + ideCache(join(sandbox, "b"), ACCOUNT({ uid: "u-b" }), { idAtRoot: true }) + const a = await _internal.lingmaDecode(join(sandbox, "a")) + expect(a).toMatchObject({ machineId: MACHINE, uid: "1234567890123456", access: "pt-AbCdEfGhIjKlMnOpQrStUvW", orgId: "65f0c1d2e3a4b5c6d7e8f901", email: "milk@corp.example" }) + expect((await _internal.lingmaDecode(join(sandbox, "b"))).uid).toBe("u-b") + // another machine's id doesn't open it + ideCache(join(sandbox, "c"), ACCOUNT()) + writeFileSync(join(sandbox, "c", "cache", "id"), "00000000-0000-0000-0000-000000000000") + expect((await _internal.lingmaDecode(join(sandbox, "c"))).reason).toContain("doesn't open") + expect((await _internal.lingmaDecode(join(sandbox, "none"))).reason).toContain("no cache/id") +}) + +test("a domain that answers 404 at the probe signs in with the account Qoder CN IDE holds, asking the domain nothing else", async () => { + const end = Date.now() + 6 * 3600_000 + ideCache(cosy, ACCOUNT({ expire_time: end })) + const m = lingmaMethod(await QoderCNAuthPlugin({ client: store().client })) + const flow = await m.authorize({ dedicated: `https://${HOST}/` }) + expect(flow.method).toBe("auto") + expect(flow.instructions).toContain("milk@corp.example") + const cred = await flow.callback() + expect(cred).toMatchObject({ + type: "success", + access: "pt-AbCdEfGhIjKlMnOpQrStUvW", + refresh: "", + expires: end, + uid: "1234567890123456", + orgId: "65f0c1d2e3a4b5c6d7e8f901", + machineId: MACHINE, + accountId: `milk@corp.example (${HOST})`, + dedicated: HOST, + lingma: true, + }) + expect(seen.map((s) => s.host + s.path)).toEqual([HOST + "/algo/api/v1/version"]) +}) + +test("the IDE's own folder is found with no override", async () => { + delete process.env.QODERCN_COSY_HOME + const own = + process.platform === "darwin" + ? join(sandbox, "Library", "Application Support", "QoderCN", "SharedClientCache") + : process.platform === "win32" + ? join(process.env.APPDATA, "QoderCN", "SharedClientCache") + : join(process.env.XDG_CONFIG_HOME, "QoderCN", "SharedClientCache") + ideCache(own, ACCOUNT()) + const flow = await lingmaMethod(await QoderCNAuthPlugin({ client: store().client })).authorize({ dedicated: HOST }) + expect((await flow.callback()).machineId).toBe(MACHINE) +}) + +test("with no IDE sign-in, or a lapsed one, the sign-in says so and where it looked", async () => { + const m = lingmaMethod(await QoderCNAuthPlugin({ client: store().client })) + const none = await m.authorize({ dedicated: HOST }).catch((e) => e) + expect(none.message).toContain("no Qoder CN IDE sign-in found") + expect(none.message).toContain(cosy) + ideCache(cosy, ACCOUNT({ expire_time: Date.now() - 1000 })) + await expect(m.authorize({ dedicated: HOST })).rejects.toThrow("ended") +}) + +test("a Lingma account chats on the domain's origin, signed and written as the IDE's worker sends it", async () => { + route = (at) => (at === HOST + CHAT ? sse(OK) : new Response("", { status: 404 })) + const s = store(signedIn()) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + expect(opts.baseURL).toBe(ORIGIN) + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(ask) }) + expect(res.status).toBe(200) + const out = await res.json() + expect(out.choices[0].message.content).toBe("OK") + expect(out.model).toBe("qmodel_latest") + expect(seen.map((x) => x.host)).toEqual([HOST]) + const [c] = chats() + expect(c.search).toBe("?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1") + const h = c.headers + expect(h.get("cosy-clienttype")).toBe("0") + expect(h.get("cosy-version")).toBe("2.5.18") + expect(h.get("cosy-machineid")).toBe(MACHINE) + expect(h.get("cosy-user")).toBe("1234567890123456") + for (const gone of ["cosy-scene", "cosy-business-product", "cosy-business-type"]) expect([gone, h.get(gone)]).toEqual([gone, null]) + expect(h.get("accept")).toBe("text/event-stream") + expect(h.get("x-request-id")).toMatch(/^[0-9a-f-]{36}$/) + const body = JSON.parse(_internal.decodeBody(c.body)) + expect(body.session_type).toBe("assistant") + expect(body.business.version).toBe("2.5.18") + expect(body.model_config).toMatchObject({ key: "qmodel_latest", format: "dashscope", source: "system" }) +}) + +test("a model the domain refuses inside the stream is followed by the next the IDE knows", async () => { + for (const refusal of [NOT_HERE, frame({ error: { message: "Model not exist.", code: "model_not_found" } })]) { + seen = [] + route = (at, { body }) => { + if (at !== HOST + CHAT) return new Response("", { status: 404 }) + return sse(JSON.parse(_internal.decodeBody(body)).model_config.key === "qmodel_latest" ? refusal : OK) + } + const s = store(signedIn()) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ ...ask, stream: false }) }) + expect(res.status).toBe(200) + expect((await res.json()).model).toBe("dashscope_qmodel") + expect(chats().map(sentModel)).toEqual(["qmodel_latest", "dashscope_qmodel"]) + } +}) + +test("a 105 said in the stream is asked again with the token the IDE renewed, and saved", async () => { + ideCache(cosy, ACCOUNT({ security_oauth_token: "pt-Renewed00000000000000000" })) + route = (at, { headers }) => { + if (at !== HOST + CHAT) return new Response("", { status: 404 }) + return sse(seen.filter((x) => x.path === CHAT).length === 1 ? LAPSED : OK) + } + const s = store(signedIn()) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(ask) }) + expect(res.status).toBe(200) + expect(chats().length).toBe(2) + expect(s.auth().access).toBe("pt-Renewed00000000000000000") +}) + +test("a 105 with no newer IDE token is a 401 that marks the sign-in expired", async () => { + ideCache(cosy, ACCOUNT()) + route = (at) => (at === HOST + CHAT ? sse(LAPSED) : new Response("", { status: 404 })) + const s = store(signedIn()) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(ask) }) + expect(res.status).toBe(401) + expect(res.headers.get("x-magpie-sign-in")).toBe("expired") + expect((await res.json()).error.message).toContain("Qoder CN IDE") + expect(chats().length).toBe(1) +}) + +test("a token near its end is renewed from the IDE's cache, never by a refresh call", async () => { + ideCache(cosy, ACCOUNT({ security_oauth_token: "pt-Renewed00000000000000000" })) + route = (at) => (at === HOST + CHAT ? sse(OK) : new Response("", { status: 404 })) + const s = store(signedIn({ expires: Date.now() + 60_000 })) + const hooks = await QoderCNAuthPlugin({ client: s.client }) + const opts = await hooks.auth.loader(s.get) + expect((await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(ask) })).status).toBe(200) + expect(s.auth().access).toBe("pt-Renewed00000000000000000") + expect(seen.map((x) => x.path)).toEqual([CHAT]) + // magpie's own renewal takes the same, and nothing while the IDE has none newer + expect(await hooks.auth.refresh(signedIn())).toMatchObject({ access: "pt-Renewed00000000000000000" }) + expect(await hooks.auth.refresh(signedIn({ access: "pt-Renewed00000000000000000" }))).toBeUndefined() + expect(seen.map((x) => x.path)).toEqual([CHAT]) +}) + +test("its models are the IDE's, and usage and check-in ask the domain nothing", async () => { + const s = store(signedIn()) + const hooks = await QoderCNAuthPlugin({ client: s.client }) + const ms = await hooks.provider.models({ models: {} }, { auth: s.auth() }) + expect(Object.keys(ms)).toEqual(["qmodel_latest", "dashscope_qmodel", "q36fmodel"]) + expect(ms.qmodel_latest.api.url).toBe(ORIGIN) + expect(await hooks.auth.usage(s.get)).toMatchObject({ windows: [], signIn: "kept" }) + expect((await hooks.auth.checkin(s.get)).outcome).toBe("inactive") + expect(seen).toEqual([]) +}) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 2020a0b..0d7fc56 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.55", + "version": "0.2.56", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains", "type": "module", "main": "./index.mjs",