@magpie-community/opencode-qoder-auth 0.2.61 → 0.2.62

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 +18 -6
  2. package/index.mjs +159 -58
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -189,7 +189,7 @@ itself.
189
189
  |---|---|
190
190
  | A refused sign-in (no code, or code 105) | 401 |
191
191
  | A quota (codes 110, 112–119, 122) | 429 |
192
- | 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 |
192
+ | 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; since 0.2.62 a streamed request is answered 200 at once and kept alive with SSE comments for up to an hour, its outcome in the stream; 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 |
193
193
  | A refusal of the request itself (codes 406, 416, 430, 80411, 80412, 100400–100403) | 400, with Qoder's words |
194
194
  | "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 |
195
195
  | A failure before the answer starts | Qoder's status |
@@ -577,11 +577,23 @@ Since **0.2.28** a queued request waits its turn as Qoder's own client
577
577
  model and the plan's `queueType`, at once and then every
578
578
  `retryAfterSeconds` (held to 0.5–30s, 30s when unsaid), and once
579
579
  `isQueued` is false it waits that state's `retryAfterSeconds` and sends the
580
- same request again (up to 10 times). Qoder's client waits up to an hour;
581
- the plugin waits at most 4 minutes from the request's start, since nothing
582
- reaches the agent meanwhile (magpie keeps a stream alive with comments for
583
- 5 minutes of silence). Three failed status asks in a row, a 404, or a
584
- cancelled request end the wait early. Qoder's client also reports the end
580
+ same request again (up to 10 times). Three failed status asks in a row, a
581
+ 404, or a cancelled request end the wait early.
582
+
583
+ Since **0.2.62** a streamed request (every agent's) waits as long as
584
+ Qoder's client does, up to an hour from the request's start, where it
585
+ waited at most 4 minutes and then was a 503 that Codex retried, a stop and
586
+ a restart for the user (plugins#807). It is answered 200 at once, with an
587
+ SSE comment saying the queue (": Qoder queued the request for smodel
588
+ (this plan's queue: p3, 284 ahead); try again in 30s") and a comment every
589
+ 10 seconds while it waits. magpie counts each comment as the reply going
590
+ on: a Codex client is told `response.in_progress`, the event its 300s idle
591
+ timeout counts, and a Chat client gets the comment. What comes of the wait
592
+ goes on in the same stream: the answer, or a refusal (the queue's own after
593
+ the hour) as the stream's error. Nothing needs setting. A request that isn't
594
+ streamed has nothing to keep its client alive with, so it still waits 4
595
+ minutes at most before the 503. Claude Code takes a ping as life only 30
596
+ times in a row, about 35 minutes, so a longer wait still ends there. Qoder's client also reports the end
585
597
  of its turn to `/api/v2/service/ask/finish`; the plugin doesn't, and
586
598
  Qoder releases that lease on its own TTL. `queue.test.mjs` has the wait.
587
599
 
package/index.mjs CHANGED
@@ -1648,17 +1648,27 @@ const errorResponse = ({ status, message, signIn = status === 401 ? "kept" : und
1648
1648
  // request again in the same request_set_id under a new request_id and
1649
1649
  // chat_record_id, up to 10 times; the refused call's stream is closed. Three failed asks
1650
1650
  // in a row, a 404 (no queue there) or a state with neither field end the
1651
- // wait. Qoder's client waits up to an hour; here the whole of it is held
1652
- // under QUEUE.budget from the request's start, since nothing reaches the
1653
- // agent meanwhile: magpie keeps a stream's agent alive with comments for 5
1654
- // minutes of a vendor's silence, and then leaves it to the agent's own
1655
- // timeout. Past the budget it is the 503 with Retry-After it was before, so
1656
- // magpie may ask another account. Qoder's client also tells
1651
+ // wait. Qoder's client waits up to an hour, and so does a streamed request
1652
+ // here (QUEUE.held, from the request's start): at the first queue answer
1653
+ // it is given its 200 and an SSE comment at once, and one every
1654
+ // QUEUE.beat while it waits, so the agent is never left with nothing.
1655
+ // magpie hears the comments as the reply going on (its plugin host gives
1656
+ // a body 30 minutes between bytes, its translated replies keep the client
1657
+ // alive while the upstream is heard from) and tells a Codex client
1658
+ // response.in_progress for each, the event its 300s idle timeout counts
1659
+ // (plugins#807: at the old 4-minute cap Codex saw a 503 and a restart).
1660
+ // What comes of the wait goes on in the same stream: the answer, or the
1661
+ // refusal as the stream's error. A request not streamed has nothing to
1662
+ // keep its client alive with, and waits QUEUE.budget at most, then the
1663
+ // 503 with Retry-After it was before, so magpie may ask another account.
1664
+ // Qoder's client also tells
1657
1665
  // /api/v2/service/ask/finish when its turn ends; that is left out, and its
1658
1666
  // own log says Qoder's TTL releases the lease when finish is not heard.
1659
1667
  const QUEUE_STATUS_PATH = "/algo/api/v2/service/ask/queue/status"
1660
1668
  const QUEUE = {
1661
- budget: 4 * 60 * 1000, // the longest a request is held, its first answer's wait included
1669
+ budget: 4 * 60 * 1000, // the longest a request not streamed is held, its first answer's wait included
1670
+ held: 60 * 60 * 1000, // the longest a streamed one is, as Qoder's client waits
1671
+ beat: 10_000, // the longest a held stream's client goes without a comment
1662
1672
  shortest: 500,
1663
1673
  longest: 30_000,
1664
1674
  unsaid: 30_000, // a pause when the queue gives no retryAfterSeconds
@@ -1666,6 +1676,11 @@ const QUEUE = {
1666
1676
  failures: 3, // status asks failing in a row that end the wait
1667
1677
  ask: 30_000, // the longest one status ask may take
1668
1678
  now: () => Date.now(),
1679
+ // every calls fn each ms until the returned stop is called
1680
+ every: (fn, ms) => {
1681
+ const t = setInterval(fn, ms)
1682
+ return () => clearInterval(t)
1683
+ },
1669
1684
  pause: (ms, signal) =>
1670
1685
  new Promise((ok, no) => {
1671
1686
  if (signal?.aborted) return no(signal.reason ?? new DOMException("aborted", "AbortError"))
@@ -1779,6 +1794,73 @@ async function queueWait(api, cred, ask, first, signal, deadline, site) {
1779
1794
  }
1780
1795
  }
1781
1796
 
1797
+ // holdQueued is a streamed request's reply while Qoder's queue holds it
1798
+ // (queueWait): its 200 and a comment saying the queue now, a comment every
1799
+ // QUEUE.beat after, and then what came of the wait (follow): the answer's
1800
+ // stream, or a refusal as the stream's error, as answer ends a stream that
1801
+ // fails. signal ends the wait when the client goes, by its request's
1802
+ // signal or by cancelling this stream.
1803
+ function holdQueued(f, clientSignal) {
1804
+ const enc = new TextEncoder()
1805
+ const gone = new AbortController()
1806
+ let ctl, stop, reader
1807
+ let closed = false
1808
+ const say = (text) => {
1809
+ if (closed) return
1810
+ try {
1811
+ ctl.enqueue(enc.encode(text))
1812
+ } catch {}
1813
+ }
1814
+ const end = () => {
1815
+ stop?.()
1816
+ if (closed) return
1817
+ closed = true
1818
+ try {
1819
+ ctl.close()
1820
+ } catch {}
1821
+ }
1822
+ const body = new ReadableStream({
1823
+ start(c) {
1824
+ ctl = c
1825
+ say(`: ${String(f.message).replace(/[\r\n]+/g, " ")}\n\n`)
1826
+ stop = QUEUE.every(() => say(": queued\n\n"), QUEUE.beat)
1827
+ },
1828
+ cancel(reason) {
1829
+ stop?.()
1830
+ closed = true
1831
+ gone.abort(reason ?? new DOMException("the client went away", "AbortError"))
1832
+ reader?.cancel(reason).catch(() => {})
1833
+ },
1834
+ })
1835
+ const response = new Response(body, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
1836
+ const follow = async (done) => {
1837
+ const res = await done
1838
+ stop?.()
1839
+ if (closed) return res.body?.cancel().catch(() => {})
1840
+ if (!res.ok) {
1841
+ let message = res.statusText || `HTTP ${res.status}`
1842
+ try {
1843
+ message = (await res.json())?.error?.message ?? message
1844
+ } catch {}
1845
+ say(`data: ${JSON.stringify({ error: { message, code: res.status } })}\n\n`)
1846
+ return end()
1847
+ }
1848
+ reader = res.body.getReader()
1849
+ try {
1850
+ for (;;) {
1851
+ const { done, value } = await reader.read()
1852
+ if (done || closed) break
1853
+ ctl.enqueue(value)
1854
+ }
1855
+ } catch (e) {
1856
+ say(`data: ${JSON.stringify({ error: { message: e?.message ?? String(e), code: 502 } })}\n\n`)
1857
+ }
1858
+ end()
1859
+ }
1860
+ const signal = clientSignal ? AbortSignal.any([clientSignal, gone.signal]) : gone.signal
1861
+ return { response, signal, follow: (done) => void follow(done) }
1862
+ }
1863
+
1782
1864
  // ---- the reply ----------------------------------------------------------------
1783
1865
 
1784
1866
  const CALL_OPEN = "\x3ctool_call\x3e"
@@ -3417,65 +3499,84 @@ const makePlugin = (site) => async ({ client }) => {
3417
3499
  // resend). On a real qoder.com account (plugins#427) the free models
3418
3500
  // are queued in p3 for RESOURCE_LIMIT, about 30s at a time, and a
3419
3501
  // resend can be queued again before it is answered.
3420
- const deadline = QUEUE.now() + QUEUE.budget
3502
+ const began = QUEUE.now()
3503
+ let deadline = began + QUEUE.budget
3421
3504
  const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key }
3422
- for (let sent = 0, waited = 0; ; sent++) {
3423
- if (sent) {
3424
- body.request_id = body.chat_record_id = randomUUID()
3425
- ask.requestId = body.request_id
3426
- }
3427
- const wire = encodeBody(JSON.stringify(body))
3428
- const headers = chatHeaders(CHAT_URL, cred, wire, siteOf(site, cred), m, chatIdentity(cred.uid))
3429
- // a refused call's stream is closed: Qoder keeps a 10605 stream open
3430
- // after its one event, and a connection held open while the call is
3431
- // waited out and sent again is one more the account holds
3432
- const call = new AbortController()
3433
- const signal = init.signal ? AbortSignal.any([init.signal, call.signal]) : call.signal
3434
- let res, open
3435
- try {
3436
- res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal })
3437
- if (res.ok) open = await opened(res, chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : [])
3438
- } catch (e) {
3439
- return errorResponse({ status: 502, message: e.message })
3440
- }
3441
- const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
3442
- if (f) call.abort()
3443
- // a refused job token: renewed once (or the one renewed meanwhile)
3444
- // and the request sent again, before the refusal is said
3445
- if (f?.lapsed && getAuth && !relogged) {
3446
- relogged = true
3447
- let next
3505
+ // a streamed request queued: its 200 goes to the client at once (held),
3506
+ // and what comes of the wait follows in that stream
3507
+ let held, onHeld
3508
+ let signal = init.signal
3509
+ const heard = new Promise((ok) => (onHeld = ok))
3510
+ const run = async () => {
3511
+ for (let sent = 0, waited = 0; ; sent++) {
3512
+ if (sent) {
3513
+ body.request_id = body.chat_record_id = randomUUID()
3514
+ ask.requestId = body.request_id
3515
+ }
3516
+ const wire = encodeBody(JSON.stringify(body))
3517
+ const headers = chatHeaders(CHAT_URL, cred, wire, siteOf(site, cred), m, chatIdentity(cred.uid))
3518
+ // a refused call's stream is closed: Qoder keeps a 10605 stream open
3519
+ // after its one event, and a connection held open while the call is
3520
+ // waited out and sent again is one more the account holds
3521
+ const call = new AbortController()
3522
+ const callSignal = signal ? AbortSignal.any([signal, call.signal]) : call.signal
3523
+ let res, open
3448
3524
  try {
3449
- next = await relogin(getAuth, cred.access)
3525
+ res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: callSignal })
3526
+ if (res.ok) open = await opened(res, chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : [])
3450
3527
  } catch (e) {
3451
- return signedInError(e)
3528
+ return errorResponse({ status: 502, message: e.message })
3452
3529
  }
3453
- if (next) {
3454
- cred = asked.cred = next
3530
+ const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
3531
+ if (f) call.abort()
3532
+ // a refused job token: renewed once (or the one renewed meanwhile)
3533
+ // and the request sent again, before the refusal is said
3534
+ if (f?.lapsed && getAuth && !relogged) {
3535
+ relogged = true
3536
+ let next
3537
+ try {
3538
+ next = await relogin(getAuth, cred.access)
3539
+ } catch (e) {
3540
+ return signedInError(e)
3541
+ }
3542
+ if (next) {
3543
+ cred = asked.cred = next
3544
+ continue
3545
+ }
3546
+ }
3547
+ // a reply whose only answer was a native tool call the model never
3548
+ // named (plugins#579): nothing of it was given, so it is asked once
3549
+ // more, under a new request_id; a second one is the gateway's 502 to
3550
+ // retry or fail over
3551
+ if (f?.nameless && !renamed) {
3552
+ renamed = true
3455
3553
  continue
3456
3554
  }
3555
+ // an answered call moves its task on, as Qoder's client moves it
3556
+ if (!f) task.answered = true
3557
+ // with another account, provider or group member after this one
3558
+ // (magpie's X-Magpie-Fallback), a queued request isn't waited out:
3559
+ // its 503 goes back at once, saying the queue, and the next is asked
3560
+ if (!f?.queue || waited >= QUEUE.recoveries || fallback) return f ? errorResponse(f) : answer(open, chat, servedName)
3561
+ if (chat.stream && !held) {
3562
+ held = holdQueued(f, init.signal)
3563
+ signal = held.signal
3564
+ deadline = began + QUEUE.held
3565
+ onHeld(held.response)
3566
+ }
3567
+ try {
3568
+ if (!(await queueWait(api, cred, ask, f.queue, signal, deadline, siteOf(site, cred)))) return errorResponse(f)
3569
+ } catch (e) {
3570
+ return errorResponse({ status: 502, message: e?.message ?? String(e) })
3571
+ }
3572
+ waited++
3457
3573
  }
3458
- // a reply whose only answer was a native tool call the model never
3459
- // named (plugins#579): nothing of it was given, so it is asked once
3460
- // more, under a new request_id; a second one is the gateway's 502 to
3461
- // retry or fail over
3462
- if (f?.nameless && !renamed) {
3463
- renamed = true
3464
- continue
3465
- }
3466
- // an answered call moves its task on, as Qoder's client moves it
3467
- if (!f) task.answered = true
3468
- // with another account, provider or group member after this one
3469
- // (magpie's X-Magpie-Fallback), a queued request isn't waited out:
3470
- // its 503 goes back at once, saying the queue, and the next is asked
3471
- if (!f?.queue || waited >= QUEUE.recoveries || fallback) return f ? errorResponse(f) : answer(open, chat, servedName)
3472
- try {
3473
- if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline, siteOf(site, cred)))) return errorResponse(f)
3474
- } catch (e) {
3475
- return errorResponse({ status: 502, message: e?.message ?? String(e) })
3476
- }
3477
- waited++
3478
3574
  }
3575
+ const done = run().catch((e) => errorResponse({ status: 502, message: e?.message ?? String(e) }))
3576
+ const res = await Promise.race([done, heard])
3577
+ if (res !== held?.response) return res
3578
+ held.follow(done)
3579
+ return res
3479
3580
  }
3480
3581
 
3481
3582
  // askLingma is ask for a Lingma 1.0 account: the IDE's models, signed as
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.61",
3
+ "version": "0.2.62",
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",