@magpie-community/opencode-qoder-auth 0.2.72 → 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 +17 -4
  2. package/index.mjs +114 -15
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -111,6 +111,10 @@ itself.
111
111
  agent, built on Anthropic's Claude Agent SDK.` (since 0.2.72): Qoder
112
112
  answers a prompt with that line with 400 `Cannot find model`, whatever
113
113
  the model. The rest of the prompt and your messages go as written.
114
+ - A harness's opener, such as DeepSeek Harness's `You are an AI agent
115
+ powered by DeepSeek Harness.`, goes with a comma before `powered by`
116
+ (since 0.2.73, #1517): Qoder CN puts a request whose system prompt
117
+ holds that line, as written, in a queue that never moves.
114
118
  - Messages become text and image blocks.
115
119
  - Tool calls and results become OpenAI tool turns. Images a tool returned
116
120
  follow in a user turn.
@@ -588,7 +592,9 @@ Since **0.2.28** a queued request waits its turn as Qoder's own client
588
592
  model and the plan's `queueType`, at once and then every
589
593
  `retryAfterSeconds` (held to 0.5–30s, 30s when unsaid), and once
590
594
  `isQueued` is false it waits that state's `retryAfterSeconds` and sends the
591
- 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
592
598
  404, or a cancelled request end the wait early.
593
599
 
594
600
  Since **0.2.62** a streamed request (every agent's) waits as long as
@@ -610,9 +616,16 @@ keepalives); magpie can then rest the account or ask the next. A queue with
610
616
  others ahead is still waited out. Nothing needs setting. A request that isn't
611
617
  streamed has nothing to keep its client alive with, so it still waits 4
612
618
  minutes at most before the 503. Claude Code takes a ping as life only 30
613
- times in a row, about 35 minutes, so a longer wait still ends there. Qoder's client also reports the end
614
- of its turn to `/api/v2/service/ask/finish`; the plugin doesn't, and
615
- 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.
616
629
 
617
630
  Since **0.2.40** the wait is only for the last candidate: when magpie says
618
631
  another account, provider or routing group member follows this request
package/index.mjs CHANGED
@@ -82,6 +82,20 @@ const CLAUDE_CODE_LINE = /You\s+are\s+Claude\s+Code,\s+Anthropic's\s+official\s+
82
82
  const AGENT_SDK_LINE = "You are a Claude agent, built on Anthropic's Claude Agent SDK."
83
83
  const asAgentSDK = (text) => text.replace(CLAUDE_CODE_LINE, AGENT_SDK_LINE)
84
84
 
85
+ // Qoder CN puts a request whose system prompt holds DeepSeek Harness's
86
+ // opener, "You are an AI agent powered by DeepSeek Harness.", in a queue
87
+ // that never moves: 10605, nothing ahead, keepalives until the agent gives
88
+ // up (#1517, #1220). The same request with that line one character shorter,
89
+ // or with no such line, is answered at once, every time (lirenQa1's bisect
90
+ // on #1220: the flip sits on exactly those 48 characters; tools, size,
91
+ // max_completion_tokens and the session header changed nothing). The match
92
+ // is the line whole, as WorkBuddy's on the same opener (its OPENERS), so a
93
+ // comma before "powered by" says the same thing and passes. harnessComma
94
+ // sets it in the system text Qoder is sent only; the user's own messages go
95
+ // as written.
96
+ const HARNESS_OPENER = /(\bYou are (?:an?|the)\s[^\n.,]{0,60}?\b(?:agent|assistant))\s+(powered by|running on|running in|built on|based on)\b/gi
97
+ const harnessComma = (text) => text.replace(HARNESS_OPENER, "$1, $2")
98
+
85
99
  const hexID = () => randomUUID().replaceAll("-", "")
86
100
 
87
101
  // ---- the COSY envelope --------------------------------------------------------
@@ -1413,7 +1427,8 @@ const TASK_IDLE = 2 * 60 * 60 * 1000
1413
1427
  const taskName = (prompt) => (prompt.length > 10 ? prompt.slice(0, 10) : prompt)
1414
1428
 
1415
1429
  // taskOf is the task chat's call belongs to, in session sid: made on its
1416
- // 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).
1417
1432
  function taskOf(sid, chat, now = Date.now()) {
1418
1433
  const msgs = chat.messages ?? []
1419
1434
  const at = msgs.findLastIndex((x) => x?.role === "user")
@@ -1421,17 +1436,36 @@ function taskOf(sid, chat, now = Date.now()) {
1421
1436
  for (const [k, t] of TASKS) {
1422
1437
  if (now - t.used <= TASK_IDLE) break
1423
1438
  TASKS.delete(k)
1439
+ endTask(t)
1424
1440
  }
1425
1441
  let t = TASKS.get(key)
1426
- if (t && now - t.used > TASK_IDLE) t = undefined
1442
+ if (t && now - t.used > TASK_IDLE) {
1443
+ endTask(t)
1444
+ t = undefined
1445
+ }
1427
1446
  TASKS.delete(key)
1428
- 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
+ }
1429
1451
  t.used = now
1430
1452
  TASKS.set(key, t)
1431
- 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
+ }
1432
1458
  return t
1433
1459
  }
1434
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
+
1435
1469
  // Qoder CN's kmodel (Kimi K3.1 Pro) fails a chat whose tools hold a oneOf
1436
1470
  // with no type, even of objects only, and takes it with "type": "object"
1437
1471
  // beside it (congee949, #378: dsh's REA tools, a 502 here). typedUnions is
@@ -1516,7 +1550,7 @@ function modelConfig(m, thinking) {
1516
1550
  // passes itself last.
1517
1551
  function qoderBody(chat, m, named = "", task, site) {
1518
1552
  const given = (chat.messages ?? []).filter((x) => x.role === "system" || x.role === "developer").map((x) => textOf(x.content)).filter(Boolean).join("\n\n")
1519
- const system = asAgentSDK(given)
1553
+ const system = harnessComma(asAgentSDK(given))
1520
1554
  const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function" && t.function?.name) : []
1521
1555
  const baseSystem = site?.systemPrompt ?? QODER_SYS
1522
1556
  let sysText = system ? baseSystem + "\n\n" + system : baseSystem
@@ -1727,10 +1761,18 @@ const errorResponse = ({ status, message, signIn = status === 401 ? "kept" : und
1727
1761
  // refusal as the stream's error. A request not streamed has nothing to
1728
1762
  // keep its client alive with, and waits QUEUE.budget at most, then the
1729
1763
  // 503 with Retry-After it was before, so magpie may ask another account.
1730
- // Qoder's client also tells
1731
- // /api/v2/service/ask/finish when its turn ends; that is left out, and its
1732
- // 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.
1733
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"
1734
1776
  const QUEUE = {
1735
1777
  budget: 4 * 60 * 1000, // the longest a request not streamed is held, its first answer's wait included
1736
1778
  held: 60 * 60 * 1000, // the longest a streamed one is, as Qoder's client waits
@@ -1741,6 +1783,7 @@ const QUEUE = {
1741
1783
  recoveries: 10, // the queue waited out this many times, at most, for one request
1742
1784
  failures: 3, // status asks failing in a row that end the wait
1743
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
1744
1787
  // the longest a call waits for Qoder's first event (headers included).
1745
1788
  // Qoder CN once held a call 15 minutes with nothing sent and nothing to
1746
1789
  // log (#1204); after this it is a 504 that says so, which magpie can
@@ -1841,6 +1884,49 @@ async function queueStatus(api, cred, { requestSetId, modelKey, queueType, reque
1841
1884
  return st
1842
1885
  }
1843
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
+
1844
1930
  // stuckKey is what a queue's state says of the request's place in it, or
1845
1931
  // "" when others are ahead of it (a queue that moves while they are
1846
1932
  // served is waited out, QUEUE.stuck never ends it).
@@ -1882,11 +1968,11 @@ async function queueWait(api, cred, ask, first, signal, deadline, site) {
1882
1968
  if (!key || key !== same) {
1883
1969
  same = key
1884
1970
  since = QUEUE.now()
1885
- } else if (QUEUE.now() - since >= QUEUE.stuck && st.isQueued !== false) {
1971
+ } else if (QUEUE.now() - since >= QUEUE.stuck && !queueReady(st)) {
1886
1972
  ask.stuck = true
1887
1973
  return false
1888
1974
  }
1889
- if (st.isQueued === false) {
1975
+ if (queueReady(st)) {
1890
1976
  if (st.retryAfterSeconds > 0) await QUEUE.pause(Math.min(queuePause(st.retryAfterSeconds), Math.max(0, deadline - QUEUE.now())), signal)
1891
1977
  return QUEUE.now() < deadline
1892
1978
  }
@@ -3891,7 +3977,15 @@ const makePlugin = (site) => async ({ client }) => {
3891
3977
  // with another account, provider or group member after this one
3892
3978
  // (magpie's X-Magpie-Fallback), a queued request isn't waited out:
3893
3979
  // its 503 goes back at once, saying the queue, and the next is asked
3894
- 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))
3895
3989
  if (chat.stream && !held) {
3896
3990
  held = holdQueued(f, init.signal)
3897
3991
  signal = held.signal
@@ -3900,14 +3994,19 @@ const makePlugin = (site) => async ({ client }) => {
3900
3994
  }
3901
3995
  try {
3902
3996
  if (!(await queueWait(api, cred, ask, f.queue, signal, deadline, siteOf(site, cred))))
3903
- 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))
3904
3998
  } catch (e) {
3905
- return errorResponse({ status: 502, message: e?.message ?? String(e) })
3999
+ return giveUp(errorResponse({ status: 502, message: e?.message ?? String(e) }))
3906
4000
  }
3907
4001
  waited++
3908
4002
  }
3909
4003
  }
3910
- 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
+ })
3911
4010
  const res = await Promise.race([done, heard])
3912
4011
  if (res !== held?.response) return res
3913
4012
  held.follow(done)
@@ -4286,4 +4385,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
4286
4385
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
4287
4386
 
4288
4387
  // for tests
4289
- 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, 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.72",
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",