diff --git a/packages/autoclaw/README.md b/packages/autoclaw/README.md index ae4ef56..f1e527a 100644 --- a/packages/autoclaw/README.md +++ b/packages/autoclaw/README.md @@ -89,6 +89,7 @@ EOF | `signin` | `true` | 旧链路自动补签总开关(不影响原生 checkin) | | `signinOnUsage` | `false` | 查额度/刷新时自动补签(默认关,交给原生开关) | | `signinHour` | `null` | 限定补签小时:`8` = 仅当本地时间处于 8:00–8:59 时补签;`null` 不限 | +| `dump406` | `false` | 406 诊断落盘总开关(布尔值,`"false"` 字符串不算开)。开启后写入 `~/.config/magpie/autoclaw-406/`;`AUTOCLAW_406_DUMP_DIR` 环境变量可改址、且设了即开启(优先于本选项) | ## 对话网关与请求整形 @@ -102,6 +103,12 @@ AutoClaw 对话网关对请求形状有硬性要求,缺任一条都回 `406 No 国内版 `autoclaw-cn` 走 AutoClaw 2.1.0 managed gateway(`autoglm-acceleration-api.zhipuai.cn`);国际版 `autoclaw` 走海外直连网关(`autoglm-api.autoglm.ai`)。两者均已通过真实调用与推理验证。 +### 406 诊断落盘(默认关) + +406 的上游 body 是空的,magpie 只留 token 计数——排查"FLAGGED 没盖住的那句"需要被拒请求的原文。开启(`AUTOCLAW_406_DUMP_DIR` 环境变量,或插件选项 `"dump406": true`)后,每次 406 把**改写后实际发出的** system/developer 消息(含 `model` 字段,绝无 user/assistant/tool 内容)写成一份 JSON:文件 0600、目录 0700,只留最近 10 份(按写入时间轮转,只动 `autoclaw-406-*.json` 形状的文件,不动目录里其它任何文件)。 + +**注意隐私**:system prompt 并非不含个人信息——harness 会把工作目录、git 状态、项目指令文件、有时还有用户邮箱放进去。这是本地 0600、默认关闭的诊断文件,但开启前应当知情。`AUTOCLAW_406_DUMP_DIR` 可指向任意已有目录(轮转只删自己写的文件);默认目录在 Windows 的 GUI 进程(常无 `HOME`)下依次回退 `HOME` → `USERPROFILE` → `os.homedir()`。 + ## 已知行为 - 手机号账号只认国内 host(走 managed gateway,401/403 标记登录失效);z.ai/Google 账号只认国际 host(401/403 自动换侧重试,均拒绝时标记失效)。 diff --git a/packages/autoclaw/index.mjs b/packages/autoclaw/index.mjs index fc1e76a..d083610 100644 --- a/packages/autoclaw/index.mjs +++ b/packages/autoclaw/index.mjs @@ -18,7 +18,8 @@ */ import { createHash, randomBytes, randomUUID } from "node:crypto"; -import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; import { dirname } from "node:path"; import { Buffer } from "node:buffer"; import * as http from "node:http"; @@ -71,6 +72,11 @@ const FLAGGED = [ [/(?:Anthropic's |the )?Claude Agent SDK/gi, "the agent framework"], [/You are an AI agent powered by DeepSeek Harness/gi, "You are an AI agent powered by DeepSeek-Harness"], [/You are Claude Code/gi, "You are the Claude Code CLI"], + // 11-05: subagent prompts (fork/Explore) open "You are an agent for Claude + // Code, …" — ten 406 dumps that afternoon, all the same one line; the plain + // "You are Claude Code" rule above can't catch it. The "an agent for" part + // is generic and stays; only the harness name is masked the same way. + [/an agent for Claude Code(?! CLI)/gi, "an agent for the Claude Code CLI"], [/You are Codex/gi, "You are the Codex agent"], [/Codex CLI/gi, "Codex command-line tool"], [/You are opencode/gi, "You are the opencode agent"], @@ -81,10 +87,15 @@ const FLAGGED = [ [/operating inside pi, a coding agent harness/gi, "operating inside the pi coding agent harness"], // ZCode's opening line is "This conversation is powered by GLM-"; // the CN gateway refuses that wording with any GLM version, in any case, - // anywhere (#466: WorkBuddy renders it for a custom GLM model). A bare - // "GLM", "ChatGLM-5.3" or "the GLM-5.3 model" passes. The version stops - // before a sentence's closing period. + // anywhere (#466: WorkBuddy renders it for a custom GLM model). On 11-03 + // the same refusal caught the Fable harness's "You are powered by the + // model glm-5.3-flash[1m]." (42 x 406; probed: that line alone 406s, the + // rewritten form 200s). The version stops before a sentence's closing + // period, and a context-tier bracket ("[1m]") after it goes with it. Only + // forms with the GLM name are touched: a bare model name ("the model + // 4.6-turbo") is not one the gateway has been seen to refuse. [/This conversation is powered by GLM-([\w-]+(?:\.[\w-]+)*)/gi, "This conversation is powered by the GLM-$1 model"], + [/(powered by )the model GLM-([\w-]+(?:\.[\w-]+)*)(\s*\[[\w-]+\])?/gi, "$1the GLM-$2 model"], // WorkBuddy's CLI template still opens "You are CodeBuddy Code." (#466); // "You are CodeBuddy" alone passes. [/You are CodeBuddy Code/gi, "You are the CodeBuddy Code CLI"], @@ -138,8 +149,76 @@ function unflag(messages) { const REFUSED_HINT = "AutoClaw refuses chats whose system prompt carries another agent's identity line (Claude Code, Claude Agent SDK, Codex, opencode, Cursor, Cline, Qwen Code, ZCode, pi, DeepSeek Harness, Hermes Agent); this plugin rewrites the ones it knows, so an unknown one needs another provider in this group"; -async function explained(res) { +// A 406's diagnosis is the system prompt and nothing else. The dump is off +// by default — the body is the user's conversation, and a system prompt is +// not free of personal data either (harnesses put the working directory, git +// status, project instruction files and sometimes the user's email there) — +// and runs only when AUTOCLAW_406_DUMP_DIR names a directory, or the plugin's +// dump406 option is on (then the default directory below). What a dump holds +// is the rewritten system and developer messages only, never user, assistant +// or tool content, one file per refusal, the newest D406_KEEP kept, file mode +// 0600 in a 0700 directory. The dump directory may be any directory the user +// points at, so rotation touches only the dump's own files — every name +// matching the DUMP_NAME shape — never anything else's. Everything is +// best-effort: a dump that cannot be written never breaks the 406 it +// documents. +const D406_KEEP = 10; +// DUMP_NAME is the whole name a dump file goes by: rotation filters on this +// exact shape, so a user's own .json files in the same directory are never +// deleted (a plain *.json filter removed four of thirteen foreign files in a +// probe). +const DUMP_NAME = /^autoclaw-406-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[\w-]{8}-[\w-]+\.json$/; + +// The default dump directory, magpie's own config home. The fallbacks matter +// on Windows, where the GUI process often runs without HOME — 11-05's dumps +// landed at the CWD's drive root (C:\.config\…) until USERPROFILE backed it +// up. An empty variable is no value: XDG_CONFIG_HOME="" under ?? gave +// "/magpie/autoclaw-406"; os.homedir() is the last resort. +function dumpDefaultDir() { + const home = process.env.HOME || process.env.USERPROFILE || homedir(); + return `${process.env.XDG_CONFIG_HOME || `${home}/.config`}/magpie/autoclaw-406`; +} + +function dump406(sentBody, providerId, wantDump) { + try { + const dir = process.env.AUTOCLAW_406_DUMP_DIR || (wantDump === true ? dumpDefaultDir() : ""); + if (!dir) return; + let body; + try { + body = JSON.parse(typeof sentBody === "string" ? sentBody : JSON.stringify(sentBody)); + } catch { + return; + } + const messages = (Array.isArray(body?.messages) ? body.messages : []).filter( + (m) => m && (m.role === "system" || m.role === "developer"), + ); + if (!messages.length) return; + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const stamp = new Date().toISOString().replace(/[:.]/g, "-"); + // two refusals in the same millisecond are not the same request: the + // random tail keeps both files, and rotation goes by write time, not by + // name + writeFileSync( + `${dir}/autoclaw-406-${stamp}-${randomUUID().slice(0, 8)}-${providerId}.json`, + JSON.stringify({ model: body.model, messages }), + { mode: 0o600 }, + ); + const old = readdirSync(dir) + .filter((f) => DUMP_NAME.test(f)) + .map((f) => { + try { return { f, at: statSync(`${dir}/${f}`).mtimeMs }; } catch { return { f, at: 0 }; } + }) + .sort((a, b) => a.at - b.at) + .map((e) => e.f); + for (const f of old.slice(0, Math.max(0, old.length - D406_KEEP))) { + try { unlinkSync(`${dir}/${f}`); } catch {} + } + } catch {} +} + +async function explained(res, sentBody, providerId, options) { if (res.status < 400) return res; + if (res.status === 406 && sentBody) dump406(sentBody, providerId, options?.dump406); const headers = new Headers(res.headers); headers.delete("content-length"); headers.delete("content-encoding"); @@ -1055,7 +1134,7 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) fetch(`${host}${CHAT_PATH}`, { ...init, headers, body: nextBody, signal: init?.signal }); const res1 = await tryFetch(hosts[0]); - if (res1.status !== 401 && res1.status !== 403) return explained(res1); + if (res1.status !== 401 && res1.status !== 403) return explained(res1, nextBody, providerId, options); // a spent quota or a ban is the account's on every host: not asked again const spent1 = await refusedNotSignIn(res1); if (spent1) return spent1; @@ -1070,20 +1149,21 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "expired" }, }); } - return explained(res2); + return explained(res2, nextBody, providerId, options); } // The CN managed gateway is the AutoClaw 2.1.0 account-points // channel. It requires the system prefix and rejects max_tokens. const { payload, model } = rewriteManagedBody(init?.body); const headers = managedHeaders(accessToken, model); + const sentBody = JSON.stringify(payload); const res = await fetch(MANAGED_HOST + CN_CHAT_PATH, { ...init, method: "POST", headers, - body: JSON.stringify(payload), + body: sentBody, }); - if (res.status !== 401 && res.status !== 403) return explained(res); + if (res.status !== 401 && res.status !== 403) return explained(res, sentBody, providerId, options); const spent = await refusedNotSignIn(res); if (spent) return spent; try { res.body?.cancel?.(); } catch {} @@ -1768,5 +1848,6 @@ export const _internal = { balanceObserve, usageStatePath: () => usageStatePath ?? usageStatePathDefault(), setUsageStatePath, beijingDayOf, fetchUserProfile, accountDeviceId, accountDisplayName, startLocalOAuth, FLAGGED, unflagged, unflag, tidyBody, rewriteManagedBody, autoclawRewriteBody, explained, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT, + dumpDefaultDir, D406_KEEP, guidePageHtml, callbackPageHtml, }; diff --git a/packages/autoclaw/index.test.mjs b/packages/autoclaw/index.test.mjs index 189e70d..cdf2c37 100644 --- a/packages/autoclaw/index.test.mjs +++ b/packages/autoclaw/index.test.mjs @@ -2,14 +2,14 @@ // answer the upstream gives lands on one of its outcomes, and the plugin // factory registers both providers with every hook check.mjs looks for. import { expect, test } from "bun:test" -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs" +import { existsSync, mkdtempSync, mkdirSync, statSync, utimesSync, writeFileSync, readFileSync, readdirSync, rmSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { AutoclawAuthPlugin, AutoclawCnAuthPlugin, _internal } from "./index.mjs" const { checkinOutcome, signinConfig, bareToken, codeValue, tokenFields, refreshTokens, startLocalOAuth, - autoclawRewriteBody, unflag, unflagged, explained, FLAGGED, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT, + autoclawRewriteBody, unflag, unflagged, explained, FLAGGED, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT, dumpDefaultDir, } = _internal const b64url = (o) => Buffer.from(JSON.stringify(o)).toString("base64url") @@ -192,18 +192,28 @@ test("ZCode's and pi's identity lines are rewritten", () => { // opening line, and the CN gateway answers 406 for "This conversation is // powered by GLM-" in any case. The fixture is the reporter's line // byte for byte; each rewritten form was a 200 in the reporter's probes. +// 11-03: the same refusal caught the Fable harness's "You are powered by +// the model glm-5.3-flash[1m]." (42 x 406 in one day; probed: the line +// alone 406s, the rewritten form 200s), so a second rule rewrites that +// "powered by the model " shape, context-tier bracket and all. test("WorkBuddy's GLM opening line and CodeBuddy Code's identity line are rewritten", () => { const opening = "This conversation is powered by GLM-5.3 · AutoClaw 国内 (Zhipu)" expect(unflagged(opening)).toBe("This conversation is powered by the GLM-5.3 model · AutoClaw 国内 (Zhipu)") expect(unflagged("This conversation is powered by GLM-4")).toBe("This conversation is powered by the GLM-4 model") expect(unflagged("Intro.\nthis conversation is powered by glm-5.3.")).toBe("Intro.\nThis conversation is powered by the GLM-5.3 model.") expect(unflagged("This conversation is powered by GLM-4.5-Air.")).toBe("This conversation is powered by the GLM-4.5-Air model.") + // the Fable harness's model line: probed 406 as written, 200 rewritten + expect(unflagged("You are powered by the model glm-5.3-flash[1m].")).toBe("You are powered by the GLM-5.3-flash model.") + expect(unflagged("Powered by the model GLM-4.5-Air.")).toBe("Powered by the GLM-4.5-Air model.") // what the gateway takes stays as written for (const t of [ "This conversation is powered by GLM", "This conversation is powered by ChatGLM-5.3", "The conversation is powered by GLM-5.3", "You are powered by GLM-5.3", + "You are powered by the GLM-5.3-flash model", + "You are powered by the model claude-fable-5-1", + "powered by the model 4.6-turbo", ]) expect(unflagged(t)).toBe(t) expect(unflagged("You are CodeBuddy Code.")).toBe("You are the CodeBuddy Code CLI.") @@ -254,6 +264,55 @@ test("Hermes Agent's identity lines are rewritten", () => { expect(unflagged("You are a general-purpose AI agent called goose")).toBe("You are a general-purpose AI agent called goose") }) +// A table over every entry, so a later edit to one rule cannot silently +// break another (the 11-03 session's failing request carried three known +// lines at once, and only the missing one needed rewriting). Left side = +// what the harness opens with (or the reported line, byte for byte); +// right side = the form the gateway takes (probed, or the reporter's +// probe for that entry's original report). Idempotent on every row, so +// a cached prefix rewritten once stays put. +test("a system prompt carrying every known line at once comes out clean in one pass", () => { + const lines = [ + ["You are Claude Code, Anthropic's official CLI for Claude.", "You are the Claude Code CLI, Anthropic's official CLI for Claude."], + // 11-05: subagent prompts (fork/Explore) open with "an agent for", not + // "You are Claude Code"; ten dumps that afternoon all carried this one line + ["You are an agent for Claude Code, Anthropic's official CLI for Claude. Use the tools available to complete the task.", "You are an agent for the Claude Code CLI, Anthropic's official CLI for Claude. Use the tools available to complete the task."], + ["Intro.\nYou are an agent for Claude Code, dispatched mid-task.", "Intro.\nYou are an agent for the Claude Code CLI, dispatched mid-task."], + // the rewritten form must not grow a second CLI + ["an agent for Claude Code CLI, ask it", "an agent for Claude Code CLI, ask it"], + ["You are a Claude agent, built on Anthropic's Claude Agent SDK.", "You are a coding assistant."], + ["We build on the Claude Agent SDK; see docs.", "We build on the agent framework; see docs."], + ["You are an AI agent powered by DeepSeek Harness.", "You are an AI agent powered by DeepSeek-Harness."], + ["You are Codex, OpenAI's coding agent.", "You are the Codex agent, OpenAI's coding agent."], + ["Codex CLI is the tool you run.", "Codex command-line tool is the tool you run."], + ["You are opencode, an AI coding agent.", "You are the opencode agent, an AI coding agent."], + ["You are Cursor, a coding assistant.", "You are the Cursor agent, a coding assistant."], + ["You are Cline, a coding assistant.", "You are the Cline agent, a coding assistant."], + ["You are Qwen Code, an interactive CLI tool.", "You are the Qwen Code agent, an interactive CLI tool."], + ["You are ZCode, an interactive coding agent", "You are the ZCode agent, an interactive coding agent"], + ["operating inside pi, a coding agent harness.", "operating inside the pi coding agent harness."], + ["This conversation is powered by GLM-5.3 · AutoClaw 国内 (Zhipu)", "This conversation is powered by the GLM-5.3 model · AutoClaw 国内 (Zhipu)"], + ["You are powered by the model glm-5.3-flash[1m].", "You are powered by the GLM-5.3-flash model."], + ["You are CodeBuddy Code.", "You are the CodeBuddy Code CLI."], + ["You are Hermes Agent, built by Nous Research.", "You are the agent Hermes, built by Nous Research."], + ["You run on Hermes Agent (by Nous Research).", "You run on Hermes-Agent (by Nous Research)."], + ["You are Gemini CLI, an interactive CLI agent.", "You are the Gemini CLI agent, an interactive CLI agent."], + ["You are Kimi Code CLI, an interactive AI agent.", "You are the Kimi Code CLI agent, an interactive AI agent."], + ["You are goose, an autonomous AI agent.", "You are the goose agent, an autonomous AI agent."], + ] + for (const [inp, want] of lines) { + expect(unflagged(inp)).toBe(want) + // one pass of the whole table through one text, then that text again: + // every row stays where its own rewrite put it + expect(unflagged(unflagged(inp))).toBe(want) + } + // all lines at once, in one text: each rewritten, none twice + const all = lines.map(([inp]) => inp).join("\n") + const once = unflagged(all) + expect(unflagged(once)).toBe(once) + for (const [, want] of lines) expect(once).toContain(want) +}) + test("CN loader sends Hermes' system prompt without its identity line", async () => { const soul = "You are Hermes Agent, built by Nous Research. Be direct: match the length of your reply to the weight of the ask — a one-line question gets a one-line answer, and finished work gets a short report of what changed, what's verified, and what's left, never a replay of the process. No filler (\"Great question,\" \"I'd be happy to\"), no restating the request back, no re-summarizing what you already said, no narrating tool calls the user can see. Plain claims over adjectives; when unsure, say so plainly. Agree because it's right, not because the user said it. Depth is earned — give it when the user asks for detail, teaches, or the stakes demand it, not by default." const help = "You run on Hermes Agent (by Nous Research). When the user needs help with Hermes itself — configuring, setting up, using, extending, or troubleshooting it — or when you need to understand your own features, tools, or capabilities, the documentation at https://hermes-agent.nousresearch.com/docs is your authoritative reference and always holds the latest, most up-to-date information. The `hermes-agent` skill has the actual commands and proven workflows — load it with skill_view(name='hermes-agent') before configuring, modifying, or troubleshooting Hermes so you don't guess or invent workarounds." @@ -337,6 +396,177 @@ test("explained adds the way out to a 406 and keeps the sign-in", async () => { expect(await ok.text()).toBe('{"choices":[]}') }) +// 11-04: the reporter's capture tool truncated the failing body at 256 KB and +// the refused sentence sat past the cut. The plugin sees the body it actually +// sends, so a 406 can dump the rewritten system prompt for diagnosis. The +// body is the user's conversation, so the dump is opt-in (AUTOCLAW_406_DUMP_DIR, +// or the plugin's dump406 option) and holds the system and developer messages +// only — never user, assistant or tool content. The dump must never break the +// 406 it documents. +test("a 406 dumps the system prompt, opt-in; the oldest dumps rot away by write time", async () => { + const dir = join(mkdtempSync(tmpdir()), "autoclaw-406") + process.env.AUTOCLAW_406_DUMP_DIR = dir + try { + const refused406 = () => new Response(JSON.stringify({ error: { code: null, message: "406 Not Acceptable", type: "api_error" } }), { status: 406 }) + const line = "You are powered by the model glm-5.3-flash[1m]." + // overseas path: the loader passes the body it actually sent — the rewritten one + const raw = JSON.stringify({ model: "zai_glm-5.3-flash", messages: [{ role: "system", content: line }, { role: "user", content: "hi" }] }) + const sent = JSON.stringify(autoclawRewriteBody(raw)) + const refused = await explained(refused406(), sent, "autoclaw") + expect(refused.status).toBe(406) + const files = readdirSync(dir) + expect(files).toHaveLength(1) + const dumped = JSON.parse(readFileSync(join(dir, files[0]), "utf8")) + expect(dumped.model).toBe("zai_glm-5.3-flash") + // the refusal is about the system prompt: the user's words are not in it + expect(dumped.messages).toHaveLength(1) + expect(dumped.messages[0].role).toBe("system") + expect(dumped.messages[0].content).toBe(`${OFFICIAL_SYSTEM_PROMPT}\n\nYou are powered by the GLM-5.3-flash model.`) + expect(dumped.messages[0].content).not.toMatch(/powered by the model glm/i) + expect(JSON.stringify(dumped)).not.toContain('"hi"') + + // ten at most: an eleventh refusal drops the oldest. The pre-placed file's + // name sorts after every new one while its write time is older, so only + // rotation by write time removes it (a name sort would keep it and drop + // the newest dump instead). It carries the dump name's shape, since only + // the dump's own files rotate. + const old = join(dir, "autoclaw-406-9999-12-31T00-00-00-000Z-zzzzzzzz-autoclaw.json") + writeFileSync(old, JSON.stringify({ model: "m", messages: [{ role: "system", content: "pre-existing" }] })) + const past = new Date(Date.now() - 60_000) + utimesSync(old, past, past) + // the directory is the user's to point anywhere: foreign files — a + // settings.json, a non-dump anything — survive every refusal untouched + writeFileSync(join(dir, "settings.json"), "{}") + writeFileSync(join(dir, "keep-me.txt"), "not a dump") + for (let i = 0; i < 10; i++) { + await explained(refused406(), JSON.stringify({ model: "m", messages: [{ role: "system", content: `refusal ${i}` }] }), "autoclaw-cn") + } + const left = readdirSync(dir) + expect(left).toContain("settings.json") + expect(left).toContain("keep-me.txt") + expect(left).not.toContain("autoclaw-406-9999-12-31T00-00-00-000Z-zzzzzzzz-autoclaw.json") + const dumps = left.filter((f) => f.startsWith("autoclaw-406-")) + expect(dumps).toHaveLength(10) + const said = dumps.map((f) => JSON.parse(readFileSync(join(dir, f), "utf8")).messages[0].content).sort() + expect(said).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => `refusal ${i}`)) + + // the dump is 0600 in a 0700 directory (real modes exist off Windows) + if (process.platform !== "win32") { + const newest = dumps.at(-1) + expect(statSync(join(dir, newest)).mode & 0o777).toBe(0o600) + expect(statSync(dir).mode & 0o777).toBe(0o700) + } + + // a non-406 leaves no file, and a dump failure never breaks the 406 + await explained(new Response('{"x":1}', { status: 502 }), JSON.stringify({ model: "m", messages: [{ role: "system", content: "x" }] }), "autoclaw") + expect(readdirSync(dir)).toHaveLength(12) + // a directory that cannot be created: the path runs through a regular + // file (kept outside the dump dir, so the count above stays clean) + const blocker = join(mkdtempSync(tmpdir()), "blocker") + writeFileSync(blocker, "a file, not a directory") + process.env.AUTOCLAW_406_DUMP_DIR = join(blocker, "beneath") + const still = await explained(refused406(), JSON.stringify({ model: "m", messages: [{ role: "system", content: "x" }] }), "autoclaw") + expect(still.status).toBe(406) + expect(readdirSync(dir)).toHaveLength(12) + } finally { delete process.env.AUTOCLAW_406_DUMP_DIR } +}) + +// "dump406": "false" in plugins.json is the option OFF, not on: only a real +// boolean true arms the default directory. +test("the dump406 option takes a boolean, not any truthy value", async () => { + const fake = mkdtempSync(join(tmpdir(), "autoclaw-dumpopt-")) + const oldHome = process.env.HOME, oldProfile = process.env.USERPROFILE, oldXdg = process.env.XDG_CONFIG_HOME, oldDump = process.env.AUTOCLAW_406_DUMP_DIR + delete process.env.AUTOCLAW_406_DUMP_DIR + delete process.env.XDG_CONFIG_HOME + process.env.HOME = fake + process.env.USERPROFILE = fake + const refused406 = () => new Response("{}", { status: 406 }) + const body = JSON.stringify({ model: "m", messages: [{ role: "system", content: "opted" }] }) + try { + for (const bad of ["false", "true", 1, "yes"]) { + await explained(refused406(), body, "autoclaw", { dump406: bad }) + expect(existsSync(dumpDefaultDir())).toBe(false) + } + await explained(refused406(), body, "autoclaw", { dump406: true }) + expect(readdirSync(dumpDefaultDir())).toHaveLength(1) + } finally { + if (oldHome === undefined) delete process.env.HOME; else process.env.HOME = oldHome + if (oldProfile === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = oldProfile + if (oldXdg === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = oldXdg + if (oldDump === undefined) delete process.env.AUTOCLAW_406_DUMP_DIR; else process.env.AUTOCLAW_406_DUMP_DIR = oldDump + rmSync(join(fake, ".config"), { recursive: true, force: true }) + } +}) + +// Off by default: without the env and without the option, a 406 writes +// nothing anywhere. The dump406 option turns it on at the default directory. +test("a 406 dumps nothing unless the dump is opted into, and the option uses the default dir", async () => { + const fake = mkdtempSync(join(tmpdir(), "autoclaw-dumpopt-")) + const oldHome = process.env.HOME, oldProfile = process.env.USERPROFILE, oldXdg = process.env.XDG_CONFIG_HOME, oldDump = process.env.AUTOCLAW_406_DUMP_DIR + delete process.env.AUTOCLAW_406_DUMP_DIR + delete process.env.XDG_CONFIG_HOME + process.env.HOME = fake + process.env.USERPROFILE = fake + const refused406 = () => new Response("{}", { status: 406 }) + const body = JSON.stringify({ model: "m", messages: [{ role: "system", content: "opted" }] }) + try { + expect(existsSync(dumpDefaultDir())).toBe(false) + const refused = await explained(refused406(), body, "autoclaw") + expect(refused.status).toBe(406) + expect(existsSync(dumpDefaultDir())).toBe(false) + // the option arms the default directory + await explained(refused406(), body, "autoclaw", { dump406: true }) + expect(readdirSync(dumpDefaultDir())).toHaveLength(1) + // an empty XDG_CONFIG_HOME is no value: it falls through to HOME + process.env.XDG_CONFIG_HOME = "" + process.env.HOME = join(fake, "home2") + await explained(refused406(), body, "autoclaw", { dump406: true }) + expect(readdirSync(join(process.env.HOME, ".config/magpie/autoclaw-406"))).toHaveLength(1) + expect(existsSync(join(fake, "magpie/autoclaw-406"))).toBe(false) + } finally { + if (oldHome === undefined) delete process.env.HOME; else process.env.HOME = oldHome + if (oldProfile === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = oldProfile + if (oldXdg === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = oldXdg + if (oldDump === undefined) delete process.env.AUTOCLAW_406_DUMP_DIR; else process.env.AUTOCLAW_406_DUMP_DIR = oldDump + } +}) + +// the wiring, not just the helper: a 406 through either loader dumps the +// rewritten system prompt that loader actually sent +test("a 406 through either loader dumps the rewritten system prompt it sent", async () => { + const dir = join(mkdtempSync(tmpdir()), "autoclaw-406-wire") + process.env.AUTOCLAW_406_DUMP_DIR = dir + const realFetch = globalThis.fetch + globalThis.fetch = async () => new Response(JSON.stringify({ error: { code: null, message: "406 Not Acceptable", type: "api_error" } }), { status: 406 }) + try { + const overseas = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }) + const loader = await overseas.auth.loader(async () => ({ type: "oauth", access: "a1" })) + const body = JSON.stringify({ model: "zai_glm-5.3-flash", messages: [{ role: "system", content: "You are Claude Code, Anthropic's official CLI for Claude." }, { role: "user", content: "hi" }] }) + expect((await loader.fetch("x", { method: "POST", body })).status).toBe(406) + let files = readdirSync(dir) + expect(files).toHaveLength(1) + let dumped = JSON.parse(readFileSync(join(dir, files[0]), "utf8")) + expect(dumped.messages[0].content).toContain("You are the Claude Code CLI") + expect(dumped.messages[0].content).not.toMatch(/You are Claude Code/) + expect(JSON.stringify(dumped)).not.toContain('"hi"') + + // the CN managed channel dumps its own rewritten system too + rmSync(dir, { recursive: true, force: true }) + mkdirSync(dir, { recursive: true }) + const cn = await AutoclawCnAuthPlugin({ client: { auth: { set: async () => {} } } }) + const cnLoader = await cn.auth.loader(async () => ({ type: "oauth", access: "a1" })) + const cnBody = JSON.stringify({ model: "zaicoding_glm-5.3", messages: [{ role: "system", content: "You are a Claude agent, built on Anthropic's Claude Agent SDK." }, { role: "user", content: "hi" }] }) + expect((await cnLoader.fetch("x", { method: "POST", body: cnBody })).status).toBe(406) + files = readdirSync(dir) + expect(files).toHaveLength(1) + dumped = JSON.parse(readFileSync(join(dir, files[0]), "utf8")) + expect(dumped.messages[0].content).toBe(`${OFFICIAL_SYSTEM_PROMPT}\n\nYou are a coding assistant.`) + } finally { + globalThis.fetch = realFetch + delete process.env.AUTOCLAW_406_DUMP_DIR + } +}) + test("overseas loader().fetch drops X-Harness-Type and explains 406", async () => { const realFetch = globalThis.fetch const calls = [] @@ -629,6 +859,49 @@ test("CN preserves string and array system content", async () => { } finally { globalThis.fetch = realFetch } }) +// 11-04: the same Fable line reached the gateway in both system-content +// shapes the 11-03/11-04 captures show — one text part in an array, and a +// plain string — and both answered 406 with it in. Through both loaders the +// line that leaves is the probed 200 form, wherever it sits and whatever +// case it is in. +test("both channels rewrite the model line in a string or a text part, mid-prompt too", async () => { + const realFetch = globalThis.fetch + const line = "You are powered by the model glm-5.3-flash[1m]." + const want = "You are powered by the GLM-5.3-flash model." + for (const [factory, host] of [ + [makePlugin("autoclaw-cn"), "https://autoglm-acceleration-api.zhipuai.cn"], + [makePlugin("autoclaw"), "https://autoglm-api.autoglm.ai"], + ]) { + const calls = [] + globalThis.fetch = async (input, init) => { + calls.push({ url: String(input), body: JSON.parse(String(init?.body ?? "{}")) }) + return Response.json({ ok: true }) + } + try { + const hooks = await factory({ client: { auth: { set: async () => {} } } }, {}) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" })) + for (const content of [ + line, + [{ type: "text", text: line }], + [{ type: "text", text: "before" }, { type: "text", text: line }], + `intro\n\n${line}\n\nnext`, + "you are powered by the model glm-5.3-flash[1m].", + ]) { + await loader.fetch("x", { body: JSON.stringify({ model: "zai_glm-5.3-flash", messages: [{ role: "system", content }, { role: "user", content: "hi" }] }) }) + const sys = calls.at(-1).body.messages[0].content + const text = Array.isArray(sys) ? sys.map((p) => p.text).join("\n") : sys + expect(text).not.toMatch(/powered by (?!the GLM-[\w.-]+ model\b)/i) + // the lowercase fixture keeps its own case through the rewrite, and + // the gateway refuses case-insensitively — compare the wording only + expect(text.toLowerCase()).toContain(want.toLowerCase()) + expect(text.startsWith("You are AutoClaw. Answer the user directly and concisely.")).toBe(true) + // the user's own words still go as written + expect(calls.at(-1).body.messages[1].content).toBe("hi") + } + } finally { globalThis.fetch = realFetch } + } +}) + test("CN managed catalog uses variant objects and overseas keeps its limits", async () => { const factory = makePlugin("autoclaw-cn") const cn = await factory({ client: { auth: { set: async () => {} } } }, {}) diff --git a/packages/autoclaw/package.json b/packages/autoclaw/package.json index b6b591f..25b15d9 100644 --- a/packages/autoclaw/package.json +++ b/packages/autoclaw/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-autoclaw-auth", - "version": "0.2.15", + "version": "0.2.16", "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": "./opencode.mjs",