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(account): set routing strategy on app keys, fall back if unsupported

Marlaa42179622b5e
diff --git a/src/account/client.ts b/src/account/client.ts
index 9f402e0..af02559 100644
--- a/src/account/client.ts
+++ b/src/account/client.ts
@@ -19,6 +19,13 @@ export interface ConnectedAccount {
quota_per_unit: number;
}
+/**
+ * Key 的路由策略(Modelflare 控制台 Smart API Key 的 routing_strategy):low_cost = 低价优先,balanced = 均衡
+ * (控制台的默认:从价格居中的分组开始,先往贵的试再往便宜的试),stable = 稳定优先(分组倍率最高的先试)。
+ */
+export type RoutingStrategy = "low_cost" | "balanced" | "stable";
+export const ROUTING_STRATEGIES: readonly RoutingStrategy[] = ["low_cost", "balanced", "stable"];
+
export interface AppKey {
id: number;
name: string;
@@ -31,6 +38,8 @@ export interface AppKey {
used_usd: number;
created_at: number;
accessed_at: number;
+ /** 服务端支持路由策略时回显;没有这个字段说明服务端没认它 */
+ routing_strategy?: string;
/** 只在创建时返回一次 */
key?: string;
}
@@ -151,10 +160,10 @@ export class AccountSession {
listKeys(): Promise<AppKey[]> {
return this.request("GET", "/api-keys");
}
- createKey(name: string, limitUsd?: number): Promise<AppKey> {
- return this.request("POST", "/api-keys", { name, ...(limitUsd !== undefined ? { limit_usd: limitUsd } : {}) });
+ createKey(name: string, limitUsd?: number, routing?: RoutingStrategy): Promise<AppKey> {
+ return this.request("POST", "/api-keys", { name, ...(limitUsd !== undefined ? { limit_usd: limitUsd } : {}), ...(routing ? { routing_strategy: routing } : {}) });
}
- updateKey(id: number, patch: { name?: string; limit_usd?: number; unlimited?: boolean }): Promise<AppKey> {
+ updateKey(id: number, patch: { name?: string; limit_usd?: number; unlimited?: boolean; routing_strategy?: RoutingStrategy }): Promise<AppKey> {
return this.request("PATCH", `/api-keys/${id}`, patch);
}
async deleteKey(id: number): Promise<void> {
diff --git a/src/account/manager.ts b/src/account/manager.ts
index db16312..98a89a9 100644
--- a/src/account/manager.ts
+++ b/src/account/manager.ts
@@ -1,7 +1,7 @@
/**
* Modelflare 账户:登录 / 退出、本机设备 Key、余额与低余额提醒、每个机器人的预算 Key、
- * 用量 / 通知 / 邀请。只用 API Key 连接(没有登录账户)时,余额改从 credit_grants 读,
- * 依赖账户授权的功能(用量、通知、邀请、机器人预算)不可用。
+ * 用量 / 通知 / 邀请、Key 的性价比(路由策略)。只用 API Key 连接(没有登录账户)时,余额改从 credit_grants 读,
+ * 依赖账户授权的功能(用量、通知、邀请、机器人预算、性价比)不可用。
*/
import os from "node:os";
import { logger } from "../log.js";
@@ -9,7 +9,7 @@ import { t } from "../i18n/index.js";
import type { Store } from "../store/db.js";
import { MODELFLARE_CLIENT_ID, MODELFLARE_SCOPES, MODELFLARE_WEB, UTM, webUrl, type KeyBalance } from "../modelflare.js";
import { discover, OAuthError, revokeToken, startLogin, type LoginAttempt, type OidcEndpoints } from "./oauth.js";
-import { AccountRevokedError, AccountSession, ApiError, type AppKey, type ConnectedAccount, type UsageRow } from "./client.js";
+import { AccountRevokedError, AccountSession, ApiError, ROUTING_STRATEGIES, type AppKey, type ConnectedAccount, type RoutingStrategy, type UsageRow } from "./client.js";
import type { AccountRecord, AccountVault } from "./vault.js";
const log = logger("account");
@@ -59,10 +59,31 @@ export interface AccountStatus {
loginUrl: string;
alerts: AlertSettings;
lowBalance: boolean;
+ /** Key 的性价比:supported = Modelflare 认这个设置(回显过 routing_strategy),否则界面不显示这个控件 */
+ keyQuality: { strategy: RoutingStrategy; supported: boolean };
}
+/**
+ * 性价比(路由策略)的本机记录,存在 KV 的 account.routing 里:
+ * chosen:用户选的(没选过时按 DEFAULT_ROUTING);support:Modelflare 认不认这个字段(yes = 回显了,no = 拒绝或忽略),
+ * checkedAt:上次判断的时间(no 隔一天再试一次);applied:已经应用到本机全部 Key 的策略。
+ */
+interface RoutingState {
+ chosen?: RoutingStrategy;
+ support?: "yes" | "no";
+ checkedAt?: number;
+ applied?: RoutingStrategy;
+}
+
+export const DEFAULT_ROUTING: RoutingStrategy = "balanced";
+/** Modelflare 不认这个字段时,隔多久再试一次(服务端可能已经加上了) */
+const ROUTING_RETRY_MS = 24 * 3600_000;
+
const BOT_KEY = (botId: string) => `account.botKey.${botId}`;
const ALERTED = "account.lowBalanceAlerted";
+const ROUTING = "account.routing";
+/** 服务端拒绝了请求里的某个字段(校验失败);HTTP 200 + success:false 也按 400 算 */
+const rejected = (e: unknown) => e instanceof ApiError && (e.status === 400 || e.status === 422);
export class AccountManager {
private session: AccountSession | undefined;
@@ -82,6 +103,8 @@ export class AccountManager {
private refreshing: Promise<AccountStatus> | undefined;
private keyCheck: Promise<boolean> | undefined;
private keysChecked = { at: 0, replaced: false };
+ /** 改性价比和核对时的应用排成一队,免得旧的策略后到、盖掉新的 */
+ private routingQueue: Promise<unknown> = Promise.resolve();
constructor(
private o: {
@@ -126,6 +149,7 @@ export class AccountManager {
loginUrl: this.state === "signing_in" ? (this.login?.url ?? "") : "",
alerts,
lowBalance: bal !== null && alerts.lowBalanceUsd > 0 && bal < alerts.lowBalanceUsd,
+ keyQuality: { strategy: this.routingStrategy(), supported: this.routing().support === "yes" },
};
}
@@ -185,7 +209,7 @@ export class AccountManager {
const session = this.newSession(rec, { token: tokens.accessToken, expiresAt: tokens.expiresAt });
try {
const account = await session.account();
- const key = await session.createKey(this.deviceKeyName());
+ const key = await this.issueKey((routing) => session.createKey(this.deviceKeyName(), undefined, routing));
if (!key.key) throw new Error(t("account.no_new_key"));
try {
await this.o.hooks.connectKey(key.key);
@@ -195,6 +219,8 @@ export class AccountManager {
throw e;
}
session.updateRecord({ deviceKeyId: key.id });
+ // 刚登录时本机只有这一把 Key:它带着策略签发成功,就算已经应用过了
+ if (key.routing_strategy === this.routingStrategy()) this.saveRouting({ applied: this.routingStrategy() });
this.session = session;
this.state = "signed_in";
this.applyAccount(account);
@@ -235,6 +261,7 @@ export class AccountManager {
this.session = undefined;
this.state = "signed_out";
this.o.vault.clear();
+ this.saveRouting({ applied: undefined });
await this.o.hooks.disconnect();
for (const botId of this.botKeyIds().keys()) this.o.store.deleteKV(BOT_KEY(botId));
this.snapshot = { name: "", source: "none", balanceUsd: null, usedUsd: null, billedToEnterprise: false, updatedAt: 0, error: "" };
@@ -383,7 +410,7 @@ export class AccountManager {
id = undefined; // 在控制台里被删掉了:重新签发
}
}
- const key = await this.call((s) => s.createKey(keyName(botName), budget.limitUsd));
+ const key = await this.issueKey((routing) => this.call((s) => s.createKey(keyName(botName), budget.limitUsd, routing)));
if (!key.key) throw new Error(t("account.no_new_key"));
try {
await this.o.hooks.setBotKey(botId, key.key);
@@ -440,7 +467,7 @@ export class AccountManager {
if (!alive.has(session.record.deviceKeyId) && !this.adoptDeviceKey(session, keys, botKeys) && (await this.o.hooks.sharedKeyRejected())) {
if (this.session !== session) return false;
log.warn("device key is gone on Modelflare, issuing a new one", { id: session.record.deviceKeyId });
- const key = await this.call((s) => s.createKey(this.deviceKeyName()));
+ const key = await this.issueKey((routing) => this.call((s) => s.createKey(this.deviceKeyName(), undefined, routing)));
if (!key.key) throw new Error(t("account.no_new_key"));
try {
await this.o.hooks.connectKey(key.key);
@@ -474,6 +501,7 @@ export class AccountManager {
}
// 预算已经关掉的机器人:只把内置网关里它那把失效的 Key 拿掉
for (const botId of lost) await this.o.hooks.removeBotKey(botId).catch(() => {});
+ if (this.session === session) await this.syncRouting(session);
return replaced;
}
@@ -490,6 +518,138 @@ export class AccountManager {
return true;
}
+ // ---------- 性价比(Key 的路由策略) ----------
+
+ private routing(): RoutingState {
+ try {
+ const v = JSON.parse(this.o.store.getKV(ROUTING) ?? "{}") as RoutingState;
+ return v && typeof v === "object" ? v : {};
+ } catch {
+ return {};
+ }
+ }
+
+ private saveRouting(patch: Partial<RoutingState>): void {
+ this.o.store.setKV(ROUTING, JSON.stringify({ ...this.routing(), ...patch }));
+ }
+
+ /** 现在的性价比:用户选的,没选过时是均衡 */
+ routingStrategy(): RoutingStrategy {
+ const c = this.routing().chosen;
+ return c && ROUTING_STRATEGIES.includes(c) ? c : DEFAULT_ROUTING;
+ }
+
+ /** 记下 Modelflare 认不认这个字段;不认时写日志(只在状态变了时) */
+ private noteRouting(supported: boolean, why: string): void {
+ const before = this.routing().support;
+ this.saveRouting({ support: supported ? "yes" : "no", checkedAt: Date.now() });
+ if (!supported && before !== "no") log.warn("Modelflare doesn't accept a routing strategy on app keys", { why });
+ }
+
+ /** 签发 Key 时要带的策略:Modelflare 最近说过不认就不带(隔一天再试) */
+ private routingToSend(): RoutingStrategy | undefined {
+ const st = this.routing();
+ if (st.support === "no" && Date.now() - (st.checkedAt ?? 0) < ROUTING_RETRY_MS) return undefined;
+ return this.routingStrategy();
+ }
+
+ /**
+ * 签发一把 Key,带上性价比。被拒(400 / 422)就不带再签一次,记下"不支持";签发本身绝不因为这个字段失败。
+ * 签发成功后看回显:带回同样的 routing_strategy 才算支持,没回显说明服务端忽略了它。
+ */
+ private async issueKey(create: (routing?: RoutingStrategy) => Promise<AppKey>): Promise<AppKey> {
+ const routing = this.routingToSend();
+ if (!routing) return create();
+ let key: AppKey;
+ try {
+ key = await create(routing);
+ } catch (e) {
+ if (!rejected(e)) throw e;
+ key = await create();
+ this.noteRouting(false, `create rejected: ${(e as Error).message}`);
+ return key;
+ }
+ this.noteRouting(key.routing_strategy === routing, "create ignored the field");
+ return key;
+ }
+
+ /**
+ * 把策略应用到本机签发的全部 Key(本机 Key + 各机器人的预算 Key)。
+ * 返回 ok;unsupported = Modelflare 拒绝或忽略了这个字段;网络等其他错误照常抛出。已被删除的 Key 跳过(核对时会重签)。
+ */
+ private applyRouting(strategy: RoutingStrategy, ids: number[]): Promise<"ok" | "unsupported"> {
+ const run = async (): Promise<"ok" | "unsupported"> => {
+ for (const id of ids) {
+ let k: AppKey;
+ try {
+ k = await this.call((s) => s.updateKey(id, { routing_strategy: strategy }));
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 404) continue;
+ if (!rejected(e)) throw e;
+ this.noteRouting(false, `update rejected: ${(e as Error).message}`);
+ return "unsupported";
+ }
+ if (k?.routing_strategy !== strategy) {
+ this.noteRouting(false, "update ignored the field");
+ return "unsupported";
+ }
+ this.noteRouting(true, "");
+ }
+ this.saveRouting({ applied: strategy });
+ return "ok";
+ };
+ const p = this.routingQueue.then(run, run);
+ this.routingQueue = p.catch(() => undefined);
+ return p;
+ }
+
+ private appKeyIds(session: AccountSession): number[] {
+ return [session.record.deviceKeyId, ...this.botKeyIds().values()].filter((id) => id > 0);
+ }
+
+ /**
+ * 改性价比:先改 Modelflare 上本机签发的全部 Key,成功了才算改好。Modelflare 不认这个字段时不改,返回 409,
+ * 状态里 supported 变成 false(界面随之收起这个控件)。
+ */
+ async setRoutingStrategy(strategy: RoutingStrategy): Promise<AccountStatus> {
+ if (!this.session) throw new ApiError(t("account.sign_in_first"), 409);
+ if (!ROUTING_STRATEGIES.includes(strategy)) throw new ApiError(t("account.routing_invalid"), 400);
+ const prev = this.routing().chosen;
+ this.saveRouting({ chosen: strategy });
+ let r: "ok" | "unsupported";
+ try {
+ r = await this.applyRouting(strategy, this.appKeyIds(this.session));
+ } catch (e) {
+ this.saveRouting({ chosen: prev });
+ throw e;
+ }
+ if (r === "unsupported") {
+ this.saveRouting({ chosen: prev });
+ throw new ApiError(t("account.routing_unsupported"), 409);
+ }
+ log.info("key routing strategy changed", { strategy });
+ return this.status();
+ }
+
+ /**
+ * 核对 Key 时顺带:本机的 Key 还没用上现在的策略就补上。没选过的老用户第一次走到这里,就把默认的均衡
+ * 应用到已有的 Key 上(只这一次,之后控制台里手动改的不会被盖掉)。Modelflare 不认时隔一天再试。不抛错。
+ */
+ private async syncRouting(session: AccountSession): Promise<void> {
+ const st = this.routing();
+ const strategy = this.routingStrategy();
+ const due = st.support === "no" ? Date.now() - (st.checkedAt ?? 0) >= ROUTING_RETRY_MS : st.applied !== strategy;
+ if (!due) return;
+ const ids = this.appKeyIds(session);
+ try {
+ if ((await this.applyRouting(strategy, ids)) === "ok") {
+ log.info(st.chosen ? "applied key routing strategy" : "applied the default key routing strategy to existing keys", { strategy, keys: ids.length });
+ }
+ } catch (e) {
+ log.warn("applying key routing strategy failed", { message: (e as Error).message });
+ }
+ }
+
/** App 注入:当前机器人及其预算设置 */
botsSource: () => Array<{ id: string; name: string; budget: BotBudget }> = () => [];
}
diff --git a/src/i18n/messages/account.ts b/src/i18n/messages/account.ts
index eee75dd..3cacb0a 100644
--- a/src/i18n/messages/account.ts
+++ b/src/i18n/messages/account.ts
@@ -15,6 +15,8 @@ export const zh = {
budget_needs_login: "给机器人设预算需要先登录 Modelflare 账户",
key_reissued: "本机用的 Modelflare API Key 已被删除,已自动重新签发一把",
bot_key_reissued: "机器人「{name}」的预算 Key 已被删除,已按 ${limit} 的预算重新签发(用量从零算起)",
+ routing_invalid: "不认识的性价比选项",
+ routing_unsupported: "Modelflare 暂不支持为应用签发的 Key 设置性价比",
// oauth.ts
host_unreachable: "连不上 {host}({reason})",
discovery_failed: "读取登录配置失败(HTTP {status})",
@@ -49,6 +51,8 @@ export const en: Catalog<typeof zh> = {
budget_needs_login: "Sign in to your Modelflare account to set a bot budget",
key_reissued: "This computer's Modelflare API key was deleted, so a new one was issued automatically",
bot_key_reissued: "The budget key for bot \"{name}\" was deleted, so a new one was issued with the ${limit} budget (spending starts from zero)",
+ routing_invalid: "Unknown value option",
+ routing_unsupported: "Modelflare doesn't support this setting for app keys yet",
host_unreachable: "Can't reach {host} ({reason})",
discovery_failed: "Couldn't read the sign-in configuration (HTTP {status})",
discovery_bad_endpoint: "Invalid {key} in the sign-in configuration",
diff --git a/src/web/server.ts b/src/web/server.ts
index 37ee087..6842315 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -11,7 +11,7 @@ import { findAppRoot } from "../magpie/supervisor.js";
import { logFilePath, logger, readLogTail, registerSecret } from "../log.js";
import { diagnosticsReport, safeStatus, testAgent, testModel } from "../diagnostics.js";
import { ZOOMS, normalizeLowBalance, saveConfigFile } from "../config.js";
-import { ApiError } from "../account/client.js";
+import { ApiError, ROUTING_STRATEGIES } from "../account/client.js";
import { OAuthError } from "../account/oauth.js";
import { normalizeLine } from "../modelflare.js";
import { SseReply } from "./sse-reply.js";
@@ -444,6 +444,13 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
if (sub === "notifications" && m === "GET") return send(res, 200, { data: await accountCall(() => app.account.notifications()) });
if (sub === "invite" && m === "GET") return send(res, 200, await accountCall(() => app.account.invite()));
if (sub === "budgets" && m === "GET") return send(res, 200, { budgets: await accountCall(() => app.account.botBudgets()) });
+ if (sub === "key-quality" && m === "PUT") {
+ const b = await readJson(req);
+ const strategy = ROUTING_STRATEGIES.find((x) => x === b.strategy);
+ if (!strategy) throw new HttpError(400, t("account.routing_invalid"));
+ await accountCall(() => app.account.setRoutingStrategy(strategy));
+ return send(res, 200, status());
+ }
}
if (p === "/settings") {
if (m === "PUT") {
diff --git a/test/account.test.ts b/test/account.test.ts
index 4edb384..1436575 100644
--- a/test/account.test.ts
+++ b/test/account.test.ts
@@ -285,6 +285,103 @@ describe("AccountManager", () => {
it("没登录时不核对", async () => {
expect(await manager.repairKeys()).toBe(false);
});
+
+ // —— 性价比(Key 的路由策略 routing_strategy)——
+ const posts = () => mf.s.keyWrites.filter((w) => w.method === "POST");
+ const patches = () => mf.s.keyWrites.filter((w) => w.method === "PATCH");
+
+ it("性价比:登录签发的 Key 带着均衡;Modelflare 回显了才算支持,核对时不再重复改", async () => {
+ mf.s.routing = "echo";
+ await signIn();
+ expect(posts()).toMatchObject([{ body: { name: "AnyModelBot · test-pc", routing_strategy: "balanced" } }]);
+ expect(manager.status().keyQuality).toEqual({ strategy: "balanced", supported: true });
+ await manager.repairKeys();
+ expect(patches()).toEqual([]);
+ // 预算 Key 也带着
+ await manager.setBotBudget("b1", "写作助手", { enabled: true, limitUsd: 5 });
+ expect(posts()[1].body).toMatchObject({ limit_usd: 5, routing_strategy: "balanced" });
+ });
+
+ it("性价比:Modelflare 拒绝这个字段时不带它再签一次,登录和预算照常,之后一天内不再带;控件不显示", async () => {
+ mf.s.routing = "reject";
+ await signIn();
+ expect(calls).toEqual(["connect:sk-key-1"]);
+ expect(posts().map((w) => w.body.routing_strategy)).toEqual(["balanced", undefined]);
+ expect(manager.status().keyQuality).toEqual({ strategy: "balanced", supported: false });
+ await manager.setBotBudget("b1", "写作助手", { enabled: true, limitUsd: 5 });
+ expect(calls).toContain("bot:b1:sk-key-2");
+ expect(posts()[2].body).not.toHaveProperty("routing_strategy");
+ // 核对不去改;硬要改时 409,设置不变
+ await manager.repairKeys();
+ expect(patches()).toEqual([]);
+ await expect(manager.setRoutingStrategy("low_cost")).rejects.toMatchObject({ status: 409 });
+ expect(manager.status().keyQuality).toEqual({ strategy: "balanced", supported: false });
+ });
+
+ it("性价比:Modelflare 不认也不报错(不回显)时同样记为不支持", async () => {
+ await signIn(); // mock 默认 ignore
+ expect(posts()[0].body.routing_strategy).toBe("balanced");
+ expect(calls).toEqual(["connect:sk-key-1"]);
+ expect(manager.status().keyQuality.supported).toBe(false);
+ await manager.repairKeys();
+ expect(patches()).toEqual([]);
+ });
+
+ it("性价比:已登录、没选过的老用户第一次核对时把均衡应用到已有的全部 Key 上,只这一次", async () => {
+ mf.s.routing = "echo";
+ manager.botsSource = () => [{ id: "b1", name: "写作助手", budget: { enabled: true, limitUsd: 3 } }];
+ await signIn();
+ await until(() => calls.includes("bot:b1:sk-key-2"));
+ // 模拟升级前:Key 上没有策略,本机也没有记录
+ store.deleteKV("account.routing");
+ for (const k of mf.s.keys) delete k.routing_strategy;
+ mf.s.keyWrites = [];
+ const again = make();
+ again.botsSource = manager.botsSource;
+ expect(again.status().keyQuality).toEqual({ strategy: "balanced", supported: false });
+ await again.repairKeys();
+ expect(patches().map((w) => [w.id, w.body])).toEqual([
+ [1, { routing_strategy: "balanced" }],
+ [2, { routing_strategy: "balanced" }],
+ ]);
+ expect(mf.s.keys.map((k) => k.routing_strategy)).toEqual(["balanced", "balanced"]);
+ expect(again.status().keyQuality).toEqual({ strategy: "balanced", supported: true });
+ await again.repairKeys();
+ expect(patches()).toHaveLength(2);
+ });
+
+ it("性价比:改了就改 Modelflare 上本机的全部 Key,成功了才算;Modelflare 拒绝时不改、控件收起", async () => {
+ mf.s.routing = "echo";
+ await signIn();
+ await manager.setBotBudget("b1", "写作助手", { enabled: true, limitUsd: 5 });
+ const st = await manager.setRoutingStrategy("low_cost");
+ expect(st.keyQuality).toEqual({ strategy: "low_cost", supported: true });
+ expect(mf.s.keys.map((k) => k.routing_strategy)).toEqual(["low_cost", "low_cost"]);
+ // 新签发的也跟着
+ await manager.setBotBudget("b2", "翻译", { enabled: true, limitUsd: 1 });
+ expect(posts().at(-1)!.body.routing_strategy).toBe("low_cost");
+ mf.s.routing = "reject";
+ await expect(manager.setRoutingStrategy("stable")).rejects.toMatchObject({ status: 409 });
+ expect(manager.status().keyQuality).toEqual({ strategy: "low_cost", supported: false });
+ });
+
+ it("性价比:不支持的隔一天再试一次,Modelflare 加上了就补上", async () => {
+ await signIn(); // ignore:记为不支持
+ mf.s.routing = "echo";
+ await manager.repairKeys();
+ expect(patches()).toEqual([]);
+ const rec = JSON.parse(store.getKV("account.routing")!);
+ store.setKV("account.routing", JSON.stringify({ ...rec, checkedAt: Date.now() - 25 * 3600_000 }));
+ await manager.repairKeys();
+ expect(patches().map((w) => w.body)).toEqual([{ routing_strategy: "balanced" }]);
+ expect(manager.status().keyQuality).toEqual({ strategy: "balanced", supported: true });
+ });
+
+ it("性价比:不认识的值 400,没登录 409", async () => {
+ await expect(manager.setRoutingStrategy("balanced")).rejects.toMatchObject({ status: 409 });
+ await signIn();
+ await expect(manager.setRoutingStrategy("fastest" as never)).rejects.toMatchObject({ status: 400 });
+ });
});
describe("账户文件加密", () => {
diff --git a/test/helpers.ts b/test/helpers.ts
index 5461924..42530a1 100644
--- a/test/helpers.ts
+++ b/test/helpers.ts
@@ -328,7 +328,11 @@ export async function mockModelflare() {
access: new Set<string>(),
revoked: [] as string[],
tokenForms: [] as Record<string, string>[],
- keys: [] as Array<{ id: number; name: string; limit_usd: number | null; used_usd: number }>,
+ keys: [] as Array<{ id: number; name: string; limit_usd: number | null; used_usd: number; routing_strategy?: string }>,
+ /** 服务端怎么对待 Key 的 routing_strategy:echo = 支持(存下并回显),ignore = 不认也不报错,reject = 400 */
+ routing: "ignore" as "echo" | "ignore" | "reject",
+ /** 收到的 Key 请求(签发、修改)和请求体 */
+ keyWrites: [] as Array<{ method: string; id?: number; body: Record<string, unknown> }>,
balance: 12.5,
revokeAll: false,
/** GET /api-keys 被请求的次数 */
@@ -338,7 +342,15 @@ export async function mockModelflare() {
let n = 0;
// Key 的 id 和服务端一样只增不减:删掉一把后新签发的不会和它重号
let keySeq = 0;
- const keyOut = (k: (typeof s.keys)[number]) => ({ ...k, key_tail: `sk-key-${k.id}`.slice(-4), status: "enabled", unlimited: k.limit_usd === null, remain_usd: k.limit_usd });
+ const keyOut = ({ routing_strategy, ...k }: (typeof s.keys)[number]) => ({
+ ...k,
+ ...(s.routing === "echo" && routing_strategy ? { routing_strategy } : {}),
+ key_tail: `sk-key-${k.id}`.slice(-4),
+ status: "enabled",
+ unlimited: k.limit_usd === null,
+ remain_usd: k.limit_usd,
+ });
+ const rejectRouting = (b: Record<string, unknown>) => s.routing === "reject" && "routing_strategy" in b;
const issue = (res: http.ServerResponse) => {
const access = `at-${++n}`;
const refresh = `rt-${n}`;
@@ -385,7 +397,9 @@ export async function mockModelflare() {
if (p === "/account") return json({ success: true, data: { display_name: "Ada", username: "ada", group: "default", balance_usd: s.balance, used_usd: 3, billed_to_enterprise: false, quota_per_unit: 500000 } });
if (p === "/api-keys" && req.method === "POST") {
const b = await readJson(req);
- const k = { id: ++keySeq, name: b.name, limit_usd: b.limit_usd ?? null, used_usd: 0 };
+ s.keyWrites.push({ method: "POST", body: b });
+ if (rejectRouting(b)) return json({ success: false, message: "unknown field: routing_strategy" }, 400);
+ const k = { id: ++keySeq, name: b.name, limit_usd: b.limit_usd ?? null, used_usd: 0, ...(s.routing === "echo" && b.routing_strategy ? { routing_strategy: b.routing_strategy } : {}) };
s.keys.push(k);
return json({ success: true, data: { ...keyOut(k), key: `sk-key-${k.id}` } });
}
@@ -396,9 +410,13 @@ export async function mockModelflare() {
const m = p.match(/^\/api-keys\/(\d+)$/);
if (m && req.method === "PATCH") {
const k = s.keys.find((x) => x.id === Number(m[1]));
+ const b = await readJson(req);
+ s.keyWrites.push({ method: "PATCH", id: Number(m[1]), body: b });
if (!k) return json({ success: false, message: "not found" }, 404);
- Object.assign(k, { limit_usd: (await readJson(req)).limit_usd });
- return json({ success: true, data: k });
+ if (rejectRouting(b)) return json({ success: false, message: "unknown field: routing_strategy" }, 400);
+ if ("limit_usd" in b) k.limit_usd = b.limit_usd;
+ if (s.routing === "echo" && b.routing_strategy) k.routing_strategy = b.routing_strategy;
+ return json({ success: true, data: keyOut(k) });
}
if (m && req.method === "DELETE") {
s.keys = s.keys.filter((x) => x.id !== Number(m[1]));