@magpie-community/opencode-qoder-auth 0.2.32 → 0.2.35

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 +36 -0
  2. package/index.mjs +304 -41
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -8,6 +8,8 @@ accounts exist only on their own:
8
8
  |---|---|---|---|
9
9
  | `qoder` | qoder.com (international) | Google, GitHub or email | `QoderAuthPlugin` |
10
10
  | `qoder-cn` | qoder.cn ([Qoder CN](#qoder-cn)) | Alibaba Cloud or phone number | `QoderCNAuthPlugin` |
11
+ | `qwenwork` | gateway.qwenwork.cn ([QwenWork](#qwenwork-千问办公)) | phone number or email | `QwenWorkAuthPlugin` |
12
+ | `qwenwork-enterprise` | the enterprise's own domain ([QwenWork](#qwenwork-千问办公)) | email OTP or enterprise SSO | `QwenWorkEnterpriseAuthPlugin` |
11
13
 
12
14
  What follows is about `qoder`. Qoder CN works the same way on its own
13
15
  hosts; [its section](#qoder-cn) says what differs.
@@ -255,6 +257,33 @@ paths, client id and protocol are the public ones:
255
257
  The hosts and reply shapes come from a real VPC account's report
256
258
  (yetone/magpie#312). This plugin has not been tried with a VPC account.
257
259
 
260
+ ## QwenWork (千问办公)
261
+
262
+ `QwenWork` and `QwenWork 企业版` serve Alibaba's own QwenWork (qwenwork.cn)
263
+ on this same protocol, with the desktop client's client id, an RSA key the
264
+ Qoder one's equal, its own `qwork` scene, and the device token as the chat
265
+ token. The public cloud's sign-in is the desktop app's device flow, with
266
+ `redirect_uri=qwenwork-cn://`; usage reads the sign-in's account-context.
267
+ There is no PAT and no daily check-in on it: the `pat: false` and
268
+ `checkin: false` site fields turn both off, so Qoder's device identity is
269
+ never sent there.
270
+
271
+ The enterprise flagship (企业旗舰版, a VPC / private deployment) serves
272
+ web/openapi/api on the enterprise's **own single domain**, and its device
273
+ flow sends **no `redirect_uri`** (`/device/selectAccounts` refuses one).
274
+ Its sign-in asks for that domain — the host the admin console lives on,
275
+ like `your-company.vpc.qwenwork.cn`; `QWENWORK_ENT_DOMAIN` presets it so
276
+ the sign-in asks nothing. Every call — chat, models, refresh, usage —
277
+ routes to that host, and the account is named `<email|uid> (<domain>)`.
278
+ The login page expires in 5 minutes; a member signing in by email OTP
279
+ must have their email bound to their account in the admin console, or the
280
+ page answers 用户不存在.
281
+
282
+ The flagship deploys no model-catalog service (`/algo/api/v2/model/list`
283
+ answers 503 there), so its list falls back to the public cloud's qwork
284
+ models shipped in this package: flash, pro and qwen3.8-max-preview. A 503
285
+ falls back; any other error doesn't.
286
+
258
287
  ## Daily check-in
259
288
 
260
289
  Qoder gives credits for a daily claim (the Qoder client's campaign
@@ -387,6 +416,13 @@ The host's recheck/cache behavior is tracked in
387
416
  claim against the vendor record; a successful activity query alone is not
388
417
  proof that credits arrived.
389
418
 
419
+ ## protocol
420
+
421
+ `export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }` is
422
+ the plugin factory and its pieces, for another service on this same
423
+ protocol (QwenWork ships here; a future one can too). Its shape is not a
424
+ stable API — it changes as the packages on it need.
425
+
390
426
  ## Not here
391
427
 
392
428
  - Qoder's usage and quota display.
package/index.mjs CHANGED
@@ -81,21 +81,24 @@ function machineOS() {
81
81
 
82
82
  // userBlob is the account as the envelope carries it: AES-128-CBC under a
83
83
  // fresh key that is its own IV, the key wrapped with Qoder's RSA key.
84
- function userBlob(u) {
84
+ // userBlob and cosyHeaders take the site's own key and version when it has
85
+ // them (another QwenWork-like service on the same protocol), else Qoder's.
86
+ function userBlob(u, rsaKey = RSA_KEY) {
85
87
  const raw = JSON.stringify({ uid: u.uid, aid: "", name: u.name ?? "", email: u.email ?? "", security_oauth_token: u.access })
86
88
  const key = Buffer.from(hexID().slice(0, 16))
87
89
  const c = createCipheriv("aes-128-cbc", key, key)
88
90
  const info = Buffer.concat([c.update(raw, "utf8"), c.final()]).toString("base64")
89
- const wrapped = publicEncrypt({ key: RSA_KEY, padding: constants.RSA_PKCS1_PADDING }, key).toString("base64")
91
+ const wrapped = publicEncrypt({ key: rsaKey, padding: constants.RSA_PKCS1_PADDING }, key).toString("base64")
90
92
  return { info, key: wrapped }
91
93
  }
92
94
 
93
95
  // cosyHeaders signs a call to url whose body, in its wire form, is body.
94
- function cosyHeaders(url, u, body, ts = Math.floor(Date.now() / 1000)) {
95
- if (!u?.machineId) throw new Error("Qoder: the account has no machine id; sign in again")
96
- const blob = userBlob(u)
96
+ function cosyHeaders(url, u, body, site, ts = Math.floor(Date.now() / 1000)) {
97
+ if (!u?.machineId) throw new Error(`${site?.name ?? "Qoder"}: the account has no machine id; sign in again`)
98
+ const cosyVersion = site?.cosyVersion ?? COSY_VERSION
99
+ const blob = userBlob(u, site?.rsaKey)
97
100
  const payload = Buffer.from(
98
- JSON.stringify({ version: "v1", requestId: hexID(), info: blob.info, cosyVersion: COSY_VERSION, ideVersion: "" }),
101
+ JSON.stringify({ version: "v1", requestId: hexID(), info: blob.info, cosyVersion, ideVersion: "" }),
99
102
  ).toString("base64")
100
103
  let path = new URL(url).pathname
101
104
  if (path.startsWith("/algo")) path = path.slice(5)
@@ -106,10 +109,10 @@ function cosyHeaders(url, u, body, ts = Math.floor(Date.now() / 1000)) {
106
109
  "Accept-Encoding": "identity",
107
110
  "Content-Type": "application/json",
108
111
  Authorization: `Bearer COSY.${payload}.${sig}`,
109
- "Cosy-Business-Product": "app",
112
+ "Cosy-Business-Product": site?.businessProduct ?? "app",
110
113
  "Cosy-Business-Type": "agent",
111
114
  "Cosy-ClientIp": m,
112
- "Cosy-ClientType": "10",
115
+ "Cosy-ClientType": site?.clientType ?? "10",
113
116
  "Cosy-Data-Policy": "disagree",
114
117
  "Cosy-Date": String(ts),
115
118
  "Cosy-Key": blob.key,
@@ -117,9 +120,9 @@ function cosyHeaders(url, u, body, ts = Math.floor(Date.now() / 1000)) {
117
120
  "Cosy-MachineToken": m,
118
121
  "Cosy-MachineType": "5",
119
122
  "Cosy-MachineOS": machineOS(),
120
- "Cosy-Scene": "app",
123
+ "Cosy-Scene": site?.modelScene ?? "app",
121
124
  "Cosy-User": u.uid,
122
- "Cosy-Version": COSY_VERSION,
125
+ "Cosy-Version": cosyVersion,
123
126
  "Login-Version": "v2",
124
127
  }
125
128
  }
@@ -247,6 +250,13 @@ function vpcSite(site, instance) {
247
250
  // is not read as "no VPC", which would send the enterprise's tokens to the
248
251
  // public hosts: the account has to be signed in to again.
249
252
  function siteOf(site, a) {
253
+ // an account that names an enterprise host outright (QwenWork's enterprise
254
+ // flagship, which serves web/openapi/api on that one host) routes there;
255
+ // enterpriseHost, not the site's vpcDomain (Qoder CN's VPC suffix rule)
256
+ if (a?.enterpriseHost) {
257
+ const base = `https://${a.enterpriseHost}`
258
+ return { ...site, web: base, openapi: base, api: base, vpc: a.enterpriseHost }
259
+ }
250
260
  if (a?.vpc === undefined || a?.vpc === null || a?.vpc === "") return site
251
261
  const s = vpcSite(site, a.vpc)
252
262
  if (!s) throw new SignInGone(`${site.name}: the account's VPC instance "${a.vpc}" isn't one; sign in again`)
@@ -278,9 +288,13 @@ async function deviceSignIn(site) {
278
288
  } catch {} // a hiccup: ask again
279
289
  await new Promise((r) => setTimeout(r, 2000))
280
290
  }
281
- const jr = await openapi(site, "/api/v1/me/jobToken", { method: "POST", token: dt.token, body: { clientId: site.clientId } })
291
+ const jr = site.deviceOnly ? null : await openapi(site, "/api/v1/me/jobToken", { method: "POST", token: dt.token, body: { clientId: site.clientId } })
282
292
  let chat
283
- if (jr.status === 200) {
293
+ if (site.deviceOnly) {
294
+ // the service's device token is itself the chat token, renewed as
295
+ // one (QwenWork never makes a job token)
296
+ chat = { access: dt.token, refresh: dt.refresh_token ?? "", expires: deviceExpiry(dt), deviceChat: true }
297
+ } else if (jr.status === 200) {
284
298
  if (!String(jr.json?.token ?? "").trim()) throw new Error(`${site.name} job token: empty token in response`)
285
299
  chat = { access: jr.json.token, refresh: jr.json.refresh_token ?? "", expires: expiresAt(jr.json) }
286
300
  } else if (site.deviceChat && jr.status >= 400 && jr.status < 500) {
@@ -292,20 +306,24 @@ async function deviceSignIn(site) {
292
306
  let name = ""
293
307
  let uid = dt.user_id
294
308
  try {
295
- const ui = await openapi(site, "/api/v1/userinfo", { token: dt.token })
309
+ const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: dt.token })
296
310
  if (ui.status >= 200 && ui.status < 300) {
297
- ;[email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""]
311
+ const user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
312
+ ;[email, name] = [user?.email ?? "", user?.name ?? ""]
313
+ if (site.deviceOnly) uid = String(user?.id ?? user?.user_id ?? user?.uid ?? uid ?? "") || undefined
298
314
  // a VPC poll may give the token alone: the user is then the one
299
315
  // user info names (id, or its user_id / uid aliases)
300
316
  if (site.vpc && !String(uid ?? "").trim()) uid = String(ui.json?.id ?? ui.json?.user_id ?? ui.json?.uid ?? "") || undefined
301
317
  }
302
318
  } catch {}
319
+ if (site.deviceOnly && !String(uid ?? "").trim()) throw new Error(`${site.name}: the sign-in named no user`)
303
320
  if (site.vpc && !String(uid ?? "").trim()) throw new Error(`${site.name} (${site.vpc}): the sign-in named no user`)
304
321
  return {
305
322
  type: "success",
306
323
  ...chat,
307
- // a VPC account is told apart from the same person's public one
308
- accountId: site.vpc ? `${email || uid} (${site.vpc})` : email || dt.user_id,
324
+ // a VPC account is told apart from the same person's public one; a
325
+ // device-only one is shown by name, falling back to its id
326
+ accountId: site.vpc ? `${email || uid} (${site.vpc})` : site.deviceOnly ? email || uid || name || dt.user_id : email || dt.user_id,
309
327
  uid,
310
328
  email,
311
329
  name: name || dt.user_name || "",
@@ -313,6 +331,7 @@ async function deviceSignIn(site) {
313
331
  deviceToken: dt.token,
314
332
  deviceRefresh: dt.refresh_token ?? "",
315
333
  ...(site.vpc ? { vpc: site.vpc } : {}),
334
+ ...(site.enterpriseDomain ? { vpc: site.enterpriseDomain, enterpriseHost: site.enterpriseDomain } : {}),
316
335
  }
317
336
  },
318
337
  }
@@ -581,8 +600,15 @@ function sceneModels(listing) {
581
600
  }
582
601
 
583
602
  // modelInfos is the listing's enabled models an agent can pick: "auto"
584
- // and "default" route inside Qoder and aren't one model.
585
- function modelInfos(listing) {
603
+ // and "default" route inside Qoder and aren't one model. A site with its
604
+ // own scene reads that scene's list; one that lists all models keeps the
605
+ // disabled ones too (QwenWork's qwork scene carries its whole catalog).
606
+ function modelInfos(listing, site) {
607
+ if (site?.modelScene) {
608
+ return (Array.isArray(listing?.[site.modelScene]) ? listing[site.modelScene] : [])
609
+ .filter((m) => (site.listAllModels || m?.enable) && !["", "auto", "default"].includes(String(m.key ?? "").trim()))
610
+ .map(modelInfo)
611
+ }
586
612
  return sceneModels(listing)
587
613
  .filter((m) => m?.enable && !["", "auto", "default"].includes(String(m.key ?? "").trim()))
588
614
  .map(modelInfo)
@@ -590,9 +616,15 @@ function modelInfos(listing) {
590
616
 
591
617
  async function fetchListing(site, cred) {
592
618
  const url = site.api + MODELS_PATH
593
- const res = await fetch(url, { headers: cosyHeaders(url, cred, ""), signal: AbortSignal.timeout(15_000) })
619
+ const res = await fetch(url, { headers: cosyHeaders(url, cred, "", site), signal: AbortSignal.timeout(15_000) })
594
620
  const text = await res.text()
595
- if (!res.ok) throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}`)
621
+ if (!res.ok) {
622
+ // a service that deploys no catalog at all (QwenWork's enterprise
623
+ // flagship answers 503 "Model catalog is unavailable") falls back to
624
+ // the list its site ships
625
+ if (res.status === 503 && site.fallbackModels) return site.fallbackModels
626
+ throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}`)
627
+ }
596
628
  return JSON.parse(text)
597
629
  }
598
630
 
@@ -892,6 +924,13 @@ const TASKS = new Map()
892
924
  const TASK_MAX = 512
893
925
  const TASK_IDLE = 2 * 60 * 60 * 1000
894
926
 
927
+ // taskName is the business record's name for a task whose prompt is
928
+ // prompt, as Qoder's client names an agent task: the prompt's first ten
929
+ // characters (qoder-agent-sdk's AgentLifecycle, hdr → C6s: type
930
+ // "code_review" takes the session id, every other the prompt, sliced to
931
+ // 10 when longer).
932
+ const taskName = (prompt) => (prompt.length > 10 ? prompt.slice(0, 10) : prompt)
933
+
895
934
  // taskOf is the task chat's call belongs to, in session sid: made on its
896
935
  // first call, the same one on every call after.
897
936
  function taskOf(sid, chat, now = Date.now()) {
@@ -905,21 +944,59 @@ function taskOf(sid, chat, now = Date.now()) {
905
944
  let t = TASKS.get(key)
906
945
  if (t && now - t.used > TASK_IDLE) t = undefined
907
946
  TASKS.delete(key)
908
- t ??= { id: randomUUID(), begin: now, answered: false }
947
+ t ??= { id: randomUUID(), begin: now, answered: false, name: taskName(at < 0 ? "" : textOf(msgs[at].content)) }
909
948
  t.used = now
910
949
  TASKS.set(key, t)
911
950
  while (TASKS.size > TASK_MAX) TASKS.delete(TASKS.keys().next().value)
912
951
  return t
913
952
  }
914
953
 
954
+ // Qoder CN's kmodel (Kimi K3.1 Pro) fails a chat whose tools hold a oneOf
955
+ // with no type, even of objects only, and takes it with "type": "object"
956
+ // beside it (congee949, #378: dsh's REA tools, a 502 here). typedUnions is
957
+ // the schema with each such oneOf typed object when each branch is typed
958
+ // object itself or through a chain of local $refs; nothing else changes,
959
+ // and the caller's own schema is not touched.
960
+ const SUB_ONE = ["items", "additionalItems", "unevaluatedItems", "contains", "not", "if", "then", "else", "propertyNames", "additionalProperties", "unevaluatedProperties"]
961
+ const SUB_LIST = ["anyOf", "oneOf", "allOf", "prefixItems"]
962
+ const SUB_MAP = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]
963
+ function typedUnions(schema) {
964
+ if (!schema || typeof schema !== "object") return schema
965
+ const root = structuredClone(schema)
966
+ const isObj = (v) => v && typeof v === "object" && !Array.isArray(v)
967
+ const target = (ref) => {
968
+ if (!ref.startsWith("#/")) return undefined
969
+ let at = root
970
+ for (const k of ref.slice(2).split("/")) at = at?.[k.replaceAll("~1", "/").replaceAll("~0", "~")]
971
+ return isObj(at) ? at : undefined
972
+ }
973
+ const object = (b, seen = []) => {
974
+ if (!isObj(b)) return false
975
+ if ("type" in b) return b.type === "object"
976
+ if (typeof b.$ref !== "string" || seen.includes(b.$ref) || seen.length > 16) return false
977
+ return object(target(b.$ref), [...seen, b.$ref])
978
+ }
979
+ const walk = (s, depth) => {
980
+ if (!isObj(s) || depth > 64) return
981
+ if (!("type" in s) && Array.isArray(s.oneOf) && s.oneOf.length && s.oneOf.every((b) => object(b))) s.type = "object"
982
+ for (const k of SUB_ONE) walk(s[k], depth + 1)
983
+ for (const k of SUB_LIST) for (const v of Array.isArray(s[k]) ? s[k] : []) walk(v, depth + 1)
984
+ for (const k of SUB_MAP) if (isObj(s[k])) for (const v of Object.values(s[k])) walk(v, depth + 1)
985
+ }
986
+ walk(root, 0)
987
+ return root
988
+ }
989
+
915
990
  // qoderBody is the plaintext agent_chat_generation takes for a chat
916
991
  // completion request, for model m, in the session the agent named (named,
917
992
  // "" when none) and the task it is a call of (taskOf's, a new one when
918
- // none is given).
919
- function qoderBody(chat, m, named = "", task) {
993
+ // none is given). A site on this protocol with its own values (QwenWork)
994
+ // passes itself last.
995
+ function qoderBody(chat, m, named = "", task, site) {
920
996
  const system = (chat.messages ?? []).filter((x) => x.role === "system" || x.role === "developer").map((x) => textOf(x.content)).filter(Boolean).join("\n\n")
921
997
  const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function" && t.function?.name) : []
922
- let sysText = system ? QODER_SYS + "\n\n" + system : QODER_SYS
998
+ const baseSystem = site?.systemPrompt ?? QODER_SYS
999
+ let sysText = system ? baseSystem + "\n\n" + system : baseSystem
923
1000
  if (chat.tool_choice === "required" && tools.length) sysText += "\nYou must call an available function in this response."
924
1001
  const sys = { type: "text", text: sysText }
925
1002
  const [thinking, effort] = effortFor(chat.reasoning_effort, m)
@@ -936,10 +1013,10 @@ function qoderBody(chat, m, named = "", task) {
936
1013
  chat_record_id: request,
937
1014
  session_id: session,
938
1015
  parameters: params,
939
- business: { product: "app", version: COSY_VERSION, type: "agent", id: task.id, name: "magpie session", begin_at: task.begin, stage: task.answered ? "processing" : "start" },
1016
+ business: { product: site?.businessProduct ?? "app", version: site?.cosyVersion ?? COSY_VERSION, type: "agent", id: task.id, name: task.name ?? "", begin_at: task.begin, stage: task.answered ? "processing" : "start" },
940
1017
  agent_id: "agent_common",
941
1018
  task_id: "common",
942
- session_type: "app",
1019
+ session_type: site?.sessionType ?? "app",
943
1020
  model_config: m.config,
944
1021
  system: [sys],
945
1022
  messages: [{ role: "system", content: [sys] }, ...cacheMarked(qoderMessages(chat.messages ?? []))],
@@ -947,7 +1024,7 @@ function qoderBody(chat, m, named = "", task) {
947
1024
  if (tools.length)
948
1025
  body.tools = tools.map((t) => ({
949
1026
  type: "function",
950
- function: { name: t.function.name, description: t.function.description ?? "", parameters: t.function.parameters ?? { type: "object", properties: {} } },
1027
+ function: { name: t.function.name, description: t.function.description ?? "", parameters: typedUnions(t.function.parameters) ?? { type: "object", properties: {} } },
951
1028
  }))
952
1029
  return body
953
1030
  }
@@ -1137,11 +1214,11 @@ function queueState(text) {
1137
1214
  }
1138
1215
 
1139
1216
  // queueStatus asks Qoder's queue where the request stands.
1140
- async function queueStatus(api, cred, { requestSetId, modelKey, queueType, requestId, sessionId }, signal, deadline) {
1217
+ async function queueStatus(api, cred, { requestSetId, modelKey, queueType, requestId, sessionId }, signal, deadline, site) {
1141
1218
  const q = new URLSearchParams({ requestSetId, modelKey })
1142
1219
  if (queueType) q.set("queueType", queueType)
1143
1220
  const url = `${api}${QUEUE_STATUS_PATH}?${q}`
1144
- const headers = { ...cosyHeaders(url, cred, ""), "X-Request-ID": requestId, "X-Session-ID": sessionId }
1221
+ const headers = { ...cosyHeaders(url, cred, "", site), "X-Request-ID": requestId, "X-Session-ID": sessionId }
1145
1222
  delete headers["Content-Type"]
1146
1223
  const left = Math.min(QUEUE.ask, deadline - QUEUE.now())
1147
1224
  if (left <= 0) throw new QueueEnd("the queue's wait ran out")
@@ -1157,7 +1234,7 @@ async function queueStatus(api, cred, { requestSetId, modelKey, queueType, reque
1157
1234
  // queueWait waits in Qoder's queue for the request, from the state its
1158
1235
  // refusal gave, until the queue lets it through (true) or the wait ends
1159
1236
  // (false). A cancelled request throws.
1160
- async function queueWait(api, cred, ask, first, signal, deadline) {
1237
+ async function queueWait(api, cred, ask, first, signal, deadline, site) {
1161
1238
  let q = first ?? {}
1162
1239
  let asked = false
1163
1240
  let failed = 0
@@ -1169,7 +1246,7 @@ async function queueWait(api, cred, ask, first, signal, deadline) {
1169
1246
  if (QUEUE.now() >= deadline) return false
1170
1247
  let st
1171
1248
  try {
1172
- st = await queueStatus(api, cred, { ...ask, modelKey: q.modelKey ?? ask.modelKey, queueType: q.queueType ?? ask.queueType }, signal, deadline)
1249
+ st = await queueStatus(api, cred, { ...ask, modelKey: q.modelKey ?? ask.modelKey, queueType: q.queueType ?? ask.queueType }, signal, deadline, site)
1173
1250
  } catch (e) {
1174
1251
  if (signal?.aborted) throw signal.reason ?? e
1175
1252
  if (e instanceof QueueEnd) return false
@@ -1541,7 +1618,9 @@ class UsageStatus extends Error {
1541
1618
  }
1542
1619
  }
1543
1620
 
1544
- // fetchUsage is the usage envelope, {displayMode, qoderUsage}.
1621
+ // fetchUsage is the usage envelope, {displayMode, qoderUsage}; a site with
1622
+ // its own usage path (QwenWork's account-context) is read by
1623
+ // fetchSiteUsage below instead.
1545
1624
  async function fetchUsage(site, deviceToken) {
1546
1625
  if (!String(deviceToken ?? "").trim()) throw new Error("qoder usage: missing device token")
1547
1626
  let res
@@ -1738,7 +1817,7 @@ async function refreshDevice(site, refresh, chat = false) {
1738
1817
  }
1739
1818
  let r
1740
1819
  try {
1741
- r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh } })
1820
+ r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh, ...(site.deviceRefreshTarget ? { target: site.deviceRefreshTarget } : {}) } })
1742
1821
  } catch (e) {
1743
1822
  throw new Error(`qoder device token refresh: request failed: ${e?.message ?? e}`)
1744
1823
  }
@@ -1808,6 +1887,79 @@ function parseUsage(env) {
1808
1887
  }
1809
1888
 
1810
1889
  // SITES are Qoder's two sites, each a subscription of its own.
1890
+ // QwenWork (千问办公, qwenwork.cn) speaks this protocol on Alibaba's own
1891
+ // service, with its own scene, client id and RSA key (the same key), as its
1892
+ // desktop client sends. The models below are the public cloud's qwork list
1893
+ // at the time of writing — QWENWORK_MODELS is what magpie's config lists
1894
+ // before a sign-in, and QWORK_FALLBACK_LISTING is what the enterprise
1895
+ // flagship falls back to: it serves the same scene but deploys no catalog
1896
+ // service (/algo/api/v2/model/list answers 503 there, signed and verified).
1897
+ const QWENWORK_MODELS = [
1898
+ { id: "flash", name: "标准" },
1899
+ { id: "pro", name: "高级" },
1900
+ { id: "qwen3.8-max-preview", name: "Qwen3.8-Max" },
1901
+ ]
1902
+ const QWORK_FALLBACK_LISTING = {
1903
+ // is_vl / is_reasoning / max_input_tokens are copied from the public
1904
+ // cloud's list, not checked against a flagship's own models
1905
+ qwork: [
1906
+ { key: "flash", display_name: "标准", is_vl: false, is_reasoning: false, max_input_tokens: 131072 },
1907
+ { key: "pro", display_name: "高级", is_vl: false, is_reasoning: false, max_input_tokens: 131072 },
1908
+ { key: "qwen3.8-max-preview", display_name: "Qwen3.8-Max", is_vl: false, is_reasoning: false, max_input_tokens: 131072 },
1909
+ ],
1910
+ }
1911
+ const QWENWORK_RSA_KEY = `-----BEGIN PUBLIC KEY-----
1912
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
1913
+ 4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
1914
+ 6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
1915
+ XcW+ML9FoCI6AOvOzwIDAQAB
1916
+ -----END PUBLIC KEY-----`
1917
+ // parseAccountContext reads the account-context QwenWork's sign-in already
1918
+ // reads: plan {name, next_refresh / next_due} and quota {total, used,
1919
+ // remaining} in the plan's credit unit. One window is one pool of credits.
1920
+ const num = (v) => {
1921
+ const n = Number(v)
1922
+ if (!Number.isFinite(n)) return "0"
1923
+ return String(Math.round(n * 100) / 100)
1924
+ }
1925
+ const parseAccountContext = (ctx) => {
1926
+ const data = ctx?.data ?? {}
1927
+ const q = data.quota
1928
+ const out = {}
1929
+ if (data.plan?.name) out.plan = String(data.plan.name)
1930
+ const refresh = data.plan?.next_refresh_date ?? data.plan?.next_due_date
1931
+ if (refresh) out.until = new Date(refresh).toISOString()
1932
+ if (q && typeof q === "object") {
1933
+ const total = Number(q.total)
1934
+ const remaining = Number(q.remaining)
1935
+ const used = Number.isFinite(Number(q.used)) ? Number(q.used) : total - remaining
1936
+ if (Number.isFinite(total) && total > 0 && Number.isFinite(used) && used >= 0) {
1937
+ out.windows = [{ name: "Credits", used: Math.min(100, (100 * used) / total), display: `${num(used)} / ${num(total)} credits` }]
1938
+ }
1939
+ }
1940
+ if (!out.windows) out.error = "QwenWork: the account reports no credits"
1941
+ return out
1942
+ }
1943
+
1944
+ const QWENWORK_COMMON = {
1945
+ clientId: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb", // the desktop client's
1946
+ rsaKey: QWENWORK_RSA_KEY,
1947
+ usagePath: "/api/v1/adapter/user/account-context?include=user,plan,quota",
1948
+ parseUsage: parseAccountContext,
1949
+ cosyVersion: "1.1.59",
1950
+ redirect: "qwenwork-cn://",
1951
+ deviceOnly: true, // the device token is itself the chat token
1952
+ deviceRefreshTarget: "c",
1953
+ modelScene: "qwork", listAllModels: true,
1954
+ clientType: "6", businessProduct: "qoder_work", sessionType: "qoder_work",
1955
+ userInfoPath: "/api/v1/adapter/user/account-context?include=user,plan,quota,page,data_sharing",
1956
+ normalizeUser: v => (v?.data ?? v)?.user ?? (v?.data ?? v),
1957
+ pat: false, // no /api/v1/jobToken/exchange on gateway.qwenwork.cn
1958
+ checkin: false, // no campaigns endpoint, and no Qoder desktop identity to send
1959
+ models: QWENWORK_MODELS,
1960
+ systemPrompt: "You are QwenWork (qw), a helpful assistant. Use the instructions below and the tools available to you to assist the user.",
1961
+ }
1962
+
1811
1963
  const SITES = {
1812
1964
  qoder: {
1813
1965
  id: "qoder",
@@ -1837,6 +1989,29 @@ const SITES = {
1837
1989
  vpcDomain: "vpc.qoder.com.cn",
1838
1990
  models: CN_MODELS,
1839
1991
  },
1992
+ // QwenWork's public cloud. QWENWORK_ENT_DOMAIN (the enterprise preset)
1993
+ // is the only variable read; the sites are these constants.
1994
+ qwenwork: {
1995
+ ...QWENWORK_COMMON,
1996
+ id: "qwenwork",
1997
+ name: "QwenWork",
1998
+ web: "https://gateway.qwenwork.cn",
1999
+ openapi: "https://gateway.qwenwork.cn",
2000
+ api: "https://gateway.qwenwork.cn",
2001
+ },
2002
+ // QwenWork's enterprise flagship (企业旗舰版): the enterprise's own
2003
+ // domain, asked at sign-in — web/openapi/api all live on that one host,
2004
+ // and its device flow sends no redirect_uri. QWENWORK_ENT_DOMAIN presets
2005
+ // the domain so the sign-in asks nothing.
2006
+ "qwenwork-enterprise": {
2007
+ ...QWENWORK_COMMON,
2008
+ id: "qwenwork-enterprise",
2009
+ name: "QwenWork 企业版",
2010
+ web: "https://gateway.qwenwork.cn",
2011
+ openapi: "https://gateway.qwenwork.cn",
2012
+ api: "https://gateway.qwenwork.cn",
2013
+ fallbackModels: QWORK_FALLBACK_LISTING,
2014
+ },
1840
2015
  }
1841
2016
 
1842
2017
  const makePlugin = (site) => async ({ client }) => {
@@ -1963,7 +2138,7 @@ const makePlugin = (site) => async ({ client }) => {
1963
2138
  const key = listingKey(cred)
1964
2139
  let l = listings.get(key)
1965
2140
  if (!l || again) {
1966
- l = modelInfos(await fetchListing(siteOf(site, cred), cred))
2141
+ l = modelInfos(await fetchListing(siteOf(site, cred), cred), siteOf(site, cred))
1967
2142
  listings.set(key, l)
1968
2143
  }
1969
2144
  return l
@@ -1992,6 +2167,29 @@ const makePlugin = (site) => async ({ client }) => {
1992
2167
  try {
1993
2168
  const cred = await fresh(getAuth)
1994
2169
  if (renewed(cred)) signIn = "renewed"
2170
+ // a site with its own usage path (QwenWork's account-context, signed
2171
+ // like any other call and answered with its own envelope) is read
2172
+ // there; a 401 rotates the device token once, as the qoder path does
2173
+ if (site.usagePath) {
2174
+ const read = async (token) => {
2175
+ const s = siteOf(site, cred)
2176
+ const res = await fetch(`${s.openapi}${site.usagePath}`, {
2177
+ headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
2178
+ signal: AbortSignal.timeout(20_000),
2179
+ })
2180
+ if (res.status !== 200) throw new UsageStatus(res.status)
2181
+ return res.json()
2182
+ }
2183
+ let env
2184
+ try {
2185
+ env = await read(cred.deviceToken ?? cred.access)
2186
+ } catch (e) {
2187
+ if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
2188
+ if (!cred.deviceToken) throw e
2189
+ env = await read(await deviceToken(getAuth, cred.deviceToken))
2190
+ }
2191
+ return { ...(site.parseUsage ? site.parseUsage(env) : { windows: [] }), signIn }
2192
+ }
1995
2193
  // A PAT account has no device token: the usage endpoint takes the job
1996
2194
  // token the exchange gave — a live PAT account answered 200 with a
1997
2195
  // qoder envelope. Its errors surface as the device path's do; there is
@@ -2150,7 +2348,7 @@ const makePlugin = (site) => async ({ client }) => {
2150
2348
  const api = siteOf(site, cred).api
2151
2349
  const CHAT_URL = api + CHAT_PATH
2152
2350
  const task = taskOf(sessionOf(chat, named), chat)
2153
- const body = qoderBody(chat, m, named, task)
2351
+ const body = qoderBody(chat, m, named, task, siteOf(site, cred))
2154
2352
  const wire = encodeBody(JSON.stringify(body))
2155
2353
  // Qoder's queue is waited out (queueWait) and the same request, its
2156
2354
  // request_set_id the one the queue knows, sent again
@@ -2158,7 +2356,7 @@ const makePlugin = (site) => async ({ client }) => {
2158
2356
  const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key }
2159
2357
  for (let waited = 0; ; waited++) {
2160
2358
  const headers = {
2161
- ...cosyHeaders(CHAT_URL, cred, wire),
2359
+ ...cosyHeaders(CHAT_URL, cred, wire, siteOf(site, cred)),
2162
2360
  Accept: "text/event-stream",
2163
2361
  "Cache-Control": "no-cache",
2164
2362
  "X-Model-Key": m.key,
@@ -2176,7 +2374,7 @@ const makePlugin = (site) => async ({ client }) => {
2176
2374
  if (!f) task.answered = true
2177
2375
  if (!f?.queue || waited >= QUEUE.recoveries) return f && !res.ok ? errorResponse(f) : answer(open, chat)
2178
2376
  try {
2179
- if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline))) return errorResponse(f)
2377
+ if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline, siteOf(site, cred)))) return errorResponse(f)
2180
2378
  } catch (e) {
2181
2379
  return errorResponse({ status: 502, message: e?.message ?? String(e) })
2182
2380
  }
@@ -2260,7 +2458,10 @@ const makePlugin = (site) => async ({ client }) => {
2260
2458
  // a PAT too (verified: HTTP 200 and a jt- token), and that job token
2261
2459
  // signs the model list and chat calls with the COSY envelope as on
2262
2460
  // qoder.com, so the exchange gives a token the chat endpoint accepts.
2263
- {
2461
+ // A site that serves no exchange path (QwenWork) sets pat: false.
2462
+ ...(site.pat === false
2463
+ ? []
2464
+ : [{
2264
2465
  type: "oauth",
2265
2466
  label: `Sign in with ${site.name} PAT`,
2266
2467
  prompts: [
@@ -2284,7 +2485,7 @@ const makePlugin = (site) => async ({ client }) => {
2284
2485
  },
2285
2486
  }
2286
2487
  },
2287
- },
2488
+ }]),
2288
2489
  // an enterprise VPC instance (Qoder CN), a method of its own so
2289
2490
  // that the sign-in above asks nothing new
2290
2491
  ...(site.vpcDomain
@@ -2311,7 +2512,10 @@ const makePlugin = (site) => async ({ client }) => {
2311
2512
  : []),
2312
2513
  ],
2313
2514
  usage,
2314
- checkin,
2515
+ // the daily check-in reads the vendor's desktop device identity and
2516
+ // posts it to the campaign endpoint: a site without one (QwenWork)
2517
+ // sets checkin: false and gets none
2518
+ ...(site.checkin === false ? {} : { checkin }),
2315
2519
  },
2316
2520
  async config(config) {
2317
2521
  config.provider ??= {}
@@ -2356,6 +2560,65 @@ const makePlugin = (site) => async ({ client }) => {
2356
2560
 
2357
2561
  export const QoderAuthPlugin = makePlugin(SITES.qoder)
2358
2562
  export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"])
2563
+ export const QwenWorkAuthPlugin = makePlugin(SITES.qwenwork)
2564
+
2565
+ // enterpriseDomain reads what the user entered as their enterprise's
2566
+ // address, as the desktop client's enterprise mode reads its endpoint
2567
+ // override: a bare host, or an https:// address with no path. Loopback- and
2568
+ // intranet-looking names are refused too. Anything else names none.
2569
+ function enterpriseDomain(input) {
2570
+ let e = String(input ?? "").trim().toLowerCase()
2571
+ if (!e) return undefined
2572
+ if (/^[a-z][a-z\d+.-]*:\/\//.test(e)) {
2573
+ let u
2574
+ try { u = new URL(e) } catch { return undefined }
2575
+ if (u.protocol !== "https:" || u.username || u.password || u.port || u.search || u.hash || (u.pathname !== "" && u.pathname !== "/")) return undefined
2576
+ if (e.endsWith("/")) e = e.slice(0, -1)
2577
+ if (u.hostname + "" !== e.slice("https://".length)) return undefined
2578
+ e = u.hostname
2579
+ }
2580
+ if (/^(\d{1,3}\.){3}\d{1,3}$/.test(e)) return undefined // a bare IP is not a domain
2581
+ if (/^(localhost|.*\.localhost|.*\.local|.*\.internal)$/.test(e)) return undefined // loopback / intranet suffixes
2582
+ if (!/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(e)) return undefined
2583
+ return e
2584
+ }
2585
+
2586
+ // The enterprise flagship's sign-in: the same device flow against the
2587
+ // enterprise's own host, which it asks for (QWENWORK_ENT_DOMAIN presets it),
2588
+ // with no redirect_uri — the flagship's /device/selectAccounts refuses one.
2589
+ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
2590
+ const base = SITES["qwenwork-enterprise"]
2591
+ const preset = enterpriseDomain(process.env.QWENWORK_ENT_DOMAIN ?? "")
2592
+ const siteFor = (domain) => ({ ...base, web: `https://${domain}`, openapi: `https://${domain}`, api: `https://${domain}`, redirect: "", enterpriseDomain: domain, vpc: domain })
2593
+ const plugin = await makePlugin(base)({ client })
2594
+ plugin.auth.methods.splice(0, plugin.auth.methods.length, {
2595
+ type: "oauth",
2596
+ label: preset ? `Sign in with ${base.name} (${preset})` : `Sign in with ${base.name}(输入企业域名)`,
2597
+ prompts: preset ? [] : [
2598
+ {
2599
+ type: "text",
2600
+ key: "domain",
2601
+ message: "你企业的千问办公旗舰版域名(企业管理后台地址栏的域名,如 your-company.vpc.qwenwork.cn)",
2602
+ placeholder: "your-company.vpc.qwenwork.cn 或 https://your-company.vpc.qwenwork.cn",
2603
+ validate: (v) => (enterpriseDomain(v) ? undefined : "请输入企业域名(或 https:// 开头的完整地址),不要带路径"),
2604
+ },
2605
+ ],
2606
+ authorize: (inputs) => {
2607
+ const domain = preset || enterpriseDomain(inputs?.domain)
2608
+ if (!domain) throw new Error("请输入企业域名(或设置 QWENWORK_ENT_DOMAIN 环境变量)")
2609
+ return deviceSignIn(siteFor(domain))
2610
+ },
2611
+ })
2612
+ return plugin
2613
+ }
2614
+
2615
+ // for another service on this same protocol (QwenWork ships one): the
2616
+ // plugin factory and its pieces, a site built as SITES' entries are (see
2617
+ // the site fields those hooks read — modelScene, listAllModels, clientType,
2618
+ // businessProduct, sessionType, systemPrompt, userInfoPath, normalizeUser,
2619
+ // deviceOnly, deviceRefreshTarget, rsaKey, cosyVersion, fallbackModels and
2620
+ // the vpcDomain branch of siteOf), and the openapi fetch.
2621
+ export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
2359
2622
 
2360
2623
  // for tests
2361
- export const _internal = { campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
2624
+ export const _internal = { typedUnions, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, 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,12 +1,12 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.32",
4
- "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)",
3
+ "version": "0.2.35",
4
+ "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": "./index.mjs",
8
8
  "files": ["index.mjs", "README.md", "LICENSE-CLIProxyAPI"],
9
- "keywords": ["opencode", "opencode-plugin", "magpie", "qoder", "qoder-cn"],
9
+ "keywords": ["opencode", "opencode-plugin", "magpie", "qoder", "qoder-cn", "qwenwork", "千问办公"],
10
10
  "license": "MIT",
11
11
  "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/qoder" }
12
12
  }