@magpie-community/opencode-qoder-auth 0.2.49 → 0.2.51

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 +26 -0
  2. package/index.mjs +150 -15
  3. package/package.json +20 -4
package/README.md CHANGED
@@ -153,6 +153,13 @@ itself.
153
153
  reasoning and usage.
154
154
  - Tool calls Qoder writes as XML or JSON in its text become tool calls.
155
155
  Tool calls it sends the OpenAI way keep Qoder's id.
156
+ - A call sent the OpenAI way that never gets its function name is never
157
+ sent on, and its arguments go nowhere (since 0.2.51, #579). If nothing
158
+ of the answer came before it, the request is sent once more; a second
159
+ such reply is a 502 that magpie can retry or fail over. If the answer
160
+ had begun (text, reasoning or a named call), the unnamed call is dropped
161
+ and the answer ends as it would have without it (`tool_calls` beside a
162
+ named call, `stop` otherwise), with a warning in magpie's log.
156
163
  - A call written in the text that can't be read, or that the stream ends
157
164
  inside, is never sent on as the answer (since 0.2.16, #132): the turn
158
165
  ends as an error, a 502 or the stream's error frame with no finish, so
@@ -302,6 +309,25 @@ paths, client id and protocol are the public ones:
302
309
  The hosts and reply shapes come from a real VPC account's report
303
310
  (yetone/magpie#312). This plugin has not been tried with a VPC account.
304
311
 
312
+ ## The card's name
313
+
314
+ An account signed in with a phone is shown by that phone — masked, `138****8000` — not by
315
+ its `accountId`, which is a uuid. Qoder CN's user info answers the number as `security_mobile`
316
+ (measured `13800138000`), so that is what the card takes.
317
+
318
+ QwenWork's phone accounts answer only the last four digits, as `name`, beside a synthetic
319
+ `phone_<uuid>@phone.local` email (measured): the card shows `****8000` and never that email.
320
+ An email sign-in keeps its email.
321
+
322
+ `accountId` stays the account's identity — what magpie keys the user's own name for
323
+ it, its proxy, model picks, caps and a gateway key's account list by — so it never
324
+ changes: it is what a sign-in and every renewal give back. The card's name is usage's
325
+ `user`, a field magpie shows and never keys by.
326
+
327
+ A sign-in reads the user info, and a renewal reads it again (outside the token lock),
328
+ so an account stored by an earlier version shows the phone on the card at its next
329
+ renewal. A failed read changes nothing and never costs a sign-in.
330
+
305
331
  ## QwenWork (千问办公)
306
332
 
307
333
  `QwenWork` and `QwenWork 企业版` serve Alibaba's own QwenWork (qwenwork.cn)
package/index.mjs CHANGED
@@ -375,10 +375,11 @@ async function deviceSignIn(site) {
375
375
  let email = ""
376
376
  let name = ""
377
377
  let uid = dt.user_id
378
+ let user = null
378
379
  try {
379
380
  const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: dt.token })
380
381
  if (ui.status >= 200 && ui.status < 300) {
381
- const user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
382
+ user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
382
383
  ;[email, name] = [user?.email ?? "", user?.name ?? ""]
383
384
  if (site.deviceOnly) uid = String(user?.id ?? user?.user_id ?? user?.uid ?? uid ?? "") || undefined
384
385
  // a VPC poll may give the token alone: the user is then the one
@@ -393,7 +394,22 @@ async function deviceSignIn(site) {
393
394
  ...chat,
394
395
  // a VPC account is told apart from the same person's public one; a
395
396
  // device-only one is shown by name, falling back to its id
396
- accountId: site.vpc ? `${email || uid} (${site.vpc})` : site.deviceOnly ? email || uid || name || dt.user_id : email || dt.user_id,
397
+ // accountId is the account's identity in magpie (its name, proxy,
398
+ // model picks and caps all hang off it, and a gateway key keys its
399
+ // list by it), so it stays exactly what main computes: the phone is a
400
+ // separate field, shown by usage's `user`, never the identity.
401
+ accountId: site.vpc
402
+ ? `${email || uid} (${site.vpc})`
403
+ : site.deviceOnly
404
+ ? email || uid || name || dt.user_id
405
+ : email || dt.user_id,
406
+ // the card's names: the phone on its own, and what magpie shows (a
407
+ // real email first, then the phone) — never the accountId
408
+ ...(() => {
409
+ const label = phoneLabelOf(user, email, name)
410
+ const suffix = (v) => (v ? (site.vpc ? `${v} (${site.vpc})` : v) : "")
411
+ return { phoneLabel: suffix(label), cardName: suffix(realEmailOf(email) || label) }
412
+ })(),
397
413
  uid,
398
414
  email,
399
415
  name: name || dt.user_name || "",
@@ -430,9 +446,11 @@ async function patSignIn(site, pat) {
430
446
  let email = ""
431
447
  let name = ""
432
448
  let uid = ""
449
+ let user = null
433
450
  try {
434
451
  const ui = await openapi(site, "/api/v1/userinfo", { token })
435
452
  if (ui.status >= 200 && ui.status < 300) {
453
+ user = ui.json
436
454
  ;[email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""]
437
455
  uid = String(ui.json?.id ?? ui.json?.user_id ?? ui.json?.uid ?? "")
438
456
  }
@@ -446,6 +464,8 @@ async function patSignIn(site, pat) {
446
464
  // so a renewed PAT sign-in must keep naming the same account. A suffix
447
465
  // here would add a second row beside the lapsed one instead.
448
466
  accountId: email || uid,
467
+ phoneLabel: phoneLabelOf(user, email, name),
468
+ cardName: realEmailOf(email) || phoneLabelOf(user, email, name),
449
469
  uid,
450
470
  email,
451
471
  name: name || "",
@@ -1691,6 +1711,9 @@ async function* events(body, tools = []) {
1691
1711
  f.call ? { tool: { index: ++index, id: "call_" + hexID(), name: f.call.name, args: f.call.args } } : f.error ? { error: { status: 502, message: f.error } } : { text: f.text }
1692
1712
  let usage
1693
1713
  let fr = ""
1714
+ // said: something of the answer has been given (text, reasoning or a
1715
+ // call), which a client may already show
1716
+ let said = false
1694
1717
  for await (const line of sseLines(body)) {
1695
1718
  if (!line.startsWith("data:")) continue
1696
1719
  const payload = line.slice(5).trim()
@@ -1713,13 +1736,17 @@ async function* events(body, tools = []) {
1713
1736
  continue
1714
1737
  }
1715
1738
  const delta = chunk?.choices?.[0]?.delta ?? {}
1716
- if (delta.reasoning_content) yield { reasoning: delta.reasoning_content }
1739
+ if (delta.reasoning_content) {
1740
+ said = true
1741
+ yield { reasoning: delta.reasoning_content }
1742
+ }
1717
1743
  if (typeof delta.content === "string")
1718
1744
  for (const f of a.feed(delta.content)) {
1719
1745
  if (!f.call && !f.error && !f.text) continue
1720
1746
  const e = piece(f)
1721
1747
  yield e
1722
1748
  if (e.error) return
1749
+ said = true
1723
1750
  }
1724
1751
  // tool calls served the OpenAI way keep Qoder's id: a result answers it
1725
1752
  for (const tc of delta.tool_calls ?? []) {
@@ -1743,7 +1770,7 @@ async function* events(body, tools = []) {
1743
1770
  yield e
1744
1771
  if (e.error) return
1745
1772
  }
1746
- a.sawTool = true
1773
+ a.sawTool = said = true
1747
1774
  call.index = ++index
1748
1775
  yield { tool: { index: call.index, id: call.id || "call_" + hexID(), name, args: call.args } }
1749
1776
  } else if (args) yield { args: { index: call.index, text: args } }
@@ -1766,14 +1793,31 @@ async function* events(body, tools = []) {
1766
1793
  const e = piece(f)
1767
1794
  yield e
1768
1795
  if (e.error) return
1769
- }
1770
- if ([...native.values()].some((call) => call.index === undefined)) {
1771
- yield { error: { status: 502, message: "the model's native tool call has no name; it is not sent on as a tool" } }
1796
+ said = true
1797
+ }
1798
+ // A native call the model began and never named is never given: a
1799
+ // client keeps an unnamed tool in its history and other providers
1800
+ // refuse it. Its arguments, held while it waited for the name, go
1801
+ // nowhere, not into the text either. With nothing said before it, the
1802
+ // reply is no answer: a 502 (nameless) that ask sends once more, then
1803
+ // the gateway's to retry or fail over. After an answer began, the call
1804
+ // is dropped and the answer ends as it would have without it, so the
1805
+ // text, reasoning and named calls already given are kept: qoder-cn's
1806
+ // qfmodel did this now and then, and the whole turn failed with an
1807
+ // error the client didn't retry (plugins#579).
1808
+ const nameless = [...native.values()].filter((call) => call.index === undefined).length
1809
+ if (nameless && !said) {
1810
+ yield { error: { status: 502, message: NAMELESS, nameless: true } }
1772
1811
  return
1773
1812
  }
1813
+ if (nameless) console.warn(`qoder: dropped ${nameless} native tool call${nameless > 1 ? "s" : ""} the model never named (plugins#579)`)
1774
1814
  yield { stop: a.sawTool ? "tool_calls" : fr === "length" ? "length" : "stop", usage }
1775
1815
  }
1776
1816
 
1817
+ // NAMELESS is the error of a reply whose only answer was a native tool
1818
+ // call the model never named.
1819
+ const NAMELESS = "the model's native tool call has no name; it is not sent on as a tool"
1820
+
1777
1821
  // answer turns Qoder's reply into the chat completion OpenAI's API gives.
1778
1822
  // A failure before the answer keeps its status; one after it ends the
1779
1823
  // stream with an error.
@@ -1864,6 +1908,70 @@ function signed(res, renewed) {
1864
1908
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
1865
1909
  }
1866
1910
 
1911
+ // ---- the card's name ----------------------------------------------------------
1912
+ //
1913
+ // The card's name is not `accountId` (a uuid is not a name, and accountId is
1914
+ // the identity magpie keys settings by). Both phone
1915
+ // sign-ins here carry the phone somewhere in their user info: Qoder CN answers
1916
+ // `security_mobile` (measured `13800138000`), QwenWork's phone accounts answer
1917
+ // only the last four digits as `name` plus a synthetic
1918
+ // `phone_<uuid>@phone.local` email (measured).
1919
+ const PHONE_EMAIL = /^phone_[0-9a-f-]+@phone\.local$/i
1920
+
1921
+ /** A phone number as the cards show it: `0086-…`/`+86 …`/bare → `138****8000`. */
1922
+ function maskPhone(raw) {
1923
+ let digits = String(raw ?? "").replace(/\D/g, "")
1924
+ if (digits.startsWith("0086") && digits.length - 4 >= 7) digits = digits.slice(4)
1925
+ else if (digits.startsWith("86") && digits.length - 2 >= 7) digits = digits.slice(2)
1926
+ // a phone is 11 digits; a shorter run is not a number to mask
1927
+ if (digits.length < 11) return ""
1928
+ return `${digits.slice(0, 3)}****${digits.slice(-4)}`
1929
+ }
1930
+
1931
+ /**
1932
+ * What a renewal puts on the record for the card: `phoneLabel` (the phone the
1933
+ * account signs in with, `138****8000` / `****8000`) and `cardName` (a real
1934
+ * email first, then the phone) — both with the VPC suffix. It renames nothing:
1935
+ * `accountId` is the identity and never changes.
1936
+ *
1937
+ * Read from the renewed token's user info. No cache: each renewal has a new
1938
+ * token, so nothing is read twice (review #487, 6).
1939
+ */
1940
+ async function refreshedNames(site, token) {
1941
+ const key = String(token ?? "")
1942
+ if (!key) return {}
1943
+ try {
1944
+ const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: key })
1945
+ if (ui.status < 200 || ui.status >= 300) return {}
1946
+ const user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
1947
+ const label = phoneLabelOf(user, user?.email, user?.name)
1948
+ const suffix = (v) => (v ? (site.vpc ? `${v} (${site.vpc})` : v) : "")
1949
+ // built as the sign-in builds it: a real email first, then the phone
1950
+ return { phoneLabel: suffix(label), cardName: suffix(realEmailOf(user?.email) || label) }
1951
+ } catch {
1952
+ return {}
1953
+ }
1954
+ }
1955
+
1956
+ /** The account's own email, when it is a real one (a synthetic phone email is not). */
1957
+ function realEmailOf(email) {
1958
+ const e = String(email ?? "").trim()
1959
+ if (!e || PHONE_EMAIL.test(e)) return ""
1960
+ return e
1961
+ }
1962
+
1963
+ /** The phone-derived part of a card's name, or "" when the account has none. */
1964
+ function phoneLabelOf(user, email, name) {
1965
+ const phone = maskPhone(user?.security_mobile ?? user?.phoneNumber ?? user?.phone ?? user?.mobile)
1966
+ if (phone) return phone
1967
+ // a synthetic phone email is never shown: its four digits are, or nothing
1968
+ if (PHONE_EMAIL.test(String(email ?? ""))) {
1969
+ const tail = String(name ?? "").trim()
1970
+ if (/^\d{4}$/.test(tail)) return `****${tail}`
1971
+ }
1972
+ return ""
1973
+ }
1974
+
1867
1975
  // changed is the fields of b that differ from a's: what auth.refresh gives.
1868
1976
  function changed(a, b) {
1869
1977
  const out = {}
@@ -2605,6 +2713,8 @@ const makePlugin = (site) => async ({ client }) => {
2605
2713
  try {
2606
2714
  const cred = await fresh(getAuth)
2607
2715
  if (renewed(cred)) signIn = "renewed"
2716
+ // the card's name: magpie takes usage's `user` for it and never as a key
2717
+ const who = cred?.cardName ? { user: cred.cardName } : {}
2608
2718
  // a site with its own usage path (QwenWork's account-context, signed
2609
2719
  // like any other call and answered with its own envelope) is read
2610
2720
  // there; a 401 rotates the device token once, as the qoder path does
@@ -2635,7 +2745,7 @@ const makePlugin = (site) => async ({ client }) => {
2635
2745
  if (site.walletsPath && ctxUser?.is_biz !== true && ctxUser?.isBiz !== true) {
2636
2746
  try { wallets = await read(token, site.walletsPath) } catch {}
2637
2747
  }
2638
- return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn }
2748
+ return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn, ...who }
2639
2749
  }
2640
2750
  // A PAT account has no device token: the usage endpoint takes the job
2641
2751
  // token the exchange gave — a live PAT account answered 200 with a
@@ -2643,7 +2753,7 @@ const makePlugin = (site) => async ({ client }) => {
2643
2753
  // no second token here to rotate and retry with.
2644
2754
  if (cred.patAuth && !cred.deviceToken) {
2645
2755
  const env = await fetchUsage(siteOf(site, cred), cred.access)
2646
- return { ...(await spareFree(cred, parseUsage(env))), signIn }
2756
+ return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who }
2647
2757
  }
2648
2758
  let env
2649
2759
  try {
@@ -2652,7 +2762,7 @@ const makePlugin = (site) => async ({ client }) => {
2652
2762
  if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
2653
2763
  env = await fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken))
2654
2764
  }
2655
- return { ...(await spareFree(cred, parseUsage(env))), signIn }
2765
+ return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who }
2656
2766
  } catch (e) {
2657
2767
  return { error: e?.message ?? String(e), signIn: e?.expired ? "expired" : signIn }
2658
2768
  }
@@ -2794,6 +2904,7 @@ const makePlugin = (site) => async ({ client }) => {
2794
2904
  asked.cred = cred
2795
2905
  let m
2796
2906
  let relogged = false
2907
+ let renamed = false
2797
2908
  const listed = (ms) => ms.find((x) => x.key === chat.model)
2798
2909
  try {
2799
2910
  m = listed(await models(cred)) ?? listed(await models(cred, true))
@@ -2868,6 +2979,14 @@ const makePlugin = (site) => async ({ client }) => {
2868
2979
  continue
2869
2980
  }
2870
2981
  }
2982
+ // a reply whose only answer was a native tool call the model never
2983
+ // named (plugins#579): nothing of it was given, so it is asked once
2984
+ // more, under a new request_id; a second one is the gateway's 502 to
2985
+ // retry or fail over
2986
+ if (f?.nameless && !renamed) {
2987
+ renamed = true
2988
+ continue
2989
+ }
2871
2990
  // an answered call moves its task on, as Qoder's client moves it
2872
2991
  if (!f) task.answered = true
2873
2992
  // with another account, provider or group member after this one
@@ -2904,19 +3023,35 @@ const makePlugin = (site) => async ({ client }) => {
2904
3023
  refreshLead: RENEW_LEAD,
2905
3024
  async refresh(auth) {
2906
3025
  if (auth?.type !== "oauth" || !auth.access || !auth.uid || !String(auth.refresh ?? "").trim()) return undefined
2907
- return locked(async () => {
3026
+ const out = await locked(async () => {
2908
3027
  // a request renewed it meanwhile (or magpie hasn't saved this
2909
3028
  // hook's last answer): what that gave, not a second refresh
2910
3029
  const a = latest(auth)
2911
- if (a.access !== auth.access && a.expires - Date.now() > RENEW_LEAD) return changed(auth, a)
3030
+ if (a.access !== auth.access && a.expires - Date.now() > RENEW_LEAD) return { next: a, renewed: false }
2912
3031
  try {
2913
- // magpie saves what this gives
2914
- return changed(auth, { ...a, ...(await renew(a)) })
3032
+ return { next: { ...a, ...(await renew(a)) }, renewed: true }
2915
3033
  } catch (e) {
2916
3034
  if (e?.expired) throw Object.assign(new Error(e.message), { signIn: "expired" })
2917
3035
  throw e
2918
3036
  }
2919
3037
  })
3038
+ const fields = changed(auth, out.next)
3039
+ if (!out.renewed) return fields
3040
+ // The name is read outside the lock: this lock is the plugin's, shared
3041
+ // by every account, and a user-info call may take 20 seconds — a chat
3042
+ // from another account must not wait on it (review #487, C). The
3043
+ // account's own site, too: a public one would send an enterprise token
3044
+ // to the public hosts (1), and the suffix must match the sign-in (2).
3045
+ try {
3046
+ const s = siteOf(site, out.next)
3047
+ const { phoneLabel, cardName } = await refreshedNames(s, out.next.access)
3048
+ const extra = {}
3049
+ if (phoneLabel) extra.phoneLabel = phoneLabel
3050
+ if (cardName) extra.cardName = cardName
3051
+ return Object.keys(extra).length ? { ...fields, ...extra } : fields
3052
+ } catch {
3053
+ return fields
3054
+ }
2920
3055
  },
2921
3056
  async loader(getAuth) {
2922
3057
  const a = await getAuth()
@@ -3125,4 +3260,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
3125
3260
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
3126
3261
 
3127
3262
  // for tests
3128
- 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 }
3263
+ export const _internal = { maskPhone, phoneLabelOf, realEmailOf, 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,12 +1,28 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.49",
3
+ "version": "0.2.51",
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",
7
7
  "exports": "./index.mjs",
8
- "files": ["index.mjs", "README.md", "LICENSE-CLIProxyAPI"],
9
- "keywords": ["opencode", "opencode-plugin", "magpie", "qoder", "qoder-cn", "qwenwork", "千问办公"],
8
+ "files": [
9
+ "index.mjs",
10
+ "README.md",
11
+ "LICENSE-CLIProxyAPI"
12
+ ],
13
+ "keywords": [
14
+ "opencode",
15
+ "opencode-plugin",
16
+ "magpie",
17
+ "qoder",
18
+ "qoder-cn",
19
+ "qwenwork",
20
+ "千问办公"
21
+ ],
10
22
  "license": "MIT",
11
- "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/qoder" }
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/magpie-community/plugins.git",
26
+ "directory": "packages/qoder"
27
+ }
12
28
  }