autoclaw 0.2.1: CN managed gateway, request shaping on both paths, OAuth guide opened by the host (#197)
Brings together #191 (CN managed gateway), #196 (request shaping and identity lines) and the #183 sign-in fix. - autoclaw-cn chat goes to AutoClaw 2.1.0's managed gateway (autoglm-acceleration-api.zhipuai.cn/autoclaw-proxy/proxy/autoclaw/chat/completions, on Zhipu's domain) with 2.1.0's headers and its four-model catalog. A 401/403 there marks the sign-in expired. - Both providers get the same request shaping: - the official one-sentence system prefix, merged into the caller's system message (string or array); - max_tokens and max_completion_tokens dropped; - other agents' identity lines in system/developer messages rewritten (FLAGGED/unflag, from #196); - no X-Harness-Type. - On the overseas path, a 406 explains itself and keeps the sign-in. Overseas chat now sends AutoClaw's own User-Agent instead of the host's. Its catalog drops zai_glm-5-turbo and the tdpsk models (400 upstream) and keeps the old limits. - Overseas OAuth: authorize returns the loopback guide URL once the listener is up, and the host opens it, so there is no shell spawn any more. Navigating to the authorization page no longer aborts the session. - autoclaw 0.2.0 -> 0.2.1. What was run at 1fe91be (reviewer): - bun test packages/autoclaw: 21 pass, 0 fail. bun scripts/check.mjs autoclaw: ok. git diff --check: clean. Merges cleanly onto main. - magpie plugin host (magpie main cb05dc2d1), sandbox HOME, with a copy whose three hosts point at a local fake: - overseas: authorize gave http://127.0.0.1:18432/, the guide returned 200, and /open-auth plus /auth/callback-google finished the sign-in; - CN: SMS sign-in worked; - streamed chat on both providers returned 200; - the fake received the prefix with "You are Claude Code" rewritten and no max_tokens on both paths; User-Agent AutoClaw/2.1.0 on CN and AutoClaw/1.18.1 overseas; no X-Harness-Type. - Not tried: real accounts or the live gateways (no credentials used). Co-authored-by: HuHong_Tao <3596843010@qq.com>
This commit is contained in:
@@ -9,12 +9,13 @@
|
||||
| `autoclaw` | Google / z.ai 网页 OAuth | `autoglm-api.autoglm.ai` | `autoclaw/zai_auto` 等 |
|
||||
| `autoclaw-cn` | 手机验证码(+86) | `autoglm-api.zhipuai.cn` | `autoclaw-cn/zai_auto` 等 |
|
||||
|
||||
两个供应商都支持 magpie 的多账号、故障切换、token 自动轮换与积分余额显示。模型为带前缀的 routeModelId(`zai_` 智谱 / `zaicoding_` coding plan / `tdpsk_` 豆包 DeepSeek):
|
||||
两个供应商都支持 magpie 的多账号、故障切换、token 自动轮换与积分余额显示。实测可用的 4 个在线模型为带前缀的 routeModelId(`zai_` 智谱 / `zaicoding_` coding plan):
|
||||
|
||||
- `zai_auto` / `zai_auto-fast`(自动路由,推荐默认)
|
||||
- `zai_glm-5.3-flash` / `zai_glm-5-turbo`
|
||||
- `zaicoding_glm-5.3`
|
||||
- `tdpsk_deepseek-v4-flash-202605` / `tdpsk_deepseek-v4-pro-202606`
|
||||
- `zai_auto` / `zai_auto-fast`(自动路由,支持 reasoning variants:low / high / max)
|
||||
- `zai_glm-5.3-flash`(极速推理,支持 reasoning variants)
|
||||
- `zaicoding_glm-5.3`(GLM-5.3 编程专项,支持 reasoning variants)
|
||||
|
||||
> 注:旧版中的 `zai_glm-5-turbo` 以及豆包 DeepSeek 映射 `tdpsk_deepseek-v4-flash-202605`、`tdpsk_deepseek-v4-pro-202606` 已被上游下线(调用均返回 `400 非法模型`),本版本已从模型列表中移除。
|
||||
|
||||
## 安装
|
||||
|
||||
@@ -72,9 +73,19 @@ EOF
|
||||
| `signinOnUsage` | `false` | 查额度/刷新时自动补签(默认关,交给原生开关) |
|
||||
| `signinHour` | `null` | 限定补签小时:`8` = 仅当本地时间处于 8:00–8:59 时补签;`null` 不限 |
|
||||
|
||||
## 对话网关与请求整形
|
||||
|
||||
AutoClaw 对话网关对请求形状有硬性要求,缺任一条都回 `406 Not Acceptable` 且 body 为空:
|
||||
- **官方 system 前缀**:必须以 `You are AutoClaw. Answer the user directly and concisely.` 开头(插件会自动合并进 caller 已有的 system 消息,无 system 时补一条最小 system)
|
||||
- **删除 max_tokens**:网关拒收 `max_tokens` / `max_completion_tokens`,插件会在发送前自动剔除
|
||||
- **不发送 X-Harness-Type**:上游收到 `X-Harness-Type` 即报 406,已删除该残留请求头
|
||||
- **改写外部 Harness 身份声明**:上游拦截 system 中包含的外部 agent 身份句(如 `You are Codex`、`You are Claude Code` 等),插件的 `unflag` 会自动将其替换为兼容措辞,避免 406 拦截
|
||||
|
||||
国内版 `autoclaw-cn` 走 AutoClaw 2.1.0 managed gateway(`autoglm-acceleration-api.zhipuai.cn`);国际版 `autoclaw` 走海外直连网关(`autoglm-api.autoglm.ai`)。两者均已通过真实调用与推理验证。
|
||||
|
||||
## 已知行为
|
||||
|
||||
- 手机号账号只认国内 host、z.ai/Google 账号只认国际 host;对话 fetch 已内置 401/403 自动换侧重试。
|
||||
- 手机号账号只认国内 host(走 managed gateway,401/403 标记登录失效);z.ai/Google 账号只认国际 host(401/403 自动换侧重试,均拒绝时标记失效)。
|
||||
- 上游模型白名单随版本变化,模型下线时上游返回 `400 非法模型`(原样透传错误消息)。
|
||||
- refresh token 与 AutoClaw 桌面端**共用会互踢**(双方都轮换),插件账号请勿同时在桌面端登录。
|
||||
- 上游偶发改协议时,`CLIENT_VERSION` / 端点路径可能需要随官方客户端更新。
|
||||
@@ -82,3 +93,9 @@ EOF
|
||||
## 免责声明
|
||||
|
||||
本包为**非官方**社区插件,与智谱 AI / OpenClaw / AutoClaw 无任何关联。实现基于对官方客户端行为的逆向分析与实测,仅供个人学习研究;使用产生的账号风险由使用者自行承担。上游协议变更可能导致插件随时失效。
|
||||
|
||||
### Local sign-in page ownership
|
||||
|
||||
The plugin waits for the loopback listener before returning its guide URL. Magpie/OpenCode opens that URL; the callback does not launch a second browser through a shell. Cancelled or expired sessions release their port; begin a new sign-in rather than reusing the old URL.
|
||||
|
||||
The guide distinguishes an intentional authorization redirect from the user closing the page. The redirect must keep the loopback callback alive; closing a guide before authorization still cancels it. The guide reports a disconnected or expired session explicitly.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { test, expect } from 'bun:test';
|
||||
import vm from 'node:vm';
|
||||
import { _internal } from './index.mjs';
|
||||
function guide(fail=false){
|
||||
const html=_internal.guidePageHtml('google');
|
||||
const start=html.indexOf('let leavingForAuthorization');
|
||||
const at=html.indexOf('document.getElementById("goBtn").addEventListener');
|
||||
const script=html.slice(start>=0?start:at,html.indexOf('boot().catch'));
|
||||
const listeners={},elements=new Map(),sent=[];
|
||||
const ctx={Blob,document:{getElementById(id){if(!elements.has(id))elements.set(id,{style:{},addEventListener(type,fn){listeners[id+':'+type]=fn}});return elements.get(id)}},window:{addEventListener(type,fn){listeners[type]=fn}},navigator:{sendBeacon(url){sent.push(url)}},fetch:async()=>{if(fail)throw Error('connection refused');return{json:async()=>({url:'https://accounts.google.test/authorize'})}},msg(){},setTimeout(fn){fn()},location:{}};
|
||||
Object.defineProperty(ctx.location,'href',{set(){listeners.beforeunload?.()}});
|
||||
vm.runInNewContext(script,ctx);
|
||||
return{sent,listeners,elements};
|
||||
}
|
||||
test('leaving the guide for authorization must not abort the localhost callback',async()=>{
|
||||
const x=guide();await x.listeners['goBtn:click']();expect(x.sent).toEqual([]);
|
||||
});
|
||||
test('closing a guide before authorization still cancels its own session',()=>{
|
||||
const x=guide();x.listeners.beforeunload();expect(x.sent).toEqual(['/abort']);
|
||||
});
|
||||
test('an expired or disconnected guide restores its action instead of navigating',async()=>{
|
||||
const x=guide(true);await x.listeners['goBtn:click']();expect(x.elements.get('goBtn').disabled).toBe(false);expect(x.sent).toEqual([]);
|
||||
});
|
||||
+236
-56
@@ -21,13 +21,14 @@ import { createHash, randomBytes } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { Buffer } from "node:buffer";
|
||||
import * as http from "node:http";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const APP_ID = "100003";
|
||||
const APP_KEY = "38d2391985e2369a5fb8227d8e6cd5e5";
|
||||
const PRODUCT = "autoclaw";
|
||||
const CHANNEL = "AutoClaw4";
|
||||
const CLIENT_VERSION = "1.18.1";
|
||||
const CN_CHANNEL = "AutoClaw26";
|
||||
const CN_CLIENT_VERSION = "2.1.0";
|
||||
const PLATFORM_TM = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : "linux";
|
||||
const USER_AGENT = `AutoClaw/${CLIENT_VERSION} (${PLATFORM_TM}-${process.arch})`;
|
||||
|
||||
@@ -35,26 +36,141 @@ const GLOBAL_HOST = "https://autoglm-api.autoglm.ai";
|
||||
const CN_HOST = "https://autoglm-api.zhipuai.cn";
|
||||
|
||||
const CHAT_PATH = "/autoclaw-proxy/proxy/autoclaw/v1/chat/completions";
|
||||
const CN_CHAT_PATH = "/autoclaw-proxy/proxy/autoclaw/chat/completions";
|
||||
const MANAGED_HOST = "https://autoglm-acceleration-api.zhipuai.cn";
|
||||
const OFFICIAL_SYSTEM_PROMPT = 'You are AutoClaw. Answer the user directly and concisely.';
|
||||
const WALLETS_PATH = `/agent-assetmgr/api/v2/wallets?biz_app_id=${PRODUCT}`;
|
||||
|
||||
const FLAGGED = [
|
||||
[/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"],
|
||||
[/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"],
|
||||
[/You are Cursor/gi, "You are the Cursor agent"],
|
||||
[/You are Cline/gi, "You are the Cline agent"],
|
||||
[/You are Qwen Code/gi, "You are the Qwen Code agent"],
|
||||
];
|
||||
|
||||
function unflagged(text) {
|
||||
for (const [re, to] of FLAGGED) text = text.replace(re, to);
|
||||
return text;
|
||||
}
|
||||
|
||||
function unflag(messages) {
|
||||
let changed = false;
|
||||
for (const m of messages) {
|
||||
if (!m || (m.role !== "system" && m.role !== "developer")) continue;
|
||||
if (typeof m.content === "string") {
|
||||
const t = unflagged(m.content);
|
||||
if (t !== m.content) {
|
||||
m.content = t;
|
||||
changed = true;
|
||||
}
|
||||
} else if (Array.isArray(m.content)) {
|
||||
for (const part of m.content) {
|
||||
if (typeof part?.text !== "string") continue;
|
||||
const t = unflagged(part.text);
|
||||
if (t !== part.text) {
|
||||
part.text = t;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
const REFUSED_HINT =
|
||||
"AutoClaw refuses chats whose system prompt carries another agent's identity line (Claude Code, Codex, opencode, Cursor, Cline, Qwen Code, DeepSeek Harness); this plugin rewrites the ones it knows, so an unknown one needs another provider in this group";
|
||||
|
||||
async function explained(res) {
|
||||
if (res.status < 400) return res;
|
||||
const headers = new Headers(res.headers);
|
||||
headers.delete("content-length");
|
||||
headers.delete("content-encoding");
|
||||
headers.set("X-Magpie-Sign-In", "kept");
|
||||
const text = await res.text().catch(() => "");
|
||||
if (res.status !== 406) return new Response(text, { status: res.status, statusText: res.statusText, headers });
|
||||
let said = "";
|
||||
try {
|
||||
said = JSON.parse(text)?.error?.message ?? "";
|
||||
} catch {}
|
||||
headers.set("content-type", "application/json");
|
||||
return new Response(
|
||||
JSON.stringify({ error: { message: `${said || "406 Not Acceptable"} — ${REFUSED_HINT}`, type: "permission_error", code: null } }),
|
||||
{ status: res.status, statusText: res.statusText, headers },
|
||||
);
|
||||
}
|
||||
|
||||
function autoclawRewriteBody(rawBody) {
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!payload || typeof payload !== "object" || !Array.isArray(payload.messages)) return null;
|
||||
|
||||
unflag(payload.messages);
|
||||
|
||||
const idx = payload.messages.findIndex((m) => m && m.role === "system");
|
||||
if (idx >= 0) {
|
||||
const cur = payload.messages[idx].content;
|
||||
if (typeof cur === "string") {
|
||||
if (!cur.startsWith(OFFICIAL_SYSTEM_PROMPT)) {
|
||||
payload.messages[idx] = { ...payload.messages[idx], content: `${OFFICIAL_SYSTEM_PROMPT}\n\n${cur}` };
|
||||
}
|
||||
} else if (Array.isArray(cur)) {
|
||||
payload.messages[idx] = {
|
||||
...payload.messages[idx],
|
||||
content: [{ type: "text", text: OFFICIAL_SYSTEM_PROMPT }, ...cur],
|
||||
};
|
||||
} else {
|
||||
payload.messages[idx] = { ...payload.messages[idx], content: OFFICIAL_SYSTEM_PROMPT };
|
||||
}
|
||||
} else {
|
||||
payload.messages = [{ role: "system", content: OFFICIAL_SYSTEM_PROMPT }, ...payload.messages];
|
||||
}
|
||||
|
||||
delete payload.max_tokens;
|
||||
delete payload.max_completion_tokens;
|
||||
return payload;
|
||||
}
|
||||
|
||||
|
||||
const OAUTH_EXPIRY_SKEW_MS = 10 * 60 * 1000;
|
||||
const FALLBACK_EXPIRES_IN_S = 5 * 3600;
|
||||
/** 本地 OAuth 会话上限:callback 的等待是 5 分钟;宿主不调 callback 时兜底释放端口。 */
|
||||
const OAUTH_SESSION_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
const VARIANTS = Object.fromEntries(["low", "high", "max"].map((effort) => [effort, { reasoningEffort: effort }]));
|
||||
|
||||
/** 模型清单:键 = magpie 里显示的 id;值里的 id = 上游接受的 routeModelId。 */
|
||||
function autoclawModels() {
|
||||
function overseasModels() {
|
||||
// Live verified overseas catalog: zai_glm-5-turbo and tdpsk_deepseek-* are gone upstream (400 非法模型).
|
||||
return {
|
||||
"zai_auto": { name: "GLM Auto (路由)", id: "zai_auto", limit: { context: 200000, output: 32000 }, reasoning: true, tool_call: true },
|
||||
"zai_auto-fast": { name: "GLM Auto Fast", id: "zai_auto-fast", limit: { context: 200000, output: 32000 }, reasoning: true, tool_call: true },
|
||||
"zai_glm-5.3-flash": { name: "GLM-5.3 Flash", id: "zai_glm-5.3-flash", limit: { context: 1000000, output: 32000 }, reasoning: true, tool_call: true },
|
||||
"zai_glm-5-turbo": { name: "GLM-5 Turbo", id: "zai_glm-5-turbo", limit: { context: 200000, output: 32000 }, reasoning: true, tool_call: true },
|
||||
"zaicoding_glm-5.3": { name: "GLM-5.3 Coding", id: "zaicoding_glm-5.3", limit: { context: 1000000, output: 131072 }, reasoning: true, tool_call: true },
|
||||
"tdpsk_deepseek-v4-flash-202605": { name: "DeepSeek V4 Flash", id: "tdpsk_deepseek-v4-flash-202605", limit: { context: 1000000, output: 384000 }, reasoning: true, tool_call: true },
|
||||
"tdpsk_deepseek-v4-pro-202606": { name: "DeepSeek V4 Pro", id: "tdpsk_deepseek-v4-pro-202606", limit: { context: 1000000, output: 384000 }, reasoning: true, tool_call: true },
|
||||
"zai_glm-5.3-flash": { name: "GLM-5.3 Flash", id: "zai_glm-5.3-flash", limit: { context: 1000000, output: 32000 }, reasoning: true, tool_call: true },
|
||||
};
|
||||
}
|
||||
|
||||
/** The CN live managed-model catalog, saved by AutoClaw 2.1.0. */
|
||||
function managedModels() {
|
||||
return {
|
||||
"zai_auto": { name: "Auto", id: "zai_auto", limit: { context: 1048576, output: 393216 }, reasoning: true, attachment: true, tool_call: true, variants: VARIANTS },
|
||||
"zai_auto-fast": { name: "Auto-Fast", id: "zai_auto-fast", limit: { context: 1048576, output: 131072 }, reasoning: true, attachment: true, tool_call: true, variants: VARIANTS },
|
||||
"zaicoding_glm-5.3": { name: "GLM-5.3", id: "zaicoding_glm-5.3", limit: { context: 1048576, output: 307200 }, reasoning: true, attachment: false, tool_call: true, variants: VARIANTS },
|
||||
"zai_glm-5.3-flash": { name: "GLM-5.3-Flash", id: "zai_glm-5.3-flash", limit: { context: 1048576, output: 131072 }, reasoning: true, attachment: true, tool_call: true, variants: VARIANTS },
|
||||
};
|
||||
}
|
||||
|
||||
function autoclawModels(providerId = "autoclaw") {
|
||||
return providerId === "autoclaw-cn" ? managedModels() : overseasModels();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 基础工具
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -371,6 +487,48 @@ async function refreshTokens(refreshToken, preferredHosts) {
|
||||
// 插件工厂
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function managedHeaders(token, model) {
|
||||
const ts = String(Math.floor(Date.now() / 1000));
|
||||
const rid = randomHex(16);
|
||||
const headers = new Headers(bizHeaders());
|
||||
headers.set("Accept", "application/json");
|
||||
headers.set("User-Agent", `AutoClaw/${CN_CLIENT_VERSION} (${PLATFORM_TM}-${process.arch})`);
|
||||
headers.set("X-Channel", CN_CHANNEL);
|
||||
headers.set("X-Version", CN_CLIENT_VERSION);
|
||||
headers.set("X-Trace-Id", rid);
|
||||
headers.set("X-Request-Id", rid);
|
||||
headers.set("X-Request-Model", model);
|
||||
headers.set("X-Client-Type", "pc");
|
||||
headers.set("x_trace_id", "autoclaw-desktop");
|
||||
headers.set("X-Agent-Id", "main");
|
||||
headers.set("X-Authorization", `Bearer ${bareToken(token)}`);
|
||||
headers.delete("Authorization");
|
||||
return headers;
|
||||
}
|
||||
|
||||
function rewriteManagedBody(body) {
|
||||
const payload = 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;
|
||||
// The gateway rejects max_tokens, but accepts both streaming modes.
|
||||
delete payload.max_tokens;
|
||||
delete payload.max_completion_tokens;
|
||||
unflag(messages);
|
||||
const [first, ...rest] = messages;
|
||||
if (first?.role === "system") {
|
||||
// Prefix inside the caller's existing system message avoids competing
|
||||
// system roles while satisfying the gateway's AutoClaw check.
|
||||
const content = Array.isArray(first.content)
|
||||
? [{ type: "text", text: OFFICIAL_SYSTEM_PROMPT }, ...first.content]
|
||||
: `${OFFICIAL_SYSTEM_PROMPT}\n\n${String(first.content ?? "")}`;
|
||||
payload.messages = [{ ...first, content }, ...rest];
|
||||
} else {
|
||||
payload.messages = [{ role: "system", content: OFFICIAL_SYSTEM_PROMPT }, ...messages];
|
||||
}
|
||||
return { payload, model };
|
||||
}
|
||||
|
||||
function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) {
|
||||
return async ({ client }, options) => ({
|
||||
config: async (cfg) => {
|
||||
@@ -379,7 +537,7 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
|
||||
name: providerName,
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
api: homeHost,
|
||||
models: autoclawModels(),
|
||||
models: autoclawModels(providerId),
|
||||
};
|
||||
},
|
||||
|
||||
@@ -413,40 +571,67 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
|
||||
return {
|
||||
baseURL: homeHost,
|
||||
async fetch(input, init) {
|
||||
const headers = new Headers(init?.headers);
|
||||
headers.set("X-Authorization", `Bearer ${accessToken}`);
|
||||
headers.set("X-Client-Type", "pc");
|
||||
headers.set("X-Product", PRODUCT);
|
||||
headers.set("X-Harness-Type", "zcode");
|
||||
headers.set("X-Tm", PLATFORM_TM);
|
||||
headers.set("X-Version", CLIENT_VERSION);
|
||||
headers.set("X-Lang", "zh-CN");
|
||||
headers.set("X-Channel", CHANNEL);
|
||||
headers.set("x_trace_id", "autoclaw-desktop");
|
||||
headers.delete("Authorization");
|
||||
if (providerId !== "autoclaw-cn") {
|
||||
const headers = new Headers(init?.headers);
|
||||
headers.set("User-Agent", USER_AGENT);
|
||||
headers.set("X-Authorization", `Bearer ${accessToken}`);
|
||||
headers.set("X-Client-Type", "pc");
|
||||
headers.set("X-Product", PRODUCT);
|
||||
headers.delete("X-Harness-Type");
|
||||
headers.set("X-Tm", PLATFORM_TM);
|
||||
headers.set("X-Version", CLIENT_VERSION);
|
||||
headers.set("X-Lang", "zh-CN");
|
||||
headers.set("X-Channel", CHANNEL);
|
||||
headers.set("x_trace_id", "autoclaw-desktop");
|
||||
headers.delete("Authorization");
|
||||
|
||||
let routeModel = "";
|
||||
try {
|
||||
const body = JSON.parse(String(init?.body ?? "{}"));
|
||||
routeModel = String(body.model ?? "");
|
||||
} catch { /* 保持空 */ }
|
||||
if (routeModel) headers.set("X-Request-Model", routeModel);
|
||||
headers.set("X-Request-Id", randomHex(16));
|
||||
let routeModel = "";
|
||||
let nextBody = init?.body;
|
||||
const rewritten = autoclawRewriteBody(init?.body);
|
||||
if (rewritten) {
|
||||
routeModel = String(rewritten.model ?? "");
|
||||
nextBody = JSON.stringify(rewritten);
|
||||
headers.delete("content-length");
|
||||
} else {
|
||||
try {
|
||||
routeModel = String(JSON.parse(String(init?.body ?? "{}")).model ?? "");
|
||||
} catch {}
|
||||
}
|
||||
if (routeModel) headers.set("X-Request-Model", routeModel);
|
||||
headers.set("X-Request-Id", randomHex(16));
|
||||
|
||||
const tryFetch = (host) =>
|
||||
fetch(`${host}${CHAT_PATH}`, { ...init, headers, signal: init?.signal });
|
||||
const tryFetch = (host) =>
|
||||
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 res1;
|
||||
const res2 = await tryFetch(hosts[1]);
|
||||
if (res2.status === 401 || res2.status === 403) {
|
||||
try { res2.body?.cancel?.(); } catch {}
|
||||
return new Response(JSON.stringify({ error: { message: "AutoClaw 登录已失效(两个 host 均拒绝该 token)", type: "invalid_request_error" } }), {
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "expired" },
|
||||
});
|
||||
const res1 = await tryFetch(hosts[0]);
|
||||
if (res1.status !== 401 && res1.status !== 403) return explained(res1);
|
||||
const res2 = await tryFetch(hosts[1]);
|
||||
if (res2.status === 401 || res2.status === 403) {
|
||||
try { res2.body?.cancel?.(); } catch {}
|
||||
return new Response(JSON.stringify({ error: { message: "AutoClaw 登录已失效(两个 host 均拒绝该 token)", type: "invalid_request_error" } }), {
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "expired" },
|
||||
});
|
||||
}
|
||||
return explained(res2);
|
||||
}
|
||||
return res2;
|
||||
|
||||
// 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 res = await fetch(MANAGED_HOST + CN_CHAT_PATH, {
|
||||
...init,
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (res.status !== 401 && res.status !== 403) return res;
|
||||
try { res.body?.cancel?.(); } catch {}
|
||||
return new Response(JSON.stringify({ error: { message: "AutoClaw 登录已失效", type: "invalid_request_error" } }), {
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "expired" },
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
@@ -632,7 +817,7 @@ const overseaOAuthMethod = {
|
||||
* url = 本地引导页(滑块在内完成,之后自动跳授权页);callback 挂起等 code,
|
||||
* 拿到后直连上游换 token。
|
||||
*/
|
||||
async function startLocalOAuth(vendor, openFn = openBrowser) {
|
||||
async function startLocalOAuth(vendor, openFn) {
|
||||
const deviceId = newDeviceId();
|
||||
const state = {
|
||||
captchaReceipt: null,
|
||||
@@ -803,6 +988,10 @@ async function startLocalOAuth(vendor, openFn = openBrowser) {
|
||||
server.listen(fixedPort, "127.0.0.1", () => resolve(fixedPort));
|
||||
});
|
||||
|
||||
// Do not hand the host a page until the listener is ready. The host owns
|
||||
// opening authorization URLs, including Windows and remote web sessions.
|
||||
await serverReady;
|
||||
|
||||
// 会话最长 OAUTH_SESSION_TIMEOUT_MS:宿主可能永远不调 callback(用户在 magpie
|
||||
// 里取消),定时器负责关服务器、释放官方 TokenServer 端口。
|
||||
let sessionDone = false;
|
||||
@@ -822,15 +1011,15 @@ async function startLocalOAuth(vendor, openFn = openBrowser) {
|
||||
sessionTimer.unref?.();
|
||||
|
||||
return {
|
||||
url: "", // 由 callback 里自行开浏览器(本地引导页),宿主不重复打开
|
||||
instructions: `已打开本地引导页(未自动打开时手动访问 http://127.0.0.1:${fixedPort}/ ):请完成滑块验证并登录授权,完成后自动返回 magpie。`,
|
||||
url: `http://127.0.0.1:${fixedPort}/`, // The host opens this only after listen succeeds.
|
||||
instructions: `本地登录页已就绪(未自动打开时手动访问 http://127.0.0.1:${fixedPort}/ ):请完成滑块验证并登录授权,完成后自动返回 magpie。`,
|
||||
method: "auto",
|
||||
async callback() {
|
||||
const port = await serverReady;
|
||||
const guide = `http://127.0.0.1:${port}/`;
|
||||
const redirectUri = `http://localhost:${port}/auth/callback-${vendor}`;
|
||||
try {
|
||||
openFn(guide);
|
||||
if (openFn) openFn(guide); // Optional test hook; production uses the host URL.
|
||||
const code = await waitFor(5 * 60 * 1000, "浏览器登录");
|
||||
const res = await callEnvelope(`/userapi/overseasv1/${vendor}-oauth-login`, {
|
||||
method: "POST",
|
||||
@@ -859,19 +1048,6 @@ async function startLocalOAuth(vendor, openFn = openBrowser) {
|
||||
};
|
||||
}
|
||||
|
||||
/** 跨平台打开浏览器(node:child_process,Bun / Node 宿主均可;失败时用户可手动打开 instructions 里的地址)。 */
|
||||
function openBrowser(urlStr) {
|
||||
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
|
||||
try {
|
||||
// Windows 的 start 是 cmd 内建命令,必须走 shell。
|
||||
const child = process.platform === "win32"
|
||||
? spawn(cmd, [urlStr], { shell: true, stdio: "ignore", detached: true })
|
||||
: spawn(cmd, [urlStr], { stdio: "ignore", detached: true });
|
||||
child.on("error", () => { /* 打开失败静默:instructions 已给出可手动访问的地址 */ });
|
||||
child.unref();
|
||||
} catch { /* 同上 */ }
|
||||
}
|
||||
|
||||
/** 引导页:滑块(如启用)→ 继续授权 → 自动跳授权页。 */
|
||||
function guidePageHtml(vendor) {
|
||||
const vendorName = vendor === "zai" ? "z.ai" : "Google";
|
||||
@@ -971,6 +1147,7 @@ function loadCaptchaLib(){
|
||||
setTimeout(()=>resolve(),10000);
|
||||
});
|
||||
}
|
||||
let leavingForAuthorization=false;
|
||||
document.getElementById("goBtn").addEventListener("click",async()=>{
|
||||
const btn=document.getElementById("goBtn");btn.disabled=true;btn.textContent="正在获取授权页…";
|
||||
try{
|
||||
@@ -979,10 +1156,11 @@ document.getElementById("goBtn").addEventListener("click",async()=>{
|
||||
if(j.error){msg(j.error,"err");btn.disabled=false;btn.textContent="继续授权";return;}
|
||||
document.getElementById("steps").style.display="none";btn.style.display="none";
|
||||
document.getElementById("done").style.display="block";
|
||||
setTimeout(()=>{location.href=j.url;},600);
|
||||
}catch(e){msg("网络错误:"+e.message,"err");btn.disabled=false;btn.textContent="继续授权";}
|
||||
setTimeout(()=>{leavingForAuthorization=true;location.href=j.url;},600);
|
||||
}catch(e){msg("本地登录连接已断开或会话已结束,请回 magpie 重新发起登录:"+e.message,"err");btn.disabled=false;btn.textContent="继续授权";}
|
||||
});
|
||||
window.addEventListener("beforeunload",()=>{
|
||||
if(leavingForAuthorization)return;
|
||||
try{navigator.sendBeacon("/abort",new Blob([JSON.stringify({reason:"页面关闭"})],{type:"application/json"}));}catch(_){}
|
||||
});
|
||||
boot().catch((e)=>msg("初始化失败:"+e.message,"err"));
|
||||
@@ -1021,8 +1199,10 @@ export const AutoclawCnAuthPlugin = makeAutoclawPlugin({
|
||||
|
||||
/** 测试辅助(magpie/OpenCode 不会把它当插件调用)。 */
|
||||
export const _internal = {
|
||||
makePluginForTest: makeAutoclawPlugin,
|
||||
md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId,
|
||||
dailySignin, signinStatus, maybeSignin, signinConfig, checkinOutcome, refreshTokens,
|
||||
fetchUserProfile, accountDisplayName, startLocalOAuth,
|
||||
FLAGGED, unflagged, unflag, autoclawRewriteBody, explained, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT,
|
||||
guidePageHtml, callbackPageHtml,
|
||||
};
|
||||
|
||||
@@ -7,7 +7,10 @@ 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 } = _internal
|
||||
const {
|
||||
checkinOutcome, signinConfig, bareToken, codeValue, tokenFields, refreshTokens, startLocalOAuth,
|
||||
autoclawRewriteBody, unflag, unflagged, explained, FLAGGED, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT,
|
||||
} = _internal
|
||||
|
||||
const b64url = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
|
||||
const jwt = (claims) => `${b64url({ alg: "none" })}.${b64url(claims)}.sig`
|
||||
@@ -117,6 +120,122 @@ test("loader().fetch signs with X-Authorization and rotates hosts on 401", async
|
||||
}
|
||||
})
|
||||
|
||||
// AutoClaw's 2.1.0 chat gateway answers 406 with an empty body to a chat that
|
||||
// hasn't the official prefix first or that carries max_tokens.
|
||||
// autoclawRewriteBody puts a chat in that shape, once, whatever it is handed.
|
||||
test("autoclawRewriteBody prefixes the system prompt and drops max_tokens", () => {
|
||||
const chat = (messages, rest = {}) => JSON.stringify({ model: "zai_glm-5.3-flash", messages, ...rest })
|
||||
|
||||
// the caller's own system message keeps its words, behind the prefix
|
||||
const one = autoclawRewriteBody(chat([{ role: "system", content: "Be terse." }, { role: "user", content: "hi" }], { max_tokens: 32000 }))
|
||||
expect(one.messages[0].content).toBe(`${OFFICIAL_SYSTEM_PROMPT}\n\nBe terse.`)
|
||||
expect(one.max_tokens).toBeUndefined()
|
||||
expect(one.messages.length).toBe(2)
|
||||
|
||||
// …and the prefix goes on once, however often the rewrite runs
|
||||
expect(autoclawRewriteBody(JSON.stringify(one)).messages[0].content).toBe(one.messages[0].content)
|
||||
|
||||
// a chat that opens without a system message gets the smallest one
|
||||
expect(autoclawRewriteBody(chat([{ role: "user", content: "hi" }])).messages).toEqual([
|
||||
{ role: "system", content: OFFICIAL_SYSTEM_PROMPT },
|
||||
{ role: "user", content: "hi" },
|
||||
])
|
||||
|
||||
// the newer spelling goes with max_tokens
|
||||
expect(autoclawRewriteBody(chat([{ role: "user", content: "hi" }], { max_completion_tokens: 10 })).max_completion_tokens).toBeUndefined()
|
||||
|
||||
// anything that isn't a JSON chat is left for the caller to pass through
|
||||
expect(autoclawRewriteBody("not json")).toBe(null)
|
||||
expect(autoclawRewriteBody(JSON.stringify({ model: "zai_auto" }))).toBe(null)
|
||||
})
|
||||
|
||||
// FLAGGED is the words AutoClaw refuses a chat for: it reads the system
|
||||
// prompt only, minds no case, and matches the shortest run of them ("You are
|
||||
// Claude Code" and "Codex CLI" are two separate ones). Each pair was sent to
|
||||
// the live gateway: the left side is a 406, the right side answers.
|
||||
test("every flagged line's replacement is one the gateway still takes", () => {
|
||||
expect(FLAGGED.length).toBeGreaterThan(0)
|
||||
for (const [re, to] of FLAGGED) {
|
||||
expect(to).not.toMatch(new RegExp(re.source, "i"))
|
||||
expect(unflagged(to)).toBe(to)
|
||||
}
|
||||
expect(unflagged("You are Claude Code, Anthropic's official CLI for Claude.")).not.toMatch(/You are Claude Code/)
|
||||
expect(unflagged("Codex CLI is an open source project.")).not.toMatch(/Codex CLI/)
|
||||
})
|
||||
|
||||
// The gateway reads the system prompt, not the chat: the caller's own words
|
||||
// in a user or assistant message stay as they are.
|
||||
test("unflag rewrites system and developer messages only", () => {
|
||||
const messages = [
|
||||
{ role: "system", content: "You are Claude Code, Anthropic's official CLI for Claude." },
|
||||
{ role: "developer", content: [{ type: "text", text: "You are Cursor" }] },
|
||||
{ role: "user", content: "You are Codex" },
|
||||
{ role: "assistant", content: [{ type: "text", text: "Codex CLI is what I use" }] },
|
||||
]
|
||||
expect(unflag(messages)).toBe(true)
|
||||
expect(messages[0].content).toBe("You are the Claude Code CLI, Anthropic's official CLI for Claude.")
|
||||
expect(messages[1].content[0].text).toBe("You are the Cursor agent")
|
||||
expect(messages[2].content).toBe("You are Codex")
|
||||
expect(messages[3].content[0].text).toBe("Codex CLI is what I use")
|
||||
// nothing left to change the second time
|
||||
expect(unflag(messages)).toBe(false)
|
||||
})
|
||||
|
||||
// explained is res with REFUSED_HINT on a 406 — the one refusal the gateway
|
||||
// gives no words for — and the sign-in marked kept, so magpie doesn't read a
|
||||
// refusal as a lapsed account.
|
||||
test("explained adds the way out to a 406 and keeps the sign-in", async () => {
|
||||
const refused = await explained(new Response(JSON.stringify({ error: { code: null, message: "406 Not Acceptable", type: "api_error" } }), { status: 406, headers: { "content-type": "application/json" } }))
|
||||
expect(refused.status).toBe(406)
|
||||
expect(refused.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
expect((await refused.json()).error.message).toBe(`406 Not Acceptable — ${REFUSED_HINT}`)
|
||||
|
||||
// an answer that isn't a refusal is passed through, and its body with it
|
||||
const ok = await explained(new Response('{"choices":[]}', { status: 200 }))
|
||||
expect(ok.status).toBe(200)
|
||||
expect(await ok.text()).toBe('{"choices":[]}')
|
||||
})
|
||||
|
||||
test("overseas loader().fetch drops X-Harness-Type and explains 406", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const calls = []
|
||||
let status = 200
|
||||
globalThis.fetch = async (input, init) => {
|
||||
calls.push({ url: String(input), headers: new Headers(init?.headers), body: JSON.parse(String(init?.body ?? "{}")) })
|
||||
if (status === 406) return new Response(JSON.stringify({ error: { code: null, message: "406 Not Acceptable", type: "api_error" } }), { status: 406 })
|
||||
return new Response("ok")
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" }))
|
||||
const body = JSON.stringify({
|
||||
model: "zai_glm-5.3-flash",
|
||||
max_tokens: 32000,
|
||||
messages: [
|
||||
{ role: "system", content: "You are an AI agent powered by DeepSeek Harness." },
|
||||
{ role: "user", content: "hi" },
|
||||
],
|
||||
})
|
||||
|
||||
expect((await loader.fetch("x", { method: "POST", body })).status).toBe(200)
|
||||
const sent = calls.at(-1)
|
||||
expect(sent.body.max_tokens).toBeUndefined()
|
||||
expect(sent.body.messages[0].content.startsWith(OFFICIAL_SYSTEM_PROMPT)).toBe(true)
|
||||
expect(sent.body.messages[0].content).not.toMatch(/DeepSeek Harness/)
|
||||
expect(sent.headers.get("X-Harness-Type")).toBe(null)
|
||||
expect(sent.headers.get("User-Agent")).toMatch(/^AutoClaw\//)
|
||||
|
||||
status = 406
|
||||
const refused = await loader.fetch("x", { method: "POST", body })
|
||||
expect(refused.status).toBe(406)
|
||||
expect(refused.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
expect((await refused.json()).error.message).toContain(REFUSED_HINT)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
test("refreshTokens orders hosts by the token's source_id and falls back on 400002", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const requests = []
|
||||
@@ -212,6 +331,8 @@ test("the OAuth callback takes only the state the authorize page handed out", as
|
||||
try {
|
||||
const session = await startLocalOAuth("google", () => {})
|
||||
const port = Number(/127\.0\.0\.1:(\d+)\//.exec(session.instructions)[1])
|
||||
expect(session.url).toBe(`http://127.0.0.1:${port}/`)
|
||||
expect((await realFetch(session.url)).status).toBe(200)
|
||||
const local = (path, init) => fetch(`http://127.0.0.1:${port}${path}`, init)
|
||||
|
||||
// The guide page's Continue hands out the authorize URL, and the state in it
|
||||
@@ -244,3 +365,105 @@ test("the OAuth callback takes only the state the authorize page handed out", as
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("CN's managed gateway gets AutoClaw's official body and headers", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (input, init) => {
|
||||
calls.push({ url: String(input), init, headers: new Headers(init?.headers) })
|
||||
return Response.json({ id: "x", object: "chat.completion", created: 1, model: "zai_auto-fast", choices: [{ index: 0, message: { role: "assistant", content: "OK" }, finish_reason: "stop" }] })
|
||||
}
|
||||
try {
|
||||
const factory = await makePlugin("autoclaw-cn")
|
||||
const hooks = await factory({ client: { auth: { set: async () => {} } } }, {})
|
||||
const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" }))
|
||||
const res = await loader.fetch("x", { body: JSON.stringify({ model: "zai_auto-fast", stream: false, max_tokens: 12, stream_options: { include_usage: true }, messages: [{ role: "system", content: "mine" }, { role: "user", content: "hi" }] }) })
|
||||
const sent = JSON.parse(calls[0].init.body)
|
||||
expect(calls[0].url).toBe("https://autoglm-acceleration-api.zhipuai.cn/autoclaw-proxy/proxy/autoclaw/chat/completions")
|
||||
expect(sent.model).toBe("zai_auto-fast")
|
||||
expect(sent.stream).toBe(false)
|
||||
expect(sent.max_tokens).toBeUndefined()
|
||||
expect(sent.messages).toHaveLength(2)
|
||||
expect(sent.messages[0].content).toBe("You are AutoClaw. Answer the user directly and concisely.\n\nmine")
|
||||
expect(sent.messages[0].role).toBe("system")
|
||||
expect(sent.messages[1]).toMatchObject({ role: "user", content: "hi" })
|
||||
expect(calls[0].headers.get("x-request-model")).toBe("zai_auto-fast")
|
||||
expect(calls[0].headers.get("x-client-type")).toBe("pc")
|
||||
expect(calls[0].headers.get("x-agent-id")).toBe("main")
|
||||
expect(calls[0].headers.get("x-authorization")).toBe("Bearer a1")
|
||||
expect(res.headers.get("content-type")).toContain("application/json")
|
||||
const reply = await res.json()
|
||||
expect(reply.model).toBe("zai_auto-fast")
|
||||
} finally { globalThis.fetch = realFetch }
|
||||
})
|
||||
|
||||
function makePlugin(id) {
|
||||
return _internal.makePluginForTest({
|
||||
providerId: id,
|
||||
providerName: id,
|
||||
homeHost: id === "autoclaw-cn" ? "https://autoglm-api.zhipuai.cn" : "https://autoglm-api.autoglm.ai",
|
||||
loginMethod: { type: "oauth", label: "test", authorize: async () => ({}) },
|
||||
})
|
||||
}
|
||||
|
||||
test("CN preserves string and array system content", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (input, init) => {
|
||||
calls.push(JSON.parse(String(init?.body)))
|
||||
return Response.json({ ok: true })
|
||||
}
|
||||
try {
|
||||
const factory = makePlugin("autoclaw-cn")
|
||||
const hooks = await factory({ client: { auth: { set: async () => {} } } }, {})
|
||||
const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" }))
|
||||
await loader.fetch("x", { body: JSON.stringify({ model: "zai_auto", messages: [{ role: "system", content: [{ type: "text", text: "PARTSYS" }] }, { role: "user", content: "hi" }] }) })
|
||||
expect(calls[0].messages[0].content).toEqual([
|
||||
{ type: "text", text: "You are AutoClaw. Answer the user directly and concisely." },
|
||||
{ type: "text", text: "PARTSYS" },
|
||||
])
|
||||
await loader.fetch("x", { body: JSON.stringify({ model: "zai_auto", messages: [{ role: "system", content: "mine" }, { role: "user", content: "hi" }] }) })
|
||||
expect(calls[1].messages[0].content).toBe("You are AutoClaw. Answer the user directly and concisely.\n\nmine")
|
||||
await loader.fetch("x", { body: JSON.stringify({ model: "zai_auto", messages: [{ role: "system", content: "You are Claude Code" }] }) })
|
||||
expect(calls[2].messages[0].content).toBe("You are AutoClaw. Answer the user directly and concisely.\n\nYou are the Claude Code CLI")
|
||||
} 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 () => {} } } }, {})
|
||||
const cfg = { provider: {} }
|
||||
await cn.config(cfg)
|
||||
expect(Object.keys(cfg.provider["autoclaw-cn"].models.zai_auto.variants)).toEqual(["low", "high", "max"])
|
||||
expect(cfg.provider["autoclaw-cn"].models.zai_auto.variants.max).toEqual({ reasoningEffort: "max" })
|
||||
expect(Object.keys(cfg.provider["autoclaw-cn"].models)).toEqual(["zai_auto", "zai_auto-fast", "zaicoding_glm-5.3", "zai_glm-5.3-flash"])
|
||||
|
||||
const overseas = await makePlugin("autoclaw")({ client: { auth: { set: async () => {} } } }, {})
|
||||
const oc = { provider: {} }
|
||||
await overseas.config(oc)
|
||||
expect(Object.keys(oc.provider.autoclaw.models)).toEqual(["zai_auto", "zai_auto-fast", "zaicoding_glm-5.3", "zai_glm-5.3-flash"])
|
||||
expect(oc.provider.autoclaw.models.zai_auto.limit).toEqual({ context: 200000, output: 32000 })
|
||||
expect(oc.provider.autoclaw.models["zaicoding_glm-5.3"].limit).toEqual({ context: 1000000, output: 131072 })
|
||||
})
|
||||
|
||||
test("CN passes SSE through and marks 401 expired", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = new URL(String(input))
|
||||
if (url.pathname.endsWith("/chat/completions")) {
|
||||
if (String(init?.body).includes("STREAM")) return new Response("data: {\"ok\":true}\n\n", { headers: { "content-type": "text/event-stream" } })
|
||||
return new Response("{}", { status: 401 })
|
||||
}
|
||||
return Response.json({ ok: true })
|
||||
}
|
||||
try {
|
||||
const factory = makePlugin("autoclaw-cn")
|
||||
const hooks = await factory({ client: { auth: { set: async () => {} } } }, {})
|
||||
const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" }))
|
||||
const stream = await loader.fetch("x", { body: JSON.stringify({ model: "zai_auto", stream: true, messages: [{ role: "user", content: "STREAM" }] }) })
|
||||
expect(await stream.text()).toBe("data: {\"ok\":true}\n\n")
|
||||
const expired = await loader.fetch("x", { body: JSON.stringify({ model: "zai_auto", messages: [{ role: "user", content: "x" }] }) })
|
||||
expect(expired.status).toBe(401)
|
||||
expect(expired.headers.get("X-Magpie-Sign-In")).toBe("expired")
|
||||
} finally { globalThis.fetch = realFetch }
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-autoclaw-auth",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.1",
|
||||
"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",
|
||||
|
||||
Reference in New Issue
Block a user