qoder 0.2.28: a queued request waits its turn in Qoder's queue and is sent again, as Qoder's client does (wallance on Discord)
wallance (Discord, magpie latest, qoder 0.2.27): Qoder's free deepseek
flash (dfmodel) through magpie ended in 503 "Qoder queued the request for
dfmodel (this plan's queue: p3); try again in 30s" after 27s, while Qoder's
own client answered the same model, slowly. magpie's gateway retries a
Retry-After of 8s at most, so the 30s was the agent's error.
What Qoder's client does, read from Qoder.app 0.4.3's
qoder-agent-sdk/dist/_worker/qoder-worker-runtime.obf.mjs ("[ModelQueue]"):
on a 10605 or a queue state it asks
GET <api>/algo/api/v2/service/ask/queue/status?requestSetId=&modelKey=&queueType=
(signed as any GET, X-Request-ID and X-Session-ID), at once and then every
retryAfterSeconds held to 0.5..30s (30s unsaid), while isQueued is true or
serviceAvailable false. Once isQueued is false it waits that state's
retryAfterSeconds and sends the same chatAsk again (same request_set_id),
up to 10 times; 3 failed status asks in a row, a 404 or a state with
neither field end it. It waits up to an hour (QODER_MODEL_QUEUE_MAX_WAIT_MS),
and tells /api/v2/service/ask/finish at the end of its turn, best effort
("server TTL will release the lease").
The plugin now does that, under a 4-minute budget from the request's
start: nothing reaches the agent meanwhile, and magpie keeps a stream's
agent alive with SSE comments for 5 minutes of silence (keepQuiet,
keepaliveLongest). Past it, the 503 with Retry-After as before, so magpie
may ask another account. A cancelled request stops the wait and sends
nothing more. The status path's /algo prefix follows the client's other
paths (it signs "/api/v2/model/list", the plugin calls
"/algo/api/v2/model/list").
Run: HOME=$(mktemp -d) bun test in packages/qoder, 185 pass; at the repo
root, 2114 pass, 0 fail, at 7fdc07f plus this change; bun
scripts/check.mjs ok. queue.test.mjs (10 tests) is 10 of 10 red on the old
index.mjs. busy.test.mjs now pins the budget to 0: its cases are Qoder
still queued once the wait is over.
Not tried: a real Qoder account (no credentials used), so the status
endpoint's reply and its /algo path are taken from the client's code, not
seen on the wire. Not done: the finish call (its body goes through the
client's wasm signer, which the plugin can't confirm), and request_set_id
is still per request where Qoder's client keeps one per turn, so each
request of an agent's turn may queue on its own.
This commit is contained in:
@@ -139,7 +139,7 @@ itself.
|
|||||||
|---|---|
|
|---|---|
|
||||||
| A refused sign-in (no code, or code 105) | 401 |
|
| A refused sign-in (no code, or code 105) | 401 |
|
||||||
| A quota (codes 110, 112–119, 122) | 429 |
|
| A quota (codes 110, 112–119, 122) | 429 |
|
||||||
| Busy or queued for the model (code 10605) | 503, with `Retry-After` from Qoder's `retryAfterSeconds` (30s when it gives none); the sign-in is untouched |
|
| 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). The sign-in is untouched |
|
||||||
| A refusal of the request itself (codes 406, 416, 430, 80411, 80412, 100400–100403) | 400, with Qoder's words |
|
| A refusal of the request itself (codes 406, 416, 430, 80411, 80412, 100400–100403) | 400, with Qoder's words |
|
||||||
| "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 |
|
| "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 |
|
||||||
| A failure before the answer starts | Qoder's status |
|
| A failure before the answer starts | Qoder's status |
|
||||||
@@ -319,6 +319,20 @@ That parser fix does not remove the provider's limit or prove that every
|
|||||||
live 401 had the same cause. A timeout likewise does not establish an
|
live 401 had the same cause. A timeout likewise does not establish an
|
||||||
empty wallet or an expired login.
|
empty wallet or an expired login.
|
||||||
|
|
||||||
|
Since **0.2.28** a queued request waits its turn as Qoder's own client
|
||||||
|
(Qoder.app 0.4.3's agent worker) waits it: it asks
|
||||||
|
`/api/v2/service/ask/queue/status` with the request's `requestSetId`, the
|
||||||
|
model and the plan's `queueType`, at once and then every
|
||||||
|
`retryAfterSeconds` (held to 0.5–30s, 30s when unsaid), and once
|
||||||
|
`isQueued` is false it waits that state's `retryAfterSeconds` and sends the
|
||||||
|
same request again (up to 10 times). Qoder's client waits up to an hour;
|
||||||
|
the plugin waits at most 4 minutes from the request's start, since nothing
|
||||||
|
reaches the agent meanwhile (magpie keeps a stream alive with comments for
|
||||||
|
5 minutes of silence). Three failed status asks in a row, a 404, or a
|
||||||
|
cancelled request end the wait early. Qoder's client also reports the end
|
||||||
|
of its turn to `/api/v2/service/ask/finish`; the plugin doesn't, and
|
||||||
|
Qoder releases that lease on its own TTL. `queue.test.mjs` has the wait.
|
||||||
|
|
||||||
For a bounded offline reproduction, run `packages/qoder/busy.test.mjs`
|
For a bounded offline reproduction, run `packages/qoder/busy.test.mjs`
|
||||||
from #185 in an isolated temporary HOME. It compares plain queue JSON,
|
from #185 in an isolated temporary HOME. It compares plain queue JSON,
|
||||||
BOM-prefixed JSON and known message wrappers, keeping explicit login and
|
BOM-prefixed JSON and known message wrappers, keeping explicit login and
|
||||||
|
|||||||
@@ -3,14 +3,21 @@
|
|||||||
// trial account on 2026-10-12, byte for byte (testdata/queued-10605.json).
|
// trial account on 2026-10-12, byte for byte (testdata/queued-10605.json).
|
||||||
// The other codes are read as Qoder's own client reads them (QoderErrorCode
|
// The other codes are read as Qoder's own client reads them (QoderErrorCode
|
||||||
// in Qoder.app's qoder-agent-sdk worker): only 105 is loginExpired there.
|
// in Qoder.app's qoder-agent-sdk worker): only 105 is loginExpired there.
|
||||||
import { afterEach, expect, test } from "bun:test"
|
import { afterEach, beforeEach, expect, test } from "bun:test"
|
||||||
import { readFileSync } from "node:fs"
|
import { readFileSync } from "node:fs"
|
||||||
import { QoderAuthPlugin, _internal } from "./index.mjs"
|
import { QoderAuthPlugin, _internal } from "./index.mjs"
|
||||||
|
|
||||||
const QUEUED = readFileSync(new URL("./testdata/queued-10605.json", import.meta.url), "utf8").trim()
|
const QUEUED = readFileSync(new URL("./testdata/queued-10605.json", import.meta.url), "utf8").trim()
|
||||||
|
|
||||||
const real = globalThis.fetch
|
const real = globalThis.fetch
|
||||||
afterEach(() => (globalThis.fetch = real))
|
// these are Qoder still queued once the wait is over: queue.test.mjs has
|
||||||
|
// the wait itself
|
||||||
|
const budget = _internal.QUEUE.budget
|
||||||
|
beforeEach(() => (_internal.QUEUE.budget = 0))
|
||||||
|
afterEach(() => {
|
||||||
|
globalThis.fetch = real
|
||||||
|
_internal.QUEUE.budget = budget
|
||||||
|
})
|
||||||
|
|
||||||
const API_CHAT = "https://api3.qoder.sh/v1/chat/completions"
|
const API_CHAT = "https://api3.qoder.sh/v1/chat/completions"
|
||||||
const ASK = { method: "POST", body: JSON.stringify({ model: "efficient", messages: [{ role: "user", content: "hi" }] }) }
|
const ASK = { method: "POST", body: JSON.stringify({ model: "efficient", messages: [{ role: "user", content: "hi" }] }) }
|
||||||
|
|||||||
+183
-21
@@ -956,7 +956,7 @@ function failure(status, text) {
|
|||||||
const model = queue?.modelKey ? ` for ${queue.modelKey}` : ""
|
const model = queue?.modelKey ? ` for ${queue.modelKey}` : ""
|
||||||
const tier = queue?.queueType ? ` (this plan's queue: ${queue.queueType})` : ""
|
const tier = queue?.queueType ? ` (this plan's queue: ${queue.queueType})` : ""
|
||||||
const what = queue?.isQueued === true ? "queued the request" : "is busy"
|
const what = queue?.isQueued === true ? "queued the request" : "is busy"
|
||||||
return { status: 503, message: `Qoder ${what}${model}${tier}; try again in ${wait}s`, retryAfter: wait, signIn: "" }
|
return { status: 503, message: `Qoder ${what}${model}${tier}; try again in ${wait}s`, retryAfter: wait, signIn: "", queue: queue ?? {} }
|
||||||
}
|
}
|
||||||
if (QUOTA_CODES.has(code)) return { status: 429, message: "usage limit reached: " + msg, signIn: "" }
|
if (QUOTA_CODES.has(code)) return { status: 429, message: "usage limit reached: " + msg, signIn: "" }
|
||||||
if (REQUEST_CODES.has(code)) return { status: 400, message: `Qoder refused the request (${code}): ${msg}`, signIn: "" }
|
if (REQUEST_CODES.has(code)) return { status: 400, message: `Qoder refused the request (${code}): ${msg}`, signIn: "" }
|
||||||
@@ -987,6 +987,148 @@ const errorResponse = ({ status, message, signIn = status === 401 ? "kept" : und
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ---- Qoder's queue -------------------------------------------------------------
|
||||||
|
|
||||||
|
// A chat Qoder answers with its queue code (10605) is waited out as Qoder's
|
||||||
|
// own client waits it (qoder-agent-sdk's worker in Qoder.app 0.4.3, its
|
||||||
|
// "[ModelQueue]" path): it asks GET /api/v2/service/ask/queue/status with
|
||||||
|
// the request's requestSetId, the model and the plan's queueType, at once
|
||||||
|
// and then every retryAfterSeconds (held to 0.5s..30s, 30s when unsaid),
|
||||||
|
// while the state says isQueued or serviceAvailable false. Once isQueued is
|
||||||
|
// false it waits that state's retryAfterSeconds, if any, and sends the same
|
||||||
|
// request again, request_set_id and all, up to 10 times. Three failed asks
|
||||||
|
// in a row, a 404 (no queue there) or a state with neither field end the
|
||||||
|
// wait. Qoder's client waits up to an hour; here the whole of it is held
|
||||||
|
// under QUEUE.budget from the request's start, since nothing reaches the
|
||||||
|
// agent meanwhile: magpie keeps a stream's agent alive with comments for 5
|
||||||
|
// minutes of a vendor's silence, and then leaves it to the agent's own
|
||||||
|
// timeout. Past the budget it is the 503 with Retry-After it was before, so
|
||||||
|
// magpie may ask another account. Qoder's client also tells
|
||||||
|
// /api/v2/service/ask/finish when its turn ends; that is left out, and its
|
||||||
|
// own log says Qoder's TTL releases the lease when finish is not heard.
|
||||||
|
const QUEUE_STATUS_PATH = "/algo/api/v2/service/ask/queue/status"
|
||||||
|
const QUEUE = {
|
||||||
|
budget: 4 * 60 * 1000, // the longest a request is held, its first answer's wait included
|
||||||
|
shortest: 500,
|
||||||
|
longest: 30_000,
|
||||||
|
unsaid: 30_000, // a pause when the queue gives no retryAfterSeconds
|
||||||
|
recoveries: 10, // the queue waited out this many times, at most, for one request
|
||||||
|
failures: 3, // status asks failing in a row that end the wait
|
||||||
|
ask: 30_000, // the longest one status ask may take
|
||||||
|
now: () => Date.now(),
|
||||||
|
pause: (ms, signal) =>
|
||||||
|
new Promise((ok, no) => {
|
||||||
|
if (signal?.aborted) return no(signal.reason ?? new DOMException("aborted", "AbortError"))
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
signal?.removeEventListener("abort", stop)
|
||||||
|
ok()
|
||||||
|
}, ms)
|
||||||
|
const stop = () => {
|
||||||
|
clearTimeout(t)
|
||||||
|
no(signal.reason ?? new DOMException("aborted", "AbortError"))
|
||||||
|
}
|
||||||
|
signal?.addEventListener("abort", stop, { once: true })
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
// queuePause is how long to wait before asking the queue again: the
|
||||||
|
// queue's retryAfterSeconds held to 0.5s..30s, or 30s when it said none.
|
||||||
|
function queuePause(seconds) {
|
||||||
|
const n = Number(seconds)
|
||||||
|
const ms = Number.isFinite(n) ? n * 1000 : QUEUE.unsaid
|
||||||
|
return Math.min(QUEUE.longest, Math.max(QUEUE.shortest, ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
class QueueEnd extends Error {}
|
||||||
|
|
||||||
|
// queueState is the queue's state in a status reply, found as Qoder's
|
||||||
|
// client finds it: the object, or one under data/result/message/body, as
|
||||||
|
// an object or a JSON string, that says isQueued or serviceAvailable.
|
||||||
|
function queueState(text) {
|
||||||
|
let root
|
||||||
|
try {
|
||||||
|
root = JSON.parse(text)
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
const todo = [root]
|
||||||
|
const seen = new Set()
|
||||||
|
while (todo.length) {
|
||||||
|
const o = todo.shift()
|
||||||
|
if (!o || typeof o !== "object" || Array.isArray(o) || seen.has(o)) continue
|
||||||
|
seen.add(o)
|
||||||
|
const flag = (v) => (typeof v === "boolean" ? v : v === "true" ? true : v === "false" ? false : undefined)
|
||||||
|
const isQueued = flag(o.isQueued)
|
||||||
|
const serviceAvailable = flag(o.serviceAvailable)
|
||||||
|
if (isQueued !== undefined || serviceAvailable !== undefined) {
|
||||||
|
const num = (v) => (v == null || v === "" || !Number.isFinite(Number(v)) ? undefined : Number(v))
|
||||||
|
const str = (v) => (typeof v === "string" && v ? v : undefined)
|
||||||
|
return { isQueued, serviceAvailable, modelKey: str(o.modelKey), queueType: str(o.queueType), retryAfterSeconds: num(o.retryAfterSeconds) }
|
||||||
|
}
|
||||||
|
for (const k of ["data", "result", "message", "body"]) {
|
||||||
|
const v = o[k]
|
||||||
|
if (v && typeof v === "object") todo.push(v)
|
||||||
|
else if (typeof v === "string")
|
||||||
|
try {
|
||||||
|
todo.push(JSON.parse(v))
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
// queueStatus asks Qoder's queue where the request stands.
|
||||||
|
async function queueStatus(api, cred, { requestSetId, modelKey, queueType, requestId, sessionId }, signal, deadline) {
|
||||||
|
const q = new URLSearchParams({ requestSetId, modelKey })
|
||||||
|
if (queueType) q.set("queueType", queueType)
|
||||||
|
const url = `${api}${QUEUE_STATUS_PATH}?${q}`
|
||||||
|
const headers = { ...cosyHeaders(url, cred, ""), "X-Request-ID": requestId, "X-Session-ID": sessionId }
|
||||||
|
delete headers["Content-Type"]
|
||||||
|
const left = Math.min(QUEUE.ask, deadline - QUEUE.now())
|
||||||
|
if (left <= 0) throw new QueueEnd("the queue's wait ran out")
|
||||||
|
const res = await fetch(url, { headers, signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(left)]) : AbortSignal.timeout(left) })
|
||||||
|
const text = await res.text()
|
||||||
|
if (res.status === 404) throw new QueueEnd("Qoder has no queue status here")
|
||||||
|
if (!res.ok) throw new Error(`queue status: HTTP ${res.status}`)
|
||||||
|
const st = queueState(text)
|
||||||
|
if (!st) throw new QueueEnd("the queue status said nothing of the queue")
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
|
||||||
|
// queueWait waits in Qoder's queue for the request, from the state its
|
||||||
|
// refusal gave, until the queue lets it through (true) or the wait ends
|
||||||
|
// (false). A cancelled request throws.
|
||||||
|
async function queueWait(api, cred, ask, first, signal, deadline) {
|
||||||
|
let q = first ?? {}
|
||||||
|
let asked = false
|
||||||
|
let failed = 0
|
||||||
|
for (;;) {
|
||||||
|
if (signal?.aborted) throw signal.reason ?? new DOMException("aborted", "AbortError")
|
||||||
|
if (QUEUE.now() >= deadline) return false
|
||||||
|
if (asked) await QUEUE.pause(Math.min(queuePause(q.retryAfterSeconds), Math.max(0, deadline - QUEUE.now())), signal)
|
||||||
|
asked = true
|
||||||
|
if (QUEUE.now() >= deadline) return false
|
||||||
|
let st
|
||||||
|
try {
|
||||||
|
st = await queueStatus(api, cred, { ...ask, modelKey: q.modelKey ?? ask.modelKey, queueType: q.queueType ?? ask.queueType }, signal, deadline)
|
||||||
|
} catch (e) {
|
||||||
|
if (signal?.aborted) throw signal.reason ?? e
|
||||||
|
if (e instanceof QueueEnd) return false
|
||||||
|
if (++failed >= QUEUE.failures) return false
|
||||||
|
q = { ...q, retryAfterSeconds: undefined }
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
failed = 0
|
||||||
|
q = { ...st, modelKey: st.modelKey ?? q.modelKey, queueType: st.queueType ?? q.queueType }
|
||||||
|
if (st.isQueued === false) {
|
||||||
|
if (st.retryAfterSeconds > 0) await QUEUE.pause(Math.min(queuePause(st.retryAfterSeconds), Math.max(0, deadline - QUEUE.now())), signal)
|
||||||
|
return QUEUE.now() < deadline
|
||||||
|
}
|
||||||
|
if (st.serviceAvailable === false || st.isQueued === true) continue
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---- the reply ----------------------------------------------------------------
|
// ---- the reply ----------------------------------------------------------------
|
||||||
|
|
||||||
const CALL_OPEN = "\x3ctool_call\x3e"
|
const CALL_OPEN = "\x3ctool_call\x3e"
|
||||||
@@ -1232,11 +1374,17 @@ async function* events(body) {
|
|||||||
// answer turns Qoder's reply into the chat completion OpenAI's API gives.
|
// answer turns Qoder's reply into the chat completion OpenAI's API gives.
|
||||||
// A failure before the answer keeps its status; one after it ends the
|
// A failure before the answer keeps its status; one after it ends the
|
||||||
// stream with an error.
|
// stream with an error.
|
||||||
async function answer(res, chat) {
|
// opened is a chat reply's events and the first of them, read before
|
||||||
|
// anything is answered: a refusal in the stream (Qoder's queue among them)
|
||||||
|
// comes first.
|
||||||
|
async function opened(res) {
|
||||||
|
const it = events(res.body)
|
||||||
|
return { it, first: await it.next() }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function answer({ it, first }, chat) {
|
||||||
const id = "chatcmpl-" + hexID()
|
const id = "chatcmpl-" + hexID()
|
||||||
const created = Math.floor(Date.now() / 1000)
|
const created = Math.floor(Date.now() / 1000)
|
||||||
const it = events(res.body)
|
|
||||||
const first = await it.next()
|
|
||||||
if (first.value?.error) return errorResponse(first.value.error)
|
if (first.value?.error) return errorResponse(first.value.error)
|
||||||
if (first.done) return errorResponse({ status: 502, message: "Qoder ended without an answer" })
|
if (first.done) return errorResponse({ status: 502, message: "Qoder ended without an answer" })
|
||||||
|
|
||||||
@@ -1889,23 +2037,37 @@ const makePlugin = (site) => async ({ client }) => {
|
|||||||
return errorResponse({ status: 502, message: e?.message ?? String(e) })
|
return errorResponse({ status: 502, message: e?.message ?? String(e) })
|
||||||
}
|
}
|
||||||
if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` })
|
if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` })
|
||||||
const CHAT_URL = siteOf(site, cred).api + CHAT_PATH
|
const api = siteOf(site, cred).api
|
||||||
const wire = encodeBody(JSON.stringify(qoderBody(chat, m)))
|
const CHAT_URL = api + CHAT_PATH
|
||||||
const headers = {
|
const body = qoderBody(chat, m)
|
||||||
...cosyHeaders(CHAT_URL, cred, wire),
|
const wire = encodeBody(JSON.stringify(body))
|
||||||
Accept: "text/event-stream",
|
// Qoder's queue is waited out (queueWait) and the same request, its
|
||||||
"Cache-Control": "no-cache",
|
// request_set_id the one the queue knows, sent again
|
||||||
"X-Model-Key": m.key,
|
const deadline = QUEUE.now() + QUEUE.budget
|
||||||
"X-Model-Source": m.source,
|
const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key }
|
||||||
|
for (let waited = 0; ; waited++) {
|
||||||
|
const headers = {
|
||||||
|
...cosyHeaders(CHAT_URL, cred, wire),
|
||||||
|
Accept: "text/event-stream",
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
"X-Model-Key": m.key,
|
||||||
|
"X-Model-Source": m.source,
|
||||||
|
}
|
||||||
|
let res, open
|
||||||
|
try {
|
||||||
|
res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal })
|
||||||
|
if (res.ok) open = await opened(res)
|
||||||
|
} catch (e) {
|
||||||
|
return errorResponse({ status: 502, message: e.message })
|
||||||
|
}
|
||||||
|
const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error
|
||||||
|
if (!f?.queue || waited >= QUEUE.recoveries) return f && !res.ok ? errorResponse(f) : answer(open, chat)
|
||||||
|
try {
|
||||||
|
if (!(await queueWait(api, cred, ask, f.queue, init.signal, deadline))) return errorResponse(f)
|
||||||
|
} catch (e) {
|
||||||
|
return errorResponse({ status: 502, message: e?.message ?? String(e) })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let res
|
|
||||||
try {
|
|
||||||
res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal })
|
|
||||||
} catch (e) {
|
|
||||||
return errorResponse({ status: 502, message: e.message })
|
|
||||||
}
|
|
||||||
if (!res.ok) return errorResponse(failure(res.status, (await res.text()).slice(0, 1 << 20)))
|
|
||||||
return answer(res, chat)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -2071,4 +2233,4 @@ export const QoderAuthPlugin = makePlugin(SITES.qoder)
|
|||||||
export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"])
|
export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"])
|
||||||
|
|
||||||
// for tests
|
// for tests
|
||||||
export const _internal = { campaignRuntime, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, SITES, decodeBody, events }
|
export const _internal = { campaignRuntime, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, SITES, decodeBody, events, QUEUE, queueState }
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@magpie-community/opencode-qoder-auth",
|
"name": "@magpie-community/opencode-qoder-auth",
|
||||||
"version": "0.2.27",
|
"version": "0.2.28",
|
||||||
"description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)",
|
"description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./index.mjs",
|
"main": "./index.mjs",
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
// Qoder's queue (code 10605) is waited out as Qoder's own client waits it
|
||||||
|
// (qoder-agent-sdk's worker in Qoder.app 0.4.3, "[ModelQueue]"): it asks
|
||||||
|
// /api/v2/service/ask/queue/status with the request's requestSetId, the
|
||||||
|
// model and the queueType until isQueued is false, waits that state's
|
||||||
|
// retryAfterSeconds and sends the same request again. wallance on Discord:
|
||||||
|
// Qoder's free dfmodel answered "Qoder queued the request for dfmodel (this
|
||||||
|
// plan's queue: p3); try again in 30s" through magpie, while Qoder's client
|
||||||
|
// answered, slowly. The refusal is the shape of the real one in
|
||||||
|
// testdata/queued-10605.json with isQueued true, as wallance's message
|
||||||
|
// says; the status replies are that shape too, not captured bytes.
|
||||||
|
//
|
||||||
|
// The clock and the pauses are the test's own (QUEUE.now, QUEUE.pause): a
|
||||||
|
// pause moves the clock on at once, and says how long it was asked to be.
|
||||||
|
import { afterEach, beforeEach, expect, test } from "bun:test"
|
||||||
|
import { QoderAuthPlugin, _internal } from "./index.mjs"
|
||||||
|
|
||||||
|
const { QUEUE } = _internal
|
||||||
|
const real = globalThis.fetch
|
||||||
|
const saved = { ...QUEUE }
|
||||||
|
let clock, pauses
|
||||||
|
beforeEach(() => {
|
||||||
|
clock = 1_000_000
|
||||||
|
pauses = []
|
||||||
|
QUEUE.now = () => clock
|
||||||
|
QUEUE.pause = async (ms, signal) => {
|
||||||
|
if (signal?.aborted) throw signal.reason
|
||||||
|
pauses.push(ms)
|
||||||
|
clock += ms
|
||||||
|
}
|
||||||
|
})
|
||||||
|
afterEach(() => {
|
||||||
|
globalThis.fetch = real
|
||||||
|
Object.assign(QUEUE, saved)
|
||||||
|
})
|
||||||
|
|
||||||
|
const API_CHAT = "https://api3.qoder.sh/v1/chat/completions"
|
||||||
|
const ask = (signal) => ({ method: "POST", body: JSON.stringify({ model: "dfmodel", messages: [{ role: "user", content: "hi" }] }), signal })
|
||||||
|
const LISTING = { chat: [{ key: "dfmodel", display_name: "DeepSeek Flash", enable: true }] }
|
||||||
|
const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } })
|
||||||
|
const QUEUED = { isQueued: true, modelKey: "dfmodel", queueCount: 3, queueType: "p3", retryAfterSeconds: 30, serviceAvailable: true, waitTime: 20 }
|
||||||
|
const refused = (q = QUEUED) => json({ code: "10605", message: JSON.stringify(q) }, 403)
|
||||||
|
const line = (body, statusCodeValue = 200) => `data:${JSON.stringify({ headers: {}, body: typeof body === "string" ? body : JSON.stringify(body), statusCodeValue })}\n\n`
|
||||||
|
const answered = () =>
|
||||||
|
new Response(line({ choices: [{ delta: { content: "hello" } }] }) + line({ choices: [{ delta: {}, finish_reason: "stop" }] }) + line("[DONE]"), {
|
||||||
|
headers: { "Content-Type": "text/event-stream" },
|
||||||
|
})
|
||||||
|
const status = (st) => json({ success: true, data: st })
|
||||||
|
|
||||||
|
// a loader whose chats are answered by chats(), in turn, and status asks by
|
||||||
|
// statuses(); what was sent is kept
|
||||||
|
async function loader({ chats, statuses }) {
|
||||||
|
const auth = { type: "oauth", access: "jt", refresh: "rt", expires: Date.now() + 3_600_000, accountId: "one@x", uid: "u1", machineId: "m1" }
|
||||||
|
const sent = { chats: [], statuses: [] }
|
||||||
|
globalThis.fetch = async (url, init = {}) => {
|
||||||
|
const u = new URL(String(url))
|
||||||
|
if (u.pathname.endsWith("/model/list")) return json(LISTING)
|
||||||
|
if (u.pathname.endsWith("/queue/status")) {
|
||||||
|
sent.statuses.push({ url: u, headers: init.headers })
|
||||||
|
return statuses(sent.statuses.length)
|
||||||
|
}
|
||||||
|
sent.chats.push(JSON.parse(_internal.decodeBody(init.body)))
|
||||||
|
return chats(sent.chats.length)
|
||||||
|
}
|
||||||
|
const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||||
|
const l = await hooks.auth.loader(async () => auth)
|
||||||
|
return { fetch: l.fetch, sent }
|
||||||
|
}
|
||||||
|
|
||||||
|
test("a queued request waits its turn in Qoder's queue and is sent again, the same request, once the queue lets it through", async () => {
|
||||||
|
const { fetch, sent } = await loader({
|
||||||
|
chats: (n) => (n === 1 ? refused() : answered()),
|
||||||
|
statuses: (n) => status(n < 3 ? { ...QUEUED, queueCount: 3 - n, retryAfterSeconds: 12 } : { isQueued: false, modelKey: "dfmodel", queueType: "p3", retryAfterSeconds: 1, serviceAvailable: true }),
|
||||||
|
})
|
||||||
|
const res = await fetch(API_CHAT, ask())
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect((await res.json()).choices[0].message.content).toBe("hello")
|
||||||
|
// asked at once, then after each state's retryAfterSeconds; once through,
|
||||||
|
// its own retryAfterSeconds before the request goes again
|
||||||
|
expect(pauses).toEqual([12_000, 12_000, 1_000])
|
||||||
|
expect(sent.chats.length).toBe(2)
|
||||||
|
// the same request: the queue knows it by its request_set_id
|
||||||
|
expect(sent.chats[1].request_set_id).toBe(sent.chats[0].request_set_id)
|
||||||
|
expect(sent.chats[1].request_id).toBe(sent.chats[0].request_id)
|
||||||
|
expect(sent.chats[1].messages).toEqual(sent.chats[0].messages)
|
||||||
|
const first = sent.statuses[0]
|
||||||
|
expect(first.url.origin + first.url.pathname).toBe("https://api3.qoder.sh/algo/api/v2/service/ask/queue/status")
|
||||||
|
expect(Object.fromEntries(first.url.searchParams)).toEqual({ requestSetId: sent.chats[0].request_set_id, modelKey: "dfmodel", queueType: "p3" })
|
||||||
|
expect(first.headers["X-Request-ID"]).toBe(sent.chats[0].request_id)
|
||||||
|
expect(first.headers["X-Session-ID"]).toBe(sent.chats[0].session_id)
|
||||||
|
expect(first.headers.Authorization).toStartWith("Bearer COSY.")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the queue's refusal in the stream is waited out the same way", async () => {
|
||||||
|
const { fetch, sent } = await loader({
|
||||||
|
chats: (n) =>
|
||||||
|
n === 1
|
||||||
|
? new Response(line({ code: "10605", message: JSON.stringify(QUEUED) }, 403), { headers: { "Content-Type": "text/event-stream" } })
|
||||||
|
: answered(),
|
||||||
|
statuses: () => status({ isQueued: false, serviceAvailable: true }),
|
||||||
|
})
|
||||||
|
const res = await fetch(API_CHAT, ask())
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect((await res.json()).choices[0].message.content).toBe("hello")
|
||||||
|
expect(sent.chats.length).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("a wait held past the budget is the 503 with Retry-After it was, the request not sent again", async () => {
|
||||||
|
const { fetch, sent } = await loader({ chats: () => refused(), statuses: () => status(QUEUED) })
|
||||||
|
const res = await fetch(API_CHAT, ask())
|
||||||
|
expect(res.status).toBe(503)
|
||||||
|
expect(res.headers.get("Retry-After")).toBe("30")
|
||||||
|
expect((await res.json()).error.message).toBe("Qoder queued the request for dfmodel (this plan's queue: p3); try again in 30s")
|
||||||
|
expect(sent.chats.length).toBe(1)
|
||||||
|
// 30s pauses, the last cut to what was left of the budget
|
||||||
|
expect(pauses.reduce((a, b) => a + b, 0)).toBe(QUEUE.budget)
|
||||||
|
expect(Math.max(...pauses)).toBe(30_000)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the pause is the queue's retryAfterSeconds held to 0.5s..30s, and 30s when it says none", async () => {
|
||||||
|
const states = [
|
||||||
|
{ ...QUEUED, retryAfterSeconds: 0.1 },
|
||||||
|
{ ...QUEUED, retryAfterSeconds: 300 },
|
||||||
|
{ ...QUEUED, retryAfterSeconds: undefined },
|
||||||
|
{ isQueued: false },
|
||||||
|
]
|
||||||
|
const { fetch } = await loader({ chats: (n) => (n === 1 ? refused() : answered()), statuses: (n) => status(states[n - 1]) })
|
||||||
|
expect((await fetch(API_CHAT, ask())).status).toBe(200)
|
||||||
|
expect(pauses).toEqual([500, 30_000, 30_000])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("service unavailable keeps waiting; the queue saying nothing of itself, or no queue there (404), ends the wait at once", async () => {
|
||||||
|
let r = await loader({
|
||||||
|
chats: (n) => (n === 1 ? refused() : answered()),
|
||||||
|
statuses: (n) => status(n === 1 ? { isQueued: false, serviceAvailable: false, retryAfterSeconds: 5 } : { isQueued: false }),
|
||||||
|
})
|
||||||
|
// isQueued false comes first, as in Qoder's client: through, after 5s
|
||||||
|
expect((await r.fetch(API_CHAT, ask())).status).toBe(200)
|
||||||
|
expect(pauses).toEqual([5_000])
|
||||||
|
|
||||||
|
pauses = []
|
||||||
|
r = await loader({
|
||||||
|
chats: (n) => (n === 1 ? refused() : answered()),
|
||||||
|
statuses: (n) => status(n === 1 ? { serviceAvailable: false, retryAfterSeconds: 2 } : { isQueued: false }),
|
||||||
|
})
|
||||||
|
expect((await r.fetch(API_CHAT, ask())).status).toBe(200)
|
||||||
|
expect(pauses).toEqual([2_000])
|
||||||
|
|
||||||
|
for (const reply of [() => status({ nothing: 1 }), () => new Response("not found", { status: 404 })]) {
|
||||||
|
pauses = []
|
||||||
|
r = await loader({ chats: () => refused(), statuses: reply })
|
||||||
|
expect((await r.fetch(API_CHAT, ask())).status).toBe(503)
|
||||||
|
expect(r.sent.statuses.length).toBe(1)
|
||||||
|
expect(r.sent.chats.length).toBe(1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("three failed status asks in a row end the wait; one between good ones doesn't", async () => {
|
||||||
|
let r = await loader({ chats: () => refused(), statuses: () => new Response("boom", { status: 500 }) })
|
||||||
|
expect((await r.fetch(API_CHAT, ask())).status).toBe(503)
|
||||||
|
expect(r.sent.statuses.length).toBe(3)
|
||||||
|
// a failed ask's pause isn't the last state's: 30s
|
||||||
|
expect(pauses).toEqual([30_000, 30_000])
|
||||||
|
|
||||||
|
pauses = []
|
||||||
|
const replies = [() => new Response("", { status: 502 }), () => status(QUEUED), () => new Response("", { status: 502 }), () => new Response("", { status: 502 }), () => status({ isQueued: false })]
|
||||||
|
r = await loader({ chats: (n) => (n === 1 ? refused() : answered()), statuses: (n) => replies[n - 1]() })
|
||||||
|
expect((await r.fetch(API_CHAT, ask())).status).toBe(200)
|
||||||
|
expect(r.sent.statuses.length).toBe(5)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the queue is waited out 10 times for one request at most", async () => {
|
||||||
|
QUEUE.budget = 24 * 60 * 60 * 1000
|
||||||
|
const { fetch, sent } = await loader({ chats: () => refused(), statuses: () => status({ isQueued: false }) })
|
||||||
|
const res = await fetch(API_CHAT, ask())
|
||||||
|
expect(res.status).toBe(503)
|
||||||
|
expect(sent.chats.length).toBe(11)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("a cancelled request stops waiting: no status asked and no request sent after", async () => {
|
||||||
|
const stop = new AbortController()
|
||||||
|
const { fetch, sent } = await loader({
|
||||||
|
chats: () => refused(),
|
||||||
|
statuses: (n) => {
|
||||||
|
if (n === 2) stop.abort(new DOMException("the client went away", "AbortError"))
|
||||||
|
return status(QUEUED)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const res = await fetch(API_CHAT, ask(stop.signal))
|
||||||
|
expect(res.status).toBe(502)
|
||||||
|
expect(sent.statuses.length).toBe(2)
|
||||||
|
expect(sent.chats.length).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the real pause ends early when the request is cancelled", async () => {
|
||||||
|
QUEUE.pause = saved.pause
|
||||||
|
const stop = new AbortController()
|
||||||
|
const p = QUEUE.pause(60_000, stop.signal)
|
||||||
|
stop.abort(new DOMException("gone", "AbortError"))
|
||||||
|
await expect(p).rejects.toThrow("gone")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the state is found where Qoder's client finds it", () => {
|
||||||
|
expect(_internal.queueState(JSON.stringify({ data: { isQueued: true, queueType: "p3", retryAfterSeconds: "7" } }))).toEqual({
|
||||||
|
isQueued: true,
|
||||||
|
serviceAvailable: undefined,
|
||||||
|
modelKey: undefined,
|
||||||
|
queueType: "p3",
|
||||||
|
retryAfterSeconds: 7,
|
||||||
|
})
|
||||||
|
expect(_internal.queueState(JSON.stringify({ code: "200", message: JSON.stringify({ isQueued: false }) }))?.isQueued).toBe(false)
|
||||||
|
expect(_internal.queueState(JSON.stringify({ result: JSON.stringify({ serviceAvailable: false }) }))?.serviceAvailable).toBe(false)
|
||||||
|
expect(_internal.queueState("not json")).toBeUndefined()
|
||||||
|
expect(_internal.queueState(JSON.stringify({ data: { queueCount: 1 } }))).toBeUndefined()
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user