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

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 +21 -0
  2. package/index.mjs +65 -20
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -166,6 +166,21 @@ itself.
166
166
 
167
167
  ## Models
168
168
 
169
+ Chat responses report the display name from the same model-list entry
170
+ used to build the request, in both JSON completions and every SSE chunk
171
+ (including usage). A blank name or a name equal to the slot key falls
172
+ back to the requested model ID. This shared behavior applies to Qoder,
173
+ Qoder CN, QwenWork and QwenWork Enterprise, including tier labels.
174
+
175
+ Reporting the name does not fetch the model list again. The existing
176
+ cache and model-list refresh behavior remain in place: a model missing
177
+ from the cache still forces a refresh, and normal list refreshes update
178
+ the configuration and name together. Model-list keys, API IDs,
179
+ `X-Model-Key` and `model_config` are unchanged; slots with the same display
180
+ name remain independently selectable. The name describes the catalog
181
+ entry used for the request, not an attestation of the backend that
182
+ executed it.
183
+
169
184
  The `provider.models` hook reads the account's own list, as Qoder's client
170
185
  asks for it (`/algo/api/v2/model/list`). It keeps the enabled models of the
171
186
  listing's `app` scene, the list Qoder's app shows and the one a request
@@ -271,6 +286,12 @@ on this same protocol, with the desktop client's client id, an RSA key the
271
286
  Qoder one's equal, its own `qwork` scene, and the device token as the chat
272
287
  token. The public cloud's sign-in is the desktop app's device flow, with
273
288
  `redirect_uri=qwenwork-cn://`; usage reads the sign-in's account-context.
289
+ A personal account's quota there has `total` and `used` null, only
290
+ `remaining`, so the card shows what is left as its balance, with each pool
291
+ (daily, monthly, long-term) from `/api/v1/adapter/user/wallets`, as
292
+ QwenWork's own client reads them; no share used is made up. An account
293
+ with a total keeps its used / total window, and a biz account (or the
294
+ enterprise flagship) never asks for the wallets.
274
295
  There is no PAT and no daily check-in on it: the `pat: false` and
275
296
  `checkin: false` site fields turn both off, so Qoder's device identity is
276
297
  never sent there.
package/index.mjs CHANGED
@@ -1685,7 +1685,7 @@ async function opened(res, tools) {
1685
1685
  return { it, first: await it.next() }
1686
1686
  }
1687
1687
 
1688
- async function answer({ it, first }, chat) {
1688
+ async function answer({ it, first }, chat, servedName = chat.model) {
1689
1689
  const id = "chatcmpl-" + hexID()
1690
1690
  const created = Math.floor(Date.now() / 1000)
1691
1691
  if (first.value?.error) return errorResponse(first.value.error)
@@ -1708,12 +1708,12 @@ async function answer({ it, first }, chat) {
1708
1708
  }
1709
1709
  if (reasoning) msg.reasoning_content = reasoning
1710
1710
  if (calls.length) msg.tool_calls = calls
1711
- return Response.json({ id, object: "chat.completion", created, model: chat.model, choices: [{ index: 0, message: msg, finish_reason: stop }], ...(usage ? { usage } : {}) })
1711
+ return Response.json({ id, object: "chat.completion", created, model: servedName, choices: [{ index: 0, message: msg, finish_reason: stop }], ...(usage ? { usage } : {}) })
1712
1712
  }
1713
1713
 
1714
1714
  const enc = new TextEncoder()
1715
1715
  const chunk = (delta, finish_reason = null, extra = {}) =>
1716
- enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model: chat.model, choices: [{ index: 0, delta, finish_reason }], ...extra })}\n\n`)
1716
+ enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model: servedName, choices: [{ index: 0, delta, finish_reason }], ...extra })}\n\n`)
1717
1717
  let pending = first
1718
1718
  let began = false
1719
1719
  const stream = new ReadableStream({
@@ -1787,7 +1787,7 @@ class UsageStatus extends Error {
1787
1787
 
1788
1788
  // fetchUsage is the usage envelope, {displayMode, qoderUsage}; a site with
1789
1789
  // its own usage path (QwenWork's account-context) is read by
1790
- // fetchSiteUsage below instead.
1790
+ // the usage hook's site.usagePath branch instead (parseAccountContext).
1791
1791
  async function fetchUsage(site, deviceToken) {
1792
1792
  if (!String(deviceToken ?? "").trim()) throw new Error("qoder usage: missing device token")
1793
1793
  let res
@@ -2083,28 +2083,59 @@ XcW+ML9FoCI6AOvOzwIDAQAB
2083
2083
  -----END PUBLIC KEY-----`
2084
2084
  // parseAccountContext reads the account-context QwenWork's sign-in already
2085
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.
2086
+ // remaining, exceeded} in the plan's credit unit, and the wallets
2087
+ // (/api/v1/adapter/user/wallets) where the public cloud has them: each
2088
+ // pool's total_balance (daily_credits, monthly_credits, longterm_credits).
2089
+ // That is what QwenWork's own client reads (QwenWorkCN.app 1.2.1,
2090
+ // out/main/main.js: fetchQuotaUsage, fetchUserWallets,
2091
+ // mergeWalletsIntoCreditBreakdown). A personal account's quota has total
2092
+ // and used null, so only what is left is known: that is the balance, with
2093
+ // each pool, and no share used is made up. An account with a total keeps
2094
+ // its window of used / total.
2087
2095
  const num = (v) => {
2088
2096
  const n = Number(v)
2089
2097
  if (!Number.isFinite(n)) return "0"
2090
2098
  return String(Math.round(n * 100) / 100)
2091
2099
  }
2092
- const parseAccountContext = (ctx) => {
2093
- const data = ctx?.data ?? {}
2094
- const q = data.quota
2100
+ // the client's unwrapAdapterResponse: the envelope's data object, else the
2101
+ // envelope itself
2102
+ const unwrap = (v) => (v?.data && typeof v.data === "object" && !Array.isArray(v.data) ? v.data : (v && typeof v === "object" ? v : {}))
2103
+ const finite = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined)
2104
+ const POOLS = [["daily_credits", "daily"], ["monthly_credits", "monthly"], ["longterm_credits", "long-term"]]
2105
+ const walletPools = (w) => {
2106
+ const d = unwrap(w)
2107
+ const out = []
2108
+ for (const [key, name] of POOLS) {
2109
+ const p = d[key]
2110
+ const b = p && typeof p === "object" ? finite(p.total_balance ?? p.totalBalance) : undefined
2111
+ if (b !== undefined && b > 0) out.push(`${name} ${num(b)}`)
2112
+ }
2113
+ return out
2114
+ }
2115
+ const parseAccountContext = (ctx, wallets) => {
2116
+ const data = unwrap(ctx)
2117
+ const q = data.quota && typeof data.quota === "object" && !Array.isArray(data.quota) ? data.quota : null
2095
2118
  const out = {}
2096
2119
  if (data.plan?.name) out.plan = String(data.plan.name)
2097
2120
  const refresh = data.plan?.next_refresh_date ?? data.plan?.next_due_date
2098
2121
  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) {
2122
+ if (q) {
2123
+ const total = finite(q.total)
2124
+ const remaining = finite(q.remaining)
2125
+ const used = finite(q.used) ?? (total !== undefined && remaining !== undefined ? total - remaining : undefined)
2126
+ if (total !== undefined && total > 0 && used !== undefined && used >= 0) {
2104
2127
  out.windows = [{ name: "Credits", used: Math.min(100, (100 * used) / total), display: `${num(used)} / ${num(total)} credits` }]
2105
2128
  }
2129
+ if (remaining !== undefined) {
2130
+ const pools = wallets ? walletPools(wallets) : []
2131
+ out.balance = `${num(remaining)} credits${pools.length ? ` (${pools.join(" · ")})` : ""}`
2132
+ // nothing left stops the account: say so as a spent window, since
2133
+ // there is no total to show a share of
2134
+ const exceeded = q.exceeded === true || q.is_quota_exceeded === true || q.isQuotaExceeded === true || remaining <= 0
2135
+ if (!out.windows && exceeded) out.windows = [{ name: "Credits", used: 100, display: "no credits left" }]
2136
+ }
2106
2137
  }
2107
- if (!out.windows) out.error = "QwenWork: the account reports no credits"
2138
+ if (!out.windows && out.balance === undefined) out.error = "QwenWork: the account reports no credits"
2108
2139
  return out
2109
2140
  }
2110
2141
 
@@ -2162,6 +2193,9 @@ const SITES = {
2162
2193
  ...QWENWORK_COMMON,
2163
2194
  id: "qwenwork",
2164
2195
  name: "QwenWork",
2196
+ // the public cloud's personal accounts have wallets; the client asks
2197
+ // for them beside the account-context, and not for an enterprise one
2198
+ walletsPath: "/api/v1/adapter/user/wallets",
2165
2199
  web: "https://gateway.qwenwork.cn",
2166
2200
  openapi: "https://gateway.qwenwork.cn",
2167
2201
  api: "https://gateway.qwenwork.cn",
@@ -2338,9 +2372,9 @@ const makePlugin = (site) => async ({ client }) => {
2338
2372
  // like any other call and answered with its own envelope) is read
2339
2373
  // there; a 401 rotates the device token once, as the qoder path does
2340
2374
  if (site.usagePath) {
2341
- const read = async (token) => {
2375
+ const read = async (token, path = site.usagePath) => {
2342
2376
  const s = siteOf(site, cred)
2343
- const res = await fetch(`${s.openapi}${site.usagePath}`, {
2377
+ const res = await fetch(`${s.openapi}${path}`, {
2344
2378
  headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
2345
2379
  signal: AbortSignal.timeout(20_000),
2346
2380
  })
@@ -2348,14 +2382,23 @@ const makePlugin = (site) => async ({ client }) => {
2348
2382
  return res.json()
2349
2383
  }
2350
2384
  let env
2385
+ let token = cred.deviceToken ?? cred.access
2351
2386
  try {
2352
- env = await read(cred.deviceToken ?? cred.access)
2387
+ env = await read(token)
2353
2388
  } catch (e) {
2354
2389
  if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
2355
2390
  if (!cred.deviceToken) throw e
2356
- env = await read(await deviceToken(getAuth, cred.deviceToken))
2391
+ token = await deviceToken(getAuth, cred.deviceToken)
2392
+ env = await read(token)
2393
+ }
2394
+ // the pools behind the balance, as the client asks for a personal
2395
+ // account's; a failed read leaves the balance without them
2396
+ let wallets
2397
+ const ctxUser = (env?.data ?? env)?.user
2398
+ if (site.walletsPath && ctxUser?.is_biz !== true && ctxUser?.isBiz !== true) {
2399
+ try { wallets = await read(token, site.walletsPath) } catch {}
2357
2400
  }
2358
- return { ...(site.parseUsage ? site.parseUsage(env) : { windows: [] }), signIn }
2401
+ return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn }
2359
2402
  }
2360
2403
  // A PAT account has no device token: the usage endpoint takes the job
2361
2404
  // token the exchange gave — a live PAT account answered 200 with a
@@ -2512,6 +2555,8 @@ const makePlugin = (site) => async ({ client }) => {
2512
2555
  return errorResponse({ status: 502, message: e?.message ?? String(e) })
2513
2556
  }
2514
2557
  if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` })
2558
+ const name = m.name?.trim()
2559
+ const servedName = name && name !== m.key ? name : chat.model
2515
2560
  const api = siteOf(site, cred).api
2516
2561
  const CHAT_URL = api + CHAT_PATH
2517
2562
  const task = taskOf(sessionOf(chat, named), chat)
@@ -2539,7 +2584,7 @@ const makePlugin = (site) => async ({ client }) => {
2539
2584
  const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
2540
2585
  // an answered call moves its task on, as Qoder's client moves it
2541
2586
  if (!f) task.answered = true
2542
- if (!f?.queue || waited >= QUEUE.recoveries) return f && !res.ok ? errorResponse(f) : answer(open, chat)
2587
+ if (!f?.queue || waited >= QUEUE.recoveries) return f && !res.ok ? errorResponse(f) : answer(open, chat, servedName)
2543
2588
  try {
2544
2589
  if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline, siteOf(site, cred)))) return errorResponse(f)
2545
2590
  } catch (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.36",
3
+ "version": "0.2.38",
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",