@magpie-community/opencode-qoder-auth 0.2.67 → 0.2.69

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/index.mjs +141 -4
  2. package/opencode2.mjs +25 -1
  3. package/package.json +1 -1
package/index.mjs CHANGED
@@ -1200,7 +1200,18 @@ function reasoningOf(m) {
1200
1200
  // thinking before the call said, and said it had none without it. A turn
1201
1201
  // with thinking and nothing else is still left out, as that client leaves
1202
1202
  // it.
1203
- function qoderMessages(msgs) {
1203
+ // Kimi on QwenWork (kimi-k3.1-pro) answers 400 "Error in upstream response"
1204
+ // to an assistant turn with tool_calls and an empty content, which is how
1205
+ // every OpenAI client records a call-only turn (nanfei892, #1213: 9-token
1206
+ // bodies, DeepSeek, GLM and Qwen on the same account fine, " " served).
1207
+ // QwenWork's own client always writes text beside a call. A Kimi model's
1208
+ // call-only turn carries one space; other models get the turn as written.
1209
+ function kimiModel(m) {
1210
+ const key = String(m?.key ?? "")
1211
+ return /^kmodel/i.test(key) || /kimi/i.test(key + " " + (m?.config?.display_name ?? "") + " " + (m?.name ?? ""))
1212
+ }
1213
+
1214
+ function qoderMessages(msgs, opts = {}) {
1204
1215
  const out = []
1205
1216
  const names = {}
1206
1217
  let seen = []
@@ -1259,7 +1270,7 @@ function qoderMessages(msgs) {
1259
1270
  return { id, type: "function", function: { name: c.function?.name, arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}) } }
1260
1271
  })
1261
1272
  const think = reasoningOf(m)
1262
- out.push({ role: "assistant", content: textOf(m.content), ...(think ? { reasoning_content: think } : {}), tool_calls: calls })
1273
+ out.push({ role: "assistant", content: textOf(m.content) || (opts.callText ?? ""), ...(think ? { reasoning_content: think } : {}), tool_calls: calls })
1263
1274
  const open = calls.map((c) => c.id)
1264
1275
  const kept = new Set()
1265
1276
  for (let j = i + 1; j < msgs.length && msgs[j].role === "tool"; j++) {
@@ -1522,7 +1533,7 @@ function qoderBody(chat, m, named = "", task, site) {
1522
1533
  session_type: site?.sessionType ?? "app",
1523
1534
  model_config: modelConfig(m, thinking),
1524
1535
  system: [sys],
1525
- messages: [{ role: "system", content: [sys] }, ...cacheMarked(qoderMessages(chat.messages ?? []))],
1536
+ messages: [{ role: "system", content: [sys] }, ...cacheMarked(qoderMessages(chat.messages ?? [], { callText: kimiModel(m) ? " " : "" }))],
1526
1537
  }
1527
1538
  if (tools.length)
1528
1539
  body.tools = tools.map((t) => ({
@@ -2036,6 +2047,71 @@ function quoted(text) {
2036
2047
  // the XML function form
2037
2048
  const callish = (v) => v.trimStart().startsWith("{") || v.includes("\x3cfunction=")
2038
2049
 
2050
+ // plugins#1113: a reply that is one JSON object holding OpenAI's own
2051
+ // tool_calls array, written as text ({"tool_calls":[{"name", "arguments"}]}),
2052
+ // is those calls. It is told apart from text by where it starts: a line of
2053
+ // its own whose object opens with the "tool_calls" key, outside code.
2054
+ const JSON_KEY = '{"tool_calls"'
2055
+ const JSON_AT_ALL = /(^|\n)[ \t]*\{\s*"tool_calls"\s*:/g
2056
+
2057
+ // jsonHold is how much of comb's end may still become JSON_KEY on a line
2058
+ // of its own (start says comb starts a line), so it is held for more
2059
+ function jsonHold(comb, start) {
2060
+ const n = comb.lastIndexOf("\n")
2061
+ if (n < 0 && !start) return 0
2062
+ const line = comb.slice(n + 1)
2063
+ const s = line.replace(/\s+/g, "")
2064
+ if (!JSON_KEY.startsWith(s)) return 0
2065
+ return line.length
2066
+ }
2067
+
2068
+ // jsonEnd is where the JSON object at the start of v ends, -1 while it is
2069
+ // not whole yet
2070
+ function jsonEnd(v) {
2071
+ let depth = 0
2072
+ let str = false
2073
+ for (let k = 0; k < v.length; k++) {
2074
+ const c = v[k]
2075
+ if (str) {
2076
+ if (c === "\\") k++
2077
+ else if (c === '"') str = false
2078
+ } else if (c === '"') str = true
2079
+ else if (c === "{" || c === "[") depth++
2080
+ else if (c === "}" || c === "]") {
2081
+ if (--depth === 0) return k + 1
2082
+ }
2083
+ }
2084
+ return -1
2085
+ }
2086
+
2087
+ // jsonCalls reads a whole {"tool_calls": [...]} object: its calls, null
2088
+ // when it holds none (it stays text), or false when one can't be read
2089
+ function jsonCalls(v) {
2090
+ let f
2091
+ try {
2092
+ f = JSON.parse(v)
2093
+ } catch {
2094
+ return false
2095
+ }
2096
+ const list = f?.tool_calls
2097
+ if (!Array.isArray(list) || !list.length) return null
2098
+ const calls = []
2099
+ for (const e of list) {
2100
+ const fn = e?.function ?? e
2101
+ let args = fn?.arguments
2102
+ if (typeof args === "string") {
2103
+ try {
2104
+ args = JSON.parse(args)
2105
+ } catch {
2106
+ return false
2107
+ }
2108
+ }
2109
+ if (!String(fn?.name ?? "").trim() || !args || typeof args !== "object" || Array.isArray(args)) return false
2110
+ calls.push({ name: fn.name.trim(), args: JSON.stringify(args) })
2111
+ }
2112
+ return calls
2113
+ }
2114
+
2039
2115
  const CUT_SHORT = "the model's tool call, written as text, was cut short; it is not sent on as the answer"
2040
2116
  const UNREADABLE = "the model's tool call, written as text, can't be read; it is not sent on as the answer"
2041
2117
 
@@ -2054,6 +2130,7 @@ class Splitter {
2054
2130
  sawTool = false
2055
2131
  after = false // a bare call just ended: the closes and blanks after it are dropped
2056
2132
  sent = "" // the text given out so far, to tell a block in code from a call
2133
+ jsonBuf = null // a {"tool_calls": ...} object being read (plugins#1113)
2057
2134
  constructor(tools = []) {
2058
2135
  this.tools = tools.filter((t) => (t?.function ?? t)?.name)
2059
2136
  }
@@ -2100,9 +2177,43 @@ class Splitter {
2100
2177
  this.after = false
2101
2178
  return rest
2102
2179
  }
2180
+ // json reads the {"tool_calls": ...} object held in jsonBuf: the input
2181
+ // left after it, null while it is not whole, or false when the turn
2182
+ // ended in an error
2183
+ json(out, end) {
2184
+ const v = this.jsonBuf
2185
+ const e = jsonEnd(v)
2186
+ if (e < 0) {
2187
+ if (!end) return null
2188
+ this.jsonBuf = null
2189
+ out.push({ error: CUT_SHORT })
2190
+ return false
2191
+ }
2192
+ this.jsonBuf = null
2193
+ const calls = jsonCalls(v.slice(0, e))
2194
+ if (calls === false) {
2195
+ out.push({ error: UNREADABLE })
2196
+ return false
2197
+ }
2198
+ if (!calls) {
2199
+ this.text(out, v.slice(0, e))
2200
+ return v.slice(e)
2201
+ }
2202
+ this.sawTool = true
2203
+ for (const c of calls) out.push({ call: c })
2204
+ return v.slice(e).replace(/^\s+/, "")
2205
+ }
2103
2206
  feed(input) {
2104
2207
  const out = []
2105
2208
  while (input) {
2209
+ if (this.jsonBuf !== null) {
2210
+ this.jsonBuf += input
2211
+ const next = this.json(out, false)
2212
+ if (next === false) return out
2213
+ if (next === null) break
2214
+ input = next
2215
+ continue
2216
+ }
2106
2217
  if (!this.inCall) {
2107
2218
  let comb = this.textBuf + input
2108
2219
  this.textBuf = ""
@@ -2117,6 +2228,25 @@ class Splitter {
2117
2228
  }
2118
2229
  const i = comb.indexOf(CALL_OPEN)
2119
2230
  const x = this.tools.length ? comb.search(XML_AT) : -1
2231
+ const start = !this.sent || this.sent.endsWith("\n")
2232
+ let k = -1
2233
+ for (const jm of comb.matchAll(JSON_AT_ALL)) {
2234
+ const at = jm.index + jm[1].length
2235
+ if ((jm[1] || start) && !quoted(this.sent + comb.slice(0, at))) {
2236
+ k = at
2237
+ break
2238
+ }
2239
+ }
2240
+ if (k >= 0 && (i < 0 || k < i) && (x < 0 || k < x)) {
2241
+ if (k > 0) this.text(out, comb.slice(0, k))
2242
+ this.jsonBuf = comb.slice(k).replace(/^[ \t]+/, "")
2243
+ input = ""
2244
+ const next = this.json(out, false)
2245
+ if (next === false) return out
2246
+ if (next === null) break
2247
+ input = next
2248
+ continue
2249
+ }
2120
2250
  if (x >= 0 && (i < 0 || x < i)) {
2121
2251
  const next = this.bare(out, comb, x, false)
2122
2252
  if (next === false) return out
@@ -2134,6 +2264,7 @@ class Splitter {
2134
2264
  }
2135
2265
  const h = this.tools.length ? comb.search(XML_HOLD) : -1
2136
2266
  if (h >= 0) keep = Math.max(keep, comb.length - h)
2267
+ keep = Math.max(keep, jsonHold(comb, !this.sent || this.sent.endsWith("\n")))
2137
2268
  if (keep < comb.length) this.text(out, comb.slice(0, comb.length - keep))
2138
2269
  this.textBuf = comb.slice(comb.length - keep)
2139
2270
  break
@@ -2166,6 +2297,12 @@ class Splitter {
2166
2297
  return out
2167
2298
  }
2168
2299
  flush() {
2300
+ if (this.jsonBuf !== null) {
2301
+ const out = []
2302
+ const next = this.json(out, true)
2303
+ if (next) this.text(out, next)
2304
+ return out
2305
+ }
2169
2306
  if (this.inCall) {
2170
2307
  const body = this.callBuf
2171
2308
  this.inCall = false
@@ -4090,4 +4227,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
4090
4227
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
4091
4228
 
4092
4229
  // for tests
4093
- 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, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
4230
+ 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, qoderMessages, kimiModel, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
package/opencode2.mjs CHANGED
@@ -575,7 +575,31 @@ async function setupPlugin(ctx, fn, live) {
575
575
  }
576
576
  } catch {}
577
577
  })()
578
- void refresh()
578
+ // A plugin still reading its list in the background when the first read
579
+ // returned (agy-cli: `agy models` and a session probe take seconds, and
580
+ // the first read gets its static list) says so through
581
+ // provider.warming(): the list is read once more when that ends, once,
582
+ // and no later than a minute on.
583
+ const warmed = async () => {
584
+ let w
585
+ try {
586
+ w = typeof hooks.provider?.warming === "function" ? hooks.provider.warming() : null
587
+ } catch {
588
+ return
589
+ }
590
+ if (!w || typeof w.then !== "function") return
591
+ let timer
592
+ await Promise.race([
593
+ Promise.resolve(w).catch(() => {}),
594
+ new Promise((r) => {
595
+ timer = setTimeout(r, 60_000)
596
+ timer.unref?.()
597
+ }),
598
+ ])
599
+ clearTimeout(timer)
600
+ if (live.on) await refresh()
601
+ }
602
+ void refresh().then(warmed, () => {})
579
603
  }
580
604
 
581
605
  export async function setup(ctx, mod = v1) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.67",
3
+ "version": "0.2.69",
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",