@magpie-community/opencode-qoder-auth 0.2.60 → 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 +170 -60
  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
@@ -1478,6 +1478,15 @@ function modelConfig(m, thinking) {
1478
1478
  }
1479
1479
  }
1480
1480
 
1481
+ // The business record also names the model: Qoder's CLI (qodercli 1.1.82,
1482
+ // qoder-worker-runtime v3 → snn + model_key) puts the chosen model's key
1483
+ // there when a prompt starts, and the server attributes the call's billing
1484
+ // from it. Without it Qoder and Qoder CN booked the call as Auto whatever
1485
+ // model_config named (plugins#692, chansee97; the same shape as #638, where
1486
+ // the model_config fix of 0.2.54 did not change the billing). Qoder.app
1487
+ // 0.4.3 and QwenWork 1.0.46 build their record without it, so a site that
1488
+ // ships such a client says businessModelKey: false.
1489
+ //
1481
1490
  // qoderBody is the plaintext agent_chat_generation takes for a chat
1482
1491
  // completion request, for model m, in the session the agent named (named,
1483
1492
  // "" when none) and the task it is a call of (taskOf's, a new one when
@@ -1505,7 +1514,7 @@ function qoderBody(chat, m, named = "", task, site) {
1505
1514
  chat_record_id: request,
1506
1515
  session_id: session,
1507
1516
  parameters: params,
1508
- business: { product: site?.businessProduct ?? "app", version: site?.cosyVersion ?? COSY_VERSION, type: "agent", id: task.id, name: task.name ?? "", begin_at: task.begin, stage: task.answered ? "processing" : "start" },
1517
+ business: { product: site?.businessProduct ?? "app", version: site?.cosyVersion ?? COSY_VERSION, type: "agent", id: task.id, name: task.name ?? "", begin_at: task.begin, stage: task.answered ? "processing" : "start", ...(site?.businessModelKey === false ? {} : { model_key: m.key }) },
1509
1518
  agent_id: "agent_common",
1510
1519
  task_id: "common",
1511
1520
  session_type: site?.sessionType ?? "app",
@@ -1639,17 +1648,27 @@ const errorResponse = ({ status, message, signIn = status === 401 ? "kept" : und
1639
1648
  // request again in the same request_set_id under a new request_id and
1640
1649
  // chat_record_id, up to 10 times; the refused call's stream is closed. Three failed asks
1641
1650
  // in a row, a 404 (no queue there) or a state with neither field end the
1642
- // wait. Qoder's client waits up to an hour; here the whole of it is held
1643
- // under QUEUE.budget from the request's start, since nothing reaches the
1644
- // agent meanwhile: magpie keeps a stream's agent alive with comments for 5
1645
- // minutes of a vendor's silence, and then leaves it to the agent's own
1646
- // timeout. Past the budget it is the 503 with Retry-After it was before, so
1647
- // 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
1648
1665
  // /api/v2/service/ask/finish when its turn ends; that is left out, and its
1649
1666
  // own log says Qoder's TTL releases the lease when finish is not heard.
1650
1667
  const QUEUE_STATUS_PATH = "/algo/api/v2/service/ask/queue/status"
1651
1668
  const QUEUE = {
1652
- 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
1653
1672
  shortest: 500,
1654
1673
  longest: 30_000,
1655
1674
  unsaid: 30_000, // a pause when the queue gives no retryAfterSeconds
@@ -1657,6 +1676,11 @@ const QUEUE = {
1657
1676
  failures: 3, // status asks failing in a row that end the wait
1658
1677
  ask: 30_000, // the longest one status ask may take
1659
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
+ },
1660
1684
  pause: (ms, signal) =>
1661
1685
  new Promise((ok, no) => {
1662
1686
  if (signal?.aborted) return no(signal.reason ?? new DOMException("aborted", "AbortError"))
@@ -1770,6 +1794,73 @@ async function queueWait(api, cred, ask, first, signal, deadline, site) {
1770
1794
  }
1771
1795
  }
1772
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
+
1773
1864
  // ---- the reply ----------------------------------------------------------------
1774
1865
 
1775
1866
  const CALL_OPEN = "\x3ctool_call\x3e"
@@ -2872,7 +2963,7 @@ const QWENWORK_COMMON = {
2872
2963
  deviceRefreshTarget: "c",
2873
2964
  clientHeaders: qwenworkClientHeaders,
2874
2965
  modelScene: "qwork", listAllModels: true,
2875
- clientType: "6", businessProduct: "qoder_work", sessionType: "qoder_work",
2966
+ clientType: "6", businessProduct: "qoder_work", sessionType: "qoder_work", businessModelKey: false,
2876
2967
  userInfoPath: "/api/v1/adapter/user/account-context?include=user,plan,quota,page,data_sharing",
2877
2968
  normalizeUser: v => (v?.data ?? v)?.user ?? (v?.data ?? v),
2878
2969
  pat: false, // no /api/v1/jobToken/exchange on gateway.qwenwork.cn
@@ -3408,65 +3499,84 @@ const makePlugin = (site) => async ({ client }) => {
3408
3499
  // resend). On a real qoder.com account (plugins#427) the free models
3409
3500
  // are queued in p3 for RESOURCE_LIMIT, about 30s at a time, and a
3410
3501
  // resend can be queued again before it is answered.
3411
- const deadline = QUEUE.now() + QUEUE.budget
3502
+ const began = QUEUE.now()
3503
+ let deadline = began + QUEUE.budget
3412
3504
  const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key }
3413
- for (let sent = 0, waited = 0; ; sent++) {
3414
- if (sent) {
3415
- body.request_id = body.chat_record_id = randomUUID()
3416
- ask.requestId = body.request_id
3417
- }
3418
- const wire = encodeBody(JSON.stringify(body))
3419
- const headers = chatHeaders(CHAT_URL, cred, wire, siteOf(site, cred), m, chatIdentity(cred.uid))
3420
- // a refused call's stream is closed: Qoder keeps a 10605 stream open
3421
- // after its one event, and a connection held open while the call is
3422
- // waited out and sent again is one more the account holds
3423
- const call = new AbortController()
3424
- const signal = init.signal ? AbortSignal.any([init.signal, call.signal]) : call.signal
3425
- let res, open
3426
- try {
3427
- res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal })
3428
- if (res.ok) open = await opened(res, chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : [])
3429
- } catch (e) {
3430
- return errorResponse({ status: 502, message: e.message })
3431
- }
3432
- const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
3433
- if (f) call.abort()
3434
- // a refused job token: renewed once (or the one renewed meanwhile)
3435
- // and the request sent again, before the refusal is said
3436
- if (f?.lapsed && getAuth && !relogged) {
3437
- relogged = true
3438
- 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
3439
3524
  try {
3440
- 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") : [])
3441
3527
  } catch (e) {
3442
- return signedInError(e)
3528
+ return errorResponse({ status: 502, message: e.message })
3443
3529
  }
3444
- if (next) {
3445
- 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
3446
3553
  continue
3447
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++
3448
3573
  }
3449
- // a reply whose only answer was a native tool call the model never
3450
- // named (plugins#579): nothing of it was given, so it is asked once
3451
- // more, under a new request_id; a second one is the gateway's 502 to
3452
- // retry or fail over
3453
- if (f?.nameless && !renamed) {
3454
- renamed = true
3455
- continue
3456
- }
3457
- // an answered call moves its task on, as Qoder's client moves it
3458
- if (!f) task.answered = true
3459
- // with another account, provider or group member after this one
3460
- // (magpie's X-Magpie-Fallback), a queued request isn't waited out:
3461
- // its 503 goes back at once, saying the queue, and the next is asked
3462
- if (!f?.queue || waited >= QUEUE.recoveries || fallback) return f ? errorResponse(f) : answer(open, chat, servedName)
3463
- try {
3464
- if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline, siteOf(site, cred)))) return errorResponse(f)
3465
- } catch (e) {
3466
- return errorResponse({ status: 502, message: e?.message ?? String(e) })
3467
- }
3468
- waited++
3469
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
3470
3580
  }
3471
3581
 
3472
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.60",
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",