@magpie-community/opencode-qoder-auth 0.2.73 → 0.2.74

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 +13 -4
  2. package/index.mjs +99 -14
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -592,7 +592,9 @@ Since **0.2.28** a queued request waits its turn as Qoder's own client
592
592
  model and the plan's `queueType`, at once and then every
593
593
  `retryAfterSeconds` (held to 0.5–30s, 30s when unsaid), and once
594
594
  `isQueued` is false it waits that state's `retryAfterSeconds` and sends the
595
- same request again (up to 10 times). Three failed status asks in a row, a
595
+ same request again (up to 10 times). Since **0.2.74** `isQueued` false with
596
+ `serviceAvailable` false is waited on too, as Qoder's client reads it
597
+ (qoderclicn 1.1.98), rather than sent into the queue again. Three failed status asks in a row, a
596
598
  404, or a cancelled request end the wait early.
597
599
 
598
600
  Since **0.2.62** a streamed request (every agent's) waits as long as
@@ -614,9 +616,16 @@ keepalives); magpie can then rest the account or ask the next. A queue with
614
616
  others ahead is still waited out. Nothing needs setting. A request that isn't
615
617
  streamed has nothing to keep its client alive with, so it still waits 4
616
618
  minutes at most before the 503. Claude Code takes a ping as life only 30
617
- times in a row, about 35 minutes, so a longer wait still ends there. Qoder's client also reports the end
618
- of its turn to `/api/v2/service/ask/finish`; the plugin doesn't, and
619
- Qoder releases that lease on its own TTL. `queue.test.mjs` has the wait.
619
+ times in a row, about 35 minutes, so a longer wait still ends there.
620
+
621
+ A queued request holds a lease in Qoder's queue (its `request_set_id` and
622
+ model) until Qoder hears `/api/v2/service/ask/finish`. Before **0.2.74** the
623
+ plugin never told it, so each lease stayed until Qoder's own TTL let it go
624
+ (plugins#1560). Now it tells finish as Qoder's client does: at once when a
625
+ request gives up waiting (the 503 above, or a cancelled request), and
626
+ otherwise when the task ends (the session's next prompt, or the task let go
627
+ after 2 hours idle). A finish that fails changes nothing for the request.
628
+ `queue.test.mjs` has the wait and the finish.
620
629
 
621
630
  Since **0.2.40** the wait is only for the last candidate: when magpie says
622
631
  another account, provider or routing group member follows this request
package/index.mjs CHANGED
@@ -1427,7 +1427,8 @@ const TASK_IDLE = 2 * 60 * 60 * 1000
1427
1427
  const taskName = (prompt) => (prompt.length > 10 ? prompt.slice(0, 10) : prompt)
1428
1428
 
1429
1429
  // taskOf is the task chat's call belongs to, in session sid: made on its
1430
- // first call, the same one on every call after.
1430
+ // first call, the same one on every call after. A task let go, or one of
1431
+ // the session's before a new prompt, ends (endTask).
1431
1432
  function taskOf(sid, chat, now = Date.now()) {
1432
1433
  const msgs = chat.messages ?? []
1433
1434
  const at = msgs.findLastIndex((x) => x?.role === "user")
@@ -1435,17 +1436,36 @@ function taskOf(sid, chat, now = Date.now()) {
1435
1436
  for (const [k, t] of TASKS) {
1436
1437
  if (now - t.used <= TASK_IDLE) break
1437
1438
  TASKS.delete(k)
1439
+ endTask(t)
1438
1440
  }
1439
1441
  let t = TASKS.get(key)
1440
- if (t && now - t.used > TASK_IDLE) t = undefined
1442
+ if (t && now - t.used > TASK_IDLE) {
1443
+ endTask(t)
1444
+ t = undefined
1445
+ }
1441
1446
  TASKS.delete(key)
1442
- t ??= { id: randomUUID(), begin: now, answered: false, name: taskName(at < 0 ? "" : textOf(msgs[at].content)) }
1447
+ if (!t) {
1448
+ for (const o of TASKS.values()) if (o.sid === sid) endTask(o)
1449
+ t = { id: randomUUID(), sid, begin: now, answered: false, name: taskName(at < 0 ? "" : textOf(msgs[at].content)) }
1450
+ }
1443
1451
  t.used = now
1444
1452
  TASKS.set(key, t)
1445
- while (TASKS.size > TASK_MAX) TASKS.delete(TASKS.keys().next().value)
1453
+ while (TASKS.size > TASK_MAX) {
1454
+ const k = TASKS.keys().next().value
1455
+ endTask(TASKS.get(k))
1456
+ TASKS.delete(k)
1457
+ }
1446
1458
  return t
1447
1459
  }
1448
1460
 
1461
+ // endTask ends task t: its queue leases are let go (release) now, or when
1462
+ // its last request in flight is done.
1463
+ function endTask(t) {
1464
+ if (!t) return
1465
+ if (t.inflight) t.ended = true
1466
+ else void release(t)
1467
+ }
1468
+
1449
1469
  // Qoder CN's kmodel (Kimi K3.1 Pro) fails a chat whose tools hold a oneOf
1450
1470
  // with no type, even of objects only, and takes it with "type": "object"
1451
1471
  // beside it (congee949, #378: dsh's REA tools, a 502 here). typedUnions is
@@ -1741,10 +1761,18 @@ const errorResponse = ({ status, message, signIn = status === 401 ? "kept" : und
1741
1761
  // refusal as the stream's error. A request not streamed has nothing to
1742
1762
  // keep its client alive with, and waits QUEUE.budget at most, then the
1743
1763
  // 503 with Retry-After it was before, so magpie may ask another account.
1744
- // Qoder's client also tells
1745
- // /api/v2/service/ask/finish when its turn ends; that is left out, and its
1746
- // own log says Qoder's TTL releases the lease when finish is not heard.
1764
+ // A queued request holds a lease in Qoder's queue, under its
1765
+ // request_set_id and model, until Qoder hears /api/v2/service/ask/finish
1766
+ // (queueFinish); unheard, only Qoder's TTL lets it go. Qoder's client
1767
+ // (qoderclicn 1.1.98 and Qoder.app's qoder-worker-runtime, "[ModelQueue]")
1768
+ // registers one on each 10605 and tells finish when its turn ends, when
1769
+ // its session ends, and at once when the request gives up waiting. The
1770
+ // plugin never told it (plugins#1560: a Qoder CN account queued in p2 and
1771
+ // p4 while its plan's credits went unused). Here a lease ends when the
1772
+ // request gives up the wait, and when its task does: the session's next
1773
+ // prompt, or the task let go for TASK_IDLE or TASK_MAX.
1747
1774
  const QUEUE_STATUS_PATH = "/algo/api/v2/service/ask/queue/status"
1775
+ const QUEUE_FINISH_PATH = "/algo/api/v2/service/ask/finish?Encode=1"
1748
1776
  const QUEUE = {
1749
1777
  budget: 4 * 60 * 1000, // the longest a request not streamed is held, its first answer's wait included
1750
1778
  held: 60 * 60 * 1000, // the longest a streamed one is, as Qoder's client waits
@@ -1755,6 +1783,7 @@ const QUEUE = {
1755
1783
  recoveries: 10, // the queue waited out this many times, at most, for one request
1756
1784
  failures: 3, // status asks failing in a row that end the wait
1757
1785
  ask: 30_000, // the longest one status ask may take
1786
+ finish: 3_000, // the longest a finish may take, as Qoder's client gives it
1758
1787
  // the longest a call waits for Qoder's first event (headers included).
1759
1788
  // Qoder CN once held a call 15 minutes with nothing sent and nothing to
1760
1789
  // log (#1204); after this it is a 504 that says so, which magpie can
@@ -1855,6 +1884,49 @@ async function queueStatus(api, cred, { requestSetId, modelKey, queueType, reque
1855
1884
  return st
1856
1885
  }
1857
1886
 
1887
+ // queueReady: the queue lets the request through, as Qoder's client reads
1888
+ // a status (qoderclicn 1.1.98, qoder-worker-runtime: isQueued false and
1889
+ // serviceAvailable not false). isQueued false with the service unavailable
1890
+ // is waited on: sent then, the request is only queued again.
1891
+ const queueReady = (st) => st.isQueued === false && st.serviceAvailable !== false
1892
+
1893
+ // queueFinish tells Qoder's queue a lease is done, as Qoder's client's
1894
+ // finish does: POST /api/v2/service/ask/finish?Encode=1, signed, its body
1895
+ // {payload, encodeVersion: "1"} encoded as a chat's is, the payload the
1896
+ // lease's model_key and request_set_id, the user's id and the
1897
+ // milliseconds since the lease began. Best effort: it waits QUEUE.finish
1898
+ // at most, and a failure leaves the lease to Qoder's TTL, as there.
1899
+ async function queueFinish(lease) {
1900
+ const { api, cred, site, requestSetId, modelKey, began } = lease
1901
+ if (!cred?.uid) return
1902
+ try {
1903
+ const url = api + QUEUE_FINISH_PATH
1904
+ const payload = JSON.stringify({ model_key: modelKey, request_set_id: requestSetId, user_id: cred.uid, time_consumed: Math.max(0, Math.round(QUEUE.now() - began)) })
1905
+ const wire = encodeBody(JSON.stringify({ payload, encodeVersion: "1" }))
1906
+ const res = await fetch(url, { method: "POST", headers: cosyHeaders(url, cred, wire, site), body: wire, signal: AbortSignal.timeout(QUEUE.finish) })
1907
+ await res.arrayBuffer()
1908
+ } catch {}
1909
+ }
1910
+
1911
+ // leaseOf registers the queue's lease for a request of task t, once for
1912
+ // its request_set_id and model, from the first 10605.
1913
+ function leaseOf(t, lease) {
1914
+ t.leases ??= new Map()
1915
+ const key = JSON.stringify([lease.requestSetId, lease.modelKey])
1916
+ if (!t.leases.has(key)) t.leases.set(key, lease)
1917
+ return key
1918
+ }
1919
+
1920
+ // release tells finish for task t's leases (key's alone when given), and
1921
+ // forgets them.
1922
+ function release(t, key) {
1923
+ if (!t?.leases?.size) return Promise.resolve()
1924
+ const done = key === undefined ? [...t.leases.values()] : t.leases.has(key) ? [t.leases.get(key)] : []
1925
+ if (key === undefined) t.leases.clear()
1926
+ else t.leases.delete(key)
1927
+ return Promise.all(done.map(queueFinish))
1928
+ }
1929
+
1858
1930
  // stuckKey is what a queue's state says of the request's place in it, or
1859
1931
  // "" when others are ahead of it (a queue that moves while they are
1860
1932
  // served is waited out, QUEUE.stuck never ends it).
@@ -1896,11 +1968,11 @@ async function queueWait(api, cred, ask, first, signal, deadline, site) {
1896
1968
  if (!key || key !== same) {
1897
1969
  same = key
1898
1970
  since = QUEUE.now()
1899
- } else if (QUEUE.now() - since >= QUEUE.stuck && st.isQueued !== false) {
1971
+ } else if (QUEUE.now() - since >= QUEUE.stuck && !queueReady(st)) {
1900
1972
  ask.stuck = true
1901
1973
  return false
1902
1974
  }
1903
- if (st.isQueued === false) {
1975
+ if (queueReady(st)) {
1904
1976
  if (st.retryAfterSeconds > 0) await QUEUE.pause(Math.min(queuePause(st.retryAfterSeconds), Math.max(0, deadline - QUEUE.now())), signal)
1905
1977
  return QUEUE.now() < deadline
1906
1978
  }
@@ -3905,7 +3977,15 @@ const makePlugin = (site) => async ({ client }) => {
3905
3977
  // with another account, provider or group member after this one
3906
3978
  // (magpie's X-Magpie-Fallback), a queued request isn't waited out:
3907
3979
  // its 503 goes back at once, saying the queue, and the next is asked
3908
- if (!f?.queue || waited >= QUEUE.recoveries || fallback) return f ? errorResponse(f) : answer(open, chat, servedName)
3980
+ if (!f?.queue) return f ? errorResponse(f) : answer(open, chat, servedName)
3981
+ // queued: the lease Qoder's queue now holds for it, let go at once
3982
+ // when the request gives up waiting, else when its task ends
3983
+ const lease = leaseOf(task, { api, cred, site: siteOf(site, cred), requestSetId: ask.requestSetId, modelKey: m.key, began: QUEUE.now() })
3984
+ const giveUp = (r) => {
3985
+ void release(task, lease)
3986
+ return r
3987
+ }
3988
+ if (waited >= QUEUE.recoveries || fallback) return giveUp(errorResponse(f))
3909
3989
  if (chat.stream && !held) {
3910
3990
  held = holdQueued(f, init.signal)
3911
3991
  signal = held.signal
@@ -3914,14 +3994,19 @@ const makePlugin = (site) => async ({ client }) => {
3914
3994
  }
3915
3995
  try {
3916
3996
  if (!(await queueWait(api, cred, ask, f.queue, signal, deadline, siteOf(site, cred))))
3917
- return errorResponse(ask.stuck ? { ...f, message: `${f.message} (the queue hasn't moved in ${Math.round(QUEUE.stuck / 60_000)} minutes with nothing ahead)` } : f)
3997
+ return giveUp(errorResponse(ask.stuck ? { ...f, message: `${f.message} (the queue hasn't moved in ${Math.round(QUEUE.stuck / 60_000)} minutes with nothing ahead)` } : f))
3918
3998
  } catch (e) {
3919
- return errorResponse({ status: 502, message: e?.message ?? String(e) })
3999
+ return giveUp(errorResponse({ status: 502, message: e?.message ?? String(e) }))
3920
4000
  }
3921
4001
  waited++
3922
4002
  }
3923
4003
  }
3924
- const done = run().catch((e) => errorResponse({ status: 502, message: e?.message ?? String(e) }))
4004
+ task.inflight = (task.inflight ?? 0) + 1
4005
+ const done = run()
4006
+ .catch((e) => errorResponse({ status: 502, message: e?.message ?? String(e) }))
4007
+ .finally(() => {
4008
+ if (--task.inflight === 0 && task.ended) void release(task)
4009
+ })
3925
4010
  const res = await Promise.race([done, heard])
3926
4011
  if (res !== held?.response) return res
3927
4012
  held.follow(done)
@@ -4300,4 +4385,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
4300
4385
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
4301
4386
 
4302
4387
  // for tests
4303
- export const _internal = { spentOf, OUTPUT_CAPS, LEARNED_CAPS, outputCap, fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, asAgentSDK, harnessComma, qoderMessages, kimiModel, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
4388
+ export const _internal = { spentOf, OUTPUT_CAPS, LEARNED_CAPS, outputCap, fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, asAgentSDK, harnessComma, qoderMessages, kimiModel, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState, queueReady }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.73",
3
+ "version": "0.2.74",
4
4
  "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",