@magpie-community/opencode-qoder-auth 0.2.39 → 0.2.41

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 +9 -1
  2. package/index.mjs +84 -19
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -158,7 +158,7 @@ itself.
158
158
  |---|---|
159
159
  | A refused sign-in (no code, or code 105) | 401 |
160
160
  | A quota (codes 110, 112–119, 122) | 429 |
161
- | Busy or queued for the model (code 10605) | Since 0.2.28 the request waits in Qoder's queue as Qoder's client does (below), then is sent again; past the wait, 503 with `Retry-After` from Qoder's `retryAfterSeconds` (30s when it gives none). The sign-in is untouched |
161
+ | Busy or queued for the model (code 10605) | Since 0.2.28 the request waits in Qoder's queue as Qoder's client does (below), then is sent again; past the wait, 503 with `Retry-After` from Qoder's `retryAfterSeconds` (30s when it gives none). Since 0.2.40, when magpie has another candidate after this request (`x-magpie-fallback: 1`), the 503 comes at once, saying the queue and how many are ahead, and magpie asks the next. The sign-in is untouched |
162
162
  | A refusal of the request itself (codes 406, 416, 430, 80411, 80412, 100400–100403) | 400, with Qoder's words |
163
163
  | "Error in upstream response", the model's own vendor behind Qoder failing, which Qoder sends as a 400 (since 0.2.24) | 502, so magpie asks again or another account; the sign-in is untouched |
164
164
  | A failure before the answer starts | Qoder's status |
@@ -427,6 +427,14 @@ cancelled request end the wait early. Qoder's client also reports the end
427
427
  of its turn to `/api/v2/service/ask/finish`; the plugin doesn't, and
428
428
  Qoder releases that lease on its own TTL. `queue.test.mjs` has the wait.
429
429
 
430
+ Since **0.2.40** the wait is only for the last candidate: when magpie says
431
+ another account, provider or routing group member follows this request
432
+ (its `x-magpie-fallback: 1` header, which the plugin host keeps from Qoder),
433
+ a queued request is answered at once with the 503 above, e.g. "Qoder queued
434
+ the request for dfmodel (this plan's queue: p3, 3 ahead); try again in
435
+ 30s", and magpie asks the next instead of keeping the agent in Qoder's
436
+ queue.
437
+
430
438
  For a bounded offline reproduction, run `packages/qoder/busy.test.mjs`
431
439
  from #185 in an isolated temporary HOME. It compares plain queue JSON,
432
440
  BOM-prefixed JSON and known message wrappers, keeping explicit login and
package/index.mjs CHANGED
@@ -38,8 +38,9 @@ import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, con
38
38
  import { execFile } from "node:child_process"
39
39
  import { readdir, stat } from "node:fs/promises"
40
40
  import { STATUS_CODES } from "node:http"
41
- import { homedir } from "node:os"
41
+ import { homedir, hostname } from "node:os"
42
42
  import { join, resolve } from "node:path"
43
+ import { domainToASCII } from "node:url"
43
44
 
44
45
  const CHAT_PATH = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1"
45
46
  const MODELS_PATH = "/algo/api/v2/model/list?Encode=1"
@@ -73,10 +74,33 @@ const hexID = () => randomUUID().replaceAll("-", "")
73
74
 
74
75
  // ---- the COSY envelope --------------------------------------------------------
75
76
 
76
- // machineOS names the machine as Qoder's desktop clients do.
77
- function machineOS() {
78
- const arch = { x64: "x86_64", ia32: "x86", arm64: "aarch64" }[process.arch] ?? process.arch
79
- return arch + "_" + process.platform
77
+ // machineOS names the machine as Qoder's desktop client does: Node's
78
+ // process.platform, so x86_64_win32 on Windows, aarch64_darwin on a Mac
79
+ // (its worker runtime's COSY_MACHINE_OS, Qoder 0.4.3). Only x64 and arm64
80
+ // are renamed; any other arch goes as Node names it.
81
+ function machineOS(arch = process.arch, platform = process.platform) {
82
+ return ({ x64: "x86_64", arm64: "aarch64" }[arch] ?? arch) + "_" + platform
83
+ }
84
+
85
+ // machineHostname is the Cosy-MachineHostname Qoder's client puts on a chat
86
+ // request: os.hostname(), sent as it is when it is printable ASCII, else
87
+ // its punycode, else made safe and marked with a hash of the original, at
88
+ // most 96 characters (its zei). "" (none is sent) for an empty name.
89
+ const HOST_SAFE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/u
90
+ function machineHostname(name = hostname()) {
91
+ const hash = (v) => createHash("sha256").update(v, "utf8").digest("hex").slice(0, 8)
92
+ const cap = (v) => {
93
+ if (v.length <= 96) return v
94
+ const head = v.slice(0, 96 - 8 - 1).replace(/[-\s]+$/u, "")
95
+ return head ? `${head}-${hash(v)}` : `unknown-${hash(v)}`
96
+ }
97
+ const v = String(name ?? "").trim()
98
+ if (!v) return ""
99
+ if (HOST_SAFE.test(v)) return cap(v)
100
+ const ascii = domainToASCII(v)
101
+ if (ascii && HOST_SAFE.test(ascii)) return cap(ascii)
102
+ const safe = v.replace(/[^\x21-\x7e]+/gu, "-").replace(/-{2,}/gu, "-").replace(/^-+|-+$/gu, "")
103
+ return cap(safe ? `${safe}-${hash(v)}` : `unknown-${hash(v)}`)
80
104
  }
81
105
 
82
106
  // userBlob is the account as the envelope carries it: AES-128-CBC under a
@@ -98,7 +122,9 @@ function cosyHeaders(url, u, body, site, ts = Math.floor(Date.now() / 1000)) {
98
122
  const cosyVersion = site?.cosyVersion ?? COSY_VERSION
99
123
  const blob = userBlob(u, site?.rsaKey)
100
124
  const payload = Buffer.from(
101
- JSON.stringify({ version: "v1", requestId: hexID(), info: blob.info, cosyVersion, ideVersion: "" }),
125
+ // the request id is a dashed UUID, as Qoder's signer makes it; its
126
+ // ideVersion is "" too
127
+ JSON.stringify({ version: "v1", requestId: randomUUID(), info: blob.info, cosyVersion, ideVersion: "" }),
102
128
  ).toString("base64")
103
129
  let path = new URL(url).pathname
104
130
  if (path.startsWith("/algo")) path = path.slice(5)
@@ -127,6 +153,25 @@ function cosyHeaders(url, u, body, site, ts = Math.floor(Date.now() / 1000)) {
127
153
  }
128
154
  }
129
155
 
156
+ // chatHeaders are the headers of a chat (agent_chat_generation) call, as
157
+ // Qoder's client builds them (its prepareInferRequest, then Vai): no
158
+ // Cosy-ClientIp; Cosy-MachineToken and Cosy-MachineType are its device
159
+ // identity's (the runtime-info the check-in reads), or left off when it has
160
+ // none, rather than the machine id cosyHeaders puts there; and the
161
+ // machine's hostname. Every other call keeps cosyHeaders' set, which is
162
+ // its prepareRequest's: there ClientIp, MachineId and MachineToken are all
163
+ // the machine id (#443).
164
+ function chatHeaders(url, u, body, site, model, identity = {}) {
165
+ const h = cosyHeaders(url, u, body, site)
166
+ delete h["Cosy-ClientIp"]
167
+ delete h["Cosy-MachineToken"]
168
+ delete h["Cosy-MachineType"]
169
+ for (const key of ["Cosy-MachineToken", "Cosy-MachineType"]) if (identity[key]) h[key] = identity[key]
170
+ const host = machineHostname()
171
+ if (host) h["Cosy-MachineHostname"] = host
172
+ return { ...h, Accept: "text/event-stream", "Cache-Control": "no-cache", "X-Model-Key": model.key, "X-Model-Source": model.source }
173
+ }
174
+
130
175
  // ---- the body codec -----------------------------------------------------------
131
176
 
132
177
  // Base64 through the client's shuffled alphabet ('$' pads), then the first
@@ -897,6 +942,10 @@ function sessionOf(chat, named = "") {
897
942
  // conversation by, from the chat.headers hook to the loader's fetch. It
898
943
  // goes no further: nothing of the request's headers is sent to Qoder.
899
944
  const SESSION = "x-magpie-qoder-session"
945
+ // FALLBACK is "1" when magpie has another candidate after this request
946
+ // (another account, provider or routing group member): a queued request is
947
+ // then answered at once rather than waited out
948
+ const FALLBACK = "x-magpie-fallback"
900
949
 
901
950
  // namedSession is the session a chat.headers hook is told, "" when it
902
951
  // names none. magpie, with no session header from the agent, makes one of
@@ -1090,7 +1139,8 @@ function failure(status, text) {
1090
1139
  const n = Number(queue?.retryAfterSeconds)
1091
1140
  const wait = Number.isFinite(n) && n > 0 ? Math.ceil(n) : BUSY_WAIT
1092
1141
  const model = queue?.modelKey ? ` for ${queue.modelKey}` : ""
1093
- const tier = queue?.queueType ? ` (this plan's queue: ${queue.queueType})` : ""
1142
+ const ahead = Number(queue?.queueCount) > 0 ? `, ${Math.floor(Number(queue.queueCount))} ahead` : ""
1143
+ const tier = queue?.queueType ? ` (this plan's queue: ${queue.queueType}${ahead})` : ahead ? ` (${ahead.slice(2)})` : ""
1094
1144
  const what = queue?.isQueued === true ? "queued the request" : "is busy"
1095
1145
  return { status: 503, message: `Qoder ${what}${model}${tier}; try again in ${wait}s`, retryAfter: wait, signIn: "", queue: queue ?? {} }
1096
1146
  }
@@ -2230,12 +2280,30 @@ const makePlugin = (site) => async ({ client }) => {
2230
2280
  campaignMachines.set(uid, entry)
2231
2281
  }
2232
2282
  try {
2233
- return await entry.promise
2283
+ const got = await entry.promise
2284
+ if (campaignMachines.get(uid) === entry) readIdentities.set(uid, { at: entry.at, headers: got })
2285
+ return got
2234
2286
  } catch (e) {
2235
2287
  if (campaignMachines.get(uid) === entry) campaignMachines.delete(uid)
2236
2288
  throw e
2237
2289
  }
2238
2290
  }
2291
+ // chatIdentity: the device identity a chat carries, as Qoder's client puts
2292
+ // its native identity on when it has one. Only one this process has
2293
+ // already read (a check-in) is used, so a chat never waits on, or is the
2294
+ // first to run, Qoder's helper; one an hour old is read again behind the
2295
+ // chat, as the desktop client renews its own hourly. {}: none yet.
2296
+ const readIdentities = new Map()
2297
+ const chatIdentity = (uid) => {
2298
+ const known = uid ? readIdentities.get(uid) : undefined
2299
+ if (!known) return {}
2300
+ const now = Date.now()
2301
+ if (now - (known.tried ?? known.at) >= CAMPAIGN_MACHINE_TTL) {
2302
+ known.tried = now
2303
+ machineForCampaign(uid).catch(() => {})
2304
+ }
2305
+ return known.headers
2306
+ }
2239
2307
  // campaignIdentity: the headers a campaigns request carries, and why
2240
2308
  // there are none where the site goes on without them (Qoder CN).
2241
2309
  const campaignIdentity = async (uid) => {
@@ -2547,7 +2615,7 @@ const makePlugin = (site) => async ({ client }) => {
2547
2615
  })
2548
2616
 
2549
2617
  // ask is the answer to a chat completion on the live account cred.
2550
- const ask = async (chat, cred, init, named = "") => {
2618
+ const ask = async (chat, cred, init, named = "", fallback = false) => {
2551
2619
  let m
2552
2620
  try {
2553
2621
  m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model)
@@ -2576,13 +2644,7 @@ const makePlugin = (site) => async ({ client }) => {
2576
2644
  ask.requestId = body.request_id
2577
2645
  }
2578
2646
  const wire = encodeBody(JSON.stringify(body))
2579
- const headers = {
2580
- ...cosyHeaders(CHAT_URL, cred, wire, siteOf(site, cred)),
2581
- Accept: "text/event-stream",
2582
- "Cache-Control": "no-cache",
2583
- "X-Model-Key": m.key,
2584
- "X-Model-Source": m.source,
2585
- }
2647
+ const headers = chatHeaders(CHAT_URL, cred, wire, siteOf(site, cred), m, chatIdentity(cred.uid))
2586
2648
  // a refused call's stream is closed: Qoder keeps a 10605 stream open
2587
2649
  // after its one event, and a connection held open while the call is
2588
2650
  // waited out and sent again is one more the account holds
@@ -2599,7 +2661,10 @@ const makePlugin = (site) => async ({ client }) => {
2599
2661
  if (f) call.abort()
2600
2662
  // an answered call moves its task on, as Qoder's client moves it
2601
2663
  if (!f) task.answered = true
2602
- if (!f?.queue || waited >= QUEUE.recoveries) return f ? errorResponse(f) : answer(open, chat, servedName)
2664
+ // with another account, provider or group member after this one
2665
+ // (magpie's X-Magpie-Fallback), a queued request isn't waited out:
2666
+ // its 503 goes back at once, saying the queue, and the next is asked
2667
+ if (!f?.queue || waited >= QUEUE.recoveries || fallback) return f ? errorResponse(f) : answer(open, chat, servedName)
2603
2668
  try {
2604
2669
  if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline, siteOf(site, cred)))) return errorResponse(f)
2605
2670
  } catch (e) {
@@ -2673,7 +2738,7 @@ const makePlugin = (site) => async ({ client }) => {
2673
2738
  }
2674
2739
  const h = new Headers(input instanceof Request ? input.headers : undefined)
2675
2740
  new Headers(init.headers ?? {}).forEach((v, k) => h.set(k, v))
2676
- return signed(await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? ""), renewed(cred))
2741
+ return signed(await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1"), renewed(cred))
2677
2742
  },
2678
2743
  }
2679
2744
  },
@@ -2848,4 +2913,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
2848
2913
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
2849
2914
 
2850
2915
  // for tests
2851
- 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 }
2916
+ export const _internal = { chatHeaders, machineOS, machineHostname, cosyHeaders, 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,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.39",
3
+ "version": "0.2.41",
4
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",