@magpie-community/opencode-qoder-auth 0.2.33 → 0.2.36

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 +43 -0
  2. package/index.mjs +489 -66
  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.
@@ -142,6 +144,13 @@ itself.
142
144
  the agent or magpie can try again. A call whose JSON is whole when the
143
145
  stream ends without its close is still the call; a tag in code or prose
144
146
  stays text.
147
+ - A call written in Anthropic's or Qwen's tags with no `<tool_call>`
148
+ around it (since 0.2.36, #323), `<function_calls>` around one or more
149
+ `<invoke name="…"><parameter name="k">v</parameter></invoke>`, or
150
+ `<function=name><parameter=k>v</parameter></function>`, is a call too,
151
+ but only for a tool the request declared; for any other, or in
152
+ backticks or a code fence, it stays text. A parameter's value is JSON
153
+ unless the tool's schema says string, in these and in `<tool_call>`.
145
154
 
146
155
  **Errors**
147
156
 
@@ -255,6 +264,33 @@ paths, client id and protocol are the public ones:
255
264
  The hosts and reply shapes come from a real VPC account's report
256
265
  (yetone/magpie#312). This plugin has not been tried with a VPC account.
257
266
 
267
+ ## QwenWork (千问办公)
268
+
269
+ `QwenWork` and `QwenWork 企业版` serve Alibaba's own QwenWork (qwenwork.cn)
270
+ on this same protocol, with the desktop client's client id, an RSA key the
271
+ Qoder one's equal, its own `qwork` scene, and the device token as the chat
272
+ token. The public cloud's sign-in is the desktop app's device flow, with
273
+ `redirect_uri=qwenwork-cn://`; usage reads the sign-in's account-context.
274
+ There is no PAT and no daily check-in on it: the `pat: false` and
275
+ `checkin: false` site fields turn both off, so Qoder's device identity is
276
+ never sent there.
277
+
278
+ The enterprise flagship (企业旗舰版, a VPC / private deployment) serves
279
+ web/openapi/api on the enterprise's **own single domain**, and its device
280
+ flow sends **no `redirect_uri`** (`/device/selectAccounts` refuses one).
281
+ Its sign-in asks for that domain — the host the admin console lives on,
282
+ like `your-company.vpc.qwenwork.cn`; `QWENWORK_ENT_DOMAIN` presets it so
283
+ the sign-in asks nothing. Every call — chat, models, refresh, usage —
284
+ routes to that host, and the account is named `<email|uid> (<domain>)`.
285
+ The login page expires in 5 minutes; a member signing in by email OTP
286
+ must have their email bound to their account in the admin console, or the
287
+ page answers 用户不存在.
288
+
289
+ The flagship deploys no model-catalog service (`/algo/api/v2/model/list`
290
+ answers 503 there), so its list falls back to the public cloud's qwork
291
+ models shipped in this package: flash, pro and qwen3.8-max-preview. A 503
292
+ falls back; any other error doesn't.
293
+
258
294
  ## Daily check-in
259
295
 
260
296
  Qoder gives credits for a daily claim (the Qoder client's campaign
@@ -387,6 +423,13 @@ The host's recheck/cache behavior is tracked in
387
423
  claim against the vendor record; a successful activity query alone is not
388
424
  proof that credits arrived.
389
425
 
426
+ ## protocol
427
+
428
+ `export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }` is
429
+ the plugin factory and its pieces, for another service on this same
430
+ protocol (QwenWork ships here; a future one can too). Its shape is not a
431
+ stable API — it changes as the packages on it need.
432
+
390
433
  ## Not here
391
434
 
392
435
  - 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
 
@@ -919,14 +951,52 @@ function taskOf(sid, chat, now = Date.now()) {
919
951
  return t
920
952
  }
921
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
+
922
990
  // qoderBody is the plaintext agent_chat_generation takes for a chat
923
991
  // completion request, for model m, in the session the agent named (named,
924
992
  // "" when none) and the task it is a call of (taskOf's, a new one when
925
- // none is given).
926
- 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) {
927
996
  const system = (chat.messages ?? []).filter((x) => x.role === "system" || x.role === "developer").map((x) => textOf(x.content)).filter(Boolean).join("\n\n")
928
997
  const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function" && t.function?.name) : []
929
- 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
930
1000
  if (chat.tool_choice === "required" && tools.length) sysText += "\nYou must call an available function in this response."
931
1001
  const sys = { type: "text", text: sysText }
932
1002
  const [thinking, effort] = effortFor(chat.reasoning_effort, m)
@@ -943,10 +1013,10 @@ function qoderBody(chat, m, named = "", task) {
943
1013
  chat_record_id: request,
944
1014
  session_id: session,
945
1015
  parameters: params,
946
- business: { product: "app", version: COSY_VERSION, type: "agent", id: task.id, name: task.name ?? "", 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" },
947
1017
  agent_id: "agent_common",
948
1018
  task_id: "common",
949
- session_type: "app",
1019
+ session_type: site?.sessionType ?? "app",
950
1020
  model_config: m.config,
951
1021
  system: [sys],
952
1022
  messages: [{ role: "system", content: [sys] }, ...cacheMarked(qoderMessages(chat.messages ?? []))],
@@ -954,7 +1024,7 @@ function qoderBody(chat, m, named = "", task) {
954
1024
  if (tools.length)
955
1025
  body.tools = tools.map((t) => ({
956
1026
  type: "function",
957
- 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: {} } },
958
1028
  }))
959
1029
  return body
960
1030
  }
@@ -1144,11 +1214,11 @@ function queueState(text) {
1144
1214
  }
1145
1215
 
1146
1216
  // queueStatus asks Qoder's queue where the request stands.
1147
- 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) {
1148
1218
  const q = new URLSearchParams({ requestSetId, modelKey })
1149
1219
  if (queueType) q.set("queueType", queueType)
1150
1220
  const url = `${api}${QUEUE_STATUS_PATH}?${q}`
1151
- 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 }
1152
1222
  delete headers["Content-Type"]
1153
1223
  const left = Math.min(QUEUE.ask, deadline - QUEUE.now())
1154
1224
  if (left <= 0) throw new QueueEnd("the queue's wait ran out")
@@ -1164,7 +1234,7 @@ async function queueStatus(api, cred, { requestSetId, modelKey, queueType, reque
1164
1234
  // queueWait waits in Qoder's queue for the request, from the state its
1165
1235
  // refusal gave, until the queue lets it through (true) or the wait ends
1166
1236
  // (false). A cancelled request throws.
1167
- async function queueWait(api, cred, ask, first, signal, deadline) {
1237
+ async function queueWait(api, cred, ask, first, signal, deadline, site) {
1168
1238
  let q = first ?? {}
1169
1239
  let asked = false
1170
1240
  let failed = 0
@@ -1176,7 +1246,7 @@ async function queueWait(api, cred, ask, first, signal, deadline) {
1176
1246
  if (QUEUE.now() >= deadline) return false
1177
1247
  let st
1178
1248
  try {
1179
- 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)
1180
1250
  } catch (e) {
1181
1251
  if (signal?.aborted) throw signal.reason ?? e
1182
1252
  if (e instanceof QueueEnd) return false
@@ -1203,8 +1273,9 @@ const FUNC = /\x3cfunction=([^>]+)\x3e([\s\S]*?)\x3c\/function\x3e/
1203
1273
  const PARAM = /\x3cparameter=([^>]+)\x3e([\s\S]*?)\x3c\/parameter\x3e/g
1204
1274
 
1205
1275
  // parseCall reads one tool-call block: JSON {name, arguments}, or the XML
1206
- // function/parameter form.
1207
- function parseCall(v) {
1276
+ // function/parameter form, its values typed as the tool's schema says
1277
+ // (xmlArgs).
1278
+ function parseCall(v, tools = []) {
1208
1279
  try {
1209
1280
  const f = JSON.parse(v.trim())
1210
1281
  if (String(f?.name ?? "").trim() && f.arguments && typeof f.arguments === "object" && !Array.isArray(f.arguments))
@@ -1212,18 +1283,106 @@ function parseCall(v) {
1212
1283
  } catch {}
1213
1284
  const m = FUNC.exec(v)
1214
1285
  if (!m || !m[1].trim()) return null
1286
+ const name = m[1].trim()
1287
+ const props = propsOf(tools, name)
1215
1288
  const args = {}
1216
1289
  for (const pm of m[2].matchAll(PARAM)) {
1217
1290
  const key = pm[1].trim()
1218
1291
  if (!key) continue
1219
- const val = pm[2].trim()
1220
- try {
1221
- args[key] = JSON.parse(val)
1222
- } catch {
1223
- args[key] = val
1224
- }
1292
+ args[key] = valueOf(pm[2].trim(), props[key])
1225
1293
  }
1226
- return { name: m[1].trim(), args: JSON.stringify(args) }
1294
+ return { name, args: JSON.stringify(args) }
1295
+ }
1296
+
1297
+ // propsOf is the parameters the request declared for tool name
1298
+ const propsOf = (tools, name) => (tools.find((t) => (t.function ?? t)?.name === name)?.function ?? {}).parameters?.properties ?? {}
1299
+
1300
+ // valueOf is a parameter's value: its text where the tool's schema says
1301
+ // string, else its JSON (an array a tool takes), else its text (#323: a
1302
+ // string holding [1, 2] became an array)
1303
+ function valueOf(v, prop) {
1304
+ if (prop?.type === "string") return v
1305
+ try {
1306
+ return JSON.parse(v.trim())
1307
+ } catch {
1308
+ return v
1309
+ }
1310
+ }
1311
+
1312
+ // Anthropic's and Qwen's call tags, written bare (no <tool_call> around
1313
+ // them), as Kimi, MiMo and Qwen models may (#323, as trae's since 0.2.19):
1314
+ // where one starts, an opener still being written, the openers a wrapper
1315
+ // is followed by, the next call's opener, a parameter's opener, and what
1316
+ // is left after a call
1317
+ const XML_AT = /<(?:antml:)?(?:function_calls>|invoke\s+name\s*=|function=)/
1318
+ const XML_HOLD = /<(?:antml:)?(?:invoke\s[^<>]{0,300}|function=[^<>]{0,300})$/
1319
+ const XML_STARTS = ["<invoke ", "<antml:invoke ", "<function="]
1320
+ const XML_MARKS = ["<function_calls>", "<antml:function_calls>", ...XML_STARTS]
1321
+ const XML_NEXT = /<(?:antml:)?invoke\s+name\s*=|<function=/
1322
+ const XML_PARAM = /<(?:antml:)?parameter(?:\s+name\s*=\s*"([^"]+)"|=([^\s>]+))\s*>/g
1323
+ const XML_CLOSES = ["</function_calls>", "</antml:function_calls>", "</invoke>", "</antml:invoke>", "</function>"]
1324
+ const XML_LEFT = /^(?:\s+|<\/(?:antml:)?(?:function_calls|invoke|function)>)+/
1325
+
1326
+ // xmlArgs reads the parameters of an invoke or function body, typed by
1327
+ // the tool's schema; closed is whether every one was closed
1328
+ function xmlArgs(s, props) {
1329
+ const opens = [...s.matchAll(XML_PARAM)]
1330
+ const args = {}
1331
+ let closed = opens.length > 0
1332
+ opens.forEach((m, k) => {
1333
+ let v = s.slice(m.index + m[0].length, k + 1 < opens.length ? opens[k + 1].index : s.length)
1334
+ const c = v.search(/<\/(?:antml:)?parameter>/)
1335
+ if (c >= 0) v = v.slice(0, c)
1336
+ else closed = false
1337
+ args[m[1] ?? m[2]] = valueOf(v.replace(/^\r?\n|\r?\n$/g, ""), props[m[1] ?? m[2]])
1338
+ })
1339
+ return { args, closed }
1340
+ }
1341
+
1342
+ // xmlCall reads a bare call in Anthropic's tags (<function_calls> around
1343
+ // one or more <invoke name="…"><parameter name="k">v</parameter>
1344
+ // </invoke>) or Qwen's (<function=…><parameter=k>v</parameter>
1345
+ // </function>), s starting at its first tag: {call, rest}, {wait} while
1346
+ // it may still become one, {text} when it is no call (a tool the request
1347
+ // didn't declare, a tag named in prose), {error} for one cut short. Only
1348
+ // a declared tool's call counts: these tags are common in prose.
1349
+ function xmlCall(s, end, tools) {
1350
+ const w = s.match(/^<(?:antml:)?function_calls>/)
1351
+ if (w) {
1352
+ const rest = s.slice(w[0].length).replace(/^\s+/, "")
1353
+ if (!end && (!rest || XML_STARTS.some((k) => k.startsWith(rest)))) return { wait: true }
1354
+ s = rest
1355
+ }
1356
+ let m = s.match(/^<(?:antml:)?invoke\s+name\s*=\s*"([^"<>]+)"\s*>/)
1357
+ let closeRe = /<\/(?:antml:)?invoke\s*>/
1358
+ if (!m) {
1359
+ m = s.match(/^<function=([^\s<>]+?)\s*>/)
1360
+ closeRe = /<\/function\s*>/
1361
+ }
1362
+ if (!m) {
1363
+ if (!end && (XML_STARTS.some((k) => k.startsWith(s)) || /^<(?:antml:)?(?:invoke\s|function=)[^<>]{0,300}$/.test(s))) return { wait: true }
1364
+ return { text: true }
1365
+ }
1366
+ const name = m[1].trim()
1367
+ if (!tools.some((t) => (t.function ?? t)?.name === name)) return { text: true }
1368
+ const body = s.slice(m[0].length)
1369
+ const c = body.match(closeRe)
1370
+ const n = body.search(XML_NEXT)
1371
+ let stop = c ? c.index : -1
1372
+ if (n >= 0 && (stop < 0 || n < stop)) stop = n
1373
+ if (stop < 0) {
1374
+ if (!end) return { wait: true }
1375
+ stop = body.length
1376
+ }
1377
+ const whole = !!c && c.index === stop
1378
+ const p = xmlArgs(body.slice(0, stop), propsOf(tools, name))
1379
+ if (!whole && !p.closed) {
1380
+ // no parameter and no close: a tag named in passing; a parameter
1381
+ // left open: the call cut short
1382
+ if (!/<(?:antml:)?parameter\b/.test(body.slice(0, stop))) return { text: true }
1383
+ return { error: CUT_SHORT }
1384
+ }
1385
+ return { call: { name, args: JSON.stringify(p.args) }, rest: whole ? body.slice(stop + c[0].length) : body.slice(stop) }
1227
1386
  }
1228
1387
 
1229
1388
  // quoted says text ends inside a code fence or an inline code span: a
@@ -1246,31 +1405,96 @@ const UNREADABLE = "the model's tool call, written as text, can't be read; it is
1246
1405
  // that the stream ended inside, is an error, never the answer (plugins#132,
1247
1406
  // as trae's since plugins#38): the turn fails so it can be tried again. A
1248
1407
  // block whose JSON is whole when the stream ends without its close is still
1249
- // the call; one that is no call at all, or one in code, stays text.
1408
+ // the call; one that is no call at all, or one in code, stays text. A bare
1409
+ // call in Anthropic's or Qwen's tags (xmlCall) is a call too, for a tool
1410
+ // the request declared (tools).
1250
1411
  class Splitter {
1251
1412
  textBuf = ""
1252
1413
  callBuf = ""
1253
1414
  inCall = false
1254
1415
  sawTool = false
1416
+ after = false // a bare call just ended: the closes and blanks after it are dropped
1255
1417
  sent = "" // the text given out so far, to tell a block in code from a call
1418
+ constructor(tools = []) {
1419
+ this.tools = tools.filter((t) => (t?.function ?? t)?.name)
1420
+ }
1256
1421
  text(out, t) {
1257
1422
  this.sent += t
1258
1423
  out.push({ text: t })
1259
1424
  }
1425
+ // bare reads text that may hold a bare call, comb starting at its tag x:
1426
+ // the input left to read, null when comb is held for more, or false
1427
+ // when the turn ended in an error
1428
+ bare(out, comb, x, end) {
1429
+ const head = comb.slice(0, x)
1430
+ const at = comb.slice(x)
1431
+ const opener = at.match(/^<[^<>]*>?/)[0]
1432
+ if (quoted(this.sent + head)) {
1433
+ this.text(out, head + opener)
1434
+ return at.slice(opener.length)
1435
+ }
1436
+ const b = xmlCall(at, end, this.tools)
1437
+ if (b.wait) {
1438
+ if (head) this.text(out, head)
1439
+ this.textBuf = at
1440
+ return null
1441
+ }
1442
+ if (b.text) {
1443
+ this.text(out, head + opener)
1444
+ return at.slice(opener.length)
1445
+ }
1446
+ if (head) this.text(out, head)
1447
+ if (b.error) {
1448
+ out.push({ error: b.error })
1449
+ return false
1450
+ }
1451
+ this.sawTool = true
1452
+ out.push({ call: b.call })
1453
+ this.after = true
1454
+ return b.rest
1455
+ }
1456
+ // left drops what is left after a bare call; null while it may still be
1457
+ // one of its closes
1458
+ left(comb, end) {
1459
+ const rest = comb.replace(XML_LEFT, "")
1460
+ if (!end && (!rest || XML_CLOSES.some((c) => c.length > rest.length && c.startsWith(rest)))) return null
1461
+ this.after = false
1462
+ return rest
1463
+ }
1260
1464
  feed(input) {
1261
1465
  const out = []
1262
1466
  while (input) {
1263
1467
  if (!this.inCall) {
1264
- const comb = this.textBuf + input
1468
+ let comb = this.textBuf + input
1265
1469
  this.textBuf = ""
1470
+ if (this.after) {
1471
+ const rest = this.left(comb, false)
1472
+ if (rest === null) {
1473
+ this.textBuf = comb
1474
+ break
1475
+ }
1476
+ comb = rest
1477
+ if (!comb) break
1478
+ }
1266
1479
  const i = comb.indexOf(CALL_OPEN)
1480
+ const x = this.tools.length ? comb.search(XML_AT) : -1
1481
+ if (x >= 0 && (i < 0 || x < i)) {
1482
+ const next = this.bare(out, comb, x, false)
1483
+ if (next === false) return out
1484
+ if (next === null) break
1485
+ input = next
1486
+ continue
1487
+ }
1267
1488
  if (i < 0) {
1268
1489
  let keep = 0
1269
- for (let n = CALL_OPEN.length - 1; n > 0; n--)
1270
- if (comb.endsWith(CALL_OPEN.slice(0, n))) {
1271
- keep = n
1272
- break
1273
- }
1490
+ for (const mark of this.tools.length ? [CALL_OPEN, ...XML_MARKS] : [CALL_OPEN])
1491
+ for (let n = Math.min(mark.length - 1, comb.length); n > keep; n--)
1492
+ if (comb.endsWith(mark.slice(0, n))) {
1493
+ keep = n
1494
+ break
1495
+ }
1496
+ const h = this.tools.length ? comb.search(XML_HOLD) : -1
1497
+ if (h >= 0) keep = Math.max(keep, comb.length - h)
1274
1498
  if (keep < comb.length) this.text(out, comb.slice(0, comb.length - keep))
1275
1499
  this.textBuf = comb.slice(comb.length - keep)
1276
1500
  break
@@ -1288,7 +1512,7 @@ class Splitter {
1288
1512
  break
1289
1513
  }
1290
1514
  const body = comb.slice(0, j)
1291
- const c = parseCall(body)
1515
+ const c = parseCall(body, this.tools)
1292
1516
  if (c) {
1293
1517
  this.sawTool = true
1294
1518
  out.push({ call: c })
@@ -1308,7 +1532,7 @@ class Splitter {
1308
1532
  this.inCall = false
1309
1533
  this.callBuf = ""
1310
1534
  if (callish(body) && !quoted(this.sent)) {
1311
- const c = parseCall(body)
1535
+ const c = parseCall(body, this.tools)
1312
1536
  if (!c) return [{ error: CUT_SHORT }]
1313
1537
  this.sawTool = true
1314
1538
  return [{ call: c }]
@@ -1318,10 +1542,23 @@ class Splitter {
1318
1542
  return [{ text: t }]
1319
1543
  }
1320
1544
  if (this.textBuf) {
1321
- const t = this.textBuf
1545
+ let t = this.textBuf
1322
1546
  this.textBuf = ""
1323
- this.sent += t
1324
- return [{ text: t }]
1547
+ if (this.after) t = this.left(t, true)
1548
+ // what was held for a bare call, read to its end: calls, then the
1549
+ // text left, or the error of one cut short
1550
+ const out = []
1551
+ while (t) {
1552
+ const x = this.tools.length ? t.search(XML_AT) : -1
1553
+ if (x < 0) {
1554
+ this.text(out, t)
1555
+ break
1556
+ }
1557
+ const next = this.bare(out, t, x, true)
1558
+ if (next === false) break
1559
+ t = this.after ? this.left(next, true) : next
1560
+ }
1561
+ return out
1325
1562
  }
1326
1563
  return []
1327
1564
  }
@@ -1344,8 +1581,8 @@ async function* sseLines(body) {
1344
1581
  // events turns Qoder's SSE into chat completion pieces: each data line's
1345
1582
  // envelope has a "body" that is an OpenAI chunk, whose content may hold
1346
1583
  // tool calls to lift out.
1347
- async function* events(body) {
1348
- const a = new Splitter()
1584
+ async function* events(body, tools = []) {
1585
+ const a = new Splitter(tools)
1349
1586
  let index = -1 // the tool call being given
1350
1587
  const native = new Map() // upstream index -> call and its output index
1351
1588
  // one piece of the split text as an event: a call, text, or a call that
@@ -1443,8 +1680,8 @@ async function* events(body) {
1443
1680
  // opened is a chat reply's events and the first of them, read before
1444
1681
  // anything is answered: a refusal in the stream (Qoder's queue among them)
1445
1682
  // comes first.
1446
- async function opened(res) {
1447
- const it = events(res.body)
1683
+ async function opened(res, tools) {
1684
+ const it = events(res.body, tools)
1448
1685
  return { it, first: await it.next() }
1449
1686
  }
1450
1687
 
@@ -1548,7 +1785,9 @@ class UsageStatus extends Error {
1548
1785
  }
1549
1786
  }
1550
1787
 
1551
- // fetchUsage is the usage envelope, {displayMode, qoderUsage}.
1788
+ // fetchUsage is the usage envelope, {displayMode, qoderUsage}; a site with
1789
+ // its own usage path (QwenWork's account-context) is read by
1790
+ // fetchSiteUsage below instead.
1552
1791
  async function fetchUsage(site, deviceToken) {
1553
1792
  if (!String(deviceToken ?? "").trim()) throw new Error("qoder usage: missing device token")
1554
1793
  let res
@@ -1745,7 +1984,7 @@ async function refreshDevice(site, refresh, chat = false) {
1745
1984
  }
1746
1985
  let r
1747
1986
  try {
1748
- r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh } })
1987
+ r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh, ...(site.deviceRefreshTarget ? { target: site.deviceRefreshTarget } : {}) } })
1749
1988
  } catch (e) {
1750
1989
  throw new Error(`qoder device token refresh: request failed: ${e?.message ?? e}`)
1751
1990
  }
@@ -1815,6 +2054,79 @@ function parseUsage(env) {
1815
2054
  }
1816
2055
 
1817
2056
  // SITES are Qoder's two sites, each a subscription of its own.
2057
+ // QwenWork (千问办公, qwenwork.cn) speaks this protocol on Alibaba's own
2058
+ // service, with its own scene, client id and RSA key (the same key), as its
2059
+ // desktop client sends. The models below are the public cloud's qwork list
2060
+ // at the time of writing — QWENWORK_MODELS is what magpie's config lists
2061
+ // before a sign-in, and QWORK_FALLBACK_LISTING is what the enterprise
2062
+ // flagship falls back to: it serves the same scene but deploys no catalog
2063
+ // service (/algo/api/v2/model/list answers 503 there, signed and verified).
2064
+ const QWENWORK_MODELS = [
2065
+ { id: "flash", name: "标准" },
2066
+ { id: "pro", name: "高级" },
2067
+ { id: "qwen3.8-max-preview", name: "Qwen3.8-Max" },
2068
+ ]
2069
+ const QWORK_FALLBACK_LISTING = {
2070
+ // is_vl / is_reasoning / max_input_tokens are copied from the public
2071
+ // cloud's list, not checked against a flagship's own models
2072
+ qwork: [
2073
+ { key: "flash", display_name: "标准", is_vl: false, is_reasoning: false, max_input_tokens: 131072 },
2074
+ { key: "pro", display_name: "高级", is_vl: false, is_reasoning: false, max_input_tokens: 131072 },
2075
+ { key: "qwen3.8-max-preview", display_name: "Qwen3.8-Max", is_vl: false, is_reasoning: false, max_input_tokens: 131072 },
2076
+ ],
2077
+ }
2078
+ const QWENWORK_RSA_KEY = `-----BEGIN PUBLIC KEY-----
2079
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
2080
+ 4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
2081
+ 6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
2082
+ XcW+ML9FoCI6AOvOzwIDAQAB
2083
+ -----END PUBLIC KEY-----`
2084
+ // parseAccountContext reads the account-context QwenWork's sign-in already
2085
+ // reads: plan {name, next_refresh / next_due} and quota {total, used,
2086
+ // remaining} in the plan's credit unit. One window is one pool of credits.
2087
+ const num = (v) => {
2088
+ const n = Number(v)
2089
+ if (!Number.isFinite(n)) return "0"
2090
+ return String(Math.round(n * 100) / 100)
2091
+ }
2092
+ const parseAccountContext = (ctx) => {
2093
+ const data = ctx?.data ?? {}
2094
+ const q = data.quota
2095
+ const out = {}
2096
+ if (data.plan?.name) out.plan = String(data.plan.name)
2097
+ const refresh = data.plan?.next_refresh_date ?? data.plan?.next_due_date
2098
+ if (refresh) out.until = new Date(refresh).toISOString()
2099
+ if (q && typeof q === "object") {
2100
+ const total = Number(q.total)
2101
+ const remaining = Number(q.remaining)
2102
+ const used = Number.isFinite(Number(q.used)) ? Number(q.used) : total - remaining
2103
+ if (Number.isFinite(total) && total > 0 && Number.isFinite(used) && used >= 0) {
2104
+ out.windows = [{ name: "Credits", used: Math.min(100, (100 * used) / total), display: `${num(used)} / ${num(total)} credits` }]
2105
+ }
2106
+ }
2107
+ if (!out.windows) out.error = "QwenWork: the account reports no credits"
2108
+ return out
2109
+ }
2110
+
2111
+ const QWENWORK_COMMON = {
2112
+ clientId: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb", // the desktop client's
2113
+ rsaKey: QWENWORK_RSA_KEY,
2114
+ usagePath: "/api/v1/adapter/user/account-context?include=user,plan,quota",
2115
+ parseUsage: parseAccountContext,
2116
+ cosyVersion: "1.1.59",
2117
+ redirect: "qwenwork-cn://",
2118
+ deviceOnly: true, // the device token is itself the chat token
2119
+ deviceRefreshTarget: "c",
2120
+ modelScene: "qwork", listAllModels: true,
2121
+ clientType: "6", businessProduct: "qoder_work", sessionType: "qoder_work",
2122
+ userInfoPath: "/api/v1/adapter/user/account-context?include=user,plan,quota,page,data_sharing",
2123
+ normalizeUser: v => (v?.data ?? v)?.user ?? (v?.data ?? v),
2124
+ pat: false, // no /api/v1/jobToken/exchange on gateway.qwenwork.cn
2125
+ checkin: false, // no campaigns endpoint, and no Qoder desktop identity to send
2126
+ models: QWENWORK_MODELS,
2127
+ systemPrompt: "You are QwenWork (qw), a helpful assistant. Use the instructions below and the tools available to you to assist the user.",
2128
+ }
2129
+
1818
2130
  const SITES = {
1819
2131
  qoder: {
1820
2132
  id: "qoder",
@@ -1844,6 +2156,29 @@ const SITES = {
1844
2156
  vpcDomain: "vpc.qoder.com.cn",
1845
2157
  models: CN_MODELS,
1846
2158
  },
2159
+ // QwenWork's public cloud. QWENWORK_ENT_DOMAIN (the enterprise preset)
2160
+ // is the only variable read; the sites are these constants.
2161
+ qwenwork: {
2162
+ ...QWENWORK_COMMON,
2163
+ id: "qwenwork",
2164
+ name: "QwenWork",
2165
+ web: "https://gateway.qwenwork.cn",
2166
+ openapi: "https://gateway.qwenwork.cn",
2167
+ api: "https://gateway.qwenwork.cn",
2168
+ },
2169
+ // QwenWork's enterprise flagship (企业旗舰版): the enterprise's own
2170
+ // domain, asked at sign-in — web/openapi/api all live on that one host,
2171
+ // and its device flow sends no redirect_uri. QWENWORK_ENT_DOMAIN presets
2172
+ // the domain so the sign-in asks nothing.
2173
+ "qwenwork-enterprise": {
2174
+ ...QWENWORK_COMMON,
2175
+ id: "qwenwork-enterprise",
2176
+ name: "QwenWork 企业版",
2177
+ web: "https://gateway.qwenwork.cn",
2178
+ openapi: "https://gateway.qwenwork.cn",
2179
+ api: "https://gateway.qwenwork.cn",
2180
+ fallbackModels: QWORK_FALLBACK_LISTING,
2181
+ },
1847
2182
  }
1848
2183
 
1849
2184
  const makePlugin = (site) => async ({ client }) => {
@@ -1970,7 +2305,7 @@ const makePlugin = (site) => async ({ client }) => {
1970
2305
  const key = listingKey(cred)
1971
2306
  let l = listings.get(key)
1972
2307
  if (!l || again) {
1973
- l = modelInfos(await fetchListing(siteOf(site, cred), cred))
2308
+ l = modelInfos(await fetchListing(siteOf(site, cred), cred), siteOf(site, cred))
1974
2309
  listings.set(key, l)
1975
2310
  }
1976
2311
  return l
@@ -1999,6 +2334,29 @@ const makePlugin = (site) => async ({ client }) => {
1999
2334
  try {
2000
2335
  const cred = await fresh(getAuth)
2001
2336
  if (renewed(cred)) signIn = "renewed"
2337
+ // a site with its own usage path (QwenWork's account-context, signed
2338
+ // like any other call and answered with its own envelope) is read
2339
+ // there; a 401 rotates the device token once, as the qoder path does
2340
+ if (site.usagePath) {
2341
+ const read = async (token) => {
2342
+ const s = siteOf(site, cred)
2343
+ const res = await fetch(`${s.openapi}${site.usagePath}`, {
2344
+ headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
2345
+ signal: AbortSignal.timeout(20_000),
2346
+ })
2347
+ if (res.status !== 200) throw new UsageStatus(res.status)
2348
+ return res.json()
2349
+ }
2350
+ let env
2351
+ try {
2352
+ env = await read(cred.deviceToken ?? cred.access)
2353
+ } catch (e) {
2354
+ if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
2355
+ if (!cred.deviceToken) throw e
2356
+ env = await read(await deviceToken(getAuth, cred.deviceToken))
2357
+ }
2358
+ return { ...(site.parseUsage ? site.parseUsage(env) : { windows: [] }), signIn }
2359
+ }
2002
2360
  // A PAT account has no device token: the usage endpoint takes the job
2003
2361
  // token the exchange gave — a live PAT account answered 200 with a
2004
2362
  // qoder envelope. Its errors surface as the device path's do; there is
@@ -2157,7 +2515,7 @@ const makePlugin = (site) => async ({ client }) => {
2157
2515
  const api = siteOf(site, cred).api
2158
2516
  const CHAT_URL = api + CHAT_PATH
2159
2517
  const task = taskOf(sessionOf(chat, named), chat)
2160
- const body = qoderBody(chat, m, named, task)
2518
+ const body = qoderBody(chat, m, named, task, siteOf(site, cred))
2161
2519
  const wire = encodeBody(JSON.stringify(body))
2162
2520
  // Qoder's queue is waited out (queueWait) and the same request, its
2163
2521
  // request_set_id the one the queue knows, sent again
@@ -2165,7 +2523,7 @@ const makePlugin = (site) => async ({ client }) => {
2165
2523
  const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key }
2166
2524
  for (let waited = 0; ; waited++) {
2167
2525
  const headers = {
2168
- ...cosyHeaders(CHAT_URL, cred, wire),
2526
+ ...cosyHeaders(CHAT_URL, cred, wire, siteOf(site, cred)),
2169
2527
  Accept: "text/event-stream",
2170
2528
  "Cache-Control": "no-cache",
2171
2529
  "X-Model-Key": m.key,
@@ -2174,7 +2532,7 @@ const makePlugin = (site) => async ({ client }) => {
2174
2532
  let res, open
2175
2533
  try {
2176
2534
  res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal })
2177
- if (res.ok) open = await opened(res)
2535
+ if (res.ok) open = await opened(res, chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : [])
2178
2536
  } catch (e) {
2179
2537
  return errorResponse({ status: 502, message: e.message })
2180
2538
  }
@@ -2183,7 +2541,7 @@ const makePlugin = (site) => async ({ client }) => {
2183
2541
  if (!f) task.answered = true
2184
2542
  if (!f?.queue || waited >= QUEUE.recoveries) return f && !res.ok ? errorResponse(f) : answer(open, chat)
2185
2543
  try {
2186
- if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline))) return errorResponse(f)
2544
+ if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline, siteOf(site, cred)))) return errorResponse(f)
2187
2545
  } catch (e) {
2188
2546
  return errorResponse({ status: 502, message: e?.message ?? String(e) })
2189
2547
  }
@@ -2267,7 +2625,10 @@ const makePlugin = (site) => async ({ client }) => {
2267
2625
  // a PAT too (verified: HTTP 200 and a jt- token), and that job token
2268
2626
  // signs the model list and chat calls with the COSY envelope as on
2269
2627
  // qoder.com, so the exchange gives a token the chat endpoint accepts.
2270
- {
2628
+ // A site that serves no exchange path (QwenWork) sets pat: false.
2629
+ ...(site.pat === false
2630
+ ? []
2631
+ : [{
2271
2632
  type: "oauth",
2272
2633
  label: `Sign in with ${site.name} PAT`,
2273
2634
  prompts: [
@@ -2291,7 +2652,7 @@ const makePlugin = (site) => async ({ client }) => {
2291
2652
  },
2292
2653
  }
2293
2654
  },
2294
- },
2655
+ }]),
2295
2656
  // an enterprise VPC instance (Qoder CN), a method of its own so
2296
2657
  // that the sign-in above asks nothing new
2297
2658
  ...(site.vpcDomain
@@ -2318,7 +2679,10 @@ const makePlugin = (site) => async ({ client }) => {
2318
2679
  : []),
2319
2680
  ],
2320
2681
  usage,
2321
- checkin,
2682
+ // the daily check-in reads the vendor's desktop device identity and
2683
+ // posts it to the campaign endpoint: a site without one (QwenWork)
2684
+ // sets checkin: false and gets none
2685
+ ...(site.checkin === false ? {} : { checkin }),
2322
2686
  },
2323
2687
  async config(config) {
2324
2688
  config.provider ??= {}
@@ -2363,6 +2727,65 @@ const makePlugin = (site) => async ({ client }) => {
2363
2727
 
2364
2728
  export const QoderAuthPlugin = makePlugin(SITES.qoder)
2365
2729
  export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"])
2730
+ export const QwenWorkAuthPlugin = makePlugin(SITES.qwenwork)
2731
+
2732
+ // enterpriseDomain reads what the user entered as their enterprise's
2733
+ // address, as the desktop client's enterprise mode reads its endpoint
2734
+ // override: a bare host, or an https:// address with no path. Loopback- and
2735
+ // intranet-looking names are refused too. Anything else names none.
2736
+ function enterpriseDomain(input) {
2737
+ let e = String(input ?? "").trim().toLowerCase()
2738
+ if (!e) return undefined
2739
+ if (/^[a-z][a-z\d+.-]*:\/\//.test(e)) {
2740
+ let u
2741
+ try { u = new URL(e) } catch { return undefined }
2742
+ if (u.protocol !== "https:" || u.username || u.password || u.port || u.search || u.hash || (u.pathname !== "" && u.pathname !== "/")) return undefined
2743
+ if (e.endsWith("/")) e = e.slice(0, -1)
2744
+ if (u.hostname + "" !== e.slice("https://".length)) return undefined
2745
+ e = u.hostname
2746
+ }
2747
+ if (/^(\d{1,3}\.){3}\d{1,3}$/.test(e)) return undefined // a bare IP is not a domain
2748
+ if (/^(localhost|.*\.localhost|.*\.local|.*\.internal)$/.test(e)) return undefined // loopback / intranet suffixes
2749
+ if (!/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(e)) return undefined
2750
+ return e
2751
+ }
2752
+
2753
+ // The enterprise flagship's sign-in: the same device flow against the
2754
+ // enterprise's own host, which it asks for (QWENWORK_ENT_DOMAIN presets it),
2755
+ // with no redirect_uri — the flagship's /device/selectAccounts refuses one.
2756
+ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
2757
+ const base = SITES["qwenwork-enterprise"]
2758
+ const preset = enterpriseDomain(process.env.QWENWORK_ENT_DOMAIN ?? "")
2759
+ const siteFor = (domain) => ({ ...base, web: `https://${domain}`, openapi: `https://${domain}`, api: `https://${domain}`, redirect: "", enterpriseDomain: domain, vpc: domain })
2760
+ const plugin = await makePlugin(base)({ client })
2761
+ plugin.auth.methods.splice(0, plugin.auth.methods.length, {
2762
+ type: "oauth",
2763
+ label: preset ? `Sign in with ${base.name} (${preset})` : `Sign in with ${base.name}(输入企业域名)`,
2764
+ prompts: preset ? [] : [
2765
+ {
2766
+ type: "text",
2767
+ key: "domain",
2768
+ message: "你企业的千问办公旗舰版域名(企业管理后台地址栏的域名,如 your-company.vpc.qwenwork.cn)",
2769
+ placeholder: "your-company.vpc.qwenwork.cn 或 https://your-company.vpc.qwenwork.cn",
2770
+ validate: (v) => (enterpriseDomain(v) ? undefined : "请输入企业域名(或 https:// 开头的完整地址),不要带路径"),
2771
+ },
2772
+ ],
2773
+ authorize: (inputs) => {
2774
+ const domain = preset || enterpriseDomain(inputs?.domain)
2775
+ if (!domain) throw new Error("请输入企业域名(或设置 QWENWORK_ENT_DOMAIN 环境变量)")
2776
+ return deviceSignIn(siteFor(domain))
2777
+ },
2778
+ })
2779
+ return plugin
2780
+ }
2781
+
2782
+ // for another service on this same protocol (QwenWork ships one): the
2783
+ // plugin factory and its pieces, a site built as SITES' entries are (see
2784
+ // the site fields those hooks read — modelScene, listAllModels, clientType,
2785
+ // businessProduct, sessionType, systemPrompt, userInfoPath, normalizeUser,
2786
+ // deviceOnly, deviceRefreshTarget, rsaKey, cosyVersion, fallbackModels and
2787
+ // the vpcDomain branch of siteOf), and the openapi fetch.
2788
+ export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
2366
2789
 
2367
2790
  // for tests
2368
- 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 }
2791
+ export const _internal = { typedUnions, Splitter, 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.33",
4
- "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)",
3
+ "version": "0.2.36",
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
  }