autoclaw 0.2.9: a history the chat gateway can't read goes put right, not as a bare 500 (#437)

tmuer (plugins#437, Windows 11, autoclaw-cn, zaicoding_glm-5.3, plugin
0.2.8) had one dsh request in 48,799 fail after 65s with AutoClaw's 500
{"message":"parse response failed"}, in 0 / out 0. Sent straight to the
CN gateway with the plugin's headers, each of six body fragments got
that same 500, while a bad model name got 400 "非法模型".

Of the six, those an agent's history can hold are now put right before
the body goes, on both channels (tidyBody):
- a message's null or missing content goes as "";
- an earlier turn's reasoning_content is left off (AutoClaw's own client
  sends none back);
- a tool call's arguments that aren't a string go as their JSON, "{}"
  for none (the call is kept, so its tool result still pairs);
- tools that aren't a non-empty list are left off with tool_choice.
Not changed: an empty messages list (the plugin always puts the system
prompt first, so none reaches the gateway) and a tool schema's
parameters.type (no agent sends "nonsense"; the reporter found every
real schema shape answered 200). $schema and strict stay, as the
reporter's own tests had them answered. max_tokens is still left off:
the gateway turns it away.

Retry on a 500 is magpie's: a plugin's 500 is retryable there
(gateway/fallback.go retryable, status >= 500) and the next member of
the group is asked when there is one. The plugin doesn't retry it.

Run: packages/autoclaw `bun test` (39 pass); `bun scripts/check.mjs`
all green.
Broken by hand: index.mjs at HEAD with the new test: red.
Not tried: the real AutoClaw gateway (no AutoClaw account here); which
of the shapes the reporter's one 65s failure had is not in its record.
This commit is contained in:
yetone
2026-10-28 00:04:17 +08:00
parent 1a560ba618
commit 26502bf93e
3 changed files with 87 additions and 3 deletions
+36 -2
View File
@@ -194,6 +194,39 @@ async function refusedNotSignIn(res) {
return (await quotaRefusal(res)) ?? (await accountRefusal(res));
}
// tidyBody puts right, in place, what an agent's history can hold that
// AutoClaw's chat gateway can't read: it answers each with 500 {"message":
// "parse response failed"} and nothing more (plugins#437, tmuer, who
// reproduced each on the CN gateway). A message's null or missing content
// goes as "", an earlier turn's reasoning_content is left off (AutoClaw's
// own client sends none back), a tool call's arguments that aren't a
// string go as their JSON ("{}" for none), and tools that aren't a
// non-empty list are left off with their tool_choice. What already reads
// right is sent as it was.
function tidyBody(payload) {
if (Array.isArray(payload.messages)) {
payload.messages = payload.messages.map((m) => {
if (!m || typeof m !== "object") return m;
const out = { ...m };
if (out.content == null) out.content = "";
delete out.reasoning_content;
if (Array.isArray(out.tool_calls)) {
out.tool_calls = out.tool_calls.map((c) => {
const args = c?.function?.arguments;
if (!c?.function || typeof args === "string") return c;
return { ...c, function: { ...c.function, arguments: args == null ? "{}" : JSON.stringify(args) } };
});
}
return out;
});
}
if ("tools" in payload && !(Array.isArray(payload.tools) && payload.tools.length)) {
delete payload.tools;
delete payload.tool_choice;
}
return payload;
}
function autoclawRewriteBody(rawBody) {
let payload;
try {
@@ -203,6 +236,7 @@ function autoclawRewriteBody(rawBody) {
}
if (!payload || typeof payload !== "object" || !Array.isArray(payload.messages)) return null;
tidyBody(payload);
unflag(payload.messages);
const idx = payload.messages.findIndex((m) => m && m.role === "system");
@@ -640,7 +674,7 @@ function managedHeaders(token, model) {
}
function rewriteManagedBody(body) {
const payload = JSON.parse(String(body ?? "{}"));
const payload = tidyBody(JSON.parse(String(body ?? "{}")));
const model = typeof payload.model === "string" ? payload.model : "zai_auto";
const messages = Array.isArray(payload.messages) ? payload.messages : [];
payload.model = model;
@@ -1351,6 +1385,6 @@ export const _internal = {
platformTm, md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId,
dailySignin, signinStatus, maybeSignin, signinAccountKey, signinConfig, checkinOutcome, refreshTokens,
fetchUserProfile, accountDeviceId, accountDisplayName, startLocalOAuth,
FLAGGED, unflagged, unflag, autoclawRewriteBody, explained, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT,
FLAGGED, unflagged, unflag, tidyBody, rewriteManagedBody, autoclawRewriteBody, explained, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT,
guidePageHtml, callbackPageHtml,
};
+50
View File
@@ -845,3 +845,53 @@ test("usage and check-in of a banned account say the ban and keep the sign-in",
globalThis.fetch = realFetch
}
})
// plugins#437 (tmuer): AutoClaw's CN gateway answers 500 {"message":"parse
// response failed"} to each of these, the reporter's own fragments sent
// straight to it. What an agent's history can hold of them is put right
// before it goes; what reads right goes as it was.
test("the shapes AutoClaw's gateway can't read go put right, on both channels (#437)", async () => {
const realFetch = globalThis.fetch
const calls = []
globalThis.fetch = async (input, init) => {
calls.push({ url: String(input), body: JSON.parse(String(init?.body ?? "{}")) })
return Response.json({ choices: [{ message: { role: "assistant", content: "ok" } }] })
}
const history = [
{ role: "user", content: "hi" },
{ role: "assistant", content: null },
{ role: "assistant", content: "a", reasoning_content: "think" },
{ role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "exec" } }] },
{ role: "tool", tool_call_id: "c1", content: "done" },
{ role: "assistant", tool_calls: [{ id: "c2", type: "function", function: { name: "read", arguments: { path: "a.txt" } } }] },
{ role: "tool", tool_call_id: "c2", content: "x" },
{ role: "assistant", content: "", tool_calls: [{ id: "c3", type: "function", function: { name: "glob", arguments: "{\"p\":\"*\"}" } }] },
]
try {
for (const make of [AutoclawCnAuthPlugin, AutoclawAuthPlugin]) {
const hooks = await make({ client: { auth: { set: async () => {} } } })
const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" }))
for (const tools of ["x", []]) {
const res = await loader.fetch("x", { method: "POST", body: JSON.stringify({ model: "zaicoding_glm-5.3", tools, tool_choice: "auto", messages: history }) })
expect(res.status).toBe(200)
const { body } = calls.at(-1)
expect("tools" in body).toBe(false)
expect("tool_choice" in body).toBe(false)
const m = body.messages.slice(1) // after the system prompt the plugin puts first
expect(m[1]).toEqual({ role: "assistant", content: "" })
expect(m[2]).toEqual({ role: "assistant", content: "a" })
expect(m[3].content).toBe("")
expect(m[3].tool_calls[0].function).toEqual({ name: "exec", arguments: "{}" })
expect(m[5].tool_calls[0].function.arguments).toBe("{\"path\":\"a.txt\"}")
expect(m[7]).toEqual(history[7]) // read right: as it was
}
// a list of tools goes as it was
const tools = [{ type: "function", function: { name: "exec", parameters: { type: "object", properties: {} } } }]
await loader.fetch("x", { method: "POST", body: JSON.stringify({ model: "zaicoding_glm-5.3", tools, tool_choice: "auto", messages: [{ role: "user", content: "hi" }] }) })
expect(calls.at(-1).body.tools).toEqual(tools)
expect(calls.at(-1).body.tool_choice).toBe("auto")
}
} finally {
globalThis.fetch = realFetch
}
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-autoclaw-auth",
"version": "0.2.8",
"version": "0.2.9",
"description": "OpenCode provider plugin for AutoClaw (Zhipu OpenClaw): oversea web sign-in (Google/z.ai) and CN phone SMS, multi-account pool, credit balance and daily check-in",
"type": "module",
"main": "./index.mjs",