🤖 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.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
feat(account): Modelflare 账户登录、余额与充值、机器人预算与生图生视频
dyk980dc82a43d4b7
diff --git a/.env.example b/.env.exampleindex 54d1053..57c9e72 100644--- a/.env.example+++ b/.env.example@@ -16,6 +16,8 @@# AMB_MAGPIE_API_KEY=# 仅开发/测试:把 Modelflare 基址指向本地 mock(界面无法设置;正式使用只有 modelflare.dev 与 origin.modelflare.dev 两条线路)# AMB_MODELFLARE_BASE_URL=http://127.0.0.1:8080/v1+# 仅开发/测试:把账户登录(OIDC 发现文档、授权、令牌)与账户接口指向本地 mock;正式使用固定为 https://modelflare.dev+# AMB_MODELFLARE_ISSUER=http://127.0.0.1:8080# 对话# AMB_DEFAULT_MODEL=openai/gpt-5.6-soldiff --git a/.gitignore b/.gitignoreindex 59875ca..7d69a91 100644--- a/.gitignore+++ b/.gitignore@@ -6,3 +6,4 @@ data/.env*.logtest-results/+.DS_Storediff --git a/README.md b/README.mdindex 54474ce..7114103 100644--- a/README.md+++ b/README.md@@ -1,7 +1,7 @@# AnyModelBot任意模型的个人 AI 助手:一个机器人 = 人设 + 默认模型 + 渠道(飞书 / 微信)。-模型来自 **[Modelflare](https://modelflare.dev)**:首次启动粘贴一个 Modelflare API Key,GPT、Claude、Grok、Gemini 等模型自动列出。+模型来自 **[Modelflare](https://modelflare.dev)**:首次启动登录(或注册)Modelflare 账户,GPT、Claude、Grok、Gemini 等模型自动列出;也可以直接粘贴一个 API Key。请求经过内置的 [magpie](https://github.com/yetone/magpie) 网关转发(实现细节,界面里不出现)。- 飞书:官方机器人,长连接(WSClient)接收事件,CardKit 流式卡片回复@@ -19,7 +19,8 @@ src/magpie/ 内置 magpie 守护:隔离目录、空闲端口、自动生成密钥、健康检查、崩溃重启、干净退出channels/ feishu/(长连接 + CardKit) weixin/(iLink,MIT 声明见 LICENSE.openclaw-weixin)store/ SQLite(node:sqlite,无需原生编译)- modelflare.ts Modelflare 线路与密钥校验(GET /v1/models)+ modelflare.ts Modelflare 线路、密钥校验(GET /v1/models)、模型路由与归因+ account/ Modelflare 账户:PKCE 回环登录、令牌轮换、余额与提醒、机器人预算 Key、模型能力与参考价web/ 管理界面服务(JSON API + 流式对话 SSE)cli/ init 首次设置向导、weixin-loginmain.ts 命令行入口@@ -36,7 +37,7 @@ vendor/magpie magpie 源码(git 子模块,构建时编译)```bashnpm installnpm run setup # 拉取 vendor/magpie 子模块并编译到 build/bin/-npm run init # 可选:终端里的首次设置(Modelflare API Key、飞书凭据)+npm run init # 可选:终端里的首次设置(登录 Modelflare 账户或粘贴 API Key、飞书凭据)npm start # 启动全部:内置网关 + 机器人 + 管理界面 http://127.0.0.1:3600/```@@ -70,13 +71,21 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令## 模型(Modelflare)-- 首次启动只有一个页面:粘贴 Modelflare API Key → 校验(`GET https://modelflare.dev/v1/models`)→ 选默认模型 → 开始对话。还没有 Key 可去 [Modelflare](https://modelflare.dev) 控制台创建。+- 首次启动只有一个页面,主按钮是「登录 / 注册 Modelflare」:在系统浏览器里登录(没有账户可当场注册)并点「继续」授权,回到本程序后自动为这台电脑签发一把专用 API Key 并连接 → 选默认模型 → 开始对话。也可以点「我有 API Key」直接粘贴一个 Key(校验 `GET https://modelflare.dev/v1/models`)。+- 登录方式:OIDC 授权码 + PKCE(RFC 7636),按 RFC 8252 作为原生应用——本程序是公共客户端(`client_id` 为 `anymodel-bot`,没有也不需要客户端密钥),授权结果回调到本机 `127.0.0.1` 的临时端口。在 Modelflare 网页个人资料页的「已授权的应用」里可以随时撤销;撤销后本程序会发现并回到登录页。+- 账户凭据(refresh token)存在数据目录的 `modelflare-account.json`(权限 600),桌面版用系统钥匙串加密(Electron safeStorage);界面只拿到账户名称。「退出登录」会撤销这台电脑的授权,Modelflare 同时删除登录时为它和各机器人签发的 Key。+- 余额:侧栏左下角和 设置 → Modelflare 显示账户钱包余额(只用 API Key 时读 `/v1/dashboard/billing/credit_grants`);「充值」打开 Modelflare 网页,回到窗口时自动刷新。余额低于提醒线(默认 $1,可改或关闭)时在应用里提醒一次,也可以设置让机器人发到你的微信 / 飞书。+- 登录后还能在 设置 → Modelflare 查看按天、按模型的用量,Modelflare 发来的通知,以及复制邀请链接。+- 机器人预算(需要登录):机器人设置 → 预算,开启后这个机器人用自己的 Key(内置网关里单独的 provider),最多花设定的美元数;关闭后回到共用的 Key。+- 生图 / 生视频:代理模式下机器人有 `generate_image`、`generate_video` 工具,由本程序带着该机器人用的 Key 调 Modelflare,结果存进机器人工作区的 `media/`,再交付到聊天。+- 模型选择器里显示上下文长度、视觉 / 工具 / 推理能力,以及每百万 tokens 输入 / 输出的起步参考价(来自公开价格目录,以账单为准)。+- 调用归因:经 Modelflare 的请求都带 `X-Modelflare-Skill: anymodel-bot/<版本>`,链接都带 `utm_source=anymodelbot`。- 线路:默认国际线路 `https://modelflare.dev/v1`;中国大陆可在「高级」或 设置 → Modelflare → 线路 选「中国大陆优化」(`https://origin.modelflare.dev/v1`)。线路由你选定,不自动切换。-- 设置 → Modelflare:查看连接状态(只显示 Key 尾号)、更换密钥、断开(机器人与会话保留,断开后回到首次连接页)、默认模型、刷新模型列表;用量与账单以 Modelflare 控制台为准。+- 设置 → Modelflare:账户、余额与充值、余额提醒、用量、通知、邀请;连接状态(只显示 Key 尾号);未登录时可更换密钥或断开(机器人与会话保留,断开后回到首次连接页);默认模型、刷新模型列表。- 对话中输入框右侧的模型按钮可为当前会话切换模型(也可设为机器人默认);`/model`、`/reset`、`/new`、`/status`、`/help` 照常可用。- 内置网关:magpie 以 `--gateway` 模式运行,使用本程序数据目录内独立的 HOME/配置目录;**不读取**你电脑上已有的 Claude/Codex 等订阅凭据,**不改写**任何 agent 配置,关闭自动更新与账户发现。它只供本进程内部调用,界面不再反代它的页面或 `/v1`。- API Key 只保存在内置网关的隔离配置中,不经过命令行参数、不写日志,前端只拿到尾号。-- 开发/测试:设置 `AMB_MAGPIE_BASE_URL` 可直接使用一个 OpenAI 兼容端点(不启动内置网关,界面视为已连接);`AMB_MODELFLARE_BASE_URL` 可把 Modelflare 基址指向本地 mock。+- 开发/测试:设置 `AMB_MAGPIE_BASE_URL` 可直接使用一个 OpenAI 兼容端点(不启动内置网关,界面视为已连接,账户功能不可用);`AMB_MODELFLARE_BASE_URL` 可把 Modelflare 基址指向本地 mock,`AMB_MODELFLARE_ISSUER` 把登录与账户接口指向本地 mock。## 界面diff --git a/dsh-runtime/plugins/amb-media.mjs b/dsh-runtime/plugins/amb-media.mjsnew file mode 100644index 0000000..b534b9f--- /dev/null+++ b/dsh-runtime/plugins/amb-media.mjs@@ -0,0 +1,60 @@+// anymodel bot image / video generation tools (MIT, part of anymodel bot).+//+// Registers generate_image and generate_video. The agent never holds a Modelflare key: each call goes+// to the host over the loopback bridge (AMB_BRIDGE_URL / AMB_BRIDGE_TOKEN), which calls Modelflare with+// this bot's key and saves the result under media/ in the workspace. The agent then delivers the file+// with the present tool.+import { defineTool } from '@deepseek-ai/dsh-tools'++export const name = 'amb-media'+export const inject = ['tools']++const TEXT_OUT = {+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },+ render: (_args, value) => [{ type: 'text', text: value.text }],+}++export function apply(ctx) {+ const url = process.env.AMB_BRIDGE_URL+ const token = process.env.AMB_BRIDGE_TOKEN+ if (!url || !token) return+ const botId = process.env.AMB_BOT_ID ?? ''++ const run = async (op, args, exec) => {+ const res = await fetch(url + '/dsh/media', {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ botId, sessionId: String(exec.agent?.session?.id ?? ''), op, args }),+ signal: exec.signal,+ })+ if (!res.ok) throw new Error(`bridge /dsh/media ${res.status}`)+ const r = await res.json()+ if (r.error) throw new Error(String(r.error))+ return { text: String(r.text ?? '') }+ }++ ctx.tools.register(defineTool({+ name: 'generate_image',+ description: 'Generate an image from a text description with an image model on Modelflare. The image is saved in the workspace under media/; deliver it with the present tool when the user should receive it. Write the prompt in detail (subject, style, composition, text in the image).',+ parameters: {+ prompt: { type: 'string', required: true, description: 'What the image should show, in detail.' },+ model: { type: 'string', description: 'Image model id. Omit to use the first one this bot may use.' },+ size: { type: 'string', description: 'Optional size such as 1024x1024, for models on the Images API.' },+ },+ output: TEXT_OUT,+ execute: (args, exec) => run('image', args, exec),+ }))++ ctx.tools.register(defineTool({+ name: 'generate_video',+ description: 'Generate a short video from a text description with a video model on Modelflare. It can take several minutes. The video is saved in the workspace under media/; deliver it with the present tool. Only use it when the user asks for a video: video generation costs much more than images.',+ parameters: {+ prompt: { type: 'string', required: true, description: 'What the video should show, in detail.' },+ model: { type: 'string', description: 'Video model id. Omit to use the first one this bot may use.' },+ seconds: { type: 'number', description: 'Optional length in seconds, if the model supports it.' },+ size: { type: 'string', description: 'Optional size such as 1280x720, if the model supports it.' },+ },+ output: TEXT_OUT,+ execute: (args, exec) => run('video', args, exec),+ }))+}diff --git a/electron/main.ts b/electron/main.tsindex 7e5859c..c75e923 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -7,7 +7,7 @@* - 设置页里的开机自启、缩放、打开数据目录经 core.desktop 回调到这里(同进程,无需 preload/IPC)* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。*/-import { app, BrowserWindow, Menu, Tray, nativeImage, shell, dialog } from "electron";+import { app, BrowserWindow, Menu, Tray, nativeImage, shell, dialog, safeStorage } from "electron";import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";@@ -130,6 +130,13 @@ async function boot(): Promise<void> {applyZoom: (z) => win?.webContents.setZoomFactor(z),openDataDir: () => void shell.openPath(config.dataDir),openInBrowser: () => void shell.openExternal(entryUrl),+ openExternal: (url) => {+ if (/^https?:/i.test(url)) void shell.openExternal(url);+ },+ // 账户凭据用系统钥匙串加密(macOS 钥匙串、Windows DPAPI、Linux Secret Service)+ secretBox: safeStorage.isEncryptionAvailable()+ ? { encrypt: (plain) => safeStorage.encryptString(plain), decrypt: (data) => safeStorage.decryptString(data) }+ : undefined,};await core.start();if (!core.web) throw new Error("管理界面未启动");diff --git a/src/account/client.ts b/src/account/client.tsnew file mode 100644index 0000000..fa9bd6e--- /dev/null+++ b/src/account/client.ts@@ -0,0 +1,155 @@+/**+ * Modelflare connected-app 接口(/api/connected-app/*)的客户端。access token 只在内存里,+ * 过期前用 refresh token 换新;refresh token 每次都会轮换,新值立刻写回本机账户文件。+ */+import { OAuthError, refreshTokens, type OidcEndpoints } from "./oauth.js";+import type { AccountRecord } from "./vault.js";++/** 授权已失效(用户在网页上撤销、账户被停用等):需要重新登录 */+export class AccountRevokedError extends Error {}++export interface ConnectedAccount {+ display_name: string;+ username: string;+ group: string;+ balance_usd: number;+ used_usd: number;+ billed_to_enterprise: boolean;+ quota_per_unit: number;+}++export interface AppKey {+ id: number;+ name: string;+ key_tail: string;+ status: "enabled" | "disabled" | "expired" | "exhausted";+ unlimited: boolean;+ limit_usd: number | null;+ remain_usd: number | null;+ used_usd: number;+ created_at: number;+ accessed_at: number;+ /** 只在创建时返回一次 */+ key?: string;+}++export interface UsageRow {+ model_name: string;+ created_at: number;+ count: number;+ quota: number;+ token_used: number;+}++export class ApiError extends Error {+ constructor(message: string, readonly status: number) {+ super(message);+ }+}++export class AccountSession {+ private access: { token: string; expiresAt: number } | undefined;+ private refreshing: Promise<string> | undefined;++ constructor(+ private o: {+ /** 资源接口所在的发行方地址 */+ issuer: string;+ /** 令牌端点等取自发现文档;第一次需要换令牌时才去读,启动时不联网 */+ endpoints: () => Promise<OidcEndpoints>;+ clientId: string;+ record: AccountRecord;+ /** 轮换后的 refresh token 必须立刻落盘,否则重启后就换不了新令牌 */+ persist: (rec: AccountRecord) => void;+ fetchImpl?: typeof fetch;+ },+ initialAccess?: { token: string; expiresAt: number },+ ) {+ this.access = initialAccess;+ }++ get record(): AccountRecord {+ return this.o.record;+ }++ private get fetch(): typeof fetch {+ return this.o.fetchImpl ?? fetch;+ }++ /** 同一时刻只换一次:refresh token 会轮换,并发地拿旧值去换,第二个必然失败 */+ async accessToken(force = false): Promise<string> {+ if (!force && this.access && Date.now() < this.access.expiresAt) return this.access.token;+ this.refreshing ??= (async () => {+ try {+ const t = await refreshTokens(await this.o.endpoints(), this.o.clientId, this.o.record.refreshToken, this.fetch);+ this.o.record = { ...this.o.record, refreshToken: t.refreshToken, scope: t.scope || this.o.record.scope };+ this.o.persist(this.o.record);+ this.access = { token: t.accessToken, expiresAt: t.expiresAt };+ return t.accessToken;+ } catch (e) {+ if (e instanceof OAuthError && e.code === "invalid_grant") throw new AccountRevokedError("Modelflare 授权已失效,请重新登录");+ throw e;+ } finally {+ this.refreshing = undefined;+ }+ })();+ return this.refreshing;+ }++ /** 调用 connected-app 接口;401 时强制换一次令牌重试,仍然 401 说明授权已撤销 */+ async request<T>(method: string, path: string, body?: unknown): Promise<T> {+ for (let attempt = 0; ; attempt++) {+ const token = await this.accessToken(attempt > 0);+ let res: Response;+ try {+ res = await this.fetch(`${this.o.issuer}/api/connected-app${path}`, {+ method,+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: "application/json",+ // 通知等内容按语言返回+ "Accept-Language": "zh-CN",+ ...(body !== undefined ? { "content-type": "application/json" } : {}),+ },+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal: AbortSignal.timeout(20_000),+ });+ } catch (e) {+ throw new ApiError(`连不上 Modelflare(${(e as Error).message})`, 0);+ }+ if (res.status === 401) {+ if (attempt === 0) continue;+ throw new AccountRevokedError("Modelflare 授权已失效,请重新登录");+ }+ const data = (await res.json().catch(() => ({}))) as { success?: boolean; data?: T; message?: string; error_description?: string };+ // 部分校验沿用控制台的写法:HTTP 200 + success:false+ if (!res.ok || data.success === false) throw new ApiError(data.message || data.error_description || `HTTP ${res.status}`, res.ok ? 400 : res.status);+ return data.data as T;+ }+ }++ account(): Promise<ConnectedAccount> {+ return this.request("GET", "/account");+ }+ usage(start: number, end: number): Promise<UsageRow[] | null> {+ return this.request("GET", `/usage?start_timestamp=${start}&end_timestamp=${end}`);+ }+ notifications(): Promise<unknown> {+ return this.request("GET", "/notifications");+ }+ invite(): Promise<string> {+ return this.request("GET", "/invite");+ }+ 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 } : {}) });+ }+ updateKey(id: number, patch: { name?: string; limit_usd?: number; unlimited?: boolean }): Promise<AppKey> {+ return this.request("PATCH", `/api-keys/${id}`, patch);+ }+ async deleteKey(id: number): Promise<void> {+ await this.request("DELETE", `/api-keys/${id}`);+ }+}diff --git a/src/account/manager.ts b/src/account/manager.tsnew file mode 100644index 0000000..4667a1f--- /dev/null+++ b/src/account/manager.ts@@ -0,0 +1,457 @@+/**+ * Modelflare 账户:登录 / 退出、本机设备 Key、余额与低余额提醒、每个机器人的预算 Key、+ * 用量 / 通知 / 邀请。只用 API Key 连接(没有登录账户)时,余额改从 credit_grants 读,+ * 依赖账户授权的功能(用量、通知、邀请、机器人预算)不可用。+ */+import os from "node:os";+import { logger } from "../log.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 type { AccountRecord, AccountVault } from "./vault.js";++const log = logger("account");++export interface AccountHooks {+ /** 把签发的 Key 接到内置网关(先校验再写入) */+ connectKey(key: string): Promise<void>;+ /** 从内置网关删除 Modelflare 连接与全部机器人 provider */+ disconnect(): Promise<void>;+ setBotKey(botId: string, key: string): Promise<void>;+ removeBotKey(botId: string): Promise<void>;+ /** 只有 API Key 时的余额;没有连接时 undefined */+ keyBalance(): Promise<KeyBalance | undefined>;+ /** 提醒:写入应用通知;push = 同时经机器人发到你的微信 / 飞书 */+ alert(text: string, push: boolean): void;+}++export interface AlertSettings {+ /** 余额低于它(美元)时提醒;0 = 不提醒 */+ lowBalanceUsd: number;+ /** 同时经机器人推送到微信 / 飞书 */+ push: boolean;+}++export interface BotBudget {+ enabled: boolean;+ limitUsd: number;+}++export type AccountState = "signed_out" | "signing_in" | "signed_in" | "unavailable";++export interface AccountStatus {+ state: AccountState;+ /** 账户名称(登录后) */+ name: string;+ /** 余额来源:account = 登录账户;key = 只用 API Key;none = 未连接 */+ source: "account" | "key" | "none";+ balanceUsd: number | null;+ usedUsd: number | null;+ billedToEnterprise: boolean;+ updatedAt: number;+ error: string;+ loginUrl: string;+ alerts: AlertSettings;+ lowBalance: boolean;+}++const BOT_KEY = (botId: string) => `account.botKey.${botId}`;+const ALERTED = "account.lowBalanceAlerted";++export class AccountManager {+ private session: AccountSession | undefined;+ private endpoints: OidcEndpoints | undefined;+ private login: LoginAttempt | undefined;+ private snapshot: Pick<AccountStatus, "name" | "source" | "balanceUsd" | "usedUsd" | "billedToEnterprise" | "updatedAt" | "error"> = {+ name: "",+ source: "none",+ balanceUsd: null,+ usedUsd: null,+ billedToEnterprise: false,+ updatedAt: 0,+ error: "",+ };+ private quotaPerUnit = 0;+ private state: AccountState = "signed_out";+ private refreshing: Promise<AccountStatus> | undefined;++ constructor(+ private o: {+ issuer: string;+ vault: AccountVault;+ store: Store;+ hooks: AccountHooks;+ alerts: () => AlertSettings;+ fetchImpl?: typeof fetch;+ hostname?: string;+ },+ ) {}++ private get fetch(): typeof fetch {+ return this.o.fetchImpl ?? fetch;+ }++ /** 读本机账户文件;读不出来时标记为不可用(不删文件,换回桌面版仍能用) */+ init(): void {+ try {+ const rec = this.o.vault.load();+ if (rec && rec.issuer === this.o.issuer) {+ this.session = this.newSession(rec);+ this.state = "signed_in";+ }+ } catch (e) {+ this.state = "unavailable";+ this.snapshot.error = (e as Error).message;+ }+ }++ get signedIn(): boolean {+ return this.state === "signed_in" && !!this.session;+ }++ status(): AccountStatus {+ const alerts = this.o.alerts();+ const bal = this.snapshot.balanceUsd;+ return {+ ...this.snapshot,+ state: this.state,+ loginUrl: this.state === "signing_in" ? (this.login?.url ?? "") : "",+ alerts,+ lowBalance: bal !== null && alerts.lowBalanceUsd > 0 && bal < alerts.lowBalanceUsd,+ };+ }++ private async ensureEndpoints(): Promise<OidcEndpoints> {+ this.endpoints ??= await discover(this.o.issuer, this.fetch);+ return this.endpoints;+ }++ private newSession(rec: AccountRecord, access?: { token: string; expiresAt: number }): AccountSession {+ return new AccountSession(+ {+ issuer: this.o.issuer,+ endpoints: () => this.ensureEndpoints(),+ clientId: MODELFLARE_CLIENT_ID,+ record: rec,+ persist: (r) => this.o.vault.save(r),+ fetchImpl: this.fetch,+ },+ access,+ );+ }++ // ---------- 登录 / 退出 ----------++ /** 开始登录:返回在浏览器里打开的地址;完成后自动签发本机 Key 并接到内置网关 */+ async startLogin(): Promise<string> {+ if (this.state === "signing_in" && this.login) return this.login.url;+ if (this.session) throw new ApiError("已经登录了 Modelflare 账户", 409);+ const ep = await this.ensureEndpoints();+ const attempt = await startLogin(ep, {+ clientId: MODELFLARE_CLIENT_ID,+ scope: MODELFLARE_SCOPES,+ extra: { ...UTM, utm_campaign: "login" },+ fetchImpl: this.fetch,+ });+ this.login = attempt;+ this.state = "signing_in";+ this.snapshot.error = "";+ void attempt.result.then(+ (tokens) => this.completeLogin(tokens),+ (e: Error) => {+ if (this.login !== attempt) return;+ this.login = undefined;+ this.state = this.session ? "signed_in" : "signed_out";+ if (!(e instanceof OAuthError && e.code === "cancelled")) this.snapshot.error = e.message;+ },+ );+ return attempt.url;+ }++ cancelLogin(): void {+ this.login?.cancel();+ }++ private async completeLogin(tokens: { accessToken: string; expiresAt: number; refreshToken: string; scope: string }): Promise<void> {+ const rec: AccountRecord = { issuer: this.o.issuer, refreshToken: tokens.refreshToken, scope: tokens.scope, deviceKeyId: 0, signedInAt: Date.now() };+ const session = this.newSession(rec, { token: tokens.accessToken, expiresAt: tokens.expiresAt });+ try {+ const account = await session.account();+ const host = this.o.hostname ?? os.hostname();+ const key = await session.createKey(`AnyModelBot · ${host}`.slice(0, 50));+ if (!key.key) throw new Error("Modelflare 没有返回新 Key");+ try {+ await this.o.hooks.connectKey(key.key);+ } catch (e) {+ // 接不上网关就不留这次授权:撤销会连同刚签发的 Key 一起删除+ await this.revokeQuietly(session);+ throw e;+ }+ this.o.vault.save({ ...session.record, deviceKeyId: key.id });+ this.session = session;+ this.state = "signed_in";+ this.applyAccount(account);+ log.info("signed in to Modelflare", { name: account.display_name || account.username });+ this.checkLowBalance();+ void this.syncBotKeys().catch((e) => log.warn("sync bot keys failed", { message: (e as Error).message }));+ } catch (e) {+ this.state = this.session ? "signed_in" : "signed_out";+ this.snapshot.error = `登录没有完成:${(e as Error).message}`;+ log.warn("login failed", { message: (e as Error).message });+ } finally {+ this.login = undefined;+ }+ }++ /** 退出登录:撤销本机授权(服务端同时删除它签发的全部 Key),再断开内置网关 */+ async logout(): Promise<{ revoked: boolean }> {+ const session = this.session;+ const revoked = session ? await this.revokeQuietly(session) : true;+ await this.forget();+ return { revoked };+ }++ private async revokeQuietly(session: AccountSession): Promise<boolean> {+ try {+ const ep = await this.ensureEndpoints();+ await revokeToken(ep, MODELFLARE_CLIENT_ID, session.record.refreshToken, this.fetch);+ return true;+ } catch (e) {+ log.warn("revoke failed", { message: (e as Error).message });+ return false;+ }+ }++ /** 本机清掉登录状态(授权已撤销或刚退出) */+ private async forget(): Promise<void> {+ this.session = undefined;+ this.state = "signed_out";+ this.o.vault.clear();+ 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: "" };+ }++ /** 授权在别处被撤销:断开并回到登录页 */+ private async onRevoked(): Promise<void> {+ log.warn("Modelflare authorization revoked");+ await this.forget();+ this.snapshot.error = "Modelflare 授权已失效(可能在网页上撤销了),请重新登录";+ this.o.hooks.alert(this.snapshot.error, false);+ }++ private async call<T>(fn: (s: AccountSession) => Promise<T>): Promise<T> {+ if (!this.session) throw new ApiError("请先登录 Modelflare 账户", 409);+ try {+ return await fn(this.session);+ } catch (e) {+ if (e instanceof AccountRevokedError) await this.onRevoked();+ throw e;+ }+ }++ // ---------- 余额 ----------++ private applyAccount(a: ConnectedAccount): void {+ this.quotaPerUnit = a.quota_per_unit;+ this.snapshot = {+ name: a.display_name || a.username,+ source: "account",+ balanceUsd: a.balance_usd,+ usedUsd: a.used_usd,+ billedToEnterprise: a.billed_to_enterprise,+ updatedAt: Date.now(),+ error: "",+ };+ }++ /** 刷新余额(并发调用合并成一次) */+ refresh(): Promise<AccountStatus> {+ this.refreshing ??= this.doRefresh().finally(() => (this.refreshing = undefined));+ return this.refreshing;+ }++ private async doRefresh(): Promise<AccountStatus> {+ try {+ if (this.session) {+ this.applyAccount(await this.call((s) => s.account()));+ } else {+ const b = await this.o.hooks.keyBalance();+ this.snapshot = {+ ...this.snapshot,+ source: b ? "key" : "none",+ balanceUsd: b ? b.available : null,+ usedUsd: b ? b.used : null,+ updatedAt: Date.now(),+ error: "",+ };+ }+ this.checkLowBalance();+ } catch (e) {+ if (!(e instanceof AccountRevokedError)) this.snapshot.error = (e as Error).message;+ }+ return this.status();+ }++ /** 余额跌破阈值时提醒一次;回到阈值以上后才会再次提醒 */+ private checkLowBalance(): void {+ const { lowBalanceUsd, push } = this.o.alerts();+ const bal = this.snapshot.balanceUsd;+ if (bal === null || lowBalanceUsd <= 0) return;+ const alerted = !!this.o.store.getKV(ALERTED);+ if (bal < lowBalanceUsd && !alerted) {+ this.o.store.setKV(ALERTED, String(Date.now()));+ this.o.hooks.alert(`Modelflare 余额只剩 $${bal.toFixed(2)},低于提醒线 $${lowBalanceUsd}。充值:${webUrl("/billing", "low-balance")}`, push);+ } else if (bal >= lowBalanceUsd && alerted) {+ this.o.store.deleteKV(ALERTED);+ }+ }++ // ---------- 用量 / 通知 / 邀请 ----------++ async usage(days: number): Promise<UsageSummary> {+ const now = Date.now();+ const start = startOfLocalDay(now - (days - 1) * 86_400_000);+ const rows = await this.call((s) => s.usage(Math.floor(start / 1000), Math.floor(now / 1000)));+ if (!this.quotaPerUnit) this.applyAccount(await this.call((s) => s.account()));+ return summarizeUsage(rows ?? [], this.quotaPerUnit, start, days);+ }++ notifications(): Promise<unknown> {+ return this.call((s) => s.notifications());+ }++ async invite(): Promise<{ code: string; url: string }> {+ const code = await this.call((s) => s.invite());+ const u = new URL("/sign-up", MODELFLARE_WEB);+ u.searchParams.set("aff", code);+ for (const [k, v] of Object.entries(UTM)) u.searchParams.set(k, v);+ u.searchParams.set("utm_campaign", "invite");+ return { code, url: u.toString() };+ }++ // ---------- 机器人预算 Key ----------++ private botKeyIds(): Map<string, number> {+ const out = new Map<string, number>();+ for (const [k, v] of this.o.store.listKV("account.botKey.")) out.set(k.slice("account.botKey.".length), Number(v));+ return out;+ }++ /** 各机器人预算 Key 的用量(只含已开启预算且 Key 仍在的机器人) */+ async botBudgets(): Promise<Record<string, Pick<AppKey, "status" | "limit_usd" | "remain_usd" | "used_usd">>> {+ const ids = this.botKeyIds();+ if (!ids.size || !this.session) return {};+ const keys = new Map((await this.call((s) => s.listKeys())).map((k) => [k.id, k]));+ const out: Record<string, Pick<AppKey, "status" | "limit_usd" | "remain_usd" | "used_usd">> = {};+ for (const [botId, id] of ids) {+ const k = keys.get(id);+ if (k) out[botId] = { status: k.status, limit_usd: k.limit_usd, remain_usd: k.remain_usd, used_usd: k.used_usd };+ }+ return out;+ }++ /**+ * 开启 / 调整 / 关闭一个机器人的预算。开启时为它签发自己的 Key(预算 = 这把 Key 的总额度),+ * 机器人的请求改走这把 Key;关闭时删除 Key,机器人回到本机共用的 Key。+ */+ async setBotBudget(botId: string, botName: string, budget: BotBudget): Promise<void> {+ if (!this.session) throw new ApiError("给机器人设预算需要先登录 Modelflare 账户", 409);+ let id = this.botKeyIds().get(botId);+ if (!budget.enabled) {+ if (id) await this.deleteKeyQuietly(id);+ await this.o.hooks.removeBotKey(botId);+ this.o.store.deleteKV(BOT_KEY(botId));+ return;+ }+ if (id) {+ try {+ await this.call((s) => s.updateKey(id!, { limit_usd: budget.limitUsd, name: keyName(botName) }));+ return;+ } catch (e) {+ if (!(e instanceof ApiError && e.status === 404)) throw e;+ id = undefined; // 在控制台里被删掉了:重新签发+ }+ }+ const key = await this.call((s) => s.createKey(keyName(botName), budget.limitUsd));+ if (!key.key) throw new Error("Modelflare 没有返回新 Key");+ try {+ await this.o.hooks.setBotKey(botId, key.key);+ } catch (e) {+ await this.deleteKeyQuietly(key.id);+ throw e;+ }+ this.o.store.setKV(BOT_KEY(botId), String(key.id));+ }++ private async deleteKeyQuietly(id: number): Promise<void> {+ try {+ await this.call((s) => s.deleteKey(id));+ } catch (e) {+ if (!(e instanceof ApiError && e.status === 404)) log.warn("delete bot key failed", { id, message: (e as Error).message });+ }+ }++ /** 登录后为开着预算、但还没有 Key 的机器人补签(换设备或重新登录后) */+ async syncBotKeys(bots: Array<{ id: string; name: string; budget: BotBudget }> = this.botsSource()): Promise<void> {+ const have = this.botKeyIds();+ for (const b of bots) if (b.budget.enabled && !have.has(b.id)) await this.setBotBudget(b.id, b.name, b.budget);+ }++ /** App 注入:当前机器人及其预算设置 */+ botsSource: () => Array<{ id: string; name: string; budget: BotBudget }> = () => [];+}++function keyName(botName: string): string {+ return `AnyModelBot · ${botName}`.slice(0, 50);+}++export function startOfLocalDay(ms: number): number {+ const d = new Date(ms);+ d.setHours(0, 0, 0, 0);+ return d.getTime();+}++export interface UsageSummary {+ days: Array<{ date: string; usd: number; requests: number }>;+ models: Array<{ model: string; usd: number; requests: number }>;+ totalUsd: number;+}++/** 把按小时、按模型的用量行汇总成本地日期的日合计与模型合计(金额 = quota / quota_per_unit) */+export function summarizeUsage(rows: UsageRow[], quotaPerUnit: number, startMs: number, days: number): UsageSummary {+ const usd = (q: number) => (quotaPerUnit > 0 ? q / quotaPerUnit : 0);+ const pad = (n: number) => String(n).padStart(2, "0");+ const dateOf = (ms: number) => {+ const d = new Date(ms);+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;+ };+ const byDay = new Map<string, { usd: number; requests: number }>();+ for (let i = 0; i < days; i++) {+ const d = new Date(startMs);+ d.setDate(d.getDate() + i);+ byDay.set(dateOf(d.getTime()), { usd: 0, requests: 0 });+ }+ const byModel = new Map<string, { usd: number; requests: number }>();+ let total = 0;+ for (const r of rows) {+ const v = usd(Number(r.quota) || 0);+ const n = Number(r.count) || 0;+ total += v;+ const day = byDay.get(dateOf(Number(r.created_at) * 1000));+ if (day) {+ day.usd += v;+ day.requests += n;+ }+ const m = byModel.get(r.model_name) ?? { usd: 0, requests: 0 };+ m.usd += v;+ m.requests += n;+ byModel.set(r.model_name, m);+ }+ return {+ days: [...byDay].map(([date, v]) => ({ date, ...v })),+ models: [...byModel].map(([model, v]) => ({ model, ...v })).sort((a, b) => b.usd - a.usd),+ totalUsd: total,+ };+}diff --git a/src/account/model-info.ts b/src/account/model-info.tsnew file mode 100644index 0000000..62ff660--- /dev/null+++ b/src/account/model-info.ts@@ -0,0 +1,97 @@+/**+ * 模型选择器里的能力与参考价:+ * - 能力来自 GET {线路}/v1/model-profiles(带 Key;上下文、视觉、工具调用、推理)。+ * - 价格来自公开价格目录 GET https://modelflare.dev/api/pricing(不带 Key,国内线路不开放)。+ * 只算按 token 计费和按次计费的模型:价格 = 基础价 × 该模型可用公开分组里最低的分组倍率 ×+ * 模型售价倍率,单位美元 / 百万 tokens(按次为美元 / 次)。这是“起步参考价”,实际以账单为准;+ * 阶梯计费、图片、视频等复杂计费不展示价格。+ */+export interface ModelInfo {+ context?: number;+ vision?: boolean;+ tools?: boolean;+ reasoning?: boolean;+ price?: { input?: number; output?: number; perCall?: number };+}++interface Profile {+ context_window?: number;+ input_modalities?: string[];+ tool_calling?: boolean;+ reasoning?: boolean;+}++export interface PricingEntry {+ model_name: string;+ quota_type: number;+ input_price?: number;+ model_ratio?: number;+ model_price?: number;+ completion_ratio?: number;+ enable_groups?: string[];+ billing_mode?: string;+ pricing_rules?: unknown;+ sale_price_multiplier?: number;+}++export interface PricingCatalog {+ data?: PricingEntry[];+ group_ratio?: Record<string, number>;+ usable_group?: Record<string, unknown>;+}++const round = (n: number) => Math.round(n * 10_000) / 10_000;++/** 一个模型的起步参考价;算不出来(复杂计费、没有可用分组)时 undefined */+export function referencePrice(entry: PricingEntry, catalog: PricingCatalog): ModelInfo["price"] {+ if (entry.billing_mode || entry.pricing_rules) return undefined;+ const ratios = (entry.enable_groups ?? [])+ .filter((g) => !catalog.usable_group || g in catalog.usable_group)+ .map((g) => catalog.group_ratio?.[g])+ .filter((r): r is number => typeof r === "number" && Number.isFinite(r) && r >= 0);+ if (!ratios.length) return undefined;+ const sale = Number(entry.sale_price_multiplier) > 0 ? Number(entry.sale_price_multiplier) : 1;+ const factor = Math.min(...ratios) * sale;+ if (entry.quota_type === 1) return typeof entry.model_price === "number" ? { perCall: round(entry.model_price * factor) } : undefined;+ if (entry.quota_type !== 0) return undefined;+ const base = typeof entry.input_price === "number" ? entry.input_price : Number(entry.model_ratio) * 2;+ if (!Number.isFinite(base)) return undefined;+ const output = Number(entry.completion_ratio);+ return { input: round(base * factor), ...(Number.isFinite(output) ? { output: round(base * output * factor) } : {}) };+}++export async function loadModelInfo(o: {+ baseUrl: string;+ apiKey: string;+ headers: Record<string, string>;+ pricingUrl: string;+ fetchImpl?: typeof fetch;+}): Promise<Record<string, ModelInfo>> {+ const f = o.fetchImpl ?? fetch;+ const get = async <T>(url: string, headers: Record<string, string>): Promise<T | undefined> => {+ try {+ const res = await f(url, { headers: { Accept: "application/json", ...headers }, signal: AbortSignal.timeout(10_000) });+ return res.ok ? ((await res.json()) as T) : undefined;+ } catch {+ return undefined;+ }+ };+ const [profiles, catalog] = await Promise.all([+ o.apiKey ? get<{ data?: Record<string, Profile> }>(`${o.baseUrl}/model-profiles`, { Authorization: `Bearer ${o.apiKey}`, ...o.headers }) : undefined,+ get<PricingCatalog>(o.pricingUrl, {}),+ ]);+ const out: Record<string, ModelInfo> = {};+ for (const [id, p] of Object.entries(profiles?.data ?? {})) {+ out[id] = {+ ...(p.context_window ? { context: p.context_window } : {}),+ ...(p.input_modalities ? { vision: p.input_modalities.includes("image") } : {}),+ ...(typeof p.tool_calling === "boolean" ? { tools: p.tool_calling } : {}),+ ...(typeof p.reasoning === "boolean" ? { reasoning: p.reasoning } : {}),+ };+ }+ for (const entry of catalog?.data ?? []) {+ const price = referencePrice(entry, catalog!);+ if (price) out[entry.model_name] = { ...out[entry.model_name], price };+ }+ return out;+}diff --git a/src/account/oauth.ts b/src/account/oauth.tsnew file mode 100644index 0000000..befc890--- /dev/null+++ b/src/account/oauth.ts@@ -0,0 +1,201 @@+/**+ * Modelflare 账户登录:OIDC 授权码 + PKCE(RFC 7636),按 RFC 8252 作为原生应用。+ * - 本程序是公共客户端:只发 client_id,没有客户端密钥;PKCE verifier 证明是同一个发起方。+ * - 回调到本机 127.0.0.1 的临时端口(服务端允许回环地址任意端口),浏览器把授权码交回给本进程。+ * - 授权地址等全部取自发现文档,并要求与发行方同源,伪造的发现文档不能把令牌引到别处。+ */+import crypto from "node:crypto";+import http from "node:http";+import type { AddressInfo } from "node:net";++export interface OidcEndpoints {+ issuer: string;+ authorization: string;+ token: string;+ revocation: string;+}++export interface TokenSet {+ accessToken: string;+ /** 毫秒时间戳;提前一分钟视为过期 */+ expiresAt: number;+ refreshToken: string;+ scope: string;+}++export class OAuthError extends Error {+ constructor(readonly code: string, message: string, readonly status?: number) {+ super(message);+ }+}++const b64url = (buf: Buffer) => buf.toString("base64url");++export function pkcePair(): { verifier: string; challenge: string } {+ const verifier = b64url(crypto.randomBytes(32));+ return { verifier, challenge: b64url(crypto.createHash("sha256").update(verifier).digest()) };+}++export async function discover(issuer: string, fetchImpl: typeof fetch = fetch): Promise<OidcEndpoints> {+ let res: Response;+ try {+ res = await fetchImpl(`${issuer}/.well-known/openid-configuration`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(15_000) });+ } catch (e) {+ throw new OAuthError("network", `连不上 ${new URL(issuer).host}(${(e as Error).message})`);+ }+ if (!res.ok) throw new OAuthError("discovery", `读取登录配置失败(HTTP ${res.status})`, res.status);+ const doc = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ const origin = new URL(issuer).origin;+ const endpoint = (key: string) => {+ const v = typeof doc[key] === "string" ? (doc[key] as string) : "";+ if (!v || new URL(v).origin !== origin) throw new OAuthError("discovery", `登录配置里的 ${key} 无效`);+ return v;+ };+ if (doc.issuer !== issuer) throw new OAuthError("discovery", "登录配置的发行方不匹配");+ return {+ issuer,+ authorization: endpoint("authorization_endpoint"),+ token: endpoint("token_endpoint"),+ revocation: endpoint("revocation_endpoint"),+ };+}++async function tokenRequest(endpoint: string, params: Record<string, string>, fetchImpl: typeof fetch): Promise<TokenSet> {+ let res: Response;+ try {+ res = await fetchImpl(endpoint, {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded", Accept: "application/json" },+ body: new URLSearchParams(params).toString(),+ signal: AbortSignal.timeout(20_000),+ });+ } catch (e) {+ throw new OAuthError("network", `连不上 Modelflare(${(e as Error).message})`);+ }+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ if (!res.ok) {+ const code = typeof body.error === "string" ? body.error : `http_${res.status}`;+ throw new OAuthError(code, typeof body.error_description === "string" ? body.error_description : `HTTP ${res.status}`, res.status);+ }+ const accessToken = String(body.access_token ?? "");+ const refreshToken = String(body.refresh_token ?? params.refresh_token ?? "");+ if (!accessToken || !refreshToken) throw new OAuthError("bad_response", "Modelflare 返回的令牌不完整");+ const ttl = Number(body.expires_in);+ return {+ accessToken,+ refreshToken,+ expiresAt: Date.now() + (Number.isFinite(ttl) && ttl > 0 ? ttl : 900) * 1000 - 60_000,+ scope: String(body.scope ?? ""),+ };+}++export function refreshTokens(ep: OidcEndpoints, clientId: string, refreshToken: string, fetchImpl: typeof fetch = fetch): Promise<TokenSet> {+ return tokenRequest(ep.token, { grant_type: "refresh_token", refresh_token: refreshToken, client_id: clientId }, fetchImpl);+}++/** 撤销 refresh token:服务端让这台设备退出登录,并删除这次授权创建的 API Key */+export async function revokeToken(ep: OidcEndpoints, clientId: string, token: string, fetchImpl: typeof fetch = fetch): Promise<void> {+ const res = await fetchImpl(ep.revocation, {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ token, client_id: clientId }).toString(),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new OAuthError(`http_${res.status}`, `退出登录失败(HTTP ${res.status})`, res.status);+}++export interface LoginAttempt {+ /** 在浏览器里打开的授权地址 */+ url: string;+ result: Promise<TokenSet>;+ cancel(): void;+}++export interface LoginOptions {+ clientId: string;+ scope: string;+ /** 带到授权请求上的额外参数(注册来源 utm_*) */+ extra?: Record<string, string>;+ timeoutMs?: number;+ fetchImpl?: typeof fetch;+}++const PAGE = (title: string, text: string) =>+ `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title>` ++ `<body style="font:16px/1.6 system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0;color:#222;background:#fafafa">` ++ `<main style="text-align:center;padding:24px"><h1 style="font-size:20px">${title}</h1><p>${text}</p></main></body></html>`;++/**+ * 开始一次登录:在 127.0.0.1 的临时端口上等浏览器回调。state 不匹配的请求一律忽略(不结束这次登录),+ * 只接受第一次合法回调;超时(默认 10 分钟,与服务端授权请求的有效期一致)或取消时结束。+ */+export async function startLogin(ep: OidcEndpoints, o: LoginOptions): Promise<LoginAttempt> {+ const fetchImpl = o.fetchImpl ?? fetch;+ const { verifier, challenge } = pkcePair();+ const state = b64url(crypto.randomBytes(24));+ let settle: { resolve: (t: TokenSet) => void; reject: (e: Error) => void };+ const result = new Promise<TokenSet>((resolve, reject) => (settle = { resolve, reject }));+ // 浏览器可能在调用方挂上处理之前就回调失败;先标记为已处理,调用方照样能拿到这个拒绝+ result.catch(() => {});+ let done = false;+ let timer: NodeJS.Timeout | undefined;+ const server = http.createServer((req, res) => {+ const u = new URL(req.url || "/", "http://127.0.0.1");+ const sameState = (v: string | null) => !!v && v.length === state.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(state));+ if (req.method !== "GET" || u.pathname !== "/callback" || done || !sameState(u.searchParams.get("state"))) {+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("not found");+ return;+ }+ const error = u.searchParams.get("error");+ const code = u.searchParams.get("code");+ const html = (status: number, title: string, text: string) => {+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(PAGE(title, text));+ };+ if (error || !code) {+ html(400, "没有完成登录", error === "access_denied" ? "你取消了这次授权,可以回到 AnyModelBot 重新登录。" : "授权没有完成,请回到 AnyModelBot 重试。");+ finish(new OAuthError(error || "invalid_request", error === "access_denied" ? "你取消了授权" : u.searchParams.get("error_description") || "授权没有完成"));+ return;+ }+ html(200, "登录完成", "可以关闭这个页面,回到 AnyModelBot。");+ done = true;+ tokenRequest(ep.token, { grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: o.clientId, code_verifier: verifier }, fetchImpl).then(+ (t) => finish(undefined, t),+ (e) => finish(e as Error),+ );+ });+ const finish = (err?: Error, tokens?: TokenSet) => {+ done = true;+ if (timer) clearTimeout(timer);+ server.closeAllConnections?.();+ server.close();+ if (err) settle.reject(err);+ else settle.resolve(tokens!);+ };+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => resolve());+ });+ const redirectUri = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`;+ timer = setTimeout(() => finish(new OAuthError("timeout", "登录等待超时,请重新开始")), o.timeoutMs ?? 10 * 60_000);+ const url = new URL(ep.authorization);+ const params: Record<string, string> = {+ response_type: "code",+ client_id: o.clientId,+ redirect_uri: redirectUri,+ scope: o.scope,+ state,+ code_challenge: challenge,+ code_challenge_method: "S256",+ prompt: "consent",+ ui_locales: "zh-CN",+ ...o.extra,+ };+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);+ return {+ url: url.toString(),+ result,+ cancel: () => {+ if (!done) finish(new OAuthError("cancelled", "已取消登录"));+ },+ };+}diff --git a/src/account/vault.ts b/src/account/vault.tsnew file mode 100644index 0000000..07cac22--- /dev/null+++ b/src/account/vault.ts@@ -0,0 +1,68 @@+/**+ * 账户凭据的本机存放:<数据目录>/modelflare-account.json(权限 600,经临时文件改名写入)。+ * 桌面版用系统钥匙串加密(Electron safeStorage);命令行 / Docker 没有钥匙串,与内置网关保存+ * API Key 的方式一致,只靠文件权限保护。refresh token 不出这个文件,界面只拿到账户名称。+ */+import fs from "node:fs";+import path from "node:path";++/** 由桌面外壳提供的加解密(系统钥匙串) */+export interface SecretBox {+ encrypt(plain: string): Buffer;+ decrypt(data: Buffer): string;+}++export interface AccountRecord {+ issuer: string;+ refreshToken: string;+ scope: string;+ /** 登录时为本机签发的 API Key(服务端 id;明文只在内置网关配置里) */+ deviceKeyId: number;+ signedInAt: number;+}++interface FileShape {+ v: 1;+ enc: "safe-storage" | "none";+ data: string;+}++export class AccountVault {+ constructor(readonly file: string, private box?: SecretBox) {}++ static at(dataDir: string, box?: SecretBox): AccountVault {+ return new AccountVault(path.join(dataDir, "modelflare-account.json"), box);+ }++ /** undefined = 没有登录;抛错 = 文件在但读不出来(例如换到了没有钥匙串的命令行版) */+ load(): AccountRecord | undefined {+ if (!fs.existsSync(this.file)) return undefined;+ const raw = JSON.parse(fs.readFileSync(this.file, "utf8")) as FileShape;+ if (raw.v !== 1) throw new Error("不认识的账户文件版本");+ let json: string;+ if (raw.enc === "safe-storage") {+ if (!this.box) throw new Error("账户凭据由桌面版加密,当前运行方式无法读取");+ json = this.box.decrypt(Buffer.from(raw.data, "base64"));+ } else {+ json = Buffer.from(raw.data, "base64").toString("utf8");+ }+ const rec = JSON.parse(json) as AccountRecord;+ if (!rec.refreshToken || !rec.issuer) throw new Error("账户文件不完整");+ return rec;+ }++ save(rec: AccountRecord): void {+ const json = JSON.stringify(rec);+ const shape: FileShape = this.box+ ? { v: 1, enc: "safe-storage", data: this.box.encrypt(json).toString("base64") }+ : { v: 1, enc: "none", data: Buffer.from(json, "utf8").toString("base64") };+ fs.mkdirSync(path.dirname(this.file), { recursive: true });+ const tmp = `${this.file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, JSON.stringify(shape) + "\n", { mode: 0o600 });+ fs.renameSync(tmp, this.file);+ }++ clear(): void {+ fs.rmSync(this.file, { force: true });+ }+}diff --git a/src/agent/bridge.ts b/src/agent/bridge.tsindex 02479b3..c8aae1e 100644--- a/src/agent/bridge.ts+++ b/src/agent/bridge.ts@@ -16,6 +16,8 @@ export interface BridgeHandlers {memory?(body: any): Promise<unknown>;/** amb-memory 插件:上下文管家判定 / 压缩回报 */steward?(body: any): Promise<unknown>;+ /** amb-media 插件:生图 / 生视频 */+ media?(body: any): Promise<unknown>;}/**@@ -113,6 +115,7 @@ export class AgentBridge {else if (url === "/dsh/cancel") out = (await this.h.cancel(body), { ok: true });else if (url === "/dsh/memory" && this.h.memory) out = await this.h.memory(body);else if (url === "/dsh/steward" && this.h.steward) out = await this.h.steward(body);+ else if (url === "/dsh/media" && this.h.media) out = await this.h.media(body);else return void res.writeHead(404).end();res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(out));}diff --git a/src/agent/host.ts b/src/agent/host.tsindex 505faf3..ca51b27 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -253,6 +253,9 @@ export class AgentHost {` name: ${yamlStr(path.join(this.o.runtimeDir, "plugins", "amb-permission.mjs"))}`," - id: amb-memory",` name: ${yamlStr(memory)}`,+ // 生图 / 生视频:宿主带着本机器人的 Key 调 Modelflare,文件存进工作区 media/+ " - id: amb-media",+ ` name: ${yamlStr(path.join(this.o.runtimeDir, "plugins", "amb-media.mjs"))}`,// sdk 配置默认不带这两个工具:ask_user_question 走 user-questions → 插件 → 审批中心;// present 只声明交付文件,由宿主在回合结束后经渠道发送。" - id: amb-tool-ask-user",diff --git a/src/agent/manager.ts b/src/agent/manager.tsindex ae23121..dca264e 100644--- a/src/agent/manager.ts+++ b/src/agent/manager.ts@@ -4,6 +4,7 @@ import { logger } from "../log.js";import { AgentBridge } from "./bridge.js";import path from "node:path";import { AgentHost, callDetail, type TurnObserver, type TurnUsage } from "./host.js";+import type { MediaService } from "./media.js";import { ApprovalCenter, type QuestionItem } from "./approvals.js";import { MemoryError, MemoryStore, type Scope } from "./memory.js";import { DEFAULT_SETTINGS, type BotSettings } from "./settings.js";@@ -30,10 +31,12 @@ export interface AgentManagerOptions {enabled: boolean;turnTimeoutMs?: number;approvalTtlMs?: number;- /** 后台小模型调用(管家判定、交接便条、记忆整理);缺省则这些功能静默跳过 */- complete?: (model: string, system: string, user: string) => Promise<string>;+ /** 后台小模型调用(管家判定、交接便条、记忆整理);缺省则这些功能静默跳过。botId 用来把请求记到该机器人的 Key 上 */+ complete?: (botId: string, model: string, system: string, user: string) => Promise<string>;/** 回合后记忆整理的防抖延迟 */reviewDelayMs?: number;+ /** 生图 / 生视频(amb-media 插件经 bridge 调用);缺省时工具返回不可用 */+ media?: MediaService;}function deferred<T>() {@@ -74,6 +77,7 @@ export class AgentManager {cancel: async (b) => void this.approvals.cancel(String(b?.id ?? ""), "agent"),memory: (b) => this.memoryOp(b),steward: (b) => this.stewardCall(b),+ media: (b) => this.mediaOp(b),});this.memory = new MemoryStore(path.join(o.dataDir, "memory"));}@@ -214,7 +218,7 @@ export class AgentManager {const group = this.o.store.getConversation(conv)?.kind === "group";let action: "switch" | "compact" | undefined;try {- const out = await this.o.complete!(this.utilityModel(botId, model), STEWARD_SYSTEM, stewardRequest(this.transcript(conv), group));+ const out = await this.o.complete!(botId, this.utilityModel(botId, model), STEWARD_SYSTEM, stewardRequest(this.transcript(conv), group));action = parseDecision(out);} catch (e) {log.warn("steward judge failed", { message: (e as Error).message.slice(0, 200) });@@ -245,7 +249,7 @@ export class AgentManager {let handoff = "";if (this.o.complete) {try {- handoff = (await this.o.complete(this.utilityModel(botId, model), HANDOFF_SYSTEM, recentTranscript(lines))).trim();+ handoff = (await this.o.complete(botId, this.utilityModel(botId, model), HANDOFF_SYSTEM, recentTranscript(lines))).trim();} catch (e) {log.warn("handoff failed, using raw tail", { message: (e as Error).message.slice(0, 200) });}@@ -282,7 +286,7 @@ export class AgentManager {const scope: Scope = c?.kind === "group" ? { kind: "group", id: conv } : { kind: "bot", id: botId };const current = this.memory.snapshot([scope]) || "(空)";const lines: Line[] = msgs.map((m) => ({ role: m.role as "user" | "assistant", text: m.content }));- const out = await this.o.complete(this.utilityModel(botId, model), REVIEW_SYSTEM, `当前记忆:\n${current}\n\n最近对话(旧→新):\n${recentTranscript(lines, 12_000)}`);+ const out = await this.o.complete(botId, this.utilityModel(botId, model), REVIEW_SYSTEM, `当前记忆:\n${current}\n\n最近对话(旧→新):\n${recentTranscript(lines, 12_000)}`);const ops = parseReview(out);for (const r of ops.remove) {try {@@ -307,6 +311,19 @@ export class AgentManager {}/** 插件 → 宿主:remember / forget / recall。 */+ /** 生图 / 生视频:只在该机器人有回合进行中时受理(工具调用只会发生在回合里) */+ private async mediaOp(b: any): Promise<{ text?: string; error?: string }> {+ const botId = String(b?.botId ?? "");+ if (!this.hosts.has(botId) || !this.activeConvs.get(botId)?.size) return { error: "unknown bot" };+ if (!this.o.media) return { error: "生成图片和视频需要连接 Modelflare" };+ try {+ return { text: await this.o.media.run(botId, String(b?.op ?? ""), (b?.args ?? {}) as Record<string, unknown>) };+ } catch (e) {+ log.warn("media tool failed", { bot: botId, message: (e as Error).message.slice(0, 300) });+ return { error: (e as Error).message };+ }+ }+private async memoryOp(b: any): Promise<{ text?: string; error?: string }> {const botId = String(b?.botId ?? "");if (!this.hosts.has(botId)) return { error: "unknown bot" };diff --git a/src/agent/media.ts b/src/agent/media.tsnew file mode 100644index 0000000..495943d--- /dev/null+++ b/src/agent/media.ts@@ -0,0 +1,170 @@+/**+ * 生图 / 生视频:代理的 generate_image / generate_video 工具经内部 bridge 调到这里,由宿主带着+ * 该机器人用的 Key 直连 Modelflare(代理子进程拿不到任何密钥),结果存进机器人工作区的 media/,+ * 再由代理用 present 交付到聊天。+ * - 模型取自 GET /v1/models?scope=authorized&kind=image|video(这把 Key 真正能用的)。+ * - 图片:Gemini 图片模型走 /v1/models/{id}:generateContent,其余走 /v1/images/generations。+ * - 视频:POST /v1/videos 建任务 → 轮询 → GET /v1/videos/{id}/content 下载。+ */+import fs from "node:fs";+import path from "node:path";+import { logger } from "../log.js";++const log = logger("agent.media");++export interface MediaOptions {+ /** Modelflare /v1 基址(随线路) */+ baseUrl: () => string;+ /** 该机器人用的 Key:它自己的预算 Key,没有就用共用 Key;未连接时为空 */+ keyFor: (botId: string) => string;+ /** 额外请求头(调用归因) */+ headers: () => Record<string, string>;+ workspace: (botId: string) => string;+ fetchImpl?: typeof fetch;+ /** 视频轮询间隔与上限(测试用) */+ pollMs?: number;+ videoTimeoutMs?: number;+}++interface MediaModel {+ id: string;+ kind?: string;+ image_route?: string;+}++const MAX_BYTES = 200 * 1024 * 1024;+const EXT: Record<string, string> = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif", "video/mp4": "mp4", "video/webm": "webm" };++export class MediaError extends Error {}++export class MediaService {+ constructor(private o: MediaOptions) {}++ private get fetch(): typeof fetch {+ return this.o.fetchImpl ?? fetch;+ }++ /** bridge 入口:返回给模型的一段文字 */+ async run(botId: string, op: string, args: Record<string, unknown>): Promise<string> {+ const prompt = String(args.prompt ?? "").trim();+ if (!prompt) throw new MediaError("缺少 prompt");+ if (op === "image") return this.image(botId, prompt, args);+ if (op === "video") return this.video(botId, prompt, args);+ throw new MediaError(`未知操作 ${op}`);+ }++ private key(botId: string): string {+ const key = this.o.keyFor(botId);+ if (!key) throw new MediaError("还没有连接 Modelflare,无法生成图片或视频");+ return key;+ }++ private async call(botId: string, method: string, p: string, body?: unknown, timeoutMs = 300_000): Promise<Response> {+ const res = await this.fetch(`${this.o.baseUrl()}${p}`, {+ method,+ headers: { Authorization: `Bearer ${this.key(botId)}`, ...this.o.headers(), ...(body !== undefined ? { "content-type": "application/json" } : {}) },+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!res.ok) {+ const detail = (await res.json().catch(() => ({}))) as { error?: { message?: string; code?: string } };+ const msg = detail.error?.message || `HTTP ${res.status}`;+ throw new MediaError(detail.error?.code === "model_not_found" ? `这把 Key 不能用这个模型:${msg}` : `Modelflare 返回错误:${msg}`);+ }+ return res;+ }++ private async models(botId: string, kind: "image" | "video"): Promise<MediaModel[]> {+ const res = await this.call(botId, "GET", `/models?scope=authorized&kind=${kind}`, undefined, 20_000);+ const body = (await res.json()) as { data?: MediaModel[] };+ return (body.data ?? []).filter((m) => m.id && (!m.kind || m.kind === kind));+ }++ private async pick(botId: string, kind: "image" | "video", wanted: unknown): Promise<MediaModel> {+ const list = await this.models(botId, kind);+ const usable = kind === "image" ? list.filter((m) => m.image_route === "images" || m.image_route === "gemini-generate-content") : list;+ if (!usable.length) throw new MediaError(kind === "image" ? "这把 Key 没有可用的图片模型" : "这把 Key 没有可用的视频模型");+ const name = String(wanted ?? "").trim();+ if (!name) return usable[0];+ const hit = usable.find((m) => m.id === name);+ if (!hit) throw new MediaError(`没有这个模型:${name}。可用:${usable.map((m) => m.id).join("、")}`);+ return hit;+ }++ private save(botId: string, kind: "image" | "video", data: Buffer, mime: string): string {+ const dir = path.join(this.o.workspace(botId), "media");+ fs.mkdirSync(dir, { recursive: true });+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");+ const ext = EXT[mime.split(";")[0].trim()] ?? (kind === "image" ? "png" : "mp4");+ let name = `${kind}-${stamp}.${ext}`;+ for (let i = 2; fs.existsSync(path.join(dir, name)); i++) name = `${kind}-${stamp}-${i}.${ext}`;+ fs.writeFileSync(path.join(dir, name), data);+ return `media/${name}`;+ }++ /** 结果地址不带我们的 Key 去取(通常是对象存储的签名地址) */+ private async download(url: string): Promise<{ data: Buffer; mime: string }> {+ if (!/^https:\/\//i.test(url)) throw new MediaError("结果地址无效");+ const res = await this.fetch(url, { signal: AbortSignal.timeout(300_000) });+ if (!res.ok) throw new MediaError(`下载结果失败(HTTP ${res.status})`);+ return this.readBody(res);+ }++ private async readBody(res: Response): Promise<{ data: Buffer; mime: string }> {+ const len = Number(res.headers.get("content-length"));+ if (Number.isFinite(len) && len > MAX_BYTES) throw new MediaError("结果文件过大");+ const data = Buffer.from(await res.arrayBuffer());+ if (data.length > MAX_BYTES) throw new MediaError("结果文件过大");+ return { data, mime: res.headers.get("content-type") || "" };+ }++ private async image(botId: string, prompt: string, args: Record<string, unknown>): Promise<string> {+ const model = await this.pick(botId, "image", args.model);+ const files: string[] = [];+ if (model.image_route === "gemini-generate-content") {+ const res = await this.call(botId, "POST", `/models/${encodeURIComponent(model.id)}:generateContent`, { contents: [{ role: "user", parts: [{ text: prompt }] }] });+ const body = (await res.json()) as { candidates?: Array<{ content?: { parts?: Array<{ inlineData?: { mimeType?: string; data?: string }; inline_data?: { mime_type?: string; data?: string } }> } }> };+ for (const c of body.candidates ?? [])+ for (const p of c.content?.parts ?? []) {+ const data = p.inlineData?.data ?? p.inline_data?.data;+ if (data) files.push(this.save(botId, "image", Buffer.from(data, "base64"), p.inlineData?.mimeType ?? p.inline_data?.mime_type ?? "image/png"));+ }+ } else {+ const size = typeof args.size === "string" && /^\d{2,5}x\d{2,5}$/.test(args.size) ? args.size : undefined;+ const res = await this.call(botId, "POST", "/images/generations", { model: model.id, prompt, ...(size ? { size } : {}) });+ const body = (await res.json()) as { data?: Array<{ b64_json?: string; url?: string }> };+ for (const item of body.data ?? []) {+ if (item.b64_json) files.push(this.save(botId, "image", Buffer.from(item.b64_json, "base64"), "image/png"));+ else if (item.url) {+ const d = await this.download(item.url);+ files.push(this.save(botId, "image", d.data, d.mime || "image/png"));+ }+ }+ }+ if (!files.length) throw new MediaError(`${model.id} 没有返回图片`);+ log.info("image generated", { bot: botId, model: model.id, files: files.length });+ return `已用 ${model.id} 生成 ${files.length} 张图片,保存在工作区:${files.join("、")}。要发给用户,请用 present 工具交付这些文件。`;+ }++ private async video(botId: string, prompt: string, args: Record<string, unknown>): Promise<string> {+ const model = await this.pick(botId, "video", args.model);+ const seconds = Number(args.seconds);+ const size = typeof args.size === "string" && /^\d{2,5}x\d{2,5}$/.test(args.size) ? args.size : undefined;+ const created = (await (await this.call(botId, "POST", "/videos", { model: model.id, prompt, ...(Number.isFinite(seconds) && seconds > 0 ? { seconds: String(Math.round(seconds)) } : {}), ...(size ? { size } : {}) })).json()) as { id?: string; task_id?: string };+ const id = created.id || created.task_id;+ if (!id) throw new MediaError("Modelflare 没有返回视频任务编号");+ const deadline = Date.now() + (this.o.videoTimeoutMs ?? 20 * 60_000);+ for (;;) {+ const t = (await (await this.call(botId, "GET", `/videos/${encodeURIComponent(id)}`, undefined, 30_000)).json()) as { status?: string; error?: { message?: string } | null };+ if (t.status === "completed") break;+ if (t.status === "failed") throw new MediaError(`视频生成失败:${t.error?.message || "未知原因"}`);+ if (Date.now() > deadline) throw new MediaError(`视频任务 ${id} 超时还没完成,可以稍后再试`);+ await new Promise((r) => setTimeout(r, this.o.pollMs ?? 5000));+ }+ const content = await this.call(botId, "GET", `/videos/${encodeURIComponent(id)}/content`, undefined, 600_000);+ const d = await this.readBody(content);+ const file = this.save(botId, "video", d.data, d.mime || "video/mp4");+ log.info("video generated", { bot: botId, model: model.id });+ return `已用 ${model.id} 生成视频,保存在工作区:${file}。要发给用户,请用 present 工具交付这个文件。`;+ }+}diff --git a/src/agent/settings.ts b/src/agent/settings.tsindex 8d5d9ba..8b03022 100644--- a/src/agent/settings.ts+++ b/src/agent/settings.ts@@ -31,6 +31,11 @@ export interface BotSettings {utilityModel: string;/** 头像角色;空 = 由机器人 id 决定 */avatar: BotAvatarKey | "";+ /**+ * 预算(需要登录 Modelflare 账户):开启后机器人用自己的 API Key,最多花 limitUsd 美元+ * (包括这把 Key 已经花掉的);关闭时与其他机器人共用本机的 Key。+ */+ budget: { enabled: boolean; limitUsd: number };}export const DEFAULT_SETTINGS: BotSettings = {@@ -40,6 +45,7 @@ export const DEFAULT_SETTINGS: BotSettings = {computerUse: { enabled: true, backend: "cua", approval: "auto" },utilityModel: "",avatar: "",+ budget: { enabled: false, limitUsd: 5 },};export function normalizeSettings(raw: unknown): BotSettings {@@ -47,6 +53,8 @@ export function normalizeSettings(raw: unknown): BotSettings {const m = r.memory && typeof r.memory === "object" ? r.memory : {};const st = r.steward && typeof r.steward === "object" ? r.steward : {};const cu = r.computerUse && typeof r.computerUse === "object" ? r.computerUse : {};+ const bg = r.budget && typeof r.budget === "object" ? r.budget : {};+ const limit = Number(bg.limitUsd);const b = (v: unknown, d: boolean) => (typeof v === "boolean" ? v : d);return {permission: r.permission === "readonly" ? "readonly" : "workspace",@@ -64,6 +72,10 @@ export function normalizeSettings(raw: unknown): BotSettings {},utilityModel: typeof r.utilityModel === "string" ? r.utilityModel.trim().slice(0, 200) : "",avatar: (BOT_AVATARS as readonly string[]).includes(r.avatar) ? r.avatar : "",+ budget: {+ enabled: b(bg.enabled, DEFAULT_SETTINGS.budget.enabled),+ limitUsd: Number.isFinite(limit) && limit >= 0 && limit <= 100_000 ? Math.round(limit * 100) / 100 : DEFAULT_SETTINGS.budget.limitUsd,+ },};}diff --git a/src/app.ts b/src/app.tsindex 7aa9fb2..51cc6de 100644--- a/src/app.ts+++ b/src/app.ts@@ -18,7 +18,24 @@ import { AgentManager } from "./agent/manager.js";import { normalizeSettings } from "./agent/settings.js";import { locateDshRuntime } from "./agent/host.js";import { findAppRoot } from "./magpie/supervisor.js";-import { MODELFLARE_LINES, modelflareBaseUrl, verifyModelflareKey, type ModelflareLine, type VerifyResult } from "./modelflare.js";+import {+ MODELFLARE_LINES,+ MODELFLARE_PROVIDER,+ botProviderId,+ fetchKeyBalance,+ modelflareBaseUrl,+ modelflareIssuer,+ routeModel,+ skillHeader,+ verifyModelflareKey,+ type ModelflareLine,+ type VerifyResult,+} from "./modelflare.js";+import { AccountManager } from "./account/manager.js";+import { AccountVault, type SecretBox } from "./account/vault.js";+import { loadModelInfo, type ModelInfo } from "./account/model-info.js";+import { MediaService } from "./agent/media.js";+import type { BotSettings } from "./agent/settings.js";const log = logger("app");@@ -29,6 +46,10 @@ export interface DesktopHooks {applyZoom(zoom: number): void;openDataDir(): void;openInBrowser(): void;+ /** 在系统浏览器里打开外部链接(Modelflare 登录、充值) */+ openExternal(url: string): void;+ /** 系统钥匙串加密(Electron safeStorage);不可用时缺省,账户凭据改靠文件权限保护 */+ secretBox?: SecretBox;}export interface ModelflareStatus {@@ -84,7 +105,11 @@ export class App {readonly channels = new Map<string, BotChannels>();web: WebServer | undefined;desktop: DesktopHooks | undefined;+ /** Modelflare 账户(登录、余额、预算);start() 时创建,桌面外壳的钥匙串那时已就绪 */+ account!: AccountManager;private notices: Array<{ at: number; level: "info" | "warn"; text: string }> = [];+ private accountTimer: NodeJS.Timeout | undefined;+ private modelInfoCache: { at: number; data: Record<string, ModelInfo> } | undefined;constructor(readonly config: AppConfig, readonly opts: AppOptions = {}) {this.store = new Store(path.join(config.dataDir, "anymodel.db"));@@ -111,8 +136,19 @@ export class App {turnTimeoutMs: config.agent.turnTimeoutMs,approvalTtlMs: config.agent.approvalTtlMs,// 后台小任务(管家判定/交接/记忆整理)直接走 magpie,不经代理子进程- complete: (model, system, user) =>- this.models.streamChat({ model, messages: [{ role: "system", content: system }, { role: "user", content: user }], signal: AbortSignal.timeout(120_000) }, () => {}),+ complete: (botId, model, system, user) =>+ this.models.streamChat(+ { model: this.routeModel(botId, model), messages: [{ role: "system", content: system }, { role: "user", content: user }], signal: AbortSignal.timeout(120_000) },+ () => {},+ ),+ media: this.magpie+ ? new MediaService({+ baseUrl: () => modelflareBaseUrl(this.config.modelflare.line),+ keyFor: (botId) => this.botKey(botId),+ headers: () => this.requestHeaders(),+ workspace: (botId) => path.join(config.dataDir, "workspaces", botId),+ })+ : undefined,});this.runtime = new BotRuntime({agent: this.agent,@@ -121,9 +157,119 @@ export class App {defaultModel: () => this.config.llm.defaultModel,contextMessages: config.llm.contextMessages,contextChars: config.llm.contextChars,+ route: (botId, model) => this.routeModel(botId, model),});}+ /** 每个经 Modelflare 的请求都带的请求头(调用归因) */+ requestHeaders(): Record<string, string> {+ return skillHeader(appVersion());+ }++ /**+ * 发给内置网关的模型 id:限定到该机器人用的 provider——开了预算的机器人用自己的 Key,+ * 其余用共用连接。外部端点模式原样发送。+ */+ routeModel(botId: string, model: string): string {+ if (!this.magpie) return model;+ const own = botProviderId(botId);+ return routeModel(model, this.magpie.hasProvider(own) ? own : (this.magpie.modelflareProviderId ?? MODELFLARE_PROVIDER));+ }++ /** 该机器人请求 Modelflare 用的 Key(只在本进程内使用) */+ private botKey(botId: string): string {+ if (!this.magpie) return "";+ return this.magpie.providerKey(botProviderId(botId)) || this.magpie.providerKey(this.magpie.modelflareProviderId ?? MODELFLARE_PROVIDER);+ }++ /** 账户管理器:start() 时创建;命令行向导不启动整套服务,直接调用这里 */+ ensureAccount(): AccountManager {+ this.account ??= this.createAccount();+ return this.account;+ }++ private createAccount(): AccountManager {+ const account = new AccountManager({+ issuer: modelflareIssuer(),+ vault: AccountVault.at(this.config.dataDir, this.desktop?.secretBox),+ store: this.store,+ alerts: () => ({ lowBalanceUsd: this.config.modelflare.lowBalanceUsd, push: this.config.modelflare.lowBalancePush }),+ hooks: {+ connectKey: async (key) => {+ const r = await this.connectModelflare(key, this.config.modelflare.line);+ if (!r.ok) throw new Error(r.message);+ },+ disconnect: () => this.disconnectModelflare(),+ setBotKey: async (botId, key) => {+ if (!this.magpie) throw new Error("外部模型端点模式下不管理 Modelflare 连接");+ await this.magpie.setBotProvider(botId, key, modelflareBaseUrl(this.config.modelflare.line), this.allowedModelflareUrls(), this.requestHeaders());+ },+ removeBotKey: async (botId) => {+ await this.magpie?.removeBotProvider(botId);+ },+ keyBalance: async () => {+ const key = this.magpie?.providerKey(this.magpie.modelflareProviderId ?? MODELFLARE_PROVIDER);+ return key ? fetchKeyBalance(modelflareBaseUrl(this.config.modelflare.line), key) : undefined;+ },+ alert: (text, push) => {+ this.notice("warn", text);+ if (push) void this.pushToOwner(text);+ },+ },+ });+ account.botsSource = () => this.store.listBots().map((b) => ({ id: b.id, name: b.name, budget: b.settings.budget }));+ account.init();+ return account;+ }++ /** 提醒经机器人发给你:用第一个能发出去的渠道(微信发给扫码的人,飞书发到最近的单聊) */+ async pushToOwner(text: string): Promise<boolean> {+ for (const bot of this.store.listBots()) {+ const ch = this.channels.get(bot.id);+ try {+ if (ch?.weixin && (await ch.weixin.notifyOwner(text))) return true;+ const chat = ch?.feishu ? this.store.listConversations(bot.id).find((c) => c.channel === "feishu" && c.kind === "dm") : undefined;+ if (chat && ch?.feishu && (await ch.feishu.notify(chat.peerId, text))) return true;+ } catch (e) {+ log.warn("push to owner failed", { bot: bot.id, message: (e as Error).message.slice(0, 200) });+ }+ }+ return false;+ }++ /** 开启 / 调整 / 关闭机器人预算:先改 Modelflare 上的 Key,成功后才保存设置 */+ async setBotBudget(botId: string, budget: BotSettings["budget"]): Promise<Bot> {+ const bot = this.store.getBot(botId);+ if (!bot) throw new Error("机器人不存在");+ await this.account.setBotBudget(bot.id, bot.name, budget);+ return this.store.updateBot(botId, { settings: { ...bot.settings, budget } })!;+ }++ /** 删除机器人时一并删掉它的预算 Key */+ async deleteBot(botId: string): Promise<void> {+ const bot = this.store.getBot(botId);+ await this.stopBot(botId);+ await this.agent.stopBot(botId);+ if (bot?.settings.budget.enabled && this.account.signedIn) {+ await this.account.setBotBudget(botId, bot.name, { ...bot.settings.budget, enabled: false }).catch((e) => log.warn("remove bot key failed", { message: (e as Error).message }));+ }+ this.store.deleteBot(botId);+ }++ /** 模型选择器里的能力与参考价(缓存一小时) */+ async modelInfo(force = false): Promise<Record<string, ModelInfo>> {+ if (!force && this.modelInfoCache && Date.now() - this.modelInfoCache.at < 3600_000) return this.modelInfoCache.data;+ const key = this.magpie?.providerKey(this.magpie.modelflareProviderId ?? MODELFLARE_PROVIDER) ?? "";+ const data = await loadModelInfo({+ baseUrl: modelflareBaseUrl(this.config.modelflare.line),+ apiKey: key,+ headers: this.requestHeaders(),+ pricingUrl: `${modelflareIssuer()}/api/pricing`,+ });+ this.modelInfoCache = { at: Date.now(), data };+ return data;+ }+notice(level: "info" | "warn", text: string): void {this.notices.push({ at: Date.now(), level, text });if (this.notices.length > 50) this.notices.shift();@@ -143,12 +289,24 @@ export class App {}}this.agent.start();+ this.ensureAccount();this.seedDefaultBot();for (const bot of this.store.listBots()) await this.startBot(bot.id);if (!this.opts.noWeb) this.web = await startWebServer(this);+ if (this.magpie && !this.opts.noWeb) {+ // 余额与低余额提醒:启动后读一次,之后每 5 分钟一次+ const tick = () => {+ if (this.account.signedIn || this.magpie?.modelflareInfo().connected) void this.account.refresh();+ };+ setTimeout(tick, 3000).unref();+ this.accountTimer = setInterval(tick, 5 * 60_000);+ this.accountTimer.unref();+ }}async stop(): Promise<void> {+ if (this.accountTimer) clearInterval(this.accountTimer);+ this.account?.cancelLogin();await this.web?.close();for (const id of [...this.channels.keys()]) await this.stopBot(id);await this.agent.stop();@@ -182,7 +340,8 @@ export class App {const baseUrl = modelflareBaseUrl(line);const r = await verifyModelflareKey(baseUrl, apiKey.trim(), { line });if (!r.ok) return r;- await this.magpie.connectModelflare(apiKey, baseUrl, this.allowedModelflareUrls());+ await this.magpie.connectModelflare(apiKey, baseUrl, this.allowedModelflareUrls(), this.requestHeaders());+ this.modelInfoCache = undefined;this.setModelflareLineConfig(line);await this.runtime.listModels(true).catch(() => []);return r;diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.tsindex 8e74983..e73b89d 100644--- a/src/channels/feishu/channel.ts+++ b/src/channels/feishu/channel.ts@@ -120,4 +120,11 @@ export class FeishuChannel {async idle(): Promise<void> {while (this.pending.size) await Promise.all([...this.pending]);}++ /** 主动提醒:发到一个已有的单聊会话;传输层不支持时返回 false */+ async notify(chatId: string, text: string): Promise<boolean> {+ if (!this.transport.sendText) return false;+ await this.transport.sendText(chatId, text);+ return true;+ }}diff --git a/src/channels/feishu/transport.ts b/src/channels/feishu/transport.tsindex 42a256b..417408b 100644--- a/src/channels/feishu/transport.ts+++ b/src/channels/feishu/transport.ts@@ -50,6 +50,8 @@ export interface FeishuTransport {replyText(replyToMessageId: string, text: string): Promise<void>;/** 上传本地文件并作为图片/文件消息回复(present 交付物) */replyFile?(replyToMessageId: string, filePath: string): Promise<void>;+ /** 主动发一条文本到会话(不是回复某条消息;用于余额提醒) */+ sendText?(chatId: string, text: string): Promise<void>;}export const CARD_ELEMENT_ID = "md";@@ -259,4 +261,12 @@ export class LarkTransport implements FeishuTransport {});check(res, "im.message.reply(text)");}++ async sendText(chatId: string, text: string): Promise<void> {+ const res: any = await this.client.im.v1.message.create({+ params: { receive_id_type: "chat_id" },+ data: { receive_id: chatId, msg_type: "text", content: JSON.stringify({ text }) },+ });+ check(res, "im.message.create(text)");+ }}diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.tsindex dbb37f4..e958c76 100644--- a/src/channels/weixin/channel.ts+++ b/src/channels/weixin/channel.ts@@ -207,6 +207,19 @@ export class WeixinChannel {this.loop = this.run(this.abort.signal).finally(() => (this.loop = undefined));}+ /**+ * 主动提醒:发给扫码登录的那个微信用户。需要他最近发过消息(有 context_token),+ * 并占用同一份回复配额;没有可用配额时放弃,返回 false。+ */+ async notifyOwner(text: string): Promise<boolean> {+ const acct = this.store.getWeixinAccount(this.botId);+ const owner = acct?.ownerUserId ?? "";+ const peer = owner ? this.store.getWeixinPeer(this.botId, owner) : undefined;+ if (!this.client || !owner || !peer?.contextToken || !this.quota.tryConsume(owner)) return false;+ await this.client.sendText(owner, text, peer.contextToken);+ return true;+ }+async stop(): Promise<void> {this.abort?.abort();await this.loop?.catch(() => {});diff --git a/src/cli/init.ts b/src/cli/init.tsindex 35f8742..b75cb27 100644--- a/src/cli/init.ts+++ b/src/cli/init.ts@@ -1,9 +1,11 @@/*** 首次设置向导(终端版;界面里也能完成同样的设置):- * 1. Modelflare API Key → 先校验(GET /v1/models),再写入内置网关的隔离配置(key 不进命令行参数)+ * 1. 连接 Modelflare:登录账户(打印登录链接,在这台电脑的浏览器里完成),或粘贴 API Key+ * (先校验 GET /v1/models,再写入内置网关的隔离配置;key 不进命令行参数)* 2. 飞书 App ID / App Secret → 写入本程序数据库*/import readline from "node:readline";+import { spawn } from "node:child_process";import { stdin, stdout } from "node:process";import { loadConfig } from "../config.js";import { App } from "../app.js";@@ -64,13 +66,23 @@ async function setup(app: App, rl: ReturnType<typeof lineReader>, dataDir: strin}await app.magpie.start();const status = app.modelflareStatus();- const hint = status.connected ? `已连接(尾号 ${status.keyTail}),回车保留` : "留空跳过,稍后可在界面里连接";- const key = await rl.ask(`Modelflare API Key(${hint}):`, true);- if (key) {- const line = (await rl.ask("线路:回车 = 国际(modelflare.dev),输入 cn = 中国大陆优化(origin.modelflare.dev):")).trim() === "cn" ? "cn" : "auto";- const r = await app.connectModelflare(key, line);- if (!r.ok) throw new Error(r.message + (r.suggestLine === "cn" ? "(可重试并选择 cn 线路)" : ""));- console.log(`✓ 已连接 Modelflare,找到 ${r.models.length} 个模型`);+ const account = app.ensureAccount();+ if (status.connected) {+ console.log(`Modelflare 已连接(尾号 ${status.keyTail}${account.signedIn ? `,账户 ${account.status().name || "已登录"}` : ""}),保留现有连接。`);+ } else {+ const how = (await rl.ask("连接 Modelflare:回车 = 登录账户(在这台电脑的浏览器里完成),输入 key = 粘贴 API Key,输入 skip = 稍后在界面里连接:")).toLowerCase();+ if (how !== "skip") {+ const line = (await rl.ask("线路:回车 = 国际(modelflare.dev),输入 cn = 中国大陆优化(origin.modelflare.dev):")).trim() === "cn" ? "cn" : "auto";+ if (how === "key") {+ const key = await rl.ask("Modelflare API Key:", true);+ const r = await app.connectModelflare(key, line);+ if (!r.ok) throw new Error(r.message + (r.suggestLine === "cn" ? "(可重试并选择 cn 线路)" : ""));+ console.log(`✓ 已连接 Modelflare,找到 ${r.models.length} 个模型`);+ } else {+ await app.setModelflareLine(line);+ await loginInBrowser(app);+ }+ }}}const appId = (await rl.ask("飞书 App ID(cli_xxx,留空跳过):")).trim();@@ -83,6 +95,37 @@ async function setup(app: App, rl: ReturnType<typeof lineReader>, dataDir: strin}}+/** 浏览器登录:回调落在本机 127.0.0.1,所以浏览器必须在这台电脑上(SSH 远程请改用 API Key) */+async function loginInBrowser(app: App): Promise<void> {+ const account = app.ensureAccount();+ const url = await account.startLogin();+ console.log(`\n在这台电脑的浏览器里打开下面的链接,登录(或注册)Modelflare 并点「继续」授权:\n${url}\n`);+ openInBrowser(url);+ for (;;) {+ await new Promise((r) => setTimeout(r, 500));+ const s = account.status();+ if (s.state === "signed_in") {+ const models = await app.runtime.listModels(true).catch(() => []);+ console.log(`✓ 已登录 ${s.name || "Modelflare"},本机 Key 已连接,找到 ${models.length} 个模型`);+ return;+ }+ if (s.state !== "signing_in") throw new Error(s.error || "登录没有完成");+ }+}++/** 尽力打开系统浏览器;打不开也没关系,链接已经打印出来了。参数直接传给程序,不经过 shell */+function openInBrowser(url: string): void {+ const [cmd, args] =+ process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];+ try {+ const child = spawn(cmd, args as string[], { stdio: "ignore", detached: true });+ child.on("error", () => {});+ child.unref();+ } catch {+ /* 没有可用的打开方式 */+ }+}+main().catch((e) => {console.error("设置失败:", (e as Error).message);process.exit(1);diff --git a/src/config.ts b/src/config.tsindex 4eba2a4..19eaaf8 100644--- a/src/config.ts+++ b/src/config.ts@@ -17,8 +17,11 @@ export interface AppConfig {/** 桌面版关闭窗口时:true 隐藏到托盘,false 退出 */closeToTray: boolean;};- /** Modelflare 线路;密钥本身只存在内置 magpie 的隔离配置里 */- modelflare: { line: ModelflareLine };+ /**+ * Modelflare 线路;密钥本身只存在内置 magpie 的隔离配置里。+ * lowBalanceUsd:余额低于它(美元)时提醒,0 = 不提醒;lowBalancePush:同时经机器人发到微信 / 飞书。+ */+ modelflare: { line: ModelflareLine; lowBalanceUsd: number; lowBalancePush: boolean };magpie: {/** managed:由本程序启动并守护内置 magpie;external:使用已有 OpenAI 兼容端点(测试/高级用法) */mode: "managed" | "external";@@ -44,6 +47,12 @@ function num(v: string | undefined, d: number): number {return Number.isFinite(n) ? n : d;}+/** 低余额提醒线(美元):0–1000,缺省 1 */+export function normalizeLowBalance(v: unknown): number {+ const n = Number(v);+ return v !== undefined && Number.isFinite(n) && n >= 0 && n <= 1000 ? n : 1;+}+export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEnv } = {}): AppConfig {const env = overrides.env ?? process.env;const dataDir = overrides.dataDir ?? (env.AMB_DATA_DIR ? path.resolve(env.AMB_DATA_DIR) : defaultDataDir());@@ -59,7 +68,11 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEnzoom: ZOOMS.includes(Number(file.ui?.zoom)) ? Number(file.ui?.zoom) : 1,closeToTray: file.ui?.closeToTray !== false,},- modelflare: { line: normalizeLine(file.modelflare?.line) },+ modelflare: {+ line: normalizeLine(file.modelflare?.line),+ lowBalanceUsd: normalizeLowBalance(file.modelflare?.lowBalanceUsd),+ lowBalancePush: file.modelflare?.lowBalancePush === true,+ },magpie: {mode: (env.AMB_MAGPIE_BASE_URL ? "external" : file.magpie?.mode) || "managed",binPath: env.AMB_MAGPIE_BIN || file.magpie?.binPath || "",diff --git a/src/core/runtime.ts b/src/core/runtime.tsindex fc0bc3f..df00504 100644--- a/src/core/runtime.ts+++ b/src/core/runtime.ts@@ -7,6 +7,7 @@ import { logger } from "../log.js";import type { AgentManager } from "../agent/manager.js";import { promptText, type QuestionItem } from "../agent/approvals.js";import { MEMORY_GUIDE } from "../agent/steward.js";+import { isBotProviderModel } from "../modelflare.js";import type { ApprovalRow } from "../store/db.js";const log = logger("runtime");@@ -19,6 +20,11 @@ export interface RuntimeOptions {contextChars: number;/** DSH 代理宿主;缺省或不可用时走纯对话路径 */agent?: AgentManager;+ /**+ * 发给模型网关前把模型 id 限定到该机器人用的 Key(共用 Key 或它自己的预算 Key)。+ * 会话与界面里保存的仍是不带 provider 的 id。缺省原样发送。+ */+ route?: (botId: string, model: string) => string;}const HELP = [@@ -38,7 +44,8 @@ export class BotRuntime {async listModels(force = false): Promise<string[]> {if (!force && this.modelCache && Date.now() - this.modelCache.at < 30_000) return this.modelCache.list;- const list = await this.opts.models.listModels();+ // 机器人预算 Key 的 provider 列出同一批模型,只展示共用连接的那份+ const list = (await this.opts.models.listModels()).filter((m) => !isBotProviderModel(m));this.modelCache = { at: Date.now(), list };return list;}@@ -73,10 +80,11 @@ export class BotRuntime {return "";});if (!model) return;+ const routed = this.opts.route ? this.opts.route(bot.id, model) : model;const agent = this.opts.agent;if (agent?.available) {- const handled = await this.handleAgent(agent, bot.id, conv.id, text, model, bot.systemPrompt, out);+ const handled = await this.handleAgent(agent, bot.id, conv.id, text, routed, bot.systemPrompt, out);if (handled) return;}@@ -90,7 +98,7 @@ export class BotRuntime {await out.apply({ type: "stream.start" });let acc = "";try {- const full = await this.opts.models.streamChat({ model, messages, signal: opts.signal }, (delta) => {+ const full = await this.opts.models.streamChat({ model: routed, messages, signal: opts.signal }, (delta) => {acc += delta;void out.apply({ type: "stream.update", text: acc });});diff --git a/src/magpie/supervisor.ts b/src/magpie/supervisor.tsindex 95da05e..6c3a5da 100644--- a/src/magpie/supervisor.ts+++ b/src/magpie/supervisor.ts@@ -5,7 +5,7 @@ import net from "node:net";import path from "node:path";import { fileURLToPath } from "node:url";import { logger } from "../log.js";-import { MODELFLARE_PROVIDER, keyTail } from "../modelflare.js";+import { BOT_PROVIDER_PREFIX, MODELFLARE_PROVIDER, botProviderId, keyTail } from "../modelflare.js";const log = logger("magpie");@@ -364,30 +364,47 @@ export class MagpieSupervisor {/*** 连接 Modelflare:没有就以占位 key 创建固定 id 的 provider,再经 /api/provider/save 写入地址与真实 key* (key 不出现在进程参数里)。重复连接 = 覆盖。baseUrl 必须是白名单里的地址。+ * headers 是每个请求额外带给 Modelflare 的请求头(调用归因)。*/- async connectModelflare(apiKey: string, baseUrl: string, allowed: string[]): Promise<void> {+ async connectModelflare(apiKey: string, baseUrl: string, allowed: string[], headers: Record<string, string> = {}): Promise<void> {+ await this.upsertProvider(this.modelflareId(), MODELFLARE_PROVIDER, "Modelflare", apiKey, baseUrl, allowed, headers);+ }++ /** 机器人自己的 provider(预算 Key):id 固定为 mfb-<botId>,机器人的请求都显式发到这个 provider */+ async setBotProvider(botId: string, apiKey: string, baseUrl: string, allowed: string[], headers: Record<string, string> = {}): Promise<void> {+ const id = botProviderId(botId);+ await this.upsertProvider(this.hasProvider(id) ? id : undefined, id, `Modelflare ${botId}`, apiKey, baseUrl, allowed, headers);+ }++ private async upsertProvider(existing: string | undefined, wantId: string, name: string, apiKey: string, baseUrl: string, allowed: string[], headers: Record<string, string>): Promise<void> {if (!allowed.includes(baseUrl)) throw new Error("不支持的 Modelflare 地址");if (!apiKey.trim()) throw new Error("缺少 API Key");- let id = this.modelflareId();+ let id = existing;if (!id) {- const add = await this.runCli(["provider", "add", "Modelflare", `id=${MODELFLARE_PROVIDER}`, `url=${baseUrl}`, "key=placeholder-key"]);+ const add = await this.runCli(["provider", "add", name, `id=${wantId}`, `url=${baseUrl}`, "key=placeholder-key"]);if (add.code !== 0) throw new Error(`创建 Modelflare 连接失败:${(add.stderr || add.stdout).trim().slice(0, 300)}`);- id = this.modelflareId() ?? (await this.findProviderId(MODELFLARE_PROVIDER));+ id = this.hasProvider(wantId) ? wantId : await this.findProviderId(wantId);}- await this.saveProvider(id, { chat: baseUrl, key: apiKey.trim() });+ await this.saveProvider(id, { chat: baseUrl, key: apiKey.trim(), headers });}- /** 切换线路:只改地址,key 不变 */+ /** 切换线路:只改地址,key 不变(机器人自己的 provider 一起切) */async setModelflareUrl(baseUrl: string, allowed: string[]): Promise<void> {if (!allowed.includes(baseUrl)) throw new Error("不支持的 Modelflare 地址");- const id = this.modelflareId();- if (!id) return;- await this.saveProvider(id, { chat: baseUrl });+ for (const id of [this.modelflareId(), ...this.botProviderIds()]) if (id) await this.saveProvider(id, { chat: baseUrl });}+ /** 断开 Modelflare:删除共用连接和所有机器人自己的 provider */async disconnectModelflare(): Promise<void> {- const id = this.modelflareId();- if (!id) return;+ for (const id of [this.modelflareId(), ...this.botProviderIds()]) if (id) await this.deleteProvider(id);+ }++ async removeBotProvider(botId: string): Promise<void> {+ const id = botProviderId(botId);+ if (this.hasProvider(id)) await this.deleteProvider(id);+ }++ private async deleteProvider(id: string): Promise<void> {if (this.state !== "running") throw new Error("模型网关未运行,稍后再试");const res = await fetch(`${this.webOrigin}/api/provider/delete`, {method: "POST",@@ -398,6 +415,29 @@ export class MagpieSupervisor {if (!res.ok) throw new Error(`断开失败:HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);}+ hasProvider(id: string): boolean {+ return this.listProviders().some((p) => p.id === id);+ }++ botProviderIds(): string[] {+ return this.listProviders()+ .map((p) => p.id)+ .filter((id) => id.startsWith(BOT_PROVIDER_PREFIX));+ }++ /**+ * provider 的明文 key:只在本进程内用于直连 Modelflare(余额、模型能力、生图),+ * 不经接口返回、不写日志。+ */+ providerKey(id: string): string {+ const key = String(this.readProviderRaw(id)?.key ?? "");+ return key && key !== "placeholder-key" ? key : "";+ }++ get modelflareProviderId(): string | undefined {+ return this.modelflareId();+ }+/** 当前 Modelflare 连接(只回传尾号,不外传 key) */modelflareInfo(): { connected: boolean; keyTail: string; baseUrl: string } {const id = this.modelflareId();@@ -412,7 +452,7 @@ export class MagpieSupervisor {return hit?.id;}- private async saveProvider(id: string, patch: Record<string, string>): Promise<void> {+ private async saveProvider(id: string, patch: Record<string, unknown>): Promise<void> {if (this.state !== "running") throw new Error("模型网关未运行,稍后再试");const p = this.readProviderRaw(id);if (!p) throw new Error(`provider ${id} not found`);@@ -424,7 +464,7 @@ export class MagpieSupervisor {});if (!res.ok) throw new Error(`保存失败:HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);const saved = this.readProviderRaw(id);- for (const [k, v] of Object.entries(patch)) if (saved?.[k] !== v) throw new Error("保存后校验失败");+ for (const [k, v] of Object.entries(patch)) if (JSON.stringify(saved?.[k] ?? {}) !== JSON.stringify(v ?? {})) throw new Error("保存后校验失败");}private readProviderRaw(id: string): Record<string, unknown> | undefined {diff --git a/src/modelflare.ts b/src/modelflare.tsindex f98c7b6..a1017c8 100644--- a/src/modelflare.ts+++ b/src/modelflare.ts@@ -13,6 +13,69 @@ export const MODELFLARE_LINES: Record<Exclude<ModelflareLine, "auto">, string> =export const MODELFLARE_PROVIDER = "modelflare";+/** Modelflare 官网:登录、注册、充值、控制台都在这里(国内线路只开放 /v1,不提供网页) */+export const MODELFLARE_WEB = "https://modelflare.dev";++/**+ * 账户登录(OIDC 授权码 + PKCE,RFC 8252 原生应用)。client_id 是公开值:本程序是公共客户端,+ * 没有也不需要客户端密钥;回调到本机 127.0.0.1 的临时端口。+ */+export const MODELFLARE_CLIENT_ID = "anymodel-bot";+export const MODELFLARE_SCOPES = "openid profile offline_access account api_keys";++/** 注册来源(Modelflare 后台按 utm_source 统计从本程序来的注册) */+export const UTM = { utm_source: "anymodelbot", utm_medium: "app" } as const;++/** 开发/测试:AMB_MODELFLARE_ISSUER 把登录与账户接口指向本地 mock(界面无法设置) */+export function modelflareIssuer(env: NodeJS.ProcessEnv = process.env): string {+ return (env.AMB_MODELFLARE_ISSUER?.trim() || MODELFLARE_WEB).replace(/\/+$/, "");+}++/** 官网页面链接,带上来源参数 */+export function webUrl(pathname: string, campaign?: string): string {+ const u = new URL(pathname, MODELFLARE_WEB);+ for (const [k, v] of Object.entries(UTM)) u.searchParams.set(k, v);+ if (campaign) u.searchParams.set("utm_campaign", campaign);+ return u.toString();+}++export const SIGNUP_URL = webUrl("/sign-up", "signup");+export const TOPUP_URL = webUrl("/billing", "topup");+export const CONSOLE_URL = webUrl("/dashboard/overview", "console");++/**+ * 调用归因:每个经 Modelflare 的请求都带 X-Modelflare-Skill(Modelflare 只记到用量日志,+ * 用来统计各集成的调用量)。版本必须是纯数字的 1–3 段。+ */+export function skillHeader(version: string): Record<string, string> {+ return /^\d{1,4}(\.\d{1,4}){0,2}$/.test(version) ? { "X-Modelflare-Skill": `anymodel-bot/${version}` } : {};+}++/** 每个开启了预算的机器人有自己的内置网关 provider(自己的 API Key) */+export const BOT_PROVIDER_PREFIX = "mfb-";+export const botProviderId = (botId: string) => BOT_PROVIDER_PREFIX + botId;++const QUALIFIED = /^(modelflare|mfb-[A-Za-z0-9_-]+)\//;++/** 去掉内置网关的 provider 前缀:modelflare/openai/x、mfb-abc/openai/x → openai/x */+export function bareModel(model: string): string {+ return model.replace(QUALIFIED, "");+}++/** 某个机器人专属 provider 列出的模型(模型列表里不展示,避免同一模型出现多次) */+export function isBotProviderModel(model: string): boolean {+ return model.startsWith(BOT_PROVIDER_PREFIX) && model.includes("/");+}++/**+ * 把模型 id 限定到某个 provider。每个请求都显式带 provider:多个 provider 提供同名模型时,+ * 不带前缀的 id 会被内置网关当成一组在它们之间路由,预算就管不住了。+ */+export function routeModel(model: string, providerId: string): string {+ const bare = bareModel(model.trim());+ return bare ? `${providerId}/${bare}` : bare;+}+export function normalizeLine(v: unknown): ModelflareLine {return v === "global" || v === "cn" ? v : "auto";}@@ -82,3 +145,27 @@ function safeHost(url: string): string {export function keyTail(key: string): string {return key.length > 4 ? key.slice(-4) : "";}++export interface KeyBalance {+ available: number;+ used: number;+ /** USD(Modelflare 以美元计价);站点改了显示单位时原样带回 */+ unit: string;+}++/**+ * 只有 API Key(没有登录账户)时的余额:GET {base}/dashboard/billing/credit_grants。+ * 返回的是整个账户钱包,不是这一把 Key 的额度;国内线路也开放这个 /v1 路径。+ */+export async function fetchKeyBalance(baseUrl: string, apiKey: string, fetchImpl: typeof fetch = fetch): Promise<KeyBalance> {+ const res = await fetchImpl(`${baseUrl}/dashboard/billing/credit_grants`, {+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`读取余额失败(HTTP ${res.status})`);+ const body = (await res.json()) as { total_available?: unknown; total_used?: unknown; unit?: unknown };+ const available = Number(body.total_available);+ const used = Number(body.total_used);+ if (!Number.isFinite(available)) throw new Error("Modelflare 返回了无法识别的余额");+ return { available, used: Number.isFinite(used) ? used : 0, unit: typeof body.unit === "string" && body.unit ? body.unit : "USD" };+}diff --git a/src/store/db.ts b/src/store/db.tsindex 0f1c5b7..ed50aae 100644--- a/src/store/db.ts+++ b/src/store/db.ts@@ -185,6 +185,14 @@ export class Store {setKV(key: string, value: string): void {this.db.prepare("INSERT INTO kv(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);}+ deleteKV(key: string): void {+ this.db.prepare("DELETE FROM kv WHERE key = ?").run(key);+ }+ /** 以 prefix 开头的全部键值 */+ listKV(prefix: string): Array<[string, string]> {+ const rows = this.db.prepare("SELECT key, value FROM kv WHERE substr(key, 1, ?) = ? ORDER BY key").all(prefix.length, prefix) as Row[];+ return rows.map((r) => [String(r.key), String(r.value)]);+ }// ---------- bots ----------private toBot(r: Row): Bot {diff --git a/src/web/server.ts b/src/web/server.tsindex f6289e6..c1994f5 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -7,7 +7,9 @@ import { appVersion, type App } from "../app.js";import type { InboundEvent, OutboundOp, ReplySession } from "../core/types.js";import { findAppRoot } from "../magpie/supervisor.js";import { logger, mask } from "../log.js";-import { ZOOMS, saveConfigFile } from "../config.js";+import { ZOOMS, normalizeLowBalance, saveConfigFile } from "../config.js";+import { ApiError } from "../account/client.js";+import { OAuthError } from "../account/oauth.js";import { normalizeLine } from "../modelflare.js";import { SseReply } from "./sse-reply.js";import { connectionFromPids } from "../agent/peer-guard.js";@@ -134,6 +136,17 @@ function publicApproval(r: ApprovalRow) {return { ...rest, questions };}+/** 账户操作的错误:Modelflare 返回的状态码原样带给界面(没有状态码的网络错误按 502) */+async function accountCall<T>(fn: () => Promise<T>): Promise<T> {+ try {+ return await fn();+ } catch (e) {+ if (e instanceof ApiError) throw new HttpError(e.status >= 400 && e.status < 500 ? e.status : 502, e.message);+ if (e instanceof OAuthError) throw new HttpError(502, e.message);+ throw e;+ }+}+function isLoopback(host: string): boolean {return host === "127.0.0.1" || host === "localhost" || host === "::1";}@@ -225,7 +238,9 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strreturn send(res, 200, { ...app.modelflareStatus(), models: r.models });}if (m === "DELETE") {- await app.disconnectModelflare();+ // 登录状态下断开 = 退出登录:先撤销授权,服务端会删除本机签发的 Key+ if (app.account.signedIn) await app.account.logout();+ else await app.disconnectModelflare();return send(res, 200, app.modelflareStatus());}}@@ -234,6 +249,58 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strawait app.setModelflareLine(normalizeLine(b.line));return send(res, 200, app.modelflareStatus());}+ if (p === "/models/info" && m === "GET") {+ if (!app.magpie) return send(res, 200, { models: {} });+ return send(res, 200, { models: await app.modelInfo(url.searchParams.get("refresh") === "1") });+ }+ if (seg[0] === "account") {+ const sub = seg.slice(1).join("/");+ if (m !== "GET" && !app.magpie) throw new HttpError(409, "外部模型端点模式下不管理 Modelflare 账户");+ // 浏览器登录的回调落在本程序所在机器的 127.0.0.1;界面监听在非本机地址(Docker、远程部署)时,+ // 用户的浏览器访问不到它,只能粘贴 API Key+ const loginAvailable = isLoopback(host);+ const status = () => ({ ...app.account.status(), loginAvailable });+ if (sub === "" && m === "GET") return send(res, 200, status());+ if (sub === "refresh" && m === "POST") {+ // 切回窗口时界面会来刷新;20 秒内刚读过就直接返回+ if (Date.now() - app.account.status().updatedAt >= 20_000) await app.account.refresh();+ return send(res, 200, status());+ }+ if (sub === "login" && m === "POST") {+ if (!loginAvailable) throw new HttpError(409, "Docker 或远程部署时无法用浏览器登录,请改用 API Key");+ const loginUrl = await accountCall(() => app.account.startLogin());+ app.desktop?.openExternal(loginUrl);+ return send(res, 200, { ...status(), loginUrl, opened: !!app.desktop });+ }+ if (sub === "login/cancel" && m === "POST") {+ app.account.cancelLogin();+ return send(res, 200, status());+ }+ if (sub === "logout" && m === "POST") {+ const r = await app.account.logout();+ return send(res, 200, { ...status(), revoked: r.revoked });+ }+ if (sub === "alerts" && m === "PUT") {+ const b = await readJson(req);+ const mf = cfg.modelflare;+ if (b.lowBalanceUsd !== undefined) {+ const v = normalizeLowBalance(b.lowBalanceUsd);+ if (v !== Number(b.lowBalanceUsd)) throw new HttpError(400, "提醒线要在 0 到 1000 美元之间");+ mf.lowBalanceUsd = v;+ }+ if (b.lowBalancePush !== undefined) mf.lowBalancePush = !!b.lowBalancePush;+ saveConfigFile(cfg.dataDir, (f) => (f.modelflare = { ...(f.modelflare ?? {}), lowBalanceUsd: mf.lowBalanceUsd, lowBalancePush: mf.lowBalancePush }));+ return send(res, 200, status());+ }+ if (sub === "usage" && m === "GET") {+ // Modelflare 一次最多给 30 天的用量+ const days = Math.min(30, Math.max(1, Math.floor(Number(url.searchParams.get("days") || 7)) || 7));+ return send(res, 200, await accountCall(() => app.account.usage(days)));+ }+ 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 (p === "/settings") {if (m === "PUT") {const b = await readJson(req);@@ -348,9 +415,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strreturn send(res, 200, { bot: publicBot(next) });}if (m === "DELETE") {- await app.stopBot(id);- await app.agent.stopBot(id);- app.store.deleteBot(id);+ await app.deleteBot(id);return send(res, 200, { ok: true });}}@@ -373,6 +438,13 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst next = app.store.updateBot(id, { settings: merged })!;return send(res, 200, { settings: next.settings, computerUse: app.agent.computerUse(id) });}+ if (sub === "budget" && m === "PUT") {+ const b = await readJson(req);+ const limitUsd = Number(b.limitUsd ?? bot.settings.budget.limitUsd);+ if (!Number.isFinite(limitUsd) || limitUsd < 0 || limitUsd > 100_000) throw new HttpError(400, "预算要在 0 到 100000 美元之间");+ const next = await accountCall(() => app.setBotBudget(id, normalizeSettings({ budget: { enabled: !!b.enabled, limitUsd } }).budget));+ return send(res, 200, { settings: next.settings });+ }if (sub === "memory" && m === "GET") {const scopes = [{ kind: "team" as const, id: "" },diff --git a/test/account.integration.test.ts b/test/account.integration.test.tsnew file mode 100644index 0000000..8091781--- /dev/null+++ b/test/account.integration.test.ts@@ -0,0 +1,106 @@+/**+ * 集成测试:真实内置 magpie + 模拟的 Modelflare(OIDC、connected-app、/v1)。经管理接口走完+ * 登录 → 自动接上本机 Key → 机器人预算 → 退出登录。需要先 npm run build:magpie;没有二进制时跳过。+ */+import { describe, it, expect, beforeAll, afterAll } from "vitest";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { App } from "../src/app.js";+import { loadConfig } from "../src/config.js";+import { resolveMagpieBinary } from "../src/magpie/supervisor.js";+import { FakeFeishu, approveInBrowser, mockModelflare, mockOpenAI, until } from "./helpers.js";++const d = resolveMagpieBinary() ? describe : describe.skip;++d("账户登录(经管理接口,真实内置网关)", () => {+ let mf: Awaited<ReturnType<typeof mockModelflare>>;+ let llm: Awaited<ReturnType<typeof mockOpenAI>>;+ let app: App;+ let base: string;+ let dataDir: string;++ beforeAll(async () => {+ mf = await mockModelflare();+ // 设备 Key 与机器人预算 Key 由 mock 依次签发为 sk-key-1、sk-key-2+ llm = await mockOpenAI({ key: ["sk-key-1", "sk-key-2"], models: ["up-model"] });+ process.env.AMB_MODELFLARE_BASE_URL = llm.url + "/v1";+ process.env.AMB_MODELFLARE_ISSUER = mf.url;+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-acct-int-"));+ app = new App(loadConfig({ dataDir, env: { AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: "http://127.0.0.1:9", AMB_AGENT: "off" } }), {+ feishuTransport: () => new FakeFeishu(),+ printQrToTerminal: false,+ });+ await app.start();+ base = app.web!.url.replace(/\/$/, "");+ }, 60_000);++ afterAll(async () => {+ delete process.env.AMB_MODELFLARE_BASE_URL;+ delete process.env.AMB_MODELFLARE_ISSUER;+ await app?.stop();+ await llm?.close();+ await mf?.close();+ });++ const api = async (p: string, method = "GET", body?: unknown) => {+ const r = await fetch(base + "/amb/api" + p, { method, headers: body !== undefined ? { "content-type": "application/json" } : {}, body: body !== undefined ? JSON.stringify(body) : undefined });+ return { status: r.status, text: await r.clone().text(), json: (await r.json().catch(() => ({}))) as any };+ };++ it("未登录:可以登录;不能设预算", async () => {+ expect((await api("/account")).json).toMatchObject({ state: "signed_out", loginAvailable: true, source: "none" });+ const r = await api("/bots/default/budget", "PUT", { enabled: true, limitUsd: 5 });+ expect(r.status).toBe(409);+ });++ it("登录:浏览器授权后自动签发本机 Key 并接到内置网关;接口不回显任何令牌", async () => {+ const start = await api("/account/login", "POST", {});+ expect(start.status).toBe(200);+ expect(start.json).toMatchObject({ state: "signing_in", opened: false });+ await approveInBrowser(mf, start.json.loginUrl);+ await until(async () => (await api("/account")).json.state === "signed_in", 15_000, 100);+ const acct = await api("/account");+ expect(acct.json).toMatchObject({ name: "Ada", source: "account", balanceUsd: 12.5 });+ expect(acct.text).not.toMatch(/rt-|at-|sk-key/);+ const conn = await api("/modelflare");+ expect(conn.json).toMatchObject({ connected: true, keyTail: "ey-1" });+ expect(conn.text).not.toContain("sk-key-1");+ const chat = await api("/bots/default/chat", "POST", { text: "登录后对话" });+ expect(chat.json.reply).toContain("你说:登录后对话");+ expect(llm.calls.at(-1)!.auth).toBe("Bearer sk-key-1");+ }, 30_000);++ it("机器人预算:开启后走它自己的 Key,用量可查;关闭后回到本机 Key", async () => {+ const on = await api("/bots/default/budget", "PUT", { enabled: true, limitUsd: 5 });+ expect(on.status).toBe(200);+ expect(on.json.settings.budget).toEqual({ enabled: true, limitUsd: 5 });+ expect((await api("/account/budgets")).json.budgets.default).toMatchObject({ limit_usd: 5 });+ await until(async () => {+ const r = await api("/bots/default/chat", "POST", { text: "预算" });+ return String(r.json.reply).includes("你说:预算") && llm.calls.at(-1)!.auth === "Bearer sk-key-2";+ }, 15_000, 300);+ const off = await api("/bots/default/budget", "PUT", { enabled: false });+ expect(off.json.settings.budget.enabled).toBe(false);+ expect(mf.s.keys.map((k) => k.id)).toEqual([1]);+ await api("/bots/default/chat", "POST", { text: "共用" });+ expect(llm.calls.at(-1)!.auth).toBe("Bearer sk-key-1");+ }, 40_000);++ it("余额提醒线:校验范围并写入 config.json", async () => {+ expect((await api("/account/alerts", "PUT", { lowBalanceUsd: 5000 })).status).toBe(400);+ const r = await api("/account/alerts", "PUT", { lowBalanceUsd: 20, lowBalancePush: true });+ expect(r.json.alerts).toEqual({ lowBalanceUsd: 20, push: true });+ expect(r.json.lowBalance).toBe(true);+ expect(JSON.parse(fs.readFileSync(path.join(dataDir, "config.json"), "utf8")).modelflare).toMatchObject({ lowBalanceUsd: 20, lowBalancePush: true });+ });++ it("退出登录:撤销授权,断开内置网关,账户文件删除", async () => {+ const r = await api("/account/logout", "POST", {});+ expect(r.json).toMatchObject({ state: "signed_out", revoked: true });+ expect(mf.s.revoked).toHaveLength(1);+ expect((await api("/modelflare")).json.connected).toBe(false);+ expect(app.magpie!.listProviders()).toEqual([]);+ expect(fs.existsSync(path.join(dataDir, "modelflare-account.json"))).toBe(false);+ }, 30_000);+});diff --git a/test/account.test.ts b/test/account.test.tsnew file mode 100644index 0000000..8f3a6ac--- /dev/null+++ b/test/account.test.ts@@ -0,0 +1,341 @@+/**+ * Modelflare 账户:本机回环 PKCE 登录、令牌轮换、撤销、设备 Key、预算 Key,以及相关纯函数。+ * 用本地 mock 模拟 Modelflare 的 OIDC 与 connected-app 接口(不连真实服务)。+ */+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import crypto from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { listen, mockModelflare, approveInBrowser, readJson } from "./helpers.js";+import { discover, startLogin, pkcePair } from "../src/account/oauth.js";+import { AccountManager, summarizeUsage, type AccountHooks } from "../src/account/manager.js";+import { AccountVault } from "../src/account/vault.js";+import { referencePrice } from "../src/account/model-info.js";+import { MediaService } from "../src/agent/media.js";+import { AgentManager } from "../src/agent/manager.js";+import { locateDshRuntime } from "../src/agent/host.js";+import { findAppRoot } from "../src/magpie/supervisor.js";+import { Store } from "../src/store/db.js";+import { bareModel, isBotProviderModel, routeModel, skillHeader } from "../src/modelflare.js";++describe("回环 PKCE 登录", () => {+ let mf: Awaited<ReturnType<typeof mockModelflare>>;+ beforeEach(async () => (mf = await mockModelflare()));+ afterEach(async () => mf.close());++ it("授权地址带公共客户端参数;state 不对的回调被忽略,正确的回调换到令牌且不带客户端密钥", async () => {+ const ep = await discover(mf.url);+ const attempt = await startLogin(ep, { clientId: "anymodel-bot", scope: "openid offline_access account api_keys", extra: { utm_source: "anymodelbot" } });+ const u = new URL(attempt.url);+ expect(u.origin + u.pathname).toBe(`${mf.url}/oauth/authorize`);+ expect(Object.fromEntries(u.searchParams)).toMatchObject({ response_type: "code", client_id: "anymodel-bot", code_challenge_method: "S256", prompt: "consent", utm_source: "anymodelbot" });+ expect(u.searchParams.get("redirect_uri")).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/);++ // 别的网页带着伪造的 state 来敲回调:不结束这次登录+ const forged = await fetch(`${u.searchParams.get("redirect_uri")}?code=x&state=forged`);+ expect(forged.status).toBe(404);++ const ok = await approveInBrowser(mf, attempt.url);+ expect(ok.status).toBe(200);+ const tokens = await attempt.result;+ expect(tokens.accessToken).toMatch(/^at-/);+ expect(tokens.refreshToken).toMatch(/^rt-/);+ const form = mf.s.tokenForms[0];+ expect(form.grant_type).toBe("authorization_code");+ expect(form.client_secret).toBeUndefined();+ // 回调端口只接受一次:再来一次连不上或 404+ const again = await fetch(`${u.searchParams.get("redirect_uri")}?code=y&state=${u.searchParams.get("state")}`).catch(() => undefined);+ expect(again === undefined || again.status === 404).toBe(true);+ });++ it("用户在授权页拒绝:登录以 access_denied 结束", async () => {+ const attempt = await startLogin(await discover(mf.url), { clientId: "anymodel-bot", scope: "openid offline_access" });+ const u = new URL(attempt.url);+ await fetch(`${u.searchParams.get("redirect_uri")}?error=access_denied&state=${u.searchParams.get("state")}`);+ await expect(attempt.result).rejects.toMatchObject({ code: "access_denied" });+ });++ it("发现文档把端点指到别的主机时拒绝", async () => {+ const evil = await listen((_req, res) => res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ issuer: "x", authorization_endpoint: "https://evil.example/a", token_endpoint: "https://evil.example/t", revocation_endpoint: "https://evil.example/r" })));+ try {+ await expect(discover(evil.url)).rejects.toMatchObject({ code: "discovery" });+ } finally {+ await evil.close();+ }+ });++ it("PKCE challenge 是 verifier 的 SHA-256(base64url)", () => {+ const { verifier, challenge } = pkcePair();+ expect(verifier.length).toBeGreaterThanOrEqual(43);+ expect(challenge).toBe(crypto.createHash("sha256").update(verifier).digest("base64url"));+ });+});++describe("AccountManager", () => {+ let mf: Awaited<ReturnType<typeof mockModelflare>>;+ let dir: string;+ let store: Store;+ let calls: string[];+ let alerts: string[];+ let manager: AccountManager;+ const hooks = (): AccountHooks => ({+ connectKey: async (key) => void calls.push(`connect:${key}`),+ disconnect: async () => void calls.push("disconnect"),+ setBotKey: async (botId, key) => void calls.push(`bot:${botId}:${key}`),+ removeBotKey: async (botId) => void calls.push(`unbot:${botId}`),+ keyBalance: async () => undefined,+ alert: (text) => void alerts.push(text),+ });+ const make = () => {+ const m = new AccountManager({ issuer: mf.url, vault: AccountVault.at(dir), store, hooks: hooks(), alerts: () => ({ lowBalanceUsd: 5, push: false }), hostname: "test-pc" });+ m.init();+ return m;+ };+ const until = async (fn: () => boolean) => {+ for (let i = 0; i < 200 && !fn(); i++) await new Promise((r) => setTimeout(r, 10));+ expect(fn()).toBe(true);+ };+ const signIn = async () => {+ const url = await manager.startLogin();+ await approveInBrowser(mf, url);+ await until(() => manager.status().state === "signed_in");+ };++ beforeEach(async () => {+ mf = await mockModelflare();+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-acct-"));+ store = new Store(":memory:");+ calls = [];+ alerts = [];+ manager = make();+ });+ afterEach(async () => {+ manager.cancelLogin();+ store.close();+ await mf.close();+ });++ it("登录后签发本机 Key 并接到内置网关;refresh token 只存在 600 权限的账户文件里", async () => {+ await signIn();+ expect(calls).toEqual(["connect:sk-key-1"]);+ expect(mf.s.keys[0].name).toBe("AnyModelBot · test-pc");+ const st = manager.status();+ expect(st).toMatchObject({ state: "signed_in", name: "Ada", source: "account", balanceUsd: 12.5 });+ expect(JSON.stringify(st)).not.toMatch(/rt-|at-/);+ const file = AccountVault.at(dir).file;+ if (process.platform !== "win32") expect(fs.statSync(file).mode & 0o777).toBe(0o600);+ expect(AccountVault.at(dir).load()).toMatchObject({ refreshToken: "rt-1", deviceKeyId: 1 });+ });++ it("重启后用 refresh token 换新令牌,轮换后的值立刻写回", async () => {+ await signIn();+ const again = make();+ expect(again.status().state).toBe("signed_in");+ await again.refresh();+ expect(again.status().balanceUsd).toBe(12.5);+ expect(AccountVault.at(dir).load()!.refreshToken).toBe("rt-2");+ expect(mf.s.refresh.has("rt-1")).toBe(false);+ });++ it("授权在网页上被撤销:断开内置网关、清掉账户文件、提示重新登录", async () => {+ await signIn();+ mf.s.revokeAll = true;+ const st = await manager.refresh();+ expect(st.state).toBe("signed_out");+ expect(calls).toContain("disconnect");+ expect(fs.existsSync(AccountVault.at(dir).file)).toBe(false);+ expect(alerts.some((a) => a.includes("授权已失效"))).toBe(true);+ });++ it("退出登录撤销 refresh token,再断开网关", async () => {+ await signIn();+ const r = await manager.logout();+ expect(r.revoked).toBe(true);+ expect(mf.s.revoked).toEqual(["rt-1"]);+ expect(calls.at(-1)).toBe("disconnect");+ expect(manager.status().state).toBe("signed_out");+ });++ it("余额跌破提醒线只提醒一次,回到线上后才会再提醒", async () => {+ await signIn();+ mf.s.balance = 4;+ await manager.refresh();+ await manager.refresh();+ expect(alerts.filter((a) => a.includes("余额只剩"))).toHaveLength(1);+ expect(manager.status().lowBalance).toBe(true);+ mf.s.balance = 6;+ await manager.refresh();+ mf.s.balance = 2;+ await manager.refresh();+ expect(alerts.filter((a) => a.includes("余额只剩"))).toHaveLength(2);+ });++ it("机器人预算:开启签发自己的 Key,调整只改上限,关闭删除 Key", async () => {+ await signIn();+ await manager.setBotBudget("b1", "写作助手", { enabled: true, limitUsd: 5 });+ expect(calls).toContain("bot:b1:sk-key-2");+ expect(mf.s.keys.find((k) => k.id === 2)).toMatchObject({ name: "AnyModelBot · 写作助手", limit_usd: 5 });+ await manager.setBotBudget("b1", "写作助手", { enabled: true, limitUsd: 8 });+ expect(mf.s.keys).toHaveLength(2);+ expect(mf.s.keys.find((k) => k.id === 2)!.limit_usd).toBe(8);+ expect(await manager.botBudgets()).toMatchObject({ b1: { limit_usd: 8 } });+ await manager.setBotBudget("b1", "写作助手", { enabled: false, limitUsd: 8 });+ expect(mf.s.keys.map((k) => k.id)).toEqual([1]);+ expect(calls).toContain("unbot:b1");+ });++ it("没登录时不能设预算", async () => {+ await expect(manager.setBotBudget("b1", "x", { enabled: true, limitUsd: 1 })).rejects.toMatchObject({ status: 409 });+ });+});++describe("账户文件加密", () => {+ it("有钥匙串时整份加密,换到没有钥匙串的运行方式读不出来", () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-vault-"));+ const box = { encrypt: (p: string) => Buffer.from([...Buffer.from(p)].map((b) => b ^ 0x5a)), decrypt: (d: Buffer) => Buffer.from([...d].map((b) => b ^ 0x5a)).toString() };+ const rec = { issuer: "https://modelflare.dev", refreshToken: "rt-secret", scope: "openid", deviceKeyId: 3, signedInAt: 1 };+ AccountVault.at(dir, box).save(rec);+ expect(fs.readFileSync(AccountVault.at(dir).file, "utf8")).not.toContain("rt-secret");+ expect(AccountVault.at(dir, box).load()).toEqual(rec);+ expect(() => AccountVault.at(dir).load()).toThrow(/桌面版加密/);+ });+});++describe("模型路由与归因", () => {+ it("每个请求都限定 provider,同一模型在不同 provider 之间不会混用", () => {+ expect(routeModel("openai/gpt-x", "modelflare")).toBe("modelflare/openai/gpt-x");+ expect(routeModel("modelflare/openai/gpt-x", "mfb-b1")).toBe("mfb-b1/openai/gpt-x");+ expect(routeModel("mfb-b1/openai/gpt-x", "modelflare")).toBe("modelflare/openai/gpt-x");+ expect(bareModel("mfb-b1/x")).toBe("x");+ expect(isBotProviderModel("mfb-b1/openai/gpt-x")).toBe(true);+ expect(isBotProviderModel("modelflare/openai/gpt-x")).toBe(false);+ });++ it("归因头只接受纯数字版本号", () => {+ expect(skillHeader("0.1.3")).toEqual({ "X-Modelflare-Skill": "anymodel-bot/0.1.3" });+ expect(skillHeader("0.1.3-beta")).toEqual({});+ });+});++describe("用量汇总", () => {+ it("按本地日期与模型合计,金额 = quota / quota_per_unit", () => {+ const start = new Date(2026, 9, 28).getTime();+ const at = (d: number, h: number) => Math.floor(new Date(2026, 9, d, h).getTime() / 1000);+ const sum = summarizeUsage(+ [+ { model_name: "a", created_at: at(28, 9), count: 2, quota: 500_000, token_used: 10 },+ { model_name: "b", created_at: at(28, 23), count: 1, quota: 250_000, token_used: 10 },+ { model_name: "a", created_at: at(30, 1), count: 3, quota: 1_000_000, token_used: 10 },+ ],+ 500_000,+ start,+ 3,+ );+ expect(sum.days).toEqual([+ { date: "2026-10-28", usd: 1.5, requests: 3 },+ { date: "2026-10-29", usd: 0, requests: 0 },+ { date: "2026-10-30", usd: 2, requests: 3 },+ ]);+ expect(sum.models[0]).toEqual({ model: "a", usd: 3, requests: 5 });+ expect(sum.totalUsd).toBe(3.5);+ });+});++describe("参考价", () => {+ const catalog = { group_ratio: { default: 1, vip: 0.8, hidden: 0.1 }, usable_group: { default: "", vip: "" } };+ it("按可用公开分组里最低的倍率算每百万 tokens 的输入 / 输出价", () => {+ expect(referencePrice({ model_name: "m", quota_type: 0, input_price: 2.5, completion_ratio: 4, enable_groups: ["default", "vip", "hidden"] }, catalog)).toEqual({ input: 2, output: 8 });+ });+ it("按次计费;复杂计费和没有可用分组的不给价格", () => {+ expect(referencePrice({ model_name: "m", quota_type: 1, model_price: 0.05, enable_groups: ["default"] }, catalog)).toEqual({ perCall: 0.05 });+ expect(referencePrice({ model_name: "m", quota_type: 0, input_price: 1, billing_mode: "tiered_expr", enable_groups: ["default"] }, catalog)).toBeUndefined();+ expect(referencePrice({ model_name: "m", quota_type: 0, input_price: 1, enable_groups: ["hidden"] }, catalog)).toBeUndefined();+ });+});++describe("生图 / 生视频", () => {+ const png = Buffer.from("89504e470d0a1a0a", "hex");+ it("用机器人的 Key 调 Images API,图片存进工作区 media/;视频建任务、轮询、下载", async () => {+ const seen: Array<{ path: string; auth?: string; skill?: string }> = [];+ let polls = 0;+ const srv = await listen(async (req, res) => {+ const u = new URL(req.url!, "http://x");+ seen.push({ path: u.pathname + u.search, auth: req.headers.authorization, skill: req.headers["x-modelflare-skill"] as string });+ const json = (o: unknown) => res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(o));+ if (u.pathname === "/v1/models") {+ return json({ data: u.searchParams.get("kind") === "image" ? [{ id: "gemini-img", kind: "image", image_route: "gemini-generate-content" }, { id: "gpt-image", kind: "image", image_route: "images" }] : [{ id: "veo", kind: "video" }] });+ }+ if (u.pathname === "/v1/images/generations") {+ expect(await readJson(req)).toMatchObject({ model: "gpt-image", prompt: "一只猫" });+ return json({ data: [{ b64_json: png.toString("base64") }] });+ }+ if (u.pathname === "/v1/videos" && req.method === "POST") return json({ id: "task-1", status: "queued" });+ if (u.pathname === "/v1/videos/task-1") return json({ id: "task-1", status: ++polls < 2 ? "in_progress" : "completed" });+ if (u.pathname === "/v1/videos/task-1/content") return res.writeHead(200, { "content-type": "video/mp4" }).end(Buffer.from("mp4"));+ res.writeHead(404).end();+ });+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-media-"));+ try {+ const media = new MediaService({ baseUrl: () => srv.url + "/v1", keyFor: (b) => (b === "b1" ? "sk-bot" : ""), headers: () => skillHeader("0.1.3"), workspace: () => ws, pollMs: 5 });+ const text = await media.run("b1", "image", { prompt: "一只猫", model: "gpt-image" });+ const rel = text.match(/media\/image-[\w-]+\.png/)![0];+ expect(fs.readFileSync(path.join(ws, rel))).toEqual(png);+ expect(text).toContain("present");+ const vtext = await media.run("b1", "video", { prompt: "海浪" });+ expect(fs.readFileSync(path.join(ws, vtext.match(/media\/video-[\w-]+\.mp4/)![0]), "utf8")).toBe("mp4");+ expect(seen.every((x) => x.auth === "Bearer sk-bot" && x.skill === "anymodel-bot/0.1.3")).toBe(true);+ await expect(media.run("b2", "image", { prompt: "x" })).rejects.toThrow(/还没有连接/);+ await expect(media.run("b1", "image", { prompt: "x", model: "nope" })).rejects.toThrow(/没有这个模型/);+ } finally {+ await srv.close();+ }+ });+});++describe("amb-media 插件与 bridge", () => {+ const runtime = locateDshRuntime(findAppRoot());++ it.skipIf(!runtime)("用真实的 dsh-tools 注册 generate_image / generate_video,调用经 bridge 带上机器人与会话", async () => {+ const seen: any[] = [];+ const bridge = await listen(async (req, res) => {+ seen.push({ url: req.url, auth: req.headers.authorization, body: await readJson(req) });+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ text: "ok" }));+ });+ const env = { ...process.env };+ try {+ Object.assign(process.env, { AMB_BRIDGE_URL: bridge.url, AMB_BRIDGE_TOKEN: "tok", AMB_BOT_ID: "b1" });+ const plugin = await import(path.join(runtime!, "plugins", "amb-media.mjs"));+ const tools: any[] = [];+ plugin.apply({ tools: { register: (t: any) => tools.push(t) } });+ expect(tools.map((t) => t.name)).toEqual(["generate_image", "generate_video"]);+ expect(await tools[0].execute({ prompt: "猫" }, { agent: { session: { id: "s1" } }, signal: AbortSignal.timeout(5000) })).toEqual({ text: "ok" });+ expect(seen).toEqual([{ url: "/dsh/media", auth: "Bearer tok", body: { botId: "b1", sessionId: "s1", op: "image", args: { prompt: "猫" } } }]);+ } finally {+ process.env = env;+ await bridge.close();+ }+ });++ it("bridge 只在该机器人有回合进行中时受理生图(别的机器人不能借它的 Key)", async () => {+ const store = new Store(":memory:");+ const calls: string[] = [];+ const media = { run: async (botId: string) => (calls.push(botId), "done") } as unknown as MediaService;+ const mgr = new AgentManager({ store, dataDir: fs.mkdtempSync(path.join(os.tmpdir(), "amb-mgr-")), runtimeDir: undefined, upstream: () => ({ baseUrl: "", apiKey: "" }), enabled: false, media });+ await mgr.bridge.start();+ try {+ const r = await fetch(`${mgr.bridge.url}/dsh/media`, {+ method: "POST",+ headers: { authorization: `Bearer ${mgr.bridge.token}`, "content-type": "application/json" },+ body: JSON.stringify({ botId: "b1", op: "image", args: { prompt: "x" } }),+ });+ expect(await r.json()).toEqual({ error: "unknown bot" });+ expect(calls).toEqual([]);+ const anon = await fetch(`${mgr.bridge.url}/dsh/media`, { method: "POST", body: "{}" });+ expect(anon.status).toBe(401);+ } finally {+ await mgr.bridge.stop();+ store.close();+ }+ });+});diff --git a/test/helpers.ts b/test/helpers.tsindex 3be5f24..2ba1624 100644--- a/test/helpers.ts+++ b/test/helpers.ts@@ -1,4 +1,5 @@import http from "node:http";+import crypto from "node:crypto";import type { AddressInfo } from "node:net";import type { FeishuMessageEvent, FeishuTransport } from "../src/channels/feishu/transport.js";@@ -22,12 +23,13 @@ async function body(req: http.IncomingMessage): Promise<any> {}/** 模拟 OpenAI 兼容端点:/v1/models + 流式 /v1/chat/completions(回声 + 模型名) */-export async function mockOpenAI(opts: { models?: string[]; key?: string; reply?: (msgs: any[], model: string) => string } = {}) {+export async function mockOpenAI(opts: { models?: string[]; key?: string | string[]; reply?: (msgs: any[], model: string) => string } = {}) {const models = opts.models ?? ["mock-a", "mock-b"];- const calls: Array<{ model: string; messages: any[]; auth?: string }> = [];+ const keys = opts.key === undefined ? undefined : ([] as string[]).concat(opts.key);+ const calls: Array<{ model: string; messages: any[]; auth?: string; skill?: string }> = [];const stats = { aborted: 0 };const srv = await listen(async (req, res) => {- if (opts.key && req.headers.authorization !== `Bearer ${opts.key}`) {+ if (keys && !keys.some((k) => req.headers.authorization === `Bearer ${k}`)) {res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: { message: "bad key" } }));return;}@@ -37,7 +39,7 @@ export async function mockOpenAI(opts: { models?: string[]; key?: string; reply?}if (req.url?.endsWith("/chat/completions") && req.method === "POST") {const b = await body(req);- calls.push({ model: b.model, messages: b.messages, auth: req.headers.authorization });+ calls.push({ model: b.model, messages: b.messages, auth: req.headers.authorization, skill: req.headers["x-modelflare-skill"] as string | undefined });const last = b.messages[b.messages.length - 1]?.content ?? "";const text = opts.reply ? opts.reply(b.messages, b.model) : `[${b.model}] 你说:${last}`;if (!b.stream) {@@ -191,3 +193,108 @@ export async function until(fn: () => boolean | Promise<boolean>, ms = 5000, ste}throw new Error("until: timeout");}++// —— Modelflare 账户(OIDC + connected-app)——++async function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {+ let body = "";+ for await (const c of req) body += c;+ return new URLSearchParams(body);+}+export async function readJson(req: http.IncomingMessage): Promise<any> {+ let body = "";+ for await (const c of req) body += c;+ return body ? JSON.parse(body) : {};+}++/** 模拟 Modelflare:发现文档、授权码 + PKCE(公共客户端)、refresh 轮换、撤销、connected-app 接口 */+export async function mockModelflare() {+ const s = {+ pending: new Map<string, { challenge: string; redirect: string }>(),+ refresh: new Set<string>(),+ 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 }>,+ balance: 12.5,+ revokeAll: false,+ };+ let base = "";+ let n = 0;+ const issue = (res: http.ServerResponse) => {+ const access = `at-${++n}`;+ const refresh = `rt-${n}`;+ s.access.add(access);+ s.refresh.add(refresh);+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ access_token: access, refresh_token: refresh, token_type: "Bearer", expires_in: 900, scope: "account api_keys offline_access openid profile" }));+ };+ const oauthError = (res: http.ServerResponse, code: string) => res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: code }));+ const srv = await listen(async (req, res) => {+ const u = new URL(req.url!, "http://x");+ const json = (o: unknown, status = 200) => res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(o));+ if (u.pathname === "/.well-known/openid-configuration") {+ return json({ issuer: base, authorization_endpoint: `${base}/oauth/authorize`, token_endpoint: `${base}/oauth/token`, revocation_endpoint: `${base}/oauth/revoke` });+ }+ if (u.pathname === "/oauth/token" && req.method === "POST") {+ const f = Object.fromEntries(await readForm(req));+ s.tokenForms.push(f);+ if (f.client_id !== "anymodel-bot" || f.client_secret) return json({ error: "invalid_client" }, 401);+ if (f.grant_type === "authorization_code") {+ const p = s.pending.get(f.code);+ s.pending.delete(f.code);+ if (!p || p.redirect !== f.redirect_uri) return oauthError(res, "invalid_grant");+ const challenge = crypto.createHash("sha256").update(f.code_verifier ?? "").digest("base64url");+ if (challenge !== p.challenge) return oauthError(res, "invalid_grant");+ return issue(res);+ }+ if (f.grant_type === "refresh_token") {+ if (s.revokeAll || !s.refresh.delete(f.refresh_token)) return oauthError(res, "invalid_grant");+ return issue(res);+ }+ return oauthError(res, "unsupported_grant_type");+ }+ if (u.pathname === "/oauth/revoke" && req.method === "POST") {+ const f = await readForm(req);+ s.revoked.push(f.get("token") ?? "");+ s.refresh.delete(f.get("token") ?? "");+ s.keys = [];+ return res.writeHead(200).end();+ }+ if (u.pathname.startsWith("/api/connected-app/")) {+ const token = String(req.headers.authorization ?? "").replace(/^Bearer /, "");+ if (s.revokeAll || !s.access.has(token)) return json({ error: "invalid_token" }, 401);+ const p = u.pathname.slice("/api/connected-app".length);+ 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: s.keys.length + 1, name: b.name, limit_usd: b.limit_usd ?? null, used_usd: 0 };+ s.keys.push(k);+ return json({ success: true, data: { ...k, key: `sk-key-${k.id}`, key_tail: `y-${k.id}`, status: "enabled", unlimited: k.limit_usd === null, remain_usd: k.limit_usd } });+ }+ if (p === "/api-keys" && req.method === "GET") return json({ success: true, data: s.keys.map((k) => ({ ...k, status: "enabled", unlimited: k.limit_usd === null, remain_usd: k.limit_usd })) });+ const m = p.match(/^\/api-keys\/(\d+)$/);+ if (m && req.method === "PATCH") {+ const k = s.keys.find((x) => x.id === Number(m[1]));+ 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 (m && req.method === "DELETE") {+ s.keys = s.keys.filter((x) => x.id !== Number(m[1]));+ return json({ success: true });+ }+ }+ res.writeHead(404).end();+ });+ base = srv.url;+ return { ...srv, s };+}++/** 模拟浏览器:用户在授权页同意后,Modelflare 把授权码带回本机回调地址 */+export async function approveInBrowser(mf: Awaited<ReturnType<typeof mockModelflare>>, loginUrl: string): Promise<Response> {+ const u = new URL(loginUrl);+ const code = `code-${crypto.randomUUID()}`;+ const redirect = u.searchParams.get("redirect_uri")!;+ mf.s.pending.set(code, { challenge: u.searchParams.get("code_challenge")!, redirect });+ return fetch(`${redirect}?code=${code}&state=${encodeURIComponent(u.searchParams.get("state")!)}`);+}diff --git a/test/magpie.integration.test.ts b/test/magpie.integration.test.tsindex df34efa..2268f4f 100644--- a/test/magpie.integration.test.ts+++ b/test/magpie.integration.test.ts@@ -5,7 +5,7 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest";import fs from "node:fs";import os from "node:os";import path from "node:path";-import { App } from "../src/app.js";+import { App, appVersion } from "../src/app.js";import { loadConfig } from "../src/config.js";import { resolveMagpieBinary } from "../src/magpie/supervisor.js";import { FakeFeishu, mockOpenAI, until } from "./helpers.js";@@ -20,7 +20,7 @@ d("内置 magpie 集成", () => {let dataDir: string;beforeAll(async () => {- llm = await mockOpenAI({ key: "mf-upstream-key-a1b2", models: ["up-model"] });+ llm = await mockOpenAI({ key: ["mf-upstream-key-a1b2", "mf-bot-key-c3d4"], models: ["up-model"] });// 仅测试:把 Modelflare 基址指向本地 mock(界面无法设置这个变量)process.env.AMB_MODELFLARE_BASE_URL = llm.url + "/v1";dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-int-"));@@ -82,8 +82,27 @@ d("内置 magpie 集成", () => {const chat = await api("/bots/default/chat", "POST", { text: "经过网关" });expect(chat.json.reply).toContain("你说:经过网关");expect(llm.calls.at(-1)!.auth).toBe("Bearer mf-upstream-key-a1b2");+ // 调用归因:内置网关把 provider 上配置的请求头带给 Modelflare+ expect(llm.calls.at(-1)!.skill).toBe(`anymodel-bot/${appVersion()}`);}, 30_000);+ it("开了预算的机器人走它自己的 Key;模型列表不重复;关掉后回到共用 Key", async () => {+ const baseUrl = process.env.AMB_MODELFLARE_BASE_URL!;+ await app.magpie!.setBotProvider("default", "mf-bot-key-c3d4", baseUrl, [baseUrl], app.requestHeaders());+ expect(app.routeModel("default", "up-model")).toBe("mfb-default/up-model");+ await until(async () => {+ const r = await api("/bots/default/chat", "POST", { text: "预算 Key" });+ return String(r.json.reply).includes("你说:预算 Key") && llm.calls.at(-1)!.auth === "Bearer mf-bot-key-c3d4";+ }, 15_000, 300);+ expect(llm.calls.at(-1)!.skill).toMatch(/^anymodel-bot\//);+ expect((await api("/models")).json.models.every((m: string) => !m.startsWith("mfb-"))).toBe(true);+ await app.magpie!.removeBotProvider("default");+ expect(app.routeModel("default", "up-model")).toBe("modelflare/up-model");+ const back = await api("/bots/default/chat", "POST", { text: "共用 Key" });+ expect(back.json.reply).toContain("你说:共用 Key");+ expect(llm.calls.at(-1)!.auth).toBe("Bearer mf-upstream-key-a1b2");+ }, 40_000);+it("切换线路写入 config.json,Key 保持不变", async () => {const r = await api("/modelflare/line", "PUT", { line: "cn" });expect(r.json).toMatchObject({ connected: true, line: "cn", keyTail: "a1b2" });diff --git a/ui/components/model-picker.js b/ui/components/model-picker.jsindex b6e32d7..9e24171 100644--- a/ui/components/model-picker.js+++ b/ui/components/model-picker.js@@ -1,13 +1,46 @@// 模型选择器(magpie picker 的样式;数据来自 Modelflare 的 /v1/models)。// 不做厂商图标栏:各厂商 logo 是第三方商标,未取得授权前不用。-import { useMemo, useRef, useState } from "preact/hooks";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";import { html, Popover, Icon } from "./ui.js";+import { api } from "../lib/api.js";+import { createStore, useStore } from "../lib/store.js";/** 内置网关列出的模型带 "modelflare/" 前缀,Modelflare 直接列出的不带;两种写法都能调用,显示与比较时去掉它 */export const normModel = (m) => (m && m.startsWith("modelflare/") ? m.slice("modelflare/".length) : m || "");export const sameModel = (a, b) => !!a && !!b && normModel(a) === normModel(b);export const shortModel = (m) => (m && m.includes("/") ? m.slice(m.lastIndexOf("/") + 1) : m);+// —— 模型能力与参考价(/models/info,后端缓存一小时;界面第一次打开选择器时取一次)——+const infoStore = createStore(null);+let infoLoading = false;+function useModelInfo() {+ const info = useStore(infoStore);+ useEffect(() => {+ if (info || infoLoading) return;+ infoLoading = true;+ api("/models/info")+ .then((d) => infoStore.set(d.models || {}))+ .catch(() => infoStore.set({}))+ .finally(() => (infoLoading = false));+ }, []);+ return info || {};+}++const num = (n) => String(+Number(n).toFixed(n < 1 ? 3 : 2));+/** 一行说明:上下文 · 视觉 工具 推理 · 每百万 tokens 输入/输出参考价(按次计费的模型是每次) */+export function modelNote(info, id) {+ const n = normModel(id);+ const i = info[n] || info[n.slice(n.lastIndexOf("/") + 1)];+ if (!i) return "";+ const parts = [];+ if (i.context) parts.push(i.context >= 1e6 ? `${num(i.context / 1e6)}M` : `${Math.round(i.context / 1000)}K`);+ const caps = [i.vision && "视觉", i.tools && "工具", i.reasoning && "推理"].filter(Boolean).join(" ");+ if (caps) parts.push(caps);+ if (i.price) parts.push(i.price.perCall !== undefined ? `$${num(i.price.perCall)}/次` : `$${num(i.price.input)}/${i.price.output !== undefined ? num(i.price.output) : "—"}`);+ return parts.join(" · ");+}+const NOTE_TITLE = "上下文 · 能力 · 每百万 tokens 输入/输出的起步参考价(美元,以账单为准)";+/** 按 "厂商/模型" 的前缀分组(没有前缀的放在最后);返回 [厂商, [[原始 id, 显示名]]] */export function groupModels(models, q = "") {const needle = q.trim().toLowerCase();@@ -30,6 +63,7 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, rconst [q, setQ] = useState("");const [sel, setSel] = useState(0);const listRef = useRef(null);+ const info = useModelInfo();const groups = useMemo(() => groupModels(models || [], q), [models, q]);const custom = q.trim() && !(models || []).some((m) => sameModel(m, q.trim())) ? q.trim() : "";const flat = [...(reset && !q ? [{ reset: true }] : []), ...groups.flatMap(([, ms]) => ms.map(([m]) => ({ m }))), ...(custom ? [{ m: custom, custom: true }] : [])];@@ -57,7 +91,7 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, rconst i = idx;return html`<li role="option" aria-selected=${sel === i} class=${`${sel === i ? "sel" : ""} ${(!it.reset && sameModel(it.m, current)) || (it.reset && !current) ? "cur" : ""}`}onPointerMove=${() => setSel(i)} onClick=${() => choose(it)}>- <span class="v">${label}</span>${note && html`<span class="n">${note}</span>`}+ <span class="v">${label}</span>${note && html`<span class="n" title=${it.reset || it.custom ? undefined : NOTE_TITLE}>${note}</span>`}<span class="check"><${Icon} name="check" size=${14} /></span></li>`;};@@ -70,7 +104,7 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, r${error && html`<li class="explained" style="pointer-events:auto"><span class="v" style="white-space:normal;color:var(--red)">获取模型列表失败:${error}</span>${onRetry && html`<button type="button" class="text" onClick=${onRetry}>重试</button>`}</li>`}${reset && !q && item({ reset: true }, reset.label, reset.note)}- ${groups.map(([g, ms]) => html`${g && html`<li class="group">${g}</li>`}${ms.map(([m, label]) => item({ m }, label))}`)}+ ${groups.map(([g, ms]) => html`${g && html`<li class="group">${g}</li>`}${ms.map(([m, label]) => item({ m }, label, modelNote(info, m)))}`)}${custom && item({ m: custom, custom: true }, `使用「${custom}」`, "自定义模型 ID")}${models && !models.length && !q && html`<li class="explained"><span class="v" style="white-space:normal">没有可用模型:这个 Key 所在的分组还没有开放模型</span></li>`}</ul>diff --git a/ui/css/settings.css b/ui/css/settings.cssindex 6b65eab..6178512 100644--- a/ui/css/settings.css+++ b/ui/css/settings.css@@ -33,6 +33,24 @@.set-body > .list:first-child { margin-top: var(--space-6); }.set-none { margin: var(--section-gap) 0; font-size: var(--fs-md); color: var(--muted); }.mf-state { display: inline-flex; align-items: center; gap: var(--space-1-5); font-size: var(--fs-sm); color: var(--fg-2); }+.balance { font-size: var(--fs-lg); font-weight: var(--fw-semibold); font-variant-numeric: tabular-nums; }+.balance.low { color: var(--red); }+.settings input.field.num-in { width: 96px; --field-h: var(--ctl-md); text-align: right; font-variant-numeric: tabular-nums; }++/* 用量:近 N 天的日柱状图 + 模型排行 */+.usage-days { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); align-items: end; gap: var(--space-1); height: 120px; padding: var(--space-2) 0; }+.usage-days .bar { display: grid; align-content: end; justify-items: center; gap: var(--space-1); height: 100%; font-size: var(--fs-2xs); color: var(--faint); }+.usage-days .bar i { display: block; width: 100%; min-height: 2px; border-radius: var(--r-sm) var(--r-sm) 0 0; background: var(--accent-solid); }+.usage-models { display: grid; gap: var(--space-1); font-size: var(--fs-sm); }+.usage-models div { display: flex; justify-content: space-between; gap: var(--space-3); }+.usage-models .v { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.usage-models .n { color: var(--muted); font-variant-numeric: tabular-nums; }+.notif { display: grid; gap: var(--space-1); padding: var(--space-3) 0; border-bottom: .5px solid var(--line); }+.notif:last-child { border-bottom: 0; }+.notif b { font-weight: var(--fw-semibold); }+.notif.unread b::before { content: ""; display: inline-block; width: 6px; height: 6px; margin-right: var(--space-1-5); border-radius: 50%; background: var(--accent-solid); vertical-align: middle; }+.notif p { font-size: var(--fs-sm); color: var(--fg-2); white-space: pre-wrap; }+.notif time { font-size: var(--fs-2xs); color: var(--faint); }/* 机器人设置:身份是带标签的输入框(参考 Codex 的编辑页) */.set-field { display: grid; gap: var(--space-2); margin-bottom: var(--space-5); }@@ -105,6 +123,8 @@/* "高级"里的行直接排在卡片里,左右贴着卡片的内容边,不再套一块玻璃 */.onboard details .row { --row-pl: 0; --row-pr: 0; margin-top: var(--space-1); }.onboard .connected { display: flex; align-items: center; gap: var(--space-2); font-size: var(--fs-lg); font-weight: var(--fw-semibold); }+.login-wait .connected { font-size: var(--fs-md); line-height: var(--lh-snug); }+.login-links { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); }.picklist { max-height: 300px; overflow-y: auto; margin: 0 calc(-1 * var(--space-1-5)); padding: 0 var(--space-1-5); }.picklist > .hint { padding: var(--space-2); }.picklist .group { padding: var(--space-2) var(--space-2) var(--space-1); font-size: var(--fs-2xs); font-weight: var(--fw-semibold); color: var(--muted); }diff --git a/ui/css/shell.css b/ui/css/shell.cssindex 5fb1364..00fbd5b 100644--- a/ui/css/shell.css+++ b/ui/css/shell.css@@ -135,6 +135,13 @@ button.thread:active { background: var(--side-press); }font-weight: var(--fw-semibold); font-size: var(--fs-sm); color: var(--fg-2);}.account .who { flex: 1; min-width: 0; font-size: var(--fs-lg); color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.account .who .bal { display: block; font-size: var(--fs-2xs); color: var(--muted); }+.account .who .bal.low { color: var(--red); }+.low-balance {+ flex: none; margin: 0 var(--space-2); padding: var(--space-2) var(--space-3); border-radius: var(--r-lg);+ font-size: var(--fs-sm); color: var(--red); background: var(--side-hover); text-decoration: none;+}+.low-balance:hover { background: var(--side-press); }.account > .ic { color: var(--muted); transition: color var(--t-fast); }.account:hover > .ic { color: var(--fg); }diff --git a/ui/lib/links.js b/ui/lib/links.jsnew file mode 100644index 0000000..eb66669--- /dev/null+++ b/ui/lib/links.js@@ -0,0 +1,24 @@+// Modelflare 官网链接:都带注册来源参数(utm_source=anymodelbot),后台用它统计从本程序来的注册与充值。+export const MF_SITE = "https://modelflare.dev";+export const MF_DOCS = "https://docs.modelflare.dev";++export function mfLink(path, campaign) {+ const u = new URL(path, MF_SITE);+ u.searchParams.set("utm_source", "anymodelbot");+ u.searchParams.set("utm_medium", "app");+ if (campaign) u.searchParams.set("utm_campaign", campaign);+ return u.toString();+}++export const MF_CONSOLE = mfLink("/dashboard/overview", "console");+export const MF_KEYS = mfLink("/keys", "keys");+export const MF_SIGNUP = mfLink("/sign-up", "signup");+export const MF_TOPUP = mfLink("/billing", "topup");+export const MF_PRICING = mfLink("/pricing", "pricing");++/** 美元金额:两位小数;很小的数保留四位,避免显示成 $0.00 */+export function usd(n) {+ if (n === null || n === undefined || !Number.isFinite(Number(n))) return "—";+ const v = Number(n);+ return `$${Math.abs(v) > 0 && Math.abs(v) < 0.01 ? v.toFixed(4) : v.toFixed(2)}`;+}diff --git a/ui/main.js b/ui/main.jsindex 5189a0d..ddd89e2 100644--- a/ui/main.js+++ b/ui/main.js@@ -13,7 +13,7 @@ import { BotAvatar, MAIN_CHAR, charOf } from "./components/avatar.js";import { Onboarding } from "./screens/onboarding.js";import { api } from "./lib/api.js";import { setThemeMode } from "./lib/theme.js";-import { failed } from "./lib/store.js";+import { failed, toast } from "./lib/store.js";// —— 路由:#/chat/<bot> · #/new · #/settings/<tab>[/<row>] · #/bot/<bot>/settings[/<section>] ——function parseHash() {@@ -126,6 +126,9 @@ function App() {const connected = !!(mf && (mf.mode === "external" || mf.connected));const [botsData, botsErr, reloadBots] = useLoader(() => (connected ? api("/bots") : Promise.resolve(null)), [connected]);const [modelsData, , loadModels] = useLoader(() => (connected ? api("/models") : Promise.resolve(null)), [connected]);+ // Modelflare 账户与余额:后端每 5 分钟读一次;界面每分钟取快照,切回窗口时请后端立刻刷新+ const [account, , , setAccount] = useLoader(() => api("/account"), [connected]);+ const managed = !!(mf && mf.mode === "managed");const [previews, setPreviews] = useState({});const [pending, setPending] = useState({});const [agentWorking, setAgentWorking] = useState({});@@ -141,6 +144,23 @@ function App() {return () => window.removeEventListener("hashchange", on);}, []);+ useInterval(() => api("/account").then(setAccount).catch(() => {}), 60_000, connected && managed);+ useEffect(() => {+ if (!connected || !managed) return;+ const on = () => document.visibilityState === "visible" && api("/account/refresh", { method: "POST", body: {} }).then(setAccount).catch(() => {});+ window.addEventListener("focus", on);+ return () => window.removeEventListener("focus", on);+ }, [connected, managed]);+ // 授权在网页上被撤销时后端会断开连接:回到登录页;余额跌破提醒线时提示一次+ const prevAccount = useRef(null);+ useEffect(() => {+ const prev = prevAccount.current;+ prevAccount.current = account;+ if (!prev || !account) return;+ if (prev.state === "signed_in" && account.state !== "signed_in") reloadMf();+ if (!prev.lowBalance && account.lowBalance) toast(`Modelflare 余额只剩 ${account.balanceUsd.toFixed(2)} 美元`, "err");+ }, [account]);+const bots = botsData ? botsData.bots : null;const wanted = route.botId || lastBot;const bot = bots && (bots.find((b) => b.id === wanted) || bots[0]);@@ -292,9 +312,9 @@ function App() {return html`<div class=${`app${panelBot ? " with-panel" : ""}`} style=${{ "--aura-hue": String(auraHue) }}>${view === "settings"? html`<${SettingsSide} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} onTab=${(t) => openSettings(t)} onBack=${() => openChat()}- username=${status && status.username} />`+ username=${status && status.username} account=${managed ? account : null} />`: html`<${Sidebar} bots=${bots} botsError=${botsErr} reloadBots=${reloadBots} selectedId=${bot && bot.id} view=${view === "chat" && bots && !bots.length ? "new" : view}- previews=${previews} pending=${pending} working=${working} username=${status && status.username}+ previews=${previews} pending=${pending} working=${working} username=${status && status.username} account=${managed ? account : null}onNew=${newBot} onSelect=${openChat} onDeleted=${onDeleted} onOpenSettings=${() => openSettings()} />`}<main class="main">${view === "chat" && bot && html`<${ChatScreen} key=${bot.id} bot=${bot} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}@@ -304,9 +324,10 @@ function App() {onCreated=${(b) => { reloadBots(); openChat(b.id); }} onCancel=${bots && bots.length ? () => openChat() : null} />`}${view === "settings" && html`<${SettingsScreen} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} focusRow=${route.row}mf=${mf} onMfChanged=${reloadMf} onSettings=${setSettings} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}- status=${status} bots=${bots} onOpenBotSettings=${openBotSettings} />`}+ status=${status} bots=${bots} onOpenBotSettings=${openBotSettings} account=${managed ? account : null} onAccount=${setAccount} />`}${view === "bot-settings" && routedBot && html`<${BotSettingsScreen} key=${routedBot.id} bot=${routedBot} section=${route.section}models=${models} modelsError=${modelsError} reloadModels=${reloadModels} defaultModel=${settings && settings.defaultModel}+ account=${managed ? account : null} onOpenSettings=${openSettings}onBack=${() => openChat(routedBot.id)} onBotUpdated=${onBotUpdated} onDeleted=${() => onDeleted(routedBot.id)} />`}${view === "bot-settings" && bots && !routedBot && html`<div class="empty-state"><b>机器人不存在</b><button type="button" class="text" onClick=${() => openChat()}>返回对话</button></div>`}</main>diff --git a/ui/screens/account.js b/ui/screens/account.jsnew file mode 100644index 0000000..238c244--- /dev/null+++ b/ui/screens/account.js@@ -0,0 +1,70 @@+// Modelflare 账户相关的弹层:登录、近 N 天用量、通知。设置页「Modelflare」分页里的行会打开它们。+import { useEffect, useState } from "preact/hooks";+import { html, Seg, Sheet, Skeleton } from "../components/ui.js";+import { AccountLogin } from "./onboarding.js";+import { api } from "../lib/api.js";+import { MF_SITE, usd } from "../lib/links.js";++/** 通知里的链接:站内路径补成官网地址;只放行 https */+const notifLink = (link) => (!link ? "" : link.startsWith("/") && !link.startsWith("//") ? MF_SITE + link : /^https:\/\//.test(link) ? link : "");++export function LoginSheet({ onClose, onSignedIn }) {+ return html`<${Sheet} title="登录 Modelflare 账户" onClose=${onClose}>+ <p class="hint">登录后会为这台电脑签发一把专用 API Key,替换现在手动填的 Key。</p>+ <${AccountLogin} hint=${false} onSignedIn=${(s) => { onSignedIn(s); onClose(); }} />+ <//>`;+}++const RANGES = [+ [7, "7 天"],+ [30, "30 天"],+];++export function UsageSheet({ onClose }) {+ const [days, setDays] = useState(7);+ const [d, setD] = useState(null);+ const [err, setErr] = useState("");+ useEffect(() => {+ setD(null);+ setErr("");+ api(`/account/usage?days=${days}`).then(setD).catch((e) => setErr(e.message));+ }, [days]);+ const max = d ? Math.max(...d.days.map((x) => x.usd), 0) : 0;+ return html`<${Sheet} title="用量" wide onClose=${onClose}>+ <div class="row compact"><div class="who"><div class="name">${d ? `合计 ${usd(d.totalUsd)}` : "读取中…"}</div></div>+ <${Seg} label="范围" options=${RANGES} value=${days} onChange=${setDays} /></div>+ ${err && html`<div class="err-text" role="alert">${err}</div>`}+ ${!d && !err && html`<${Skeleton} w="100%" h=${120} />`}+ ${d && html`<div class="usage-days" role="img" aria-label="每日花费">+ ${d.days.map((x) => html`<div class="bar" title=${`${x.date}:${usd(x.usd)},${x.requests} 次请求`}>+ <i style=${{ height: `${max > 0 ? Math.max(2, (x.usd / max) * 100) : 2}%` }}></i>${days <= 7 ? x.date.slice(5) : ""}+ </div>`)}+ </div>+ <div class="set-part">按模型</div>+ <div class="usage-models">+ ${d.models.slice(0, 12).map((m) => html`<div><span class="v">${m.model}</span><span class="n">${usd(m.usd)} · ${m.requests} 次</span></div>`)}+ ${!d.models.length && html`<p class="hint">这段时间没有用量</p>`}+ </div>`}+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div>+ <//>`;+}++export function NotificationsSheet({ onClose }) {+ const [d, setD] = useState(null);+ const [err, setErr] = useState("");+ useEffect(() => {+ api("/account/notifications").then((r) => setD(r.data || { items: [] })).catch((e) => setErr(e.message));+ }, []);+ return html`<${Sheet} title="Modelflare 通知" wide onClose=${onClose}>+ ${err && html`<div class="err-text" role="alert">${err}</div>`}+ ${!d && !err && html`<${Skeleton} w="100%" h=${80} />`}+ ${d && !d.items.length && html`<p class="hint">没有通知</p>`}+ ${d && d.items.map((n) => html`<div class=${`notif${n.read_at ? "" : " unread"}`}>+ ${n.title && html`<b>${n.title}</b>`}+ <p>${n.content}</p>+ <time>${new Date(n.created_at * 1000).toLocaleString()}</time>+ ${notifLink(n.link) && html`<a class="text" href=${notifLink(n.link)} target="_blank" rel="noopener noreferrer">查看详情 ↗</a>`}+ </div>`)}+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div>+ <//>`;+}diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.jsindex 60f79b5..c152a95 100644--- a/ui/screens/bot-settings.js+++ b/ui/screens/bot-settings.js@@ -5,6 +5,7 @@ import { BotAvatar, AvatarPicker, charOf } from "../components/avatar.js";import { ModelPicker, shortModel } from "../components/model-picker.js";import { api } from "../lib/api.js";import { confirmSheet, failed, saved } from "../lib/store.js";+import { usd } from "../lib/links.js";function Row({ id, name, sub, title, children, off }) {return html`<div class=${`row${off ? " off" : ""}`} id=${`bot-${id}`} title=${title}>@@ -23,7 +24,58 @@ function ModelButton({ value, models, modelsError, reloadModels, resetLabel, onConPick=${onChange} onClose=${() => setOpen(false)} reset=${{ label: resetLabel, onSelect: () => onChange("") }} />`}`;}-export function BotSettingsScreen({ bot, section, models, modelsError, reloadModels, defaultModel, onBack, onBotUpdated, onDeleted }) {+/**+ * 预算:开启后机器人用自己的 Modelflare API Key,最多花设定的美元数(包括这把 Key 已经花掉的);+ * 用完后它的请求会被拒绝,其他机器人不受影响。需要登录 Modelflare 账户。+ */+function BudgetRows({ bot, budget, account, onSaved, onOpenSettings }) {+ const [limit, setLimit] = useState(String(budget.limitUsd));+ const [busy, setBusy] = useState(false);+ const [use, setUse] = useState(null);+ const signedIn = !!(account && account.state === "signed_in");+ useEffect(() => setLimit(String(budget.limitUsd)), [budget.limitUsd]);+ useEffect(() => {+ if (!signedIn || !budget.enabled) return setUse(null);+ api("/account/budgets").then((r) => setUse(r.budgets[bot.id] || null)).catch(() => setUse(null));+ }, [signedIn, budget.enabled, budget.limitUsd, bot.id]);+ const save = async (enabled, limitUsd) => {+ setBusy(true);+ try {+ const r = await api(`/bots/${bot.id}/budget`, { method: "PUT", body: { enabled, limitUsd } });+ onSaved(r.settings);+ saved();+ } catch (e) {+ failed(e);+ setLimit(String(budget.limitUsd));+ } finally {+ setBusy(false);+ }+ };+ const commitLimit = () => {+ const v = Number(limit);+ if (!Number.isFinite(v) || v < 0) return setLimit(String(budget.limitUsd));+ if (v !== budget.limitUsd) save(budget.enabled, v);+ };+ if (!signedIn) {+ return html`<${Row} id="budget" name="预算" sub="登录 Modelflare 账户后,可以给这个机器人单独设花费上限">+ <button type="button" class="text accent" onClick=${() => onOpenSettings("modelflare", "account")}>去登录</button>+ <//>`;+ }+ const sub = !budget.enabled+ ? "与其他机器人共用本机的 Key,不单独限额"+ : use+ ? `已用 ${usd(use.used_usd)},还剩 ${usd(use.remain_usd)}${use.status === "exhausted" ? " · 已用完,机器人暂停调用模型" : ""}`+ : "用这个机器人自己的 Key,花到上限就停";+ return html`<${Row} id="budget" name="预算" sub=${sub}>+ <${Switch} label="预算" value=${budget.enabled} disabled=${busy} onChange=${(v) => save(v, Number(limit) || budget.limitUsd)} />+ <//>+ <${Row} id="budget-limit" name="上限(美元)" sub="包括已经花掉的部分;调高后用完的 Key 会自动恢复" off=${!budget.enabled}>+ <input class="field num-in" type="number" min="0" step="1" inputmode="decimal" aria-label="预算上限(美元)" value=${limit} disabled=${!budget.enabled || busy}+ onInput=${(e) => setLimit(e.target.value)} onBlur=${commitLimit} onKeyDown=${(e) => e.key === "Enter" && e.target.blur()} />+ <//>`;+}++export function BotSettingsScreen({ bot, section, models, modelsError, reloadModels, defaultModel, account, onOpenSettings, onBack, onBotUpdated, onDeleted }) {const [d, setD] = useState(null);const [name, setName] = useState(bot.name);const [prompt, setPrompt] = useState(bot.systemPrompt || "");@@ -111,6 +163,8 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod<${Row} id="utility" name="后台小任务模型" sub="记忆整理、上下文管家与交接便条">${s && html`<${ModelButton} value=${s.utilityModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels} resetLabel="与对话模型相同" onChange=${(m) => put({ utilityModel: m })} />`}<//>+ ${s && account && html`<${BudgetRows} bot=${bot} budget=${s.budget} account=${account} onOpenSettings=${onOpenSettings}+ onSaved=${(settings) => setD((v) => ({ ...v, settings }))} />`}</div>${!s && html`<div class="list"><div class="row"><${Skeleton} w="45%" /></div><div class="row"><${Skeleton} w="35%" /></div></div>`}diff --git a/ui/screens/onboarding.js b/ui/screens/onboarding.jsindex 37292b9..4b544fa 100644--- a/ui/screens/onboarding.js+++ b/ui/screens/onboarding.js@@ -1,13 +1,13 @@-// 首次启动 / 断开后:只有一个动作——粘贴 Modelflare API Key。不是向导路由,而是"未连接"时的整页空态。+// 首次启动 / 退出登录后:"未连接"时的整页空态。主操作是登录 / 注册 Modelflare(在系统浏览器里完成,+// 回来后自动签发本机 Key 并连接);也可以展开后直接粘贴一个 API Key。不是向导路由。import { useEffect, useMemo, useRef, useState } from "preact/hooks";-import { html, Icon, Notice, Seg, Spinner } from "../components/ui.js";+import { html, Icon, Notice, Seg, Spinner, CopyButton } from "../components/ui.js";import { BotAvatar, MAIN_CHAR } from "../components/avatar.js";import { groupModels } from "../components/model-picker.js";import { api } from "../lib/api.js";+import { MF_CONSOLE, MF_DOCS, MF_KEYS } from "../lib/links.js";-// 控制台 API Keys 页还没有稳定的深链地址,先指向官网首页(登录后可进控制台)-export const MF_CONSOLE = "https://modelflare.dev";-export const MF_DOCS = "https://docs.modelflare.dev";+export { MF_CONSOLE, MF_DOCS };export const LINE_OPTIONS = [["auto", "自动"],["global", "国际"],@@ -102,6 +102,70 @@ export function KeyForm({ line: initialLine = "auto", onConnected, onFace, showL</form>`;}+/**+ * 登录 / 注册 Modelflare:桌面版由主进程在系统浏览器里打开授权页;浏览器版在新标签页打开(被拦截时+ * 用下面的链接)。等待期间每秒读一次账户状态,登录完成(本机 Key 已接上)后 onSignedIn(status)。+ */+export function AccountLogin({ onSignedIn, onFace, label = "登录 / 注册 Modelflare", hint = true }) {+ const [waiting, setWaiting] = useState(false);+ const [url, setUrl] = useState("");+ const [err, setErr] = useState("");+ useEffect(() => onFace?.(waiting ? "thinking" : "idle"), [waiting]);+ useEffect(() => {+ if (!waiting) return;+ let stop = false;+ const t = setInterval(async () => {+ const s = await api("/account").catch(() => null);+ if (!s || stop) return;+ if (s.state === "signed_in") {+ stop = true;+ setWaiting(false);+ onSignedIn(s);+ } else if (s.state !== "signing_in") {+ stop = true;+ setWaiting(false);+ if (s.error) {+ setErr(s.error);+ onFace?.("error");+ }+ }+ }, 1000);+ return () => clearInterval(t);+ }, [waiting]);+ const start = async () => {+ setErr("");+ try {+ const r = await api("/account/login", { method: "POST", body: {} });+ setUrl(r.loginUrl);+ setWaiting(true);+ if (!r.opened) window.open(r.loginUrl, "_blank", "noopener");+ } catch (e) {+ setErr(e.message);+ onFace?.("error");+ }+ };+ const cancel = () => {+ setWaiting(false);+ api("/account/login/cancel", { method: "POST", body: {} }).catch(() => {});+ };+ if (waiting) {+ return html`<div class="list login-wait" role="status">+ <div class="connected"><${Spinner} /> 请在浏览器里登录或注册 Modelflare,并点「继续」授权</div>+ <p class="hint">完成后会自动回到这里。浏览器没有打开?</p>+ <div class="login-links">+ <a class="btn" href=${url} target="_blank" rel="noopener noreferrer">打开登录页 ↗</a>+ <${CopyButton} text=${url} label="复制登录链接" />+ <button type="button" class="text" onClick=${cancel}>取消</button>+ </div>+ </div>`;+ }+ return html`<div class="list">+ <button type="button" class="btn primary lg block" onClick=${start}>${label}</button>+ ${err && html`<div class="err-text" role="alert">${err}</div>`}+ ${hint && html`<p class="hint">在浏览器里用 Modelflare 账户登录(没有账户可以当场注册),授权后本机会自动获得一把专用 API Key。</p>`}+ </div>`;+}+function ModelStep({ models, initial, onDone }) {const [q, setQ] = useState("");const [cur, setCur] = useState(initial && models.includes(initial) ? initial : models[0] || "");@@ -138,23 +202,52 @@ function ModelStep({ models, initial, onDone }) {export function Onboarding({ status, gateway, defaultModel, onDone }) {const [models, setModels] = useState(null);+ const [useKey, setUseKey] = useState(false);+ // Docker / 远程部署:浏览器登录的回调到不了本程序,只能用 API Key+ const [loginAvailable, setLoginAvailable] = useState(true);+ // 授权在网页上被撤销后会回到这里:说明原因+ const [why, setWhy] = useState("");+ useEffect(() => {+ api("/account")+ .then((a) => {+ if (a.error) setWhy(a.error);+ if (a.loginAvailable === false) {+ setLoginAvailable(false);+ setUseKey(true);+ }+ })+ .catch(() => {});+ }, []);const [face, setFace] = useState("idle");const [cue, setCue] = useState(null);const onFace = (f) => (f === "error" ? setCue({ kind: "error", at: Date.now() }) : setFace(f));+ const loadModels = () =>+ api("/models")+ .then((d) => setModels(d.models || []))+ .catch(() => setModels([]));return html`<main class="onboard" data-screen="onboarding"><div class="onboard-col"><div class="onboard-hero"><${BotAvatar} char=${MAIN_CHAR} size=${88} state=${face} cue=${cue} lively pokeable greet /><h1>用 Modelflare 开始</h1>- <p>粘贴 API Key,GPT、Claude、Grok、Gemini 等模型会自动列出。</p>+ <p>登录后 GPT、Claude、Grok、Gemini 等模型会自动列出,余额和用量也能在这里看。</p></div>${gateway && gateway.mode === "managed" && gateway.state === "failed" && html`<${Notice} tone="red">内置模型网关没有启动:${gateway.lastError || "未知原因"}。修复后重启应用再连接。<//>`}- ${models === null- ? html`<${KeyForm} line=${status.line} onFace=${onFace} onConnected=${(r) => (setFace("idle"), setModels(r.models || []))} />- <div class="links">- <a href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">还没有 Key?去 Modelflare 控制台创建 ↗</a>- </div>`- : html`<${ModelStep} models=${models} initial=${defaultModel} onDone=${onDone} />`}+ ${why && models === null && html`<${Notice} tone="amber">${why}<//>`}+ ${models !== null+ ? html`<${ModelStep} models=${models} initial=${defaultModel} onDone=${onDone} />`+ : useKey+ ? html`<${KeyForm} line=${status.line} onFace=${onFace} onConnected=${(r) => (setFace("idle"), setModels(r.models || []))} />+ <div class="links">+ <a href=${MF_KEYS} target="_blank" rel="noopener noreferrer">在 Modelflare 控制台创建 Key ↗</a>+ ${loginAvailable+ ? html`<button type="button" class="text" onClick=${() => setUseKey(false)}>改用账户登录</button>`+ : html`<span>当前是 Docker 或远程部署,无法用浏览器登录</span>`}+ </div>`+ : html`<${AccountLogin} onFace=${onFace} onSignedIn=${loadModels} />+ <div class="links">+ <button type="button" class="text" onClick=${() => setUseKey(true)}>我有 API Key</button>+ </div>`}</div></main>`;}diff --git a/ui/screens/settings.js b/ui/screens/settings.jsindex 1ed4197..dfee5bd 100644--- a/ui/screens/settings.js+++ b/ui/screens/settings.js@@ -4,8 +4,10 @@ import { useEffect, useMemo, useRef, useState } from "preact/hooks";import { html, Icon, Seg, Switch, Sheet, CopyButton, Skeleton } from "../components/ui.js";import { AccountButton } from "./sidebar.js";import { ModelPicker, shortModel } from "../components/model-picker.js";-import { KeyForm, LINE_OPTIONS, MF_CONSOLE, MF_DOCS } from "./onboarding.js";+import { KeyForm, LINE_OPTIONS } from "./onboarding.js";+import { LoginSheet, NotificationsSheet, UsageSheet } from "./account.js";import { api } from "../lib/api.js";+import { MF_CONSOLE, MF_DOCS, MF_TOPUP, usd } from "../lib/links.js";import { useStore, confirmSheet, failed, saved } from "../lib/store.js";import { themeMode, setThemeMode } from "../lib/theme.js";@@ -25,6 +27,12 @@ const ZOOMS = [[1.5, "150%"],];const GATEWAY = { running: "运行中", starting: "启动中", restarting: "重启中", failed: "失败", stopped: "已停止", external: "外部端点" };+const ALERT_LINES = [+ [0, "不提醒"],+ [1, "$1"],+ [5, "$5"],+ [20, "$20"],+];function Row({ id, name, sub, title, children, flash, off }) {return html`<div class=${`row${flash ? " flash" : ""}${off ? " off" : ""}`} id=${`set-${id}`} title=${title}>@@ -55,7 +63,7 @@ function NoticesSheet({ onClose }) {}/** 设置时的侧栏:返回应用 | 查找设置 | 分页 | 账户 */-export function SettingsSide({ tab, query, onQuery, onTab, onBack, username }) {+export function SettingsSide({ tab, query, onQuery, onTab, onBack, username, account }) {const searching = !!query.trim();return html`<aside class="side" aria-label="设置"><div class="side-top start">@@ -73,14 +81,17 @@ export function SettingsSide({ tab, query, onQuery, onTab, onBack, username }) {onClick=${() => { onQuery(""); onTab(t); }}><${Icon} name=${icon} size=${16} /><span>${label}</span></button>`;})}</nav>- <div class="side-foot"><${AccountButton} username=${username} on onClick=${() => onTab("general")} /></div>+ <div class="side-foot"><${AccountButton} username=${username} account=${account} on onClick=${() => onTab("general")} /></div></aside>`;}-export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onMfChanged, onSettings, models, modelsError, reloadModels, status, bots, onOpenBotSettings }) {+export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onMfChanged, onSettings, models, modelsError, reloadModels, status, bots, onOpenBotSettings, account: acct, onAccount }) {const [s, setS] = useState(null);const [rekey, setRekey] = useState(false);const [notices, setNotices] = useState(false);+ const [sheet, setSheet] = useState(""); // login | usage | notifications+ const [invite, setInvite] = useState(null);+ const [unread, setUnread] = useState(null);const [cu, setCu] = useState(null);const [flash, setFlash] = useState("");const mode = useStore(themeMode);@@ -132,8 +143,37 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onMfailed(e);}};+ const logout = async () => {+ if (!(await confirmSheet({ title: "退出 Modelflare 账户?", body: "会撤销这台电脑的授权,并删除登录时为它和各机器人签发的 API Key。机器人和会话都会保留。", confirmLabel: "退出登录", danger: true }))) return;+ try {+ const r = await api("/account/logout", { method: "POST", body: {} });+ if (!r.revoked) failed("服务端没有确认撤销:本机已退出,可在 Modelflare 网页的「已授权的应用」里再撤销一次");+ onAccount(r);+ onMfChanged();+ } catch (e) {+ failed(e);+ }+ };+ const refreshBalance = () =>+ api("/account/refresh", { method: "POST", body: {} })+ .then(onAccount)+ .catch(failed);+ const putAlerts = (patch) =>+ api("/account/alerts", { method: "PUT", body: patch })+ .then((r) => {+ onAccount(r);+ saved();+ })+ .catch(failed);const desktop = !!(s && s.desktop);const managed = mf && mf.mode === "managed";+ const signedIn = !!(acct && acct.state === "signed_in");+ // 登录后才有邀请码和通知;进入 Modelflare 分页时读一次+ useEffect(() => {+ if (!signedIn || tab !== "modelflare") return;+ api("/account/invite").then(setInvite).catch(() => setInvite(null));+ api("/account/notifications").then((r) => setUnread(r.data ? r.data.unread_count : null)).catch(() => setUnread(null));+ }, [signedIn, tab]);// —— 行定义:每行一个稳定 id,可被搜索、可被深链(#/settings/<tab>/<id>)——const rows = useMemo(() => {@@ -150,13 +190,37 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onMdesktop && { tab: "general", id: "browser", name: "在浏览器中打开", sub: "用系统浏览器打开同一个本机界面", keys: "browser",ctl: html`<button type="button" class="text" onClick=${() => api("/desktop/open-in-browser", { method: "POST", body: {} }).catch(failed)}>打开</button>` },- { tab: "modelflare", id: "connection", name: "连接", sub: managed ? "API Key 只保存在本机" : "由环境变量 AMB_MAGPIE_BASE_URL 指定的端点(开发/测试)", keys: "密钥 key api 断开 更换",+ managed && acct && { tab: "modelflare", id: "account", name: "Modelflare 账户",+ sub: signedIn ? `${acct.name || "已登录"}${acct.billedToEnterprise ? " · 由企业钱包付费" : ""}` : acct.state === "unavailable" ? acct.error : "登录后可以查看用量、通知和邀请链接,也能给机器人单独设预算", keys: "登录 注册 账户 退出 account login",+ ctl: signedIn+ ? html`<button type="button" class="text danger" onClick=${logout}>退出登录</button>`+ : acct.loginAvailable === false+ ? html`<span class="val">Docker / 远程部署不支持浏览器登录</span>`+ : html`<button type="button" class="text accent" onClick=${() => setSheet("login")}>登录 / 注册</button>` },+ { tab: "modelflare", id: "connection", name: signedIn ? "本机 Key" : "连接",+ sub: !managed ? "由环境变量 AMB_MAGPIE_BASE_URL 指定的端点(开发/测试)" : signedIn ? "登录时为这台电脑签发,退出登录会一并删除" : "API Key 只保存在本机", keys: "密钥 key api 断开 更换",ctl: managed? html`<span class="mf-state"><span class=${`dot ${mf.connected ? "ok" : "err"}`}></span>${mf.connected ? "已连接" : "未连接"}</span>${mf.keyTail && html`<span class="val">••••${mf.keyTail}</span>`}- <button type="button" class="text" onClick=${() => setRekey(true)}>更换密钥</button>- <button type="button" class="text danger" onClick=${disconnect}>断开</button>`+ ${!signedIn && html`<button type="button" class="text" onClick=${() => setRekey(true)}>更换密钥</button>+ <button type="button" class="text danger" onClick=${disconnect}>断开</button>`}`: html`<span class="val" title=${mf && mf.baseUrl}>${mf && mf.baseUrl}</span>` },+ managed && acct && mf.connected && { tab: "modelflare", id: "balance", name: "余额",+ sub: acct.error ? `读取失败:${acct.error}` : acct.source === "key" ? "这把 Key 所在账户的钱包余额" : acct.updatedAt ? `更新于 ${new Date(acct.updatedAt).toLocaleTimeString()}` : "读取中…", keys: "余额 充值 钱包 balance top up",+ ctl: html`<span class=${`balance${acct.lowBalance ? " low" : ""}`}>${usd(acct.balanceUsd)}</span>+ <button type="button" class="icon-btn" title="刷新" aria-label="刷新余额" onClick=${refreshBalance}><${Icon} name="refresh" size=${14} /></button>+ <a class="btn" href=${MF_TOPUP} target="_blank" rel="noopener noreferrer">充值 ↗</a>` },+ managed && acct && mf.connected && { tab: "modelflare", id: "low-balance", name: "余额提醒", sub: "余额低于这个数时在应用里提醒一次,充值后重新计", keys: "提醒 余额不足 low balance",+ ctl: html`<${Seg} label="余额提醒" value=${acct.alerts.lowBalanceUsd} onChange=${(v) => putAlerts({ lowBalanceUsd: v })}+ options=${ALERT_LINES.some(([v]) => v === acct.alerts.lowBalanceUsd) ? ALERT_LINES : [...ALERT_LINES, [acct.alerts.lowBalanceUsd, usd(acct.alerts.lowBalanceUsd)]]} />` },+ managed && acct && mf.connected && acct.alerts.lowBalanceUsd > 0 && { tab: "modelflare", id: "low-balance-push", name: "提醒也发到微信 / 飞书", sub: "由机器人发给你:微信发给扫码登录的人(需要他最近发过消息),飞书发到最近的单聊", keys: "推送 提醒 微信 飞书",+ ctl: html`<${Switch} label="提醒也发到微信 / 飞书" value=${acct.alerts.push} onChange=${(v) => putAlerts({ lowBalancePush: v })} />` },+ signedIn && { tab: "modelflare", id: "usage", name: "用量", sub: "按天、按模型的花费", keys: "用量 花费 账单 usage",+ ctl: html`<button type="button" class="text" onClick=${() => setSheet("usage")}>查看</button>` },+ signedIn && { tab: "modelflare", id: "notifications", name: "通知", sub: unread ? `${unread} 条未读` : "Modelflare 发给你的通知与公告", keys: "通知 公告 消息 notification",+ ctl: html`<button type="button" class="text" onClick=${() => setSheet("notifications")}>查看</button>` },+ signedIn && invite && { tab: "modelflare", id: "invite", name: "邀请好友", sub: "好友通过你的链接注册并充值,你会获得返利", keys: "邀请 返利 推广 invite",+ ctl: html`<span class="val">${invite.code}</span><${CopyButton} text=${invite.url} label="复制邀请链接" />` },managed && { tab: "modelflare", id: "line", name: "线路", sub: "中国大陆访问更稳定可选优化线路;切换后新请求生效", keys: "大陆 国际 origin 网络",ctl: html`<${Seg} label="线路" value=${mf.line} onChange=${setLine} options=${LINE_OPTIONS} />` },{ tab: "modelflare", id: "default-model", name: "默认模型", sub: "机器人没有单独指定时使用", keys: "模型 model",@@ -164,8 +228,8 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onMonChange=${(m) => put({ defaultModel: m }, { defaultModel: m })} />` },{ tab: "modelflare", id: "models", name: "可用模型", sub: modelsError ? `获取失败:${modelsError}` : "这个 Key 所在分组开放的模型", keys: "列表 刷新",ctl: html`<span class="val num">${models ? `${models.length} 个` : "…"}</span><button type="button" class="text" onClick=${() => reloadModels().then(() => saved())}>刷新</button>` },- { tab: "modelflare", id: "billing", name: "用量与账单", sub: "用量、余额与价格以 Modelflare 主站为准", keys: "余额 价格 充值 usage",- ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">在 Modelflare 控制台查看 ↗</a>` },+ { tab: "modelflare", id: "console", name: "Modelflare 控制台", sub: "账单、发票与 API Key 管理", keys: "控制台 账单 console",+ ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">打开 ↗</a>` },{ tab: "computer", id: "cu-status", name: "电脑操作后端", sub: cu ? cu.reason : "读取中…", keys: "computer use cua 辅助功能 屏幕录制",ctl: html`<span class=${`dot ${cu ? (cu.available ? "ok" : "err") : ""}`}></span>` },@@ -174,6 +238,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onMctl: bots && bots[0] && html`<button type="button" class="text" onClick=${() => onOpenBotSettings(bots[0].id, "computer")}>打开机器人设置</button>` },{ tab: "privacy", id: "key-storage", name: "密钥存放", sub: "Modelflare 密钥只在本机内置网关的隔离配置里,不写日志、不进命令行参数", ctl: null, keys: "安全" },+ { tab: "privacy", id: "account-storage", name: "账户凭据", sub: "登录 Modelflare 的凭据只存在数据目录,桌面版用系统钥匙串加密;界面只拿到账户名称", ctl: null, keys: "安全 登录 钥匙串" },{ tab: "privacy", id: "token", name: "访问令牌", sub: s.listen.tokenRequired ? "需要令牌:界面监听在非本机地址,或桌面版每次启动随机生成" : "只监听本机,无需令牌", keys: "token 令牌",ctl: html`<span class=${`dot ${s.listen.tokenRequired ? "ok" : ""}`}></span>` },{ tab: "privacy", id: "sandbox", name: "机器人沙箱", sub: "来自机器人沙箱的请求会被本机界面拒绝,机器人无法自行批准操作或读取配置", ctl: null, keys: "安全 dsh" },@@ -194,7 +259,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onM{ tab: "about", id: "links", name: "Modelflare", sub: "官网与文档",ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">modelflare.dev ↗</a><a class="text" href=${MF_DOCS} target="_blank" rel="noopener noreferrer">文档 ↗</a>` },].filter(Boolean);- }, [s, mf, mode, models, modelsError, cu, status, bots]);+ }, [s, mf, mode, models, modelsError, cu, status, bots, acct, invite, unread]);const needle = q.trim().toLowerCase();const shown = needle ? rows.filter((r) => `${r.name} ${r.sub || ""} ${r.keys || ""}`.toLowerCase().includes(needle)) : rows.filter((r) => r.tab === tab);@@ -213,5 +278,8 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onM<${KeyForm} line=${mf.line} showLine=${false} submitLabel="验证并保存" onConnected=${() => { setRekey(false); saved(); onMfChanged(); reloadModels(); }} /><//>`}${notices && html`<${NoticesSheet} onClose=${() => setNotices(false)} />`}+ ${sheet === "login" && html`<${LoginSheet} onClose=${() => setSheet("")} onSignedIn=${(r) => { onAccount(r); onMfChanged(); reloadModels(); }} />`}+ ${sheet === "usage" && html`<${UsageSheet} onClose=${() => setSheet("")} />`}+ ${sheet === "notifications" && html`<${NotificationsSheet} onClose=${() => { setSheet(""); setUnread(null); }} />`}</section>`;}diff --git a/ui/screens/sidebar.js b/ui/screens/sidebar.jsindex 9925556..dfbd975 100644--- a/ui/screens/sidebar.js+++ b/ui/screens/sidebar.js@@ -6,18 +6,28 @@ import { BotAvatar } from "../components/avatar.js";import { api } from "../lib/api.js";import { confirmSheet, failed, toast } from "../lib/store.js";import { fmtAgo } from "../lib/format.js";+import { MF_TOPUP, usd } from "../lib/links.js";-/** 左下角账户:头像字母 + 用户名 + 齿轮,点开设置 */-export function AccountButton({ username, on, onClick }) {- const me = (username || "本机用户").trim();+/** 左下角账户:头像字母 + 名称(登录后是 Modelflare 账户名)与余额 + 齿轮,点开设置 */+export function AccountButton({ username, account, on, onClick }) {+ const me = ((account && account.state === "signed_in" && account.name) || username || "本机用户").trim();+ const bal = account && account.balanceUsd !== null && account.balanceUsd !== undefined ? usd(account.balanceUsd) : "";return html`<button type="button" class=${`account${on ? " on" : ""}`} title="设置(⌘,)" aria-label="打开设置" onClick=${onClick}><span class="me" aria-hidden="true">${me.slice(0, 1).toUpperCase()}</span>- <span class="who">${me}</span>+ <span class="who">${me}${bal && html`<span class=${`bal num${account.lowBalance ? " low" : ""}`}>余额 ${bal}</span>`}</span><${Icon} name="gear" size=${15} /></button>`;}-export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previews, pending, working, username, onNew, onSelect, onDeleted, onOpenSettings }) {+/** 余额低于提醒线时,侧栏底部常驻一条提示 */+function LowBalance({ account }) {+ if (!account || !account.lowBalance) return null;+ return html`<a class="low-balance" href=${MF_TOPUP} target="_blank" rel="noopener noreferrer" role="status">+ 余额只剩 ${usd(account.balanceUsd)},去充值 ↗+ </a>`;+}++export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previews, pending, working, username, account, onNew, onSelect, onDeleted, onOpenSettings }) {const [q, setQ] = useState("");const [ctx, setCtx] = useState(null); // { bot, x, y }const [renaming, setRenaming] = useState("");@@ -89,7 +99,8 @@ export function Sidebar({ bots, botsError, reloadBots, selectedId, view, preview</button>`;})}</nav>- <div class="side-foot"><${AccountButton} username=${username} onClick=${onOpenSettings} /></div>+ <${LowBalance} account=${account} />+ <div class="side-foot"><${AccountButton} username=${username} account=${account} onClick=${onOpenSettings} /></div>${ctx && html`<${Menu} anchor=${{ left: ctx.x, right: ctx.x, top: ctx.y, bottom: ctx.y, width: 0 }} width=${200} label=${`${ctx.bot.name} 的操作`} onClose=${() => setCtx(null)}items=${[{ label: "重命名", onSelect: () => { setRenameText(ctx.bot.name); setRenaming(ctx.bot.id); } },