loomy: a too-long refusal is reworded so magpie tries a longer window (#529)

When Loomy answers 400, 413 or 422 with a body that says the content is too long (内容太长了 / 内容过长), the plugin now rewords that body to 上下文超出长度限制, the phrase magpie's too-long matcher recognises. The status code is kept. magpie then treats the reply as a context-length refusal and tries a model with a longer window, where before it gave up on the request. The rewrite is in retryableRefusal() and runs on the loader's !res.ok path. fake.mjs gains chatRefusal. Version 0.1.0 -> 0.1.1.

Reviewed at 2bb41e0 (Mac mini, Bun 1.4.2, through mote-run, sandbox HOME):
- Repo suite (`HOME=$(mktemp -d) bun test`): 3813 pass, 8 skip, 0 fail.
- `bun scripts/check.mjs`: exit 0.
- Broken by hand: with retryableRefusal returning null, 3 loomy tests go red (the over-length Kimi-k2.6 chat test, the 400 rewrite, and the 413/422 cases). They pass again once it is restored.
This commit is contained in:
MYCF711
2026-10-30 23:06:49 +08:00
committed by GitHub
parent eee889afab
commit b177d69b83
4 changed files with 100 additions and 3 deletions
+3
View File
@@ -26,6 +26,7 @@ export function fakeLoomy() {
smsSent: null, // {phone, msgid}
logins: 0,
chatCalls: [],
chatRefusal: null, // set to an upstream message to answer 400 instead
firstLoginCalls: 0,
dailyBalance: 3000, // the day's first first-login refreshes it to 5000
recordsReads: 0,
@@ -38,6 +39,7 @@ export function fakeLoomy() {
state.smsSent = null
state.logins = 0
state.chatCalls = []
state.chatRefusal = null
state.firstLoginCalls = 0
state.dailyBalance = 3000
state.recordsReads = 0
@@ -119,6 +121,7 @@ export function fakeLoomy() {
if (!/charset\s*=\s*"?utf-8/i.test(ct)) return json(400, { code: "100009", desc: "content-type must name utf-8" })
const body = await req.json().catch(() => ({}))
state.chatCalls.push({ body })
if (state.chatRefusal) return json(400, { error: { message: state.chatRefusal, type: "invalid_request_error" } })
const reply = body.stream
? new Response(
[
+42 -2
View File
@@ -80,6 +80,41 @@ const expired = (message) => Object.assign(new Error(message), { signIn: "expire
const errorResponse = (status, message) =>
new Response(JSON.stringify({ error: { message } }), { status, headers: { "content-type": "application/json" } })
/**
* 「内容太长了,请精简输入或开启新对话」 does not name 「上下文」, so magpie
* versions before v0.1.2189 do not match it with `tooLongRe`
* (`internal/gateway/gateway.go`): the try is filed as an error that rests the
* account, the group's other members are never asked, and the whole turn fails.
*
* This rewrites the wording to one `tooLongRe` knows, so the agent compacts
* instead of the turn failing. The status code is passed through unchanged:
* whether the request is really over length or the upstream is merely busy is
* not something this plugin can tell from the body, and guessing wrong (turning
* a real overflow into a 502) makes magpie retry every account and end the turn
* in 502.
*
* v0.1.2189 and later already match this wording in the host, so this is a
* fallback for older hosts.
*
* ⚠ History: the 502 branch was removed on review. A fixed character threshold
* knows nothing about the model's own window (Kimi-k2.6 is 262,144 tokens, but
* 1.5M ASCII characters is already ~375k tokens), so it reported genuine
* over-length requests as upstream failures — magpie then retried every account
* and the turn ended in 502. This version only rewrites the wording; it never
* changes the status.
*/
const TOO_LONG_SAID = /内容太长(了)?|内容过长/
const TOO_LONG_REWORDED = "上下文超出长度限制"
function retryableRefusal(status, body) {
if (status !== 400 && status !== 413 && status !== 422) return null
if (!TOO_LONG_SAID.test(body)) return null
return new Response(body.replace(TOO_LONG_SAID, TOO_LONG_REWORDED), {
status,
headers: { "content-type": "application/json", "x-loomy-vendor-status": String(status) },
})
}
async function bodyText(input, init) {
const b = init.body ?? (input instanceof Request ? await input.clone().text() : undefined)
return typeof b === "string" ? b : new TextDecoder().decode(b)
@@ -394,8 +429,12 @@ export async function LoomyAuthPlugin({ client } = {}) {
return errorResponse(502, e?.message ?? String(e))
}
if (res.status === 401 || res.status === 403) return errorResponse(401, "Loomy 登录态已失效,请重新登录")
if (!res.ok)
return errorResponse(res.status, `Loomy 上游返回 ${res.status}: ${(await res.text().catch(() => "")).slice(0, 4096) || "无错误说明"}`)
if (!res.ok) {
const raw = await res.text().catch(() => "")
const refusal = retryableRefusal(res.status, raw)
if (refusal) return refusal
return errorResponse(res.status, `Loomy 上游返回 ${res.status}: ${raw.slice(0, 4096) || "无错误说明"}`)
}
// the answer streams through as it came (OpenAI-shaped)
return res
},
@@ -525,6 +564,7 @@ export async function LoomyAuthPlugin({ client } = {}) {
// for tests
export const _internal = {
retryableRefusal,
ID,
NAME,
STATIC_MODELS,
+54
View File
@@ -78,6 +78,20 @@ describe("chat", () => {
expect(fake.state.chatCalls[0].body.model).toBe("spark-x")
})
test("a genuinely over-length Kimi-k2.6 request still comes back 400", async () => {
// 150 万 ASCII 字符 ≈ 37.5 万 token,对 262,144 窗口的 Kimi-k2.6 是真超长。
// 旧实现按固定 200 万字符阈值判成「上游瞬时故障」并改成 502,magpie 会换号重试到整轮失败。
fake.state.chatRefusal = "内容太长了,请精简输入或开启新对话"
const loader = await plugin.auth.loader(getAuth)
const huge = "word ".repeat(300_000)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "kimi-k2.6", stream: false, messages: [{ role: "user", content: huge }] }),
})
expect(res.status).toBe(400)
expect(await res.text()).toContain("上下文超出长度限制")
})
test("reasoning effort folds to low/medium/high", async () => {
const loader = await plugin.auth.loader(getAuth)
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
@@ -295,3 +309,43 @@ describe("helpers", () => {
expect(_internal.splitRateSuffix("Model (free)")).toEqual({ name: "Model (free)", rate: undefined })
})
})
// ── 「内容太长了」的分流 ────────────────────────────────────────────────
//
// 上游这条 400 不含「上下文」:v0.1.2189 之前的 magpie 的 tooLongRe 认不出,
// 这笔 try 就被当成错误、账号被休息、组里其它成员一次没被问,整轮失败。
// 这里只改写文案(状态码不变),让旧宿主也能认成 overflow;
// v0.1.2189 起宿主自己认得,这是给旧宿主的兜底。
describe("a 400 that says the content is too long", () => {
// magpie `internal/gateway/gateway.go` 的 tooLongRe 中文两条 —— 逐字抄,改这里等于改契约
const tooLongRe = /上下文(长度)?(超|过长)|超(过|出)(了)?(模型)?(的)?(最大)?上下文/
const vendor = "内容太长了,请精简输入或开启新对话"
test("改写成 tooLongRe 认得的说法,状态码保持 400", async () => {
const out = _internal.retryableRefusal(400, JSON.stringify({ error: { message: vendor } }))
expect(out).not.toBeNull()
expect(out.status).toBe(400)
const body = await out.text()
expect(body).toMatch(tooLongRe)
expect(body).not.toContain("内容太长")
})
test("413 与 422 同办,状态码不变", async () => {
for (const status of [413, 422]) {
const out = _internal.retryableRefusal(status, vendor)
expect(out.status).toBe(status)
expect(await out.text()).toMatch(tooLongRe)
}
})
test("别的 400 不碰", () => {
expect(_internal.retryableRefusal(400, JSON.stringify({ error: { message: "invalid api key" } }))).toBeNull()
})
test("不是 400/413/422 的不碰(2xx 是 SSE 干流)", () => {
expect(_internal.retryableRefusal(200, vendor)).toBeNull()
expect(_internal.retryableRefusal(429, vendor)).toBeNull()
expect(_internal.retryableRefusal(500, vendor)).toBeNull()
})
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-loomy-auth",
"version": "0.1.0",
"version": "0.1.1",
"description": "OpenCode & Magpie provider plugin for Loomy (讯飞, loomyad.xunfei.cn): SMS sign-in, chat, models, the two point wallets and the daily first-login grant",
"type": "module",
"main": "./index.mjs",