Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

feat(agent): fall back to Chat Completions when a model rejects Responses/Messages

Marla344671d0e4e4
diff --git a/README.md b/README.md
index 5180ad9..36ad6e1 100644
--- a/README.md
+++ b/README.md
@@ -90,7 +90,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令
- 对话中输入框右侧的模型按钮可为当前会话切换模型(也可设为机器人默认);`/model`、`/reset`、`/new`、`/status`、`/stop`、`/help` 照常可用。
- 处理过程:代理回合的每一步(模型请求及用时与 tokens、工具调用及参数与输出、重试、子代理)折叠在回复上方的"用时"一行里,点开查看;微信 / 飞书会话在信息面板 → 最近会话里看,正在处理的那一轮实时显示并可中止。
- 卡住的消息:`/stop`(任何渠道)或信息面板里的「中止」立即结束正在处理的回合;代理 10 分钟没有任何进展(模型不回、工具不动、只在重试;等你批准或回答不算)会自动中止,单回合最长 30 分钟(`AMB_AGENT_IDLE_TIMEOUT_MS`、`AMB_AGENT_TURN_TIMEOUT_MS` 可调)。DSH 没有中断单个回合的接口,中止时会重启该机器人的代理进程。前一条还在处理时发来的新消息会先收到一句提示;`/status` 显示它走到了哪一步、多久没有进展。
-- 代理的对话接口:代理按 Modelflare 公开目录里该模型支持的接口选——有 Responses API 的(GPT-5.4 及以后、Grok 4.5 及以后、DeepSeek V4、GLM-5、Kimi K3 等)走 `/v1/responses`(推理模型默认推理强度 medium,加密推理随历史回放);没有 Responses、有 Anthropic Messages 的(Claude)走 `/v1/messages`;其余模型、拿不到目录时(离线、中国大陆线路)以及外部端点走 Chat Completions。接口在拉起代理进程时选定(故障排查的代理状态里显示 `api`);`AMB_AGENT_API=chat` 强制全部走 Chat Completions(排查用)。纯对话(非代理)仍走 Chat Completions。
+- 代理的对话接口:代理按 Modelflare 公开目录里该模型支持的接口选——有 Responses API 的(GPT-5.4 及以后、Grok 4.5 及以后、DeepSeek V4、GLM-5、Kimi K3 等)走 `/v1/responses`(推理模型默认推理强度 medium,加密推理随历史回放);没有 Responses、有 Anthropic Messages 的(Claude)走 `/v1/messages`;其余模型、拿不到目录时(离线、中国大陆线路)以及外部端点走 Chat Completions。接口在拉起代理进程时选定(故障排查的代理状态里显示 `api`);`AMB_AGENT_API=chat` 强制全部走 Chat Completions(排查用)。纯对话(非代理)仍走 Chat Completions。安全网:某个模型在 Responses / Messages 上的请求被上游拒绝(HTTP 400/404/405/415/422 或“不支持的参数 / 接口”,限流、余额、权限、上游故障、上下文过长不算)时,这个模型 24 小时内改走 Chat Completions(记在数据目录的 `dsh/api-fallback.json`,日志有警告,代理状态显示 `openai-completions (fallback: 原因)`);这一轮如果还没调用过工具,代理换到 Chat 上自动重做一遍,用户照常收到回复,已经调用过工具的则照常报错、下一轮起走 Chat。
- 内置网关:magpie 以 `--gateway` 模式运行,使用本程序数据目录内独立的 HOME/配置目录;**不读取**你电脑上已有的 Claude/Codex 等订阅凭据,**不改写**任何 agent 配置,关闭自动更新与账户发现。它只供本进程内部调用,界面不再反代它的页面或 `/v1`。
- API Key 只保存在内置网关的隔离配置中,不经过命令行参数、不写日志,前端只拿到尾号。
- 开发/测试:设置 `AMB_MAGPIE_BASE_URL` 可直接使用一个 OpenAI 兼容端点(不启动内置网关,界面视为已连接,账户功能不可用);`AMB_MODELFLARE_BASE_URL` 可把 Modelflare 基址指向本地 mock,`AMB_MODELFLARE_ISSUER` 把登录与账户接口指向本地 mock。
diff --git a/src/agent/activity.ts b/src/agent/activity.ts
index 1504ce3..8f7b53c 100644
--- a/src/agent/activity.ts
+++ b/src/agent/activity.ts
@@ -140,6 +140,10 @@ export class ActivityLog {
}
case "llm/retry-started":
return false;
+ case "api/fallback":
+ // 宿主发的:上游不接受这个接口上的请求,换 Chat Completions 重做这一轮
+ this.put({ id: `f${time}`, kind: "retry", title: "改用 Chat Completions 重试", summary: oneLine(`${data.from ?? ""} 被拒:${data.reason ?? ""}`), status: "ok", at: time });
+ return true;
case "compaction/start":
this.put({ id: `c${time}`, kind: "compact", title: "压缩上下文", status: "running", at: time });
return true;
diff --git a/src/agent/api-fallback.ts b/src/agent/api-fallback.ts
new file mode 100644
index 0000000..2310117
--- /dev/null
+++ b/src/agent/api-fallback.ts
@@ -0,0 +1,127 @@
+/**
+ * 代理接口的回退:某个模型在 Responses / Anthropic Messages 上被上游拒绝(请求形状不被接受)后,
+ * 记下"这个模型 → Chat Completions",一段时间内(默认 24 小时)代理对它直接走 Chat。
+ * 按去掉内置网关前缀的模型 id 记(所有机器人共用),存在数据目录里,重启后仍然有效。
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { logger } from "../log.js";
+import { bareModel } from "../modelflare.js";
+
+const log = logger("agent.api");
+
+export const API_FALLBACK_TTL_MS = 24 * 3600_000;
+
+export interface ApiFallback {
+ /** 被拒的接口 */
+ from: string;
+ /** 一行原因(状态码与上游的说法,已脱敏) */
+ reason: string;
+ at: number;
+ until: number;
+}
+
+/** 这些状态码说明是请求本身不被这个接口接受(参数、路径、格式),不是限流、余额、权限或上游故障 */
+const SHAPE_STATUSES = new Set([400, 404, 405, 415, 422]);
+/** 没有状态码时(流里才报错):错误说的是参数 / 接口不支持 */
+const SHAPE_TEXT =
+ /\b(unsupported|unknown|unrecognized|unexpected|invalid)[ _-](parameter|param|field|argument|endpoint|api|protocol|path|route)s?\b|\b(not|isn't|is not) supported\b|\bdoes not support\b|\bunsupported_(parameter|value|api|endpoint)\b|\bunknown_parameter\b|\bno route\b|\bnot found\b.*\b(endpoint|path|route)\b/i;
+/** 状态码像,但其实是别的问题(上下文太长、内容审核、额度、限流):换接口也没用,不回退 */
+const NOT_SHAPE_TEXT =
+ /context[ _-]?(length|window)|too long|too many tokens|maximum context|token limit|content[ _-]?(policy|filter|management)|safety|flagged|rate[ _-]?limit|quota|insufficient|balance|credit|budget|billing/i;
+/** 没有状态码时,错误里带着这些状态码就不算 */
+const NOT_SHAPE_STATUS = /\b(401|402|403|408|409|429|5\d\d)\b/;
+
+const clip = (s: string, n: number) => {
+ const one = s.replace(/\s+/g, " ").trim();
+ return one.length > n ? one.slice(0, n - 1) + "…" : one;
+};
+
+/** 上游错误体里的那句话(OpenAI、Anthropic 都是 error.message) */
+function upstreamMessage(body: string): string {
+ try {
+ const j = JSON.parse(body);
+ const m = j?.error?.message ?? j?.message ?? j?.detail;
+ if (typeof m === "string" && m.trim()) return m;
+ } catch {
+ /* 不是 JSON */
+ }
+ return body;
+}
+
+/**
+ * 这个回合失败是不是因为接口不接受我们的请求:返回一行原因,不是则 undefined。
+ * rejections 是 bridge 在这一轮看到的、本机器人发往 Responses / Messages 的上游错误(状态码 + 错误体);
+ * turnError 是代理报的错误(流里才出错时只有它)。
+ */
+export function shapeRejection(rejections: Array<{ status: number; error: string }>, turnError: string): string | undefined {
+ for (const r of [...rejections].reverse()) {
+ if (!SHAPE_STATUSES.has(r.status)) continue;
+ const msg = upstreamMessage(r.error);
+ if (NOT_SHAPE_TEXT.test(msg)) continue;
+ return clip(`HTTP ${r.status}${msg ? `: ${msg}` : ""}`, 200);
+ }
+ if (SHAPE_TEXT.test(turnError) && !NOT_SHAPE_TEXT.test(turnError) && !NOT_SHAPE_STATUS.test(turnError)) return clip(turnError, 200);
+ return undefined;
+}
+
+/** 模型 → 回退记录。file 不给时只在内存里(测试、没有数据目录时) */
+export class ApiFallbacks {
+ private m = new Map<string, ApiFallback>();
+
+ constructor(
+ private file?: string,
+ private ttlMs = API_FALLBACK_TTL_MS,
+ ) {
+ if (!file) return;
+ try {
+ const j = JSON.parse(fs.readFileSync(file, "utf8"));
+ for (const [k, v] of Object.entries(j?.models ?? {})) {
+ const e = v as ApiFallback;
+ if (Number(e?.until) > Date.now()) this.m.set(k, { from: String(e.from ?? ""), reason: String(e.reason ?? ""), at: Number(e.at) || 0, until: Number(e.until) });
+ }
+ } catch {
+ /* 没有或坏了:从空开始 */
+ }
+ }
+
+ private key(model: string): string {
+ return bareModel(model.trim());
+ }
+
+ get(model: string): ApiFallback | undefined {
+ const k = this.key(model);
+ const e = this.m.get(k);
+ if (e && e.until <= Date.now()) {
+ this.m.delete(k);
+ this.save();
+ return undefined;
+ }
+ return e;
+ }
+
+ set(model: string, from: string, reason: string): ApiFallback {
+ const at = Date.now();
+ const e = { from, reason, at, until: at + this.ttlMs };
+ this.m.set(this.key(model), e);
+ this.save();
+ return e;
+ }
+
+ list(): Array<ApiFallback & { model: string }> {
+ const now = Date.now();
+ return [...this.m].filter(([, e]) => e.until > now).map(([model, e]) => ({ model, ...e }));
+ }
+
+ private save(): void {
+ if (!this.file) return;
+ try {
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
+ const tmp = `${this.file}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify({ models: Object.fromEntries(this.m) }, null, 2) + "\n", { mode: 0o600 });
+ fs.renameSync(tmp, this.file);
+ } catch (e) {
+ log.warn("saving agent API fallbacks failed", { message: (e as Error).message });
+ }
+ }
+}
diff --git a/src/agent/bridge.ts b/src/agent/bridge.ts
index 12c4ad9..e2a99ba 100644
--- a/src/agent/bridge.ts
+++ b/src/agent/bridge.ts
@@ -26,6 +26,17 @@ export type ProxyEvent =
| { phase: "response"; id: number; path: string; status: number; ms: number; error?: string }
| { phase: "error"; id: number; path: string; ms: number; error: string };
+/** 上游拒绝了一个模型请求(状态码 ≥ 400):哪个机器人的代理进程发的、哪个路径、状态码、错误体(已脱敏、截断) */
+export interface Rejection {
+ bot?: string;
+ path: string;
+ status: number;
+ error: string;
+}
+
+/** 代理进程在每个模型请求上带的头:标明是哪个机器人发的(bridge 用它归属上游错误,不转给上游) */
+export const BOT_HEADER = "x-amb-bot";
+
/**
* 仅回环的内部桥:DSH 子进程用每次启动随机生成的令牌访问。
* - /v1/*:模型代理(Chat Completions、Responses、Anthropic Messages),把令牌换成真实网关密钥(子进程环境里没有任何真实密钥)
@@ -37,6 +48,7 @@ export class AgentBridge {
port = 0;
private seq = 0;
private proxyListeners = new Set<(e: ProxyEvent) => void>();
+ private rejectionListeners = new Set<(e: Rejection) => void>();
constructor(private h: BridgeHandlers) {
registerSecret(this.token);
@@ -57,6 +69,12 @@ export class AgentBridge {
}
}
+ /** 订阅上游拒绝(代理接口回退用;不解析请求体,开销很小);返回取消函数 */
+ onRejection(fn: (e: Rejection) => void): () => void {
+ this.rejectionListeners.add(fn);
+ return () => this.rejectionListeners.delete(fn);
+ }
+
get url(): string {
return `http://127.0.0.1:${this.port}`;
}
@@ -117,7 +135,7 @@ export class AgentBridge {
const target = up.baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "") + url;
const headers: Record<string, string> = {};
for (const [k, v] of Object.entries(req.headers)) {
- if (["host", "authorization", "x-api-key", "connection", "content-length", "transfer-encoding", "cookie"].includes(k) || v === undefined) continue;
+ if (["host", "authorization", "x-api-key", BOT_HEADER, "connection", "content-length", "transfer-encoding", "cookie"].includes(k) || v === undefined) continue;
headers[k] = Array.isArray(v) ? v.join(", ") : v;
}
// 令牌只在本机有效:换成真实密钥;Anthropic 客户端发来的 x-api-key 也换掉(magpie 两种都认)
@@ -152,8 +170,16 @@ export class AgentBridge {
// 上游报错:读完错误体(不大)记日志,再原样转给子进程
const text = await r.text().catch(() => "");
const error = redactText(text.slice(0, 1000));
- log.warn("model request rejected by upstream", { path: p, status: r.status, ms: Date.now() - t0, body: error });
+ const bot = typeof req.headers[BOT_HEADER] === "string" ? (req.headers[BOT_HEADER] as string) : undefined;
+ log.warn("model request rejected by upstream", { path: p, status: r.status, ms: Date.now() - t0, bot, body: error });
this.emitProxy({ phase: "response", id, path: p, status: r.status, ms: Date.now() - t0, error });
+ for (const fn of this.rejectionListeners) {
+ try {
+ fn({ bot, path: p, status: r.status, error });
+ } catch {
+ /* ignore */
+ }
+ }
res.writeHead(r.status, out);
return void res.end(text);
}
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 16d1e74..8a704fb 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -4,7 +4,8 @@ import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { lineLogger, logger } from "../log.js";
import type { Store } from "../store/db.js";
-import type { AgentBridge } from "./bridge.js";
+import { BOT_HEADER, type AgentBridge, type Rejection } from "./bridge.js";
+import { ApiFallbacks, shapeRejection, type ApiFallback } from "./api-fallback.js";
import os from "node:os";
import { findAppRoot } from "../magpie/supervisor.js";
import { adaptSkill, mcpPatchLines, resolveComputerUse, type CuResolved } from "./computer-use.js";
@@ -146,6 +147,24 @@ export class TurnStopped extends Error {
}
}
+/**
+ * 回合失败,原因是上游不接受这个接口上的请求(Responses / Anthropic Messages 被拒)。已记下回退;
+ * retryable:这一轮还没有调用过工具、也没有别的回合在用这个代理进程,可以换 Chat Completions 重做一遍。
+ */
+export class ApiRejected extends Error {
+ constructor(
+ message: string,
+ readonly api: AgentApi,
+ readonly reason: string,
+ readonly retryable: boolean,
+ ) {
+ super(message);
+ }
+}
+
+/** 换接口重做时交给模型的话(上一条用户消息已经在会话里) */
+export const RETRY_NOTE = "[系统提示]\n上一条用户消息因模型接口不兼容没有处理,现已换用其它接口。请直接处理上面那条用户消息。";
+
export interface AgentHostOptions {
botId: string;
dataDir: string;
@@ -164,6 +183,8 @@ export interface AgentHostOptions {
contextWindow?: (model: string) => Promise<number | undefined>;
/** 模型支持的接口与是否推理(Modelflare 模型资料),用来选对话接口;不知道时 undefined,走 Chat Completions */
apiInfo?: (model: string) => Promise<ModelApiInfo | undefined>;
+ /** 被上游拒绝过的模型 → 改走 Chat Completions(所有机器人共用,存在数据目录);不给时只在本进程内记 */
+ apiFallbacks?: ApiFallbacks;
}
export type HostState = "stopped" | "starting" | "running" | "backoff" | "error";
@@ -338,6 +359,9 @@ export class AgentHost {
model = "";
/** 当前子进程跟模型说话用的接口 */
api: AgentApi | "" = "";
+ /** 当前子进程因为回退才走 Chat Completions:回退记录(状态里显示原因) */
+ fallback: ApiFallback | undefined;
+ private ownFallbacks: ApiFallbacks | undefined;
/** 当前子进程补丁里写的上下文窗口与最大输出 */
private limits: { window: number; maxTokens: number } | undefined;
private harness: SdkHarness | undefined;
@@ -427,6 +451,9 @@ export class AgentHost {
// 接口按模型选(agentApi):Responses / Anthropic Messages / Chat Completions
...wire.provider,
" apiKeyEnv: AMB_MAGPIE_KEY",
+ // 标明是哪个机器人发的:bridge 据此把上游错误归到这个代理进程(不转给上游)
+ " headers:",
+ ` ${BOT_HEADER}: ${yamlStr(this.o.botId)}`,
" models:",
` - id: ${yamlStr(model)}`,
` name: ${yamlStr(model.split("/").pop() || model)}`,
@@ -675,6 +702,10 @@ exec "$REAL" "$@"
log.info("model changed, restarting dsh", { bot: this.o.botId, model });
await this.closeHarness();
}
+ if (this.harness && this.api && this.api !== "openai-completions" && this.fallbacks.get(this.model) && this.active === 0) {
+ log.info("model was rejected on its API before, restarting dsh on Chat Completions", { bot: this.o.botId, model: this.model, api: this.api });
+ await this.closeHarness();
+ }
if (this.harness && this.sig !== this.settingsSig() && this.active === 0) {
log.info("bot settings or PowerShell changed, restarting dsh", { bot: this.o.botId });
await this.closeHarness();
@@ -734,7 +765,11 @@ exec "$REAL" "$@"
const pwshPath = await pwshProbe.dshPath();
const ask = <T>(p: Promise<T | undefined> | undefined) => withTimeoutOr(p ?? Promise.resolve(undefined), 3000, undefined).catch(() => undefined);
const [known, info] = await Promise.all([ask(this.o.contextWindow?.(model)), ask(this.o.apiInfo?.(model))]);
- const api = agentApi(info?.endpoints);
+ const chosen = agentApi(info?.endpoints);
+ // 这个模型在该接口上被拒过(24 小时内):直接走 Chat Completions
+ const fb = chosen !== "openai-completions" ? this.fallbacks.get(model) : undefined;
+ const api: AgentApi = fb ? "openai-completions" : chosen;
+ this.fallback = fb;
const patch = this.writePatch(model, apps, pwshPath, modelLimits(model, known), api, info?.reasoning);
this.sig = this.settingsSig();
const timeoutMs = this.initTimeoutMs();
@@ -877,7 +912,28 @@ exec "$REAL" "$@"
*/
imageInput = !(process.versions.electron && process.platform === "linux") && process.env.AMB_DSH_IMAGES !== "0";
+ get fallbacks(): ApiFallbacks {
+ return this.o.apiFallbacks ?? (this.ownFallbacks ??= new ApiFallbacks());
+ }
+
+ /**
+ * 跑一个回合。Responses / Anthropic Messages 上的请求被上游拒绝(请求形状不被接受,不是限流、余额、故障)时:
+ * 记下这个模型改走 Chat Completions;这一轮还没调用过工具的话,把代理进程换到 Chat 上重做一遍(只重做一次)。
+ */
async runTurn(input: TurnInput): Promise<{ text: string; sessionId: string; files: string[]; usage: TurnUsage }> {
+ try {
+ return await this.runOnce(input);
+ } catch (e) {
+ if (!(e instanceof ApiRejected) || !e.retryable || input.signal?.aborted) throw e;
+ log.warn("agent turn rejected on its API; retrying it once over Chat Completions", { bot: this.o.botId, model: input.model, api: e.api, reason: e.reason });
+ input.observer?.onEvent?.("api/fallback", { from: e.api, to: "openai-completions", reason: e.reason }, Date.now());
+ // ensure() 看到回退记录,空闲时把子进程换到 Chat 上。用户这条消息(连同图片)在被拒之前已经存进会话,
+ // 不再发一遍,只请模型处理它
+ return await this.runOnce({ ...input, text: RETRY_NOTE, images: undefined });
+ }
+ }
+
+ private async runOnce(input: TurnInput): Promise<{ text: string; sessionId: string; files: string[]; usage: TurnUsage }> {
const h = await this.ensure(input.model);
const s = await this.sessionFor(h, input.conversationId);
// 在等进程 / 会话时就被中止了:消息还没交出去,不用重启子进程
@@ -890,6 +946,14 @@ exec "$REAL" "$@"
const usage: TurnUsage = { tokens: 0, window: lim.window, maxTokens: lim.maxTokens };
const images = this.imageInput ? (input.images ?? []) : [];
let unlisten = () => {};
+ // 这一轮:用的接口、调用过几次工具、上游拒绝过本机器人的哪些模型请求
+ const api = this.api || "openai-completions";
+ let toolCalls = 0;
+ const rejections: Rejection[] = [];
+ const offRejection =
+ this.o.bridge.onRejection?.((r) => {
+ if (r.bot === this.o.botId && /\/v1\/(responses|messages)$/.test(r.path)) rejections.push(r);
+ }) ?? (() => {});
try {
const timeoutMs = this.o.turnTimeoutMs ?? 30 * 60_000;
const prompt = images.length ? [{ type: "text", text: input.text }, ...images.map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType }))] : input.text;
@@ -902,6 +966,7 @@ exec "$REAL" "$@"
const ev = n.params.event;
const data = ev?.data ?? {};
if (ev?.type === "tool/call") {
+ toolCalls++;
this.calls.set(String(data.callId), { name: String(data.name), args: String(data.arguments ?? ""), at: Date.now() });
if (this.calls.size > 500) this.calls.delete(this.calls.keys().next().value!);
if (data.name === "present") presented.push(...presentPaths(String(data.arguments ?? "")));
@@ -930,7 +995,13 @@ exec "$REAL" "$@"
});
const r = await Promise.race([run, stopped]);
this.failures = 0;
- if (!r.finalResponse && turnError) throw new Error(turnError);
+ const rejected = turnError !== undefined && api !== "openai-completions" ? shapeRejection(rejections, turnError) : undefined;
+ if (rejected) this.rememberFallback(input.model, api, rejected);
+ if (!r.finalResponse && turnError) {
+ // 已经调用过工具(命令可能已经执行)就不重做,照常报错;下一轮起走 Chat
+ if (rejected) throw new ApiRejected(turnError, api, rejected, toolCalls === 0 && presented.length === 0 && this.active === 1);
+ throw new Error(turnError);
+ }
return { text: r.finalResponse, sessionId: s.id, files: deliverables(this.workspace, presented), usage };
} catch (e) {
if (e instanceof TurnStopped) {
@@ -945,12 +1016,25 @@ exec "$REAL" "$@"
} finally {
clearTimeout(timer);
unlisten();
+ offRejection();
this.active--;
}
}
+ private rememberFallback(model: string, api: AgentApi, reason: string): void {
+ const fb = this.fallbacks.set(model, api, reason);
+ log.warn("upstream rejected the agent's requests on this API; using Chat Completions for this model", {
+ bot: this.o.botId,
+ model,
+ api,
+ reason,
+ until: new Date(fb.until).toISOString(),
+ });
+ }
+
status(): Record<string, unknown> {
- return { state: this.state, pid: this.pid, model: this.model, api: this.api || undefined, restarts: this.restarts, lastError: this.lastError, workspace: this.workspace, activeTurns: this.active };
+ const api = this.api ? (this.fallback ? `${this.api} (fallback: ${this.fallback.reason})` : this.api) : undefined;
+ return { state: this.state, pid: this.pid, model: this.model, api, restarts: this.restarts, lastError: this.lastError, workspace: this.workspace, activeTurns: this.active };
}
/** 故障排查用的完整状态(含 stderr 尾部与最近一次退出) */
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index 879c8fc..87307e2 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -5,6 +5,7 @@ import { AgentBridge } from "./bridge.js";
import path from "node:path";
import { AgentHost, TurnStopped, callDetail, type ModelApiInfo, type TurnInput, type TurnObserver, type TurnUsage } from "./host.js";
import { ActivityLog, type ActivityStep } from "./activity.js";
+import { ApiFallbacks, type ApiFallback } from "./api-fallback.js";
import type { MediaModel, MediaPlan, MediaService } from "./media.js";
import { APPROVAL_TTL_MS, ApprovalCenter, type QuestionItem } from "./approvals.js";
import { MemoryError, MemoryStore, type Scope } from "./memory.js";
@@ -82,6 +83,8 @@ export class AgentManager {
/** botId → 正在进行回合的会话(子代理 session 无映射时用来归属审批) */
private activeConvs = new Map<string, Set<string>>();
readonly memory: MemoryStore;
+ /** 在 Responses / Anthropic Messages 上被拒过、暂时改走 Chat Completions 的模型(所有机器人共用) */
+ readonly apiFallbacks: ApiFallbacks;
/** 会话 → 管家判定(是否原地压缩),插件在代理空闲时取 */
private decisions = new Map<string, { promise: Promise<boolean>; resolve: (v: boolean) => void }>();
/** 会话 → 下一回合开始前要等的事(判定、压缩完成) */
@@ -106,6 +109,7 @@ export class AgentManager {
media: (b) => this.mediaOp(b),
});
this.memory = new MemoryStore(path.join(o.dataDir, "memory"));
+ this.apiFallbacks = new ApiFallbacks(path.join(o.dataDir, "dsh", "api-fallback.json"));
}
/** 生图 / 生视频服务;未接内置网关时没有 */
@@ -138,6 +142,7 @@ export class AgentManager {
media: !!this.o.media,
contextWindow: this.o.contextWindow,
apiInfo: this.o.apiInfo,
+ apiFallbacks: this.apiFallbacks,
});
this.hosts.set(botId, h);
}
@@ -600,12 +605,20 @@ export class AgentManager {
}
/** 故障排查:运行时位置 + 每个已创建的代理进程的详细状态(stderr 尾部、最近一次退出)+ 进行中的回合 */
- diagnostics(): { enabled: boolean; available: boolean; runtimeDir?: string; hosts: Record<string, Record<string, unknown>>; turns: Array<{ conversationId: string; botId: string; forMs: number; idleMs?: number; lastStep?: ActivityStep }> } {
+ diagnostics(): {
+ enabled: boolean;
+ available: boolean;
+ runtimeDir?: string;
+ hosts: Record<string, Record<string, unknown>>;
+ apiFallbacks: Array<ApiFallback & { model: string }>;
+ turns: Array<{ conversationId: string; botId: string; forMs: number; idleMs?: number; lastStep?: ActivityStep }>;
+ } {
return {
enabled: this.o.enabled,
available: this.available,
runtimeDir: this.o.runtimeDir,
hosts: Object.fromEntries([...this.hosts].map(([id, h]) => [id, h.diagnostics()])),
+ apiFallbacks: this.apiFallbacks.list(),
turns: [...this.turnsInProgress].map(([conversationId, t]) => ({
conversationId,
botId: t.botId,
diff --git a/src/diagnostics.ts b/src/diagnostics.ts
index 6b71273..bdddb40 100644
--- a/src/diagnostics.ts
+++ b/src/diagnostics.ts
@@ -7,6 +7,7 @@ import os from "node:os";
import { appVersion, type App } from "./app.js";
import type { HostEvent } from "./agent/host.js";
import { isModelPath, type ProxyEvent } from "./agent/bridge.js";
+import { shapeRejection } from "./agent/api-fallback.js";
import { logFilePath, logger, readLogTail, redactText, redactValue } from "./log.js";
import { bareModel } from "./modelflare.js";
import { pwshProbe, pwshReportLine } from "./agent/pwsh.js";
@@ -248,11 +249,15 @@ export async function testAgent(app: App, opts: { botId?: string; model?: string
const d = host.diagnostics() as { startingForMs?: number; initStage?: string };
st("spawn").detail = `等待正在进行的启动(已 ${Math.round((d.startingForMs ?? 0) / 1000)} 秒,阶段:${d.initStage ?? "-"})`;
}
+ /** 这一轮 Responses / Messages 被拒、代理换 Chat 重做:模型这一步等重做的结果,期间的重启不算失败 */
+ let rejected: { path: string; why: string } | undefined;
const offHost = host.on((e: HostEvent) => {
if (e.type === "spawned") st("spawn").detail = `pid ${e.pid ?? "?"},等待初始化…`;
else if (e.type === "initialized") mark("spawn", "ok", `pid ${e.pid ?? "?"}`, e.ms);
else if (e.type === "failed") mark("spawn", "fail", e.message);
else if (e.type === "exit") {
+ // 接口被拒、代理换到 Chat Completions 重做:这次退出是有意的重启
+ if (rejected && st("model").status === "pending") return;
const pending = failedAlready() ? undefined : stages.find((s) => s.status === "pending");
if (pending) mark(pending.id, "fail", `代理进程退出(code=${e.code ?? "-"}, signal=${e.signal ?? "-"})${host.stderrTail.length ? `;stderr:${host.stderrTail.slice(-5).join(" | ")}` : ""}`);
}
@@ -269,7 +274,13 @@ export async function testAgent(app: App, opts: { botId?: string; model?: string
return;
}
if (!ours.has(e.id) || st("model").status !== "pending") return;
- if (e.phase === "response") mark("model", e.status < 400 ? "ok" : "fail", e.status < 400 ? `HTTP ${e.status}` : `HTTP ${e.status}${e.error ? `:${e.error}` : ""}`, e.ms);
+ // Responses / Messages 第一次被拒(请求形状不被接受):代理会换 Chat Completions 重做,等重做的结果
+ if (e.phase === "response" && !rejected && /\/v1\/(responses|messages)$/.test(e.path)) {
+ const why = e.status >= 400 ? shapeRejection([{ status: e.status, error: e.error ?? "" }], "") : undefined;
+ if (why) return void (rejected = { path: e.path, why });
+ }
+ const after = rejected ? `(${rejected.path} 被拒:${rejected.why};已改用 Chat Completions)` : "";
+ if (e.phase === "response") mark("model", e.status < 400 ? "ok" : "fail", e.status < 400 ? `HTTP ${e.status}${after}` : `HTTP ${e.status}${e.error ? `:${e.error}` : ""}${after}`, e.ms);
else mark("model", "fail", e.error, e.ms);
});
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index 90ff9cd..1883e97 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -6,7 +6,7 @@ import module from "node:module";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { App } from "../src/app.js";
import { loadConfig } from "../src/config.js";
-import { locateDshRuntime } from "../src/agent/host.js";
+import { RETRY_NOTE, locateDshRuntime } from "../src/agent/host.js";
import { findAppRoot } from "../src/magpie/supervisor.js";
import { listen } from "./helpers.js";
@@ -158,6 +158,11 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
const catalog: Record<string, string[]> = {};
/** FLAKY:每条这样的用户消息第一次请求先失败一次(Responses 503、Messages 429),看代理会不会重试 */
const flaked = new Set<string>();
+ /**
+ * 上游不接受某个模型在 Responses / Messages 上的请求(Chat 照常):always 每次都 400;after-tool 带着工具结果时 400;
+ * busy 每次都 503(不是请求形状的问题)
+ */
+ const rejects: Record<string, "always" | "after-tool" | "busy"> = {};
const hung: http.ServerResponse[] = [];
let base = "";
@@ -165,7 +170,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
function plan(messages: any[]): Step {
let lastUser = -1;
for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
+ if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|COUNTER|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
}
const user = textOf(messages[lastUser]?.content);
const tools = messages.slice(lastUser + 1).filter((m) => m.role === "tool");
@@ -191,6 +196,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
{ name: "glob", args: { pattern: "*.png" } },
...(canStripTypes ? [{ name: "workflow", args: { script: "return { answer: 6 * 7 }", meta: { name: "calc", description: "multiply" } } }] : []),
]],
+ [/COUNTER/, [{ name: "bash", args: { description: "run", command: "echo ran >> counter.txt && wc -l < counter.txt" } }]],
[/LOOPBACK/, [{ name: "bash", args: { description: "run", command: `python3 -c "import urllib.request as u\ntry:\n print('API', u.urlopen('${base}/amb/api/status').status)\nexcept Exception as e:\n print('API', getattr(e,'code',e))"` } }]],
];
for (const [re, steps] of scripts) {
@@ -218,6 +224,17 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
calls.push({ api, model: b.model, body: b, headers: req.headers, error: error ?? (flaky ? `${flaky}` : undefined) });
if (error) return void res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: error } }));
if (flaky) return void res.writeHead(flaky, { "content-type": "application/json" }).end(JSON.stringify({ type: "error", error: { type: flaky === 429 ? "rate_limit_error" : "api_error", message: "slow down" } }));
+ const rule = api === "chat" ? undefined : rejects[b.model];
+ if (rule === "busy") {
+ calls[calls.length - 1].error = "503";
+ return void res.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: { type: "api_error", message: "upstream overloaded" } }));
+ }
+ if (rule === "always" || (rule === "after-tool" && msgs.some((m: any) => m.role === "tool"))) {
+ calls[calls.length - 1].error = "400";
+ return void res
+ .writeHead(400, { "content-type": "application/json" })
+ .end(JSON.stringify({ error: { message: "Unsupported parameter: 'reasoning.summary' is not supported with this model.", type: "invalid_request_error", param: "reasoning.summary", code: "unsupported_parameter" } }));
+ }
const step = b.tools ? plan(msgs) : { text: "标题" };
if ("hang" in step && step.hang) return void hung.push(res);
if (process.env.AMB_TEST_LLM_LOG) fs.appendFileSync(process.env.AMB_TEST_LLM_LOG, JSON.stringify({ url: req.url, stream: b.stream, tools: (b.tools ?? []).map((t: any) => t.function?.name ?? t.name), msgs: msgs.map((m: any) => [m.role, textOf(m.content).slice(0, 200), m.tool_calls?.map((t: any) => t.function?.name)]), step }) + "\n");
@@ -527,9 +544,81 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
expect(r.reply).toBe("好的");
expect(callsFor(model, from).filter((c) => c.body.tools).map((c) => `${c.api}:${c.error ?? "ok"}`)).toEqual([`${api}:${status}`, `${api}:ok`]);
expect(r.steps.some((s) => s.kind === "retry")).toBe(true);
+ // 限流、上游故障不是接口的问题:不回退
+ expect(app.agent.apiFallbacks.get(model)).toBeUndefined();
}
}, 180_000);
+ // —— 安全网:Responses / Messages 被上游拒绝(请求形状不被接受)→ 这个模型改走 Chat Completions ——
+ const fallbackFile = () => JSON.parse(fs.readFileSync(path.join(dataDir, "dsh", "api-fallback.json"), "utf8")).models;
+
+ it("a 400 on /v1/responses: the turn is redone over Chat Completions, and the model stays on Chat", async () => {
+ catalog["deepseek-mock"] = ["openai", "openai-response", "anthropic", "gemini"];
+ rejects["deepseek-mock"] = "always";
+ const host = app.agent.host("default");
+ const from = calls.length;
+ const r = await turnOn("fb-user", "deepseek-mock", "QUICKSORT despite rejection");
+ expect(r.reply).toContain("[1, 2, 3, 5, 7, 9]");
+ const mine = callsFor("deepseek-mock", from).filter((c) => c.body.tools);
+ expect(mine.map((c) => `${c.api}:${c.error ?? "ok"}`)).toEqual(["responses:400", "chat:ok", "chat:ok"]);
+ // 重做的那次:用户这条消息只交给模型一次,工具只跑一次
+ const users = mine[1].body.messages.filter((m: any) => m.role === "user" && /QUICKSORT despite/.test(textOf(m.content)));
+ expect(users).toHaveLength(1);
+ expect(textOf(mine[1].body.messages.findLast((m: any) => m.role === "user").content)).toBe(RETRY_NOTE);
+ expect(r.steps.filter((s) => s.kind === "tool")).toHaveLength(1);
+ expect(r.steps.find((s) => s.kind === "retry")).toMatchObject({ title: "改用 Chat Completions 重试", summary: expect.stringContaining("HTTP 400: Unsupported parameter") });
+ // 状态、故障排查、磁盘上的记录(按去掉前缀的模型 id,24 小时)
+ expect(host.api).toBe("openai-completions");
+ expect(host.status().api).toBe("openai-completions (fallback: HTTP 400: Unsupported parameter: 'reasoning.summary' is not supported with this model.)");
+ const diag = ((await (await fetch(`${base}/amb/api/diagnostics`)).json()) as any).agent;
+ expect(diag.hosts.default.api).toContain("fallback: HTTP 400");
+ expect(diag.apiFallbacks.map((f: any) => [f.model, f.from])).toContainEqual(["deepseek-mock", "openai-responses"]);
+ const rec = fallbackFile()["deepseek-mock"];
+ expect(rec).toMatchObject({ from: "openai-responses", reason: expect.stringContaining("HTTP 400") });
+ expect(rec.until - rec.at).toBe(24 * 3600_000);
+ expect(JSON.stringify(fallbackFile())).not.toContain("gw-key");
+
+ // 下一轮直接走 Chat,不再先试 Responses
+ const next = calls.length;
+ expect((await turnOn("fb-user", "deepseek-mock", "QUICKSORT again on chat")).reply).toContain("[1, 2, 3, 5, 7, 9]");
+ expect(callsFor("deepseek-mock", next).map((c) => c.api)).toEqual(callsFor("deepseek-mock", next).map(() => "chat"));
+ }, 180_000);
+
+ it("a persistent 503 is not a rejection of the API: no fallback, the turn fails as before", async () => {
+ catalog["gpt-busy"] = ["openai", "openai-response"];
+ rejects["gpt-busy"] = "busy";
+ const from = calls.length;
+ const r = await turnOn("busy-user", "gpt-busy", "hello busy");
+ expect(r.reply).toMatch(/⚠️/);
+ const mine = callsFor("gpt-busy", from).filter((c) => c.body.tools);
+ expect(mine.length).toBeGreaterThan(1); // 代理自己重试过
+ expect(mine.every((c) => c.api === "responses" && c.error === "503")).toBe(true);
+ expect(app.agent.apiFallbacks.get("gpt-busy")).toBeUndefined();
+ expect(app.agent.host("default").api).toBe("openai-responses");
+ expect(r.steps.some((s) => s.title === "改用 Chat Completions 重试")).toBe(false);
+ }, 180_000);
+
+ it("a rejection after a tool ran is not redone (the tool is not run twice), but the next turn uses Chat", async () => {
+ catalog["glm-mock"] = ["openai", "openai-response", "anthropic"];
+ rejects["glm-mock"] = "after-tool";
+ const counter = path.join(dataDir, "workspaces", "default", "counter.txt");
+ fs.rmSync(counter, { force: true });
+ const from = calls.length;
+ const r = await turnOn("after-tool-user", "glm-mock", "COUNTER once");
+ expect(r.reply).toMatch(/⚠️/);
+ expect(r.reply).toContain("Unsupported parameter");
+ expect(fs.readFileSync(counter, "utf8")).toBe("ran\n");
+ expect(callsFor("glm-mock", from).filter((c) => c.body.tools).map((c) => `${c.api}:${c.error ?? "ok"}`)).toEqual(["responses:ok", "responses:400"]);
+ expect(app.agent.apiFallbacks.get("mfb-x/glm-mock")).toMatchObject({ from: "openai-responses" });
+
+ const next = calls.length;
+ const again = await turnOn("after-tool-user", "glm-mock", "COUNTER twice");
+ expect(again.reply).toContain("RESULT<<2");
+ expect(fs.readFileSync(counter, "utf8")).toBe("ran\nran\n");
+ expect(callsFor("glm-mock", next).filter((c) => c.body.tools).map((c) => `${c.api}:${c.error ?? "ok"}`)).toEqual(["chat:ok", "chat:ok"]);
+ expect(app.agent.host("default").status().api).toMatch(/^openai-completions \(fallback: HTTP 400/);
+ }, 180_000);
+
it("vision models get the image itself over Responses and Messages too", async () => {
if (!app.agent.host("default").imageInput) return; // Linux 上的 Electron:只给路径(见上一个图片用例)
expect((await turnOn("resp-img", "gpt-6-mock", "LOOKIMG", [png])).reply).toMatch(/^SEEN<<data:image\/(png|jpeg|webp);base64\|path>>$/);
diff --git a/test/agent.unit.test.ts b/test/agent.unit.test.ts
index 2edadbf..6d725b0 100644
--- a/test/agent.unit.test.ts
+++ b/test/agent.unit.test.ts
@@ -7,7 +7,9 @@ import { ApprovalCenter, parseAnswer, promptText } from "../src/agent/approvals.
import { WeixinReply } from "../src/channels/weixin/channel.js";
import { WeixinQuota } from "../src/channels/weixin/quota.js";
import { AgentHost, agentApi, modelLimits, type AgentApi } from "../src/agent/host.js";
-import { AgentBridge, type ProxyEvent } from "../src/agent/bridge.js";
+import { AgentBridge, BOT_HEADER, type ProxyEvent, type Rejection } from "../src/agent/bridge.js";
+import { ApiFallbacks, shapeRejection } from "../src/agent/api-fallback.js";
+import { ActivityLog } from "../src/agent/activity.js";
import { listen } from "./helpers.js";
let dir: string;
@@ -267,6 +269,8 @@ describe("agent API per model", () => {
it("the patch names the API; Anthropic's base URL is the bridge root (the SDK adds /v1/messages)", () => {
const chat = patchFor("mfb-b/gemini-3.6-flash", "openai-completions");
expect(chat).toContain(' api: openai-completions\n baseURL: "http://127.0.0.1:1/v1"\n');
+ // 每个模型请求都标明机器人(bridge 用来归属上游错误)
+ expect(chat).toContain(` apiKeyEnv: AMB_MAGPIE_KEY\n headers:\n ${BOT_HEADER}: "b"\n`);
expect(chat).not.toMatch(/reasoning|compat/);
const claude = patchFor("mfb-b/claude-sonnet-5", "anthropic-messages", true);
expect(claude).toContain(' api: anthropic-messages\n baseURL: "http://127.0.0.1:1"\n');
@@ -326,6 +330,22 @@ describe("agent bridge model proxy", () => {
expect(seen[0].headers["x-api-key"]).toBeUndefined();
});
+ it("the bot header is not forwarded; upstream rejections are reported with the bot that sent the request", async () => {
+ await up.close();
+ up = await listen(async (req, res) => {
+ seen.push({ path: req.url!, headers: req.headers, body: "" });
+ res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: { message: `bad ${bridge.token}` } }));
+ });
+ const got: Rejection[] = [];
+ bridge.onRejection((r) => void got.push(r));
+ const r = await post("/v1/responses", { authorization: `Bearer ${bridge.token}`, [BOT_HEADER]: "bot-7" }, { model: "m", input: [] });
+ expect(r.status).toBe(400);
+ expect(seen[0].headers[BOT_HEADER]).toBeUndefined();
+ expect(got).toEqual([{ bot: "bot-7", path: "/v1/responses", status: 400, error: expect.stringContaining("bad ") }]);
+ // 错误体已脱敏(令牌不进日志、不进回退原因)
+ expect(got[0].error).not.toContain(bridge.token);
+ });
+
it("rejects a wrong token in either header", async () => {
expect((await post("/v1/messages", { "x-api-key": "nope" }, {})).status).toBe(401);
expect((await post("/v1/responses", { authorization: "Bearer nope" }, {})).status).toBe(401);
@@ -348,3 +368,71 @@ describe("agent bridge model proxy", () => {
]);
});
});
+
+describe("agent API fallback", () => {
+ const unsupported = JSON.stringify({ error: { message: "Unsupported parameter: 'reasoning.summary'", type: "invalid_request_error", code: "unsupported_parameter" } });
+
+ it("request-shape rejections (400/404/405/415/422) fall back; the reason is the upstream's message", () => {
+ expect(shapeRejection([{ status: 400, error: unsupported }], "magpie API error (400): …")).toBe("HTTP 400: Unsupported parameter: 'reasoning.summary'");
+ for (const status of [404, 405, 415, 422]) expect(shapeRejection([{ status, error: "no such route" }], "x")).toBe(`HTTP ${status}: no such route`);
+ expect(shapeRejection([{ status: 400, error: "" }], "x")).toBe("HTTP 400");
+ // 最近的一次说了算
+ expect(shapeRejection([{ status: 503, error: "x" }, { status: 422, error: "unknown field 'include'" }], "")).toBe("HTTP 422: unknown field 'include'");
+ });
+
+ it("rate limits, quota, auth, server errors, context overflow and content filters do not", () => {
+ for (const status of [401, 402, 403, 408, 409, 429, 500, 502, 503, 504, 529]) expect(shapeRejection([{ status, error: unsupported }], `${status} unsupported parameter`)).toBeUndefined();
+ expect(shapeRejection([{ status: 400, error: JSON.stringify({ error: { message: "This model's maximum context length is 200000 tokens", code: "context_length_exceeded" } }) }], "")).toBeUndefined();
+ expect(shapeRejection([{ status: 400, error: "Input is too long for requested model." }], "")).toBeUndefined();
+ expect(shapeRejection([{ status: 400, error: "Your request was flagged by our content policy" }], "")).toBeUndefined();
+ expect(shapeRejection([{ status: 400, error: "insufficient balance" }], "")).toBeUndefined();
+ expect(shapeRejection([], "pi-ai stream idle timeout after 300000ms")).toBeUndefined();
+ expect(shapeRejection([], "")).toBeUndefined();
+ });
+
+ it("without a status (error only in the stream): an 'unsupported / unknown parameter or endpoint' message falls back", () => {
+ expect(shapeRejection([], "Error Code invalid_request_error: Unsupported parameter: 'reasoning.effort'")).toMatch(/^Error Code/);
+ expect(shapeRejection([], "unknown_parameter: prompt_cache_retention")).toBeTruthy();
+ expect(shapeRejection([], "This endpoint does not support tools of type custom")).toBeTruthy();
+ expect(shapeRejection([], "429: unsupported parameter while rate limited")).toBeUndefined();
+ expect(shapeRejection([], "Rate limit reached for requests")).toBeUndefined();
+ });
+
+ it("is keyed by the bare model id, kept on disk for 24 hours, and expires", () => {
+ const file = path.join(dir, "dsh", "api-fallback.json");
+ const a = new ApiFallbacks(file);
+ a.set("mfb-b1/deepseek-v4-pro", "openai-responses", "HTTP 400: nope");
+ expect(a.get("modelflare/deepseek-v4-pro")).toMatchObject({ from: "openai-responses", reason: "HTTP 400: nope" });
+ expect(a.get("deepseek-v4-pro")).toBeTruthy();
+ expect(a.get("gpt-6-sol")).toBeUndefined();
+ const rec = JSON.parse(fs.readFileSync(file, "utf8")).models["deepseek-v4-pro"];
+ expect(rec.until - rec.at).toBe(24 * 3600_000);
+ if (process.platform !== "win32") expect(fs.statSync(file).mode & 0o777).toBe(0o600);
+ // 重启后仍然有效
+ expect(new ApiFallbacks(file).list()).toEqual([expect.objectContaining({ model: "deepseek-v4-pro", from: "openai-responses" })]);
+ // 过期了就不算,也从文件里去掉
+ const short = new ApiFallbacks(file, -1);
+ short.set("glm-5.3", "anthropic-messages", "HTTP 404");
+ expect(short.get("glm-5.3")).toBeUndefined();
+ expect(Object.keys(JSON.parse(fs.readFileSync(file, "utf8")).models)).not.toContain("glm-5.3");
+ // 文件坏了:从空开始
+ fs.writeFileSync(file, "{oops");
+ expect(new ApiFallbacks(file).list()).toEqual([]);
+ // 不给文件:只在内存里
+ const mem = new ApiFallbacks();
+ mem.set("x", "openai-responses", "r");
+ expect(mem.get("x")).toBeTruthy();
+ });
+
+ it("host status names the fallback; the activity log shows the redo as a retry step", () => {
+ const host = new AgentHost({ botId: "b", dataDir: dir, runtimeDir: "/rt", bridge: { url: "http://127.0.0.1:1" } as any, store });
+ host.api = "openai-responses";
+ expect(host.status().api).toBe("openai-responses");
+ host.api = "openai-completions";
+ host.fallback = { from: "openai-responses", reason: "HTTP 400: Unsupported parameter", at: 0, until: 1 };
+ expect(host.status().api).toBe("openai-completions (fallback: HTTP 400: Unsupported parameter)");
+ const log = new ActivityLog();
+ log.apply("api/fallback", { from: "openai-responses", to: "openai-completions", reason: "HTTP 400: Unsupported parameter" }, 1000);
+ expect(log.steps).toEqual([expect.objectContaining({ kind: "retry", title: "改用 Chat Completions 重试", summary: "openai-responses 被拒:HTTP 400: Unsupported parameter", status: "ok" })]);
+ });
+});