Skip to content

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

feat: owner + allowlist admission and a durable outbox for WeChat / Feishu

Marlabf15a751a426
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index d456c91..92beff8 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -123,6 +123,38 @@ DSH 的传递依赖以未修改形式随附,各自许可证保存在包目录
(MIT,Copyright (c) 2026 DeepSeek Harness Team):它的注意力原则、按请求重算的 system-prompt 段与 prompt 测试。
文字和代码为本项目重写,未复制其代码。
+## dsh-superagent(持久化出站队列的设计 — MIT)
+
+来源:https://github.com/deepseek-ai/dsh-superagent-prototype (DeepSeek Harness Team 的研究原型)
+
+`src/core/outbox.ts`(持久化出站队列)的设计改编自它的 `src/app/outbox.ts` 与 `src/app/effects.ts`:
+消息先写回执再发送、同一 id 只发一次、同一会话按顺序发且前一条失败会挡住后面的、`Later`(暂时不能发,不计失败)、
+指数退避重试、关机时把没发完的留到下次启动。代码按本项目的 sqlite 存储与渠道重新编写,未直接复制。
+
+```
+MIT License
+
+Copyright (c) 2026 DeepSeek Harness Team
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
## DS Bot(长期记忆、上下文管家、机器人设置 — Apache-2.0)
来源:https://github.com/Fei2411/DS-Bot
diff --git a/src/agent/approvals.ts b/src/agent/approvals.ts
index 48d41c6..981a583 100644
--- a/src/agent/approvals.ts
+++ b/src/agent/approvals.ts
@@ -71,7 +71,8 @@ export class ApprovalCenter {
}
private newCode(): string {
- const pending = new Set(this.store.listApprovals({ status: "pending", limit: 500 }).map((r) => r.code));
+ // 也避开待处理的使用请求的配对码(主人回复「同意 1234」时不会认错)
+ const pending = new Set([...this.store.listApprovals({ status: "pending", limit: 500 }).map((r) => r.code), ...this.store.pendingAccessCodes()]);
for (let i = 0; i < 50; i++) {
const c = String(crypto.randomInt(0, 10000)).padStart(4, "0");
if (!pending.has(c)) return c;
diff --git a/src/app.ts b/src/app.ts
index b7d47b6..2cb2770 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -7,6 +7,8 @@ import { OpenAICompatClient, type ModelClient } from "./llm/client.js";
import { BotRuntime } from "./core/runtime.js";
import { KeyedQueue } from "./core/queue.js";
import { deferNotice, interruptedText, takeInterrupted, type Interrupted } from "./core/recovery.js";
+import { Outbox } from "./core/outbox.js";
+import { AccessControl } from "./core/access.js";
import type { ChannelStatus } from "./core/types.js";
import { MagpieSupervisor } from "./magpie/supervisor.js";
import { FeishuChannel } from "./channels/feishu/channel.js";
@@ -111,6 +113,10 @@ export class App {
readonly agent: AgentManager;
readonly queue = new KeyedQueue();
readonly channels = new Map<string, BotChannels>();
+ /** 持久化的出站队列:最终回复、文件、重要通知先落库再发,重启后接着发 */
+ readonly outbox: Outbox;
+ /** 谁能和机器人对话:主人 + 允许名单 + 使用请求 */
+ readonly access: AccessControl;
web: WebServer | undefined;
desktop: DesktopHooks | undefined;
/** Modelflare 账户(登录、余额、预算);start() 时创建,桌面外壳的钥匙串那时已就绪 */
@@ -142,6 +148,12 @@ export class App {
log: logFilePath(),
});
this.store = new Store(path.join(config.dataDir, "anymodel.db"));
+ this.outbox = new Outbox(this.store);
+ this.outbox.onGone = (row) => {
+ const bot = this.store.getBot(row.botId);
+ this.notice("warn", `机器人「${bot?.name ?? row.botId}」有一条${row.channel === "weixin" ? "微信" : "飞书"}消息没能发出去:${row.error}`);
+ };
+ this.access = new AccessControl(this.store, { notify: (to, text, id) => this.reach(to, text, id) });
if (config.magpie.mode === "managed") {
this.magpie = new MagpieSupervisor({ dataDir: config.dataDir, binPath: config.magpie.binPath || undefined });
}
@@ -207,9 +219,22 @@ export class App {
contextMessages: config.llm.contextMessages,
contextChars: config.llm.contextChars,
route: (botId, model) => this.routeModel(botId, model),
+ access: this.access,
});
}
+ /** 主动给某个渠道的某个人发通知(使用请求、批准结果):能发就进出站队列,返回是否已排队 */
+ private reach(to: { botId: string; channel: string; peerId: string }, text: string, id: string): boolean {
+ const ch = this.channels.get(to.botId);
+ try {
+ if (to.channel === "weixin") return !!ch?.weixin?.tell(to.peerId, text, id);
+ if (to.channel === "feishu") return !!ch?.feishu?.notify(to.peerId, text, id);
+ } catch (e) {
+ log.warn("notify failed", { bot: to.botId, channel: to.channel, message: (e as Error).message });
+ }
+ return false;
+ }
+
/**
* 启动后在后台拉起默认机器人的代理进程(AMB_AGENT_PREWARM=0 关闭)。第一次启动要加载上万个运行时文件,
* 杀毒软件逐个扫描时可能要几分钟;提前做,用户发第一条消息时多半已经就绪。
@@ -339,8 +364,9 @@ export class App {
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;
+ // 飞书:发给主人;还没设主人时发到最近的单聊
+ const chat = ch?.feishu ? (this.access.owner(bot.id, "feishu")?.peerId ?? this.store.listConversations(bot.id).find((c) => c.channel === "feishu" && c.kind === "dm")?.peerId) : undefined;
+ if (chat && ch?.feishu?.notify(chat, text)) return true;
} catch (e) {
log.warn("push to owner failed", { bot: bot.id, message: (e as Error).message.slice(0, 200) });
}
@@ -415,6 +441,8 @@ export class App {
this.seedDefaultBot();
// 上次退出或崩溃时没处理完的消息:渠道开始收新消息之前取走标记,渠道起来后告诉用户
const interrupted = takeInterrupted(this.store);
+ // 出站队列先开:渠道上线时登记发送函数,上次没发完的消息接着发
+ this.outbox.start();
for (const bot of this.store.listBots()) await this.startBot(bot.id);
if (interrupted.length) void this.tellInterrupted(interrupted);
if (!this.opts.noWeb) this.web = await startWebServer(this);
@@ -479,6 +507,8 @@ export class App {
if (this.picksTimer) clearInterval(this.picksTimer);
this.account?.cancelLogin();
await this.web?.close();
+ // 不再开始新的发送,等正在发的结束;没发完的留在库里,下次启动接着发
+ await this.outbox.stop();
for (const id of [...this.channels.keys()]) await this.stopBot(id);
await this.agent.stop();
await this.magpie?.stop();
@@ -588,7 +618,7 @@ export class App {
this.channels.set(botId, ch);
if (bot.feishuAppId && bot.feishuAppSecret && !ch.feishu) {
const transport = this.opts.feishuTransport?.(bot) ?? new LarkTransport(bot.feishuAppId, bot.feishuAppSecret);
- ch.feishu = new FeishuChannel(bot.id, transport, this.runtime, this.queue, this.config.feishu.throttleMs);
+ ch.feishu = new FeishuChannel(bot.id, transport, this.runtime, this.queue, this.config.feishu.throttleMs, this.outbox);
ch.feishuError = undefined;
ch.feishu.start().catch((e) => {
ch.feishuError = (e as Error).message;
@@ -601,6 +631,7 @@ export class App {
fetchImpl: this.opts.weixinFetch,
cdnBaseUrl: this.config.weixin.cdnBaseUrl,
pollTimeoutMs: this.opts.weixinPollTimeoutMs,
+ outbox: this.outbox,
});
ch.weixin.onExpired = () => this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在信息面板的「渠道」里重新扫码`);
ch.weixin.start();
@@ -636,7 +667,10 @@ export class App {
ch.weixinLogin = login;
void login.run().then(async (res) => {
if (!res) return;
+ // 换了一个微信扫码:原来的主人留在允许名单里(可在机器人设置里移除),不会被拦在外面
+ const prevOwner = this.store.getWeixinAccount(botId)?.ownerUserId;
this.store.saveWeixinAccount({ botId, botToken: res.botToken, ilinkBotId: res.ilinkBotId, baseUrl: res.baseUrl, ownerUserId: res.userId });
+ if (prevOwner && prevOwner !== res.userId) this.access.allow(botId, "weixin", prevOwner, "previous-owner");
const bot = this.store.getBot(botId);
if (bot && !bot.weixinEnabled) this.store.updateBot(botId, { weixinEnabled: true });
await ch.weixin?.stop();
diff --git a/src/channels/feishu/card.ts b/src/channels/feishu/card.ts
index f3a30c4..0c06d67 100644
--- a/src/channels/feishu/card.ts
+++ b/src/channels/feishu/card.ts
@@ -1,13 +1,106 @@
+import crypto from "node:crypto";
import type { OutboundOp, ReplySession } from "../../core/types.js";
import { splitText } from "../../core/types.js";
+import { Gone, ReplyIds, stableId, type Outbox } from "../../core/outbox.js";
+import type { OutboxBody, OutboxKind, OutboxRow } from "../../store/db.js";
import { CARD_ELEMENT_ID, actionCardSpec, type FeishuTransport } from "./transport.js";
import { logger } from "../../log.js";
const log = logger("feishu.card");
+/** 文件、审批卡片临时发不出去时先重试这么多次,再改发文本 */
+const FILE_RETRIES = 2;
+
+/** 网络断开、超时这类过一会儿可能就好的错误(飞书返回错误码、本地文件读不了不算) */
+function transient(e: unknown): boolean {
+ const x = e as { rejected?: boolean; syscall?: string };
+ if (x?.rejected) return false;
+ return !(x?.syscall && ["open", "read", "stat"].includes(x.syscall)) && !/too large/i.test(String((e as Error)?.message));
+}
+
+/**
+ * 把一条出站记录发到飞书。最终回复先写进流式卡片(只在第一次尝试;卡片已经是全文就只收尾),
+ * 卡片失败或重试时改发文本回复。每段带确定的 uuid,飞书 1 小时内对同一 uuid 只发一次。
+ */
+export async function deliverFeishu(transport: FeishuTransport, row: OutboxRow, progress: (n: number) => void, retry = true): Promise<void> {
+ const b = row.body;
+ // 分段回复:progress = 已发出的段数,崩溃重启后从下一段接着发;uuidBase 让卡片和降级文本的 uuid 不撞
+ const replyText = async (text: string, uuidBase = 0) => {
+ const chunks = splitText(text, 4000);
+ for (let i = row.progress; i < chunks.length; i++) {
+ await transport.replyText(row.replyTo, chunks[i], stableId(row.id, uuidBase + i));
+ progress(i + 1);
+ }
+ };
+ switch (row.kind) {
+ case "text": {
+ const text = b.text ?? "";
+ if (b.cardId && row.attempts === 0 && row.progress === 0) {
+ let shown = !!b.shown;
+ const seq = b.cardSeq ?? 1;
+ try {
+ if (!shown) {
+ await transport.updateCardText(b.cardId, CARD_ELEMENT_ID, text, seq);
+ shown = true;
+ }
+ await transport.finishCard(b.cardId, seq + 1, text.replace(/\s+/g, " ").slice(0, 60));
+ return;
+ } catch (e) {
+ log.warn("card finish failed, sending text", { message: (e as Error).message });
+ // 卡片上已经是全文:不重复发
+ if (shown) return;
+ }
+ }
+ return replyText(text);
+ }
+ case "notice": {
+ if (!transport.sendText) throw new Gone("飞书传输层不支持主动发消息");
+ await transport.sendText(row.peerId, b.text ?? "", stableId(row.id, 0));
+ return;
+ }
+ case "file": {
+ const name = b.name ?? "文件";
+ if (transport.replyFile && row.progress === 0) {
+ try {
+ await transport.replyFile(row.replyTo, b.path ?? "", stableId(row.id, 0));
+ return;
+ } catch (e) {
+ if (retry && transient(e) && row.attempts < FILE_RETRIES) throw e;
+ log.warn("feishu file upload failed", { name, message: (e as Error).message.slice(0, 200) });
+ }
+ progress(1);
+ }
+ await transport.replyText(row.replyTo, `⚠️ 文件「${name}」发送失败,可在工作区中查看。`, stableId(row.id, 1));
+ return;
+ }
+ case "card": {
+ if (b.card && transport.replyActionCard && row.progress === 0) {
+ try {
+ await transport.replyActionCard(row.replyTo, b.card, stableId(row.id, 0));
+ return;
+ } catch (e) {
+ if (retry && transient(e) && row.attempts < FILE_RETRIES) throw e;
+ log.warn("action card failed, sending text", { message: (e as Error).message });
+ }
+ }
+ return replyText(b.text ?? "", 1);
+ }
+ }
+}
+
+/** 回复会话把消息交给出站队列需要的东西:key 由入站消息推出(同一条入站的第 n 条回复 id 固定) */
+export interface FeishuOutbox {
+ outbox: Outbox;
+ botId: string;
+ chatId: string;
+ key: string;
+ ttlMs?: number;
+}
+
/**
* 飞书回复会话:CardKit 流式卡片(~400ms 节流,单卡 ≤10 次/秒),结束时关闭 streaming_mode。
* 卡片创建/发送失败或中途失败 → 降级为纯文本回复。
+ * 最终回复、文件、审批卡片先写进出站队列(持久化、按会话排队、失败重试);流式的中间内容不经过它。没给队列时(单元测试)直接发。
*/
export class FeishuReply implements ReplySession {
private cardId: string | undefined;
@@ -19,8 +112,14 @@ export class FeishuReply implements ReplySession {
private fallback = false;
private started = false;
private closed = false;
+ private ids = new ReplyIds();
- constructor(private transport: FeishuTransport, private replyTo: string, private throttleMs = 400) {}
+ constructor(
+ private transport: FeishuTransport,
+ private replyTo: string,
+ private throttleMs = 400,
+ private out?: FeishuOutbox,
+ ) {}
get usedCard(): boolean {
return !!this.cardId && !this.fallback;
@@ -39,29 +138,33 @@ export class FeishuReply implements ReplySession {
case "stream.finish":
return this.finish(op.text);
case "text":
- return this.sendText(op.text);
+ return this.post("text", { text: op.text }, this.ids.of("text", op.text));
case "file":
await this.inflight;
- if (this.transport.replyFile) {
- try {
- await this.transport.replyFile(this.replyTo, op.path);
- return;
- } catch (e) {
- log.warn("feishu file upload failed", { name: op.name, message: (e as Error).message.slice(0, 200) });
- }
- }
- return this.sendText(`⚠️ 文件「${op.name}」发送失败,可在工作区中查看。`);
- case "interactive":
- if (op.buttons?.length && this.transport.replyActionCard) {
- try {
- const title = op.kind === "approval" ? `需批准(${op.code ?? ""})` : "需要你的回答";
- await this.transport.replyActionCard(this.replyTo, actionCardSpec(title, op.prompt, op.buttons));
- return;
- } catch (e) {
- log.warn("action card failed, sending text", { message: (e as Error).message });
- }
- }
- return this.sendText(op.requestId ? op.prompt : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") : ""}`);
+ return this.post("file", { path: op.path, name: op.name }, this.ids.of("file", op.path));
+ case "interactive": {
+ const text = op.requestId ? op.prompt : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") : ""}`;
+ const title = op.kind === "approval" ? `需批准(${op.code ?? ""})` : "需要你的回答";
+ const card = op.buttons?.length ? actionCardSpec(title, op.prompt, op.buttons) : undefined;
+ // 审批/提问十分钟后过期,发不出去就不必再等
+ return this.post(card ? "card" : "text", { text, ...(card ? { card } : {}) }, this.ids.of("prompt", op.requestId ?? text), 10 * 60_000);
+ }
+ }
+ }
+
+ /** 交给出站队列(先落库再发,等第一次发送结束);没有队列就直接发 */
+ private async post(kind: OutboxKind, body: OutboxBody, role: string, ttlMs?: number): Promise<void> {
+ if (this.out) {
+ const { outbox, botId, chatId, key } = this.out;
+ await outbox.send({ id: `fs:${botId}:${key}:${role}`, botId, channel: "feishu", peerId: chatId, kind, body, replyTo: this.replyTo, ttlMs: ttlMs ?? this.out.ttlMs });
+ return;
+ }
+ const row = { id: crypto.randomUUID(), kind, body, replyTo: this.replyTo, progress: 0, attempts: 0 } as OutboxRow;
+ try {
+ await deliverFeishu(this.transport, row, () => {}, false);
+ } catch (e) {
+ if (!(e instanceof Gone)) throw e;
+ log.warn("feishu reply dropped", { reason: e.message });
}
}
@@ -96,6 +199,7 @@ export class FeishuReply implements ReplySession {
}
}
+ /** 最终回复:写进卡片并收尾(卡片不可用时发文本)——这一步经出站队列,崩溃重启后会补发 */
private async finish(text: string): Promise<void> {
this.closed = true;
if (this.timer) {
@@ -104,20 +208,10 @@ export class FeishuReply implements ReplySession {
}
await this.inflight;
if (!this.started) await this.start();
- if (this.fallback || !this.cardId) return this.sendText(text);
- try {
- if (text !== this.flushed) {
- await this.transport.updateCardText(this.cardId, CARD_ELEMENT_ID, text, ++this.seq);
- this.flushed = text;
- }
- await this.transport.finishCard(this.cardId, ++this.seq, text.replace(/\s+/g, " ").slice(0, 60));
- } catch (e) {
- log.warn("card finish failed, sending text", { message: (e as Error).message });
- if (this.flushed !== text) await this.sendText(text);
- }
- }
-
- private async sendText(text: string): Promise<void> {
- for (const chunk of splitText(text, 4000)) await this.transport.replyText(this.replyTo, chunk);
+ const role = this.ids.final();
+ if (this.fallback || !this.cardId) return this.post("text", { text }, role);
+ const cardSeq = this.seq + 1;
+ this.seq += 2;
+ return this.post("text", { text, cardId: this.cardId, cardSeq, shown: text === this.flushed }, role);
}
}
diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.ts
index 8b1e30e..292885b 100644
--- a/src/channels/feishu/channel.ts
+++ b/src/channels/feishu/channel.ts
@@ -2,7 +2,9 @@ import type { ChannelCapabilities, ChannelStatus, InboundEvent, Part } from "../
import { Dedup, KeyedQueue } from "../../core/queue.js";
import type { BotRuntime } from "../../core/runtime.js";
import type { FeishuMessageEvent, FeishuTransport } from "./transport.js";
-import { FeishuReply } from "./card.js";
+import { FeishuReply, deliverFeishu } from "./card.js";
+import { Outbox, stableId } from "../../core/outbox.js";
+import type { Store } from "../../store/db.js";
import { logger } from "../../log.js";
export const FEISHU_CAPS: ChannelCapabilities = {
@@ -54,6 +56,9 @@ export class FeishuChannel {
private log = logger("feishu");
/** 测试用:等待所有已入队任务 */
readonly pending = new Set<Promise<void>>();
+ /** 出站队列(App 共用一个;没给时用内存库自己建一个) */
+ readonly outbox: Outbox;
+ private unregister: (() => void) | undefined;
constructor(
private botId: string,
@@ -61,9 +66,20 @@ export class FeishuChannel {
private runtime: BotRuntime,
private queue: KeyedQueue,
private throttleMs = 400,
- ) {}
+ outbox?: Outbox,
+ store?: Store,
+ ) {
+ if (outbox) this.outbox = outbox;
+ else {
+ if (!store) throw new Error("FeishuChannel needs an outbox or a store");
+ this.outbox = new Outbox(store);
+ this.outbox.start();
+ }
+ }
async start(): Promise<void> {
+ // 上线:出站队列里这个机器人的飞书消息(含上次没发完的)由这里发
+ this.unregister ??= this.outbox.register(this.botId, "feishu", (row, progress) => deliverFeishu(this.transport, row, progress));
await this.transport.start(
(ev) => this.onMessage(ev),
(state, detail) => {
@@ -75,6 +91,8 @@ export class FeishuChannel {
}
async stop(): Promise<void> {
+ this.unregister?.();
+ this.unregister = undefined;
await this.transport.stop();
this.status = { state: "disabled", since: Date.now() };
}
@@ -98,13 +116,14 @@ export class FeishuChannel {
// 没处理掉但带 ack 的(前一条还在处理):先说一声,消息照常入队
const intercepted = this.runtime.interceptReply(inbound);
if (intercepted.ack) {
- const p = this.transport.replyText(ev.messageId, intercepted.ack).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));
+ const ack = new FeishuReply(this.transport, ev.messageId, this.throttleMs, { outbox: this.outbox, botId: this.botId, chatId: ev.chatId, key: `${ev.messageId}:ack`, ttlMs: 10 * 60_000 });
+ const p = ack.apply({ type: "text", text: intercepted.ack }).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));
this.pending.add(p);
void p.finally(() => this.pending.delete(p));
}
if (intercepted.handled) return;
const p = this.queue.run(`feishu:${this.botId}:${ev.chatId}`, async () => {
- const reply = new FeishuReply(this.transport, ev.messageId, this.throttleMs);
+ const reply = new FeishuReply(this.transport, ev.messageId, this.throttleMs, { outbox: this.outbox, botId: this.botId, chatId: ev.chatId, key: ev.messageId });
try {
await this.runtime.handle(inbound, reply);
} catch (e) {
@@ -118,12 +137,17 @@ export class FeishuChannel {
async idle(): Promise<void> {
while (this.pending.size) await Promise.all([...this.pending]);
+ await this.outbox.idle();
}
- /** 主动提醒:发到一个已有的单聊会话;传输层不支持时返回 false */
- async notify(chatId: string, text: string): Promise<boolean> {
+ /**
+ * 主动发一条通知到单聊会话(余额提醒、使用请求、批准结果):进出站队列,id 不给时同样的内容一分钟内只发一次。
+ * 传输层不支持主动发消息时返回 false。
+ */
+ notify(chatId: string, text: string, id?: string): boolean {
if (!this.transport.sendText) return false;
- await this.transport.sendText(chatId, text);
+ const key = id ?? `notice:${this.botId}:feishu:${stableId(`${chatId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`;
+ void this.outbox.send({ id: key, botId: this.botId, channel: "feishu", peerId: chatId, kind: "notice", body: { text } });
return true;
}
}
diff --git a/src/channels/feishu/transport.ts b/src/channels/feishu/transport.ts
index 417408b..34bfad0 100644
--- a/src/channels/feishu/transport.ts
+++ b/src/channels/feishu/transport.ts
@@ -41,17 +41,18 @@ export interface FeishuTransport {
onCardAction?: CardActionHandler,
): Promise<void>;
/** 发送带按钮的交互卡片(审批/提问);未实现时降级为文本 */
- replyActionCard?(replyToMessageId: string, card: Record<string, unknown>): Promise<void>;
+ replyActionCard?(replyToMessageId: string, card: Record<string, unknown>, uuid?: string): Promise<void>;
stop(): Promise<void>;
createStreamingCard(initial: string): Promise<string>;
sendCardReply(replyToMessageId: string, cardId: string): Promise<void>;
updateCardText(cardId: string, elementId: string, text: string, sequence: number): Promise<void>;
finishCard(cardId: string, sequence: number, summary: string): Promise<void>;
- replyText(replyToMessageId: string, text: string): Promise<void>;
+ /** uuid:出站队列给的确定 id,飞书 1 小时内对同一 uuid 只发一次(去重) */
+ replyText(replyToMessageId: string, text: string, uuid?: string): Promise<void>;
/** 上传本地文件并作为图片/文件消息回复(present 交付物) */
- replyFile?(replyToMessageId: string, filePath: string): Promise<void>;
- /** 主动发一条文本到会话(不是回复某条消息;用于余额提醒) */
- sendText?(chatId: string, text: string): Promise<void>;
+ replyFile?(replyToMessageId: string, filePath: string, uuid?: string): Promise<void>;
+ /** 主动发一条文本到会话(不是回复某条消息;用于余额提醒、使用请求通知) */
+ sendText?(chatId: string, text: string, uuid?: string): Promise<void>;
}
export const CARD_ELEMENT_ID = "md";
@@ -101,8 +102,9 @@ export function actionCardSpec(title: string, text: string, buttons: Array<{ lab
};
}
+/** 飞书返回了错误码:出站队列把它当作"平台拒绝"(试几次就放弃),网络错误则一直重试到过期 */
function check(res: { code?: number; msg?: string } | undefined, what: string): void {
- if (res && typeof res.code === "number" && res.code !== 0) throw new Error(`${what} failed: code=${res.code} msg=${res.msg}`);
+ if (res && typeof res.code === "number" && res.code !== 0) throw Object.assign(new Error(`${what} failed: code=${res.code} msg=${res.msg}`), { rejected: true, code: res.code });
}
export class LarkTransport implements FeishuTransport {
@@ -221,15 +223,15 @@ export class LarkTransport implements FeishuTransport {
check(res, "cardkit.card.settings");
}
- async replyActionCard(replyToMessageId: string, card: Record<string, unknown>): Promise<void> {
+ async replyActionCard(replyToMessageId: string, card: Record<string, unknown>, uuid?: string): Promise<void> {
const res: any = await this.client.im.v1.message.reply({
path: { message_id: replyToMessageId },
- data: { msg_type: "interactive", content: JSON.stringify(card) },
+ data: { msg_type: "interactive", content: JSON.stringify(card), ...(uuid ? { uuid } : {}) },
});
check(res, "im.message.reply(action card)");
}
- async replyFile(replyToMessageId: string, filePath: string): Promise<void> {
+ async replyFile(replyToMessageId: string, filePath: string, uuid?: string): Promise<void> {
const buf = await fsp.readFile(filePath);
const name = path.basename(filePath);
const ext = path.extname(name).toLowerCase().slice(1);
@@ -250,22 +252,22 @@ export class LarkTransport implements FeishuTransport {
msgType = "file";
content = JSON.stringify({ file_key: key });
}
- const res: any = await this.client.im.v1.message.reply({ path: { message_id: replyToMessageId }, data: { msg_type: msgType, content } });
+ const res: any = await this.client.im.v1.message.reply({ path: { message_id: replyToMessageId }, data: { msg_type: msgType, content, ...(uuid ? { uuid } : {}) } });
check(res, `im.message.reply(${msgType})`);
}
- async replyText(replyToMessageId: string, text: string): Promise<void> {
+ async replyText(replyToMessageId: string, text: string, uuid?: string): Promise<void> {
const res: any = await this.client.im.v1.message.reply({
path: { message_id: replyToMessageId },
- data: { msg_type: "text", content: JSON.stringify({ text }) },
+ data: { msg_type: "text", content: JSON.stringify({ text }), ...(uuid ? { uuid } : {}) },
});
check(res, "im.message.reply(text)");
}
- async sendText(chatId: string, text: string): Promise<void> {
+ async sendText(chatId: string, text: string, uuid?: 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 }) },
+ data: { receive_id: chatId, msg_type: "text", content: JSON.stringify({ text }), ...(uuid ? { uuid } : {}) },
});
check(res, "im.message.create(text)");
}
diff --git a/src/channels/weixin/api.ts b/src/channels/weixin/api.ts
index abad87d..5cc4649 100644
--- a/src/channels/weixin/api.ts
+++ b/src/channels/weixin/api.ts
@@ -212,6 +212,11 @@ export class WeixinApiError extends Error {
get sessionExpired(): boolean {
return this.ret === SESSION_EXPIRED_ERRCODE || this.errcode === SESSION_EXPIRED_ERRCODE;
}
+ /** 服务端明确拒绝(有错误码或 HTTP 4xx):出站队列试几次就放弃;网络错误、5xx 一直重试到过期 */
+ get rejected(): boolean {
+ if (this.sessionExpired) return false;
+ return (this.ret !== undefined && this.ret !== 0) || (this.errcode !== undefined && this.errcode !== 0) || /HTTP 4\d\d/.test(this.message);
+ }
}
export interface IlinkClientOptions {
@@ -307,15 +312,16 @@ export class IlinkClient {
return resp;
}
- async sendText(toUserId: string, text: string, contextToken: string): Promise<void> {
- await this.sendItem(toUserId, { type: MessageItemType.TEXT, text_item: { text } }, contextToken);
+ /** clientId:出站队列给的确定 id(同一条消息的同一段每次相同),不给就随机 */
+ async sendText(toUserId: string, text: string, contextToken: string, clientId?: string): Promise<void> {
+ await this.sendItem(toUserId, { type: MessageItemType.TEXT, text_item: { text } }, contextToken, clientId);
}
/**
* 发送本地文件:getuploadurl → AES-128-ECB 加密后 POST 到 CDN → sendmessage 媒体条目。
* 移植自 openclaw-weixin src/cdn/upload.ts、src/cdn/cdn-upload.ts、src/messaging/send.ts。
*/
- async sendMedia(toUserId: string, filePath: string, contextToken: string): Promise<void> {
+ async sendMedia(toUserId: string, filePath: string, contextToken: string, clientId?: string): Promise<void> {
const plain = await fs.readFile(filePath);
const kind = mediaKind(filePath);
const filekey = crypto.randomBytes(16).toString("hex");
@@ -367,7 +373,7 @@ export class IlinkClient {
: kind === "video"
? { type: MessageItemType.VIDEO, video_item: { media, video_size: filesize } }
: { type: MessageItemType.FILE, file_item: { media, file_name: path.basename(filePath), len: String(plain.length) } };
- await this.sendItem(toUserId, item, contextToken);
+ await this.sendItem(toUserId, item, contextToken, clientId);
}
private get cdnBase(): string {
@@ -437,7 +443,7 @@ export class IlinkClient {
return { kind, data };
}
- private async sendItem(toUserId: string, item: MessageItem, contextToken: string): Promise<void> {
+ private async sendItem(toUserId: string, item: MessageItem, contextToken: string, clientId?: string): Promise<void> {
const raw = await this.request(
"POST",
"ilink/bot/sendmessage",
@@ -445,7 +451,7 @@ export class IlinkClient {
msg: {
from_user_id: "",
to_user_id: toUserId,
- client_id: `amb:${Date.now()}-${crypto.randomBytes(4).toString("hex")}`,
+ client_id: clientId ? `amb:${clientId}` : `amb:${Date.now()}-${crypto.randomBytes(4).toString("hex")}`,
message_type: MessageType.BOT,
message_state: 2, // FINISH
context_token: contextToken || undefined,
diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.ts
index 1bf407d..41f1f31 100644
--- a/src/channels/weixin/channel.ts
+++ b/src/channels/weixin/channel.ts
@@ -1,8 +1,10 @@
+import crypto from "node:crypto";
import type { ChannelCapabilities, ChannelStatus, InboundEvent, OutboundOp, Part, ReplySession } from "../../core/types.js";
import { splitText } from "../../core/types.js";
import { Dedup, KeyedQueue } from "../../core/queue.js";
import type { BotRuntime } from "../../core/runtime.js";
-import type { Store } from "../../store/db.js";
+import type { OutboxBody, OutboxKind, OutboxRow, Store } from "../../store/db.js";
+import { Gone, Later, Outbox, ReplyIds, stableId } from "../../core/outbox.js";
import { IlinkClient, MessageItemType, MessageType, WeixinApiError, hasDownloadableMedia, type InboundMedia, type MessageItem, type WeixinMessage } from "./api.js";
import { StreamingMarkdownFilter } from "./markdown-filter.js";
import { WeixinQuota } from "./quota.js";
@@ -70,16 +72,90 @@ function mediaItems(items: MessageItem[] | undefined): MessageItem[] {
return (items ?? []).flatMap((it) => [it, ...(it.ref_msg?.message_item ? [it.ref_msg.message_item] : [])]).filter(hasDownloadableMedia);
}
+const deliverLog = logger("weixin.send");
+/** 回复太长、本轮配额不够时,最后一条末尾的说明 */
+const OVER_QUOTA_NOTE = "\n\n…(回复过长,已达到本轮可发送条数上限,请回复任意消息继续)";
+/** 文件临时发不出去(网络、CDN 5xx)时先重试这么多次,再改发一句"发送失败" */
+const MEDIA_RETRIES = 2;
+/** ack、审批提示:过一会儿就没意义了,发不出去不必一直等 */
+export const SHORT_TTL_MS = 10 * 60_000;
+
+/** 网络断开、超时、5xx 这类过一会儿可能就好的错误(本地文件读不了、平台拒绝、CDN 4xx 不算) */
+function transient(e: unknown): boolean {
+ const x = e as { rejected?: boolean; fatal?: boolean; syscall?: string };
+ if (x?.rejected || x?.fatal) return false;
+ return !(x?.syscall && ["open", "read", "stat", "scandir"].includes(x.syscall));
+}
+
+/** 能不能给这个人发:要有会话凭证、24 小时窗口没过、还有配额;不能就放弃(Gone),返回凭证 */
+function reachable(quota: WeixinQuota, userId: string): string {
+ const peer = quota.peer(userId);
+ if (!peer?.contextToken) throw new Gone("对方还没有给机器人发过消息,微信不允许主动发送");
+ if (!quota.open(userId)) throw new Gone("对方超过 24 小时没有发消息,微信不再允许回复");
+ if (quota.remaining(userId) <= 0) throw new Gone("本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条)");
+ return peer.contextToken;
+}
+
+/**
+ * 把一条出站记录发到微信:文本按 4000 字切分,配额不够时截断并在末尾说明;文件走 CDN,发不出去改发一句说明。
+ * 发送成功才扣配额(出站队列按会话一条一条发,先查后扣不会超发);每段带确定的 client_id。
+ */
+export async function deliverWeixin(client: IlinkClient, quota: WeixinQuota, row: OutboxRow, progress: (n: number) => void, retry = true): Promise<void> {
+ const user = row.peerId;
+ const token = reachable(quota, user);
+ if (row.kind === "file") {
+ const name = row.body.name ?? "文件";
+ if (row.progress === 0) {
+ try {
+ // 上传失败不占配额
+ await client.sendMedia(user, row.body.path ?? "", token, stableId(row.id, 0));
+ quota.tryConsume(user);
+ return;
+ } catch (e) {
+ if (retry && transient(e) && row.attempts < MEDIA_RETRIES) throw e;
+ deliverLog.warn("weixin media send failed", { name, message: (e as Error).message.slice(0, 200) });
+ }
+ progress(1);
+ }
+ await client.sendText(user, `⚠️ 文件「${name}」发送失败,可在工作区中查看。`, token, stableId(row.id, 1));
+ quota.tryConsume(user);
+ return;
+ }
+ const text = row.body.text ?? "";
+ const chunks = splitText(row.body.raw ? text.trim() : filterMarkdown(text), WEIXIN_CAPS.maxTextLength);
+ let rest = chunks.slice(row.progress);
+ const budget = quota.remaining(user);
+ if (rest.length > budget) {
+ rest = rest.slice(0, budget);
+ rest[budget - 1] = rest[budget - 1].slice(0, WEIXIN_CAPS.maxTextLength - OVER_QUOTA_NOTE.length) + OVER_QUOTA_NOTE;
+ }
+ for (let i = 0; i < rest.length; i++) {
+ const n = row.progress + i;
+ await client.sendText(user, rest[i], token, stableId(row.id, n));
+ quota.tryConsume(user);
+ progress(n + 1);
+ }
+}
+
+/** 回复会话把消息交给出站队列需要的东西:key 由入站消息推出(同一条入站的第 n 条回复 id 固定) */
+export interface WeixinOutbox {
+ outbox: Outbox;
+ botId: string;
+ key: string;
+ ttlMs?: number;
+}
+
/**
* 微信回复会话:不流式;生成期间只显示“正在输入”(每 5 秒续期),结束时一次性发送最终回复(>4000 字切分),遵守配额。
* 不发送工具调用进度;只有最终回复、审批/提问提示和交付文件会成为聊天消息,配额全部留给它们。
+ * 这些消息先写进出站队列(持久化、按会话排队、失败重试),没给队列时(单元测试)直接发。
*/
export class WeixinReply implements ReplySession {
private ticket: string | undefined;
private typingTimer: NodeJS.Timeout | undefined;
private typingOn = false;
private chain: Promise<void> = Promise.resolve();
- readonly sent: string[] = [];
+ private ids = new ReplyIds();
private log = logger("weixin.reply");
constructor(
@@ -87,6 +163,7 @@ export class WeixinReply implements ReplySession {
private userId: string,
private contextToken: string,
private quota: WeixinQuota,
+ private out?: WeixinOutbox,
) {}
private enqueue(fn: () => Promise<void>): Promise<void> {
@@ -103,41 +180,46 @@ export class WeixinReply implements ReplySession {
case "stream.start":
case "stream.update":
return;
- case "stream.finish":
+ case "stream.finish": {
+ const role = this.ids.final();
+ return this.enqueue(() => this.post("text", { text: op.text }, role));
+ }
case "text":
- return this.enqueue(() => this.send(op.text));
+ return this.enqueue(() => this.post("text", { text: op.text }, this.ids.of("text", op.text)));
case "file":
- return this.enqueue(async () => {
- if (this.quota.remaining(this.userId) <= 0) {
- this.log.warn("weixin quota exhausted, file dropped", { userId: this.userId });
- return;
- }
- try {
- // 上传失败不占配额;发送串行,先查后扣不会超发
- await this.client.sendMedia(this.userId, op.path, this.contextToken);
- this.quota.tryConsume(this.userId);
- this.sent.push(`[文件] ${op.name}`);
- } catch (e) {
- this.log.warn("weixin media send failed", { name: op.name, message: (e as Error).message.slice(0, 200) });
- if (this.quota.tryConsume(this.userId)) {
- const t = `⚠️ 文件「${op.name}」发送失败,可在工作区中查看。`;
- await this.client.sendText(this.userId, t, this.contextToken);
- this.sent.push(t);
- }
- }
- });
+ return this.enqueue(() => this.post("file", { path: op.path, name: op.name }, this.ids.of("file", op.path)));
case "interactive": {
const text = op.requestId
? op.prompt // 代理请求:提示里已含编号/回复方式
: `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") + "\n(回复编号选择)" : ""}`;
return this.enqueue(async () => {
- await this.send(text, { raw: !!op.requestId });
+ await this.post("text", { text, raw: !!op.requestId }, this.ids.of("prompt", op.requestId ?? text), SHORT_TTL_MS);
if (this.typingOn) await this.typing(true);
});
}
}
}
+ /** 交给出站队列(先落库再发,等第一次发送结束);没有队列就直接发 */
+ private async post(kind: OutboxKind, body: OutboxBody, role: string, ttlMs?: number): Promise<void> {
+ if (kind === "text" && this.typingTimer) {
+ clearInterval(this.typingTimer);
+ this.typingTimer = undefined;
+ }
+ if (this.out) {
+ const { outbox, botId, key } = this.out;
+ await outbox.send({ id: `wx:${botId}:${key}:${role}`, botId, channel: "weixin", peerId: this.userId, kind, body, ttlMs: ttlMs ?? this.out.ttlMs });
+ return;
+ }
+ const row = { id: crypto.randomUUID(), peerId: this.userId, kind, body, progress: 0, attempts: 0 } as OutboxRow;
+ try {
+ await deliverWeixin(this.client, this.quota, row, () => {}, false);
+ } catch (e) {
+ if (!(e instanceof Gone)) throw e;
+ this.log.warn("weixin reply dropped", { userId: this.userId, reason: e.message });
+ }
+ }
+
private async typing(on: boolean): Promise<void> {
try {
if (on) {
@@ -157,31 +239,6 @@ export class WeixinReply implements ReplySession {
this.log.debug("typing failed", { message: (e as Error).message });
}
}
-
- private async send(text: string, o: { raw?: boolean; maxChunks?: number } = {}): Promise<void> {
- if (this.typingTimer) {
- clearInterval(this.typingTimer);
- this.typingTimer = undefined;
- }
- let chunks = splitText(o.raw ? text.trim() : filterMarkdown(text), WEIXIN_CAPS.maxTextLength);
- if (o.maxChunks) chunks = chunks.slice(0, o.maxChunks);
- const budget = this.quota.remaining(this.userId);
- if (budget <= 0) {
- this.log.warn("weixin quota exhausted, reply dropped", { userId: this.userId });
- return;
- }
- let toSend = chunks;
- if (chunks.length > budget) {
- toSend = chunks.slice(0, budget);
- const note = "\n\n…(回复过长,已达到本轮可发送条数上限,请回复任意消息继续)";
- toSend[budget - 1] = toSend[budget - 1].slice(0, WEIXIN_CAPS.maxTextLength - note.length) + note;
- }
- for (const c of toSend) {
- if (!this.quota.tryConsume(this.userId)) break;
- await this.client.sendText(this.userId, c, this.contextToken);
- this.sent.push(c);
- }
- }
}
/** 微信 iLink 渠道:getupdates 长轮询 → 每用户串行队列 → 运行时。 */
@@ -195,6 +252,9 @@ export class WeixinChannel {
private log = logger("weixin");
readonly quota: WeixinQuota;
readonly pending = new Set<Promise<void>>();
+ /** 出站队列(App 共用一个;单独构造时自己建一个) */
+ readonly outbox: Outbox;
+ private unregister: (() => void) | undefined;
/** -14 会话过期时的通知回调(UI/日志) */
onExpired: ((botId: string) => void) | undefined;
@@ -203,9 +263,14 @@ export class WeixinChannel {
private store: Store,
private runtime: BotRuntime,
private queue: KeyedQueue,
- private opts: { fetchImpl?: typeof fetch; cdnBaseUrl?: string; pollTimeoutMs?: number; retryDelayMs?: number; backoffMs?: number } = {},
+ private opts: { fetchImpl?: typeof fetch; cdnBaseUrl?: string; pollTimeoutMs?: number; retryDelayMs?: number; backoffMs?: number; outbox?: Outbox } = {},
) {
this.quota = new WeixinQuota(store, botId);
+ if (opts.outbox) this.outbox = opts.outbox;
+ else {
+ this.outbox = new Outbox(store);
+ this.outbox.start();
+ }
}
get running(): boolean {
@@ -222,25 +287,44 @@ export class WeixinChannel {
this.client = new IlinkClient({ baseUrl: acct.baseUrl, token: acct.botToken, fetchImpl: this.opts.fetchImpl, cdnBaseUrl: this.opts.cdnBaseUrl });
this.abort = new AbortController();
this.loop = this.run(this.abort.signal).finally(() => (this.loop = undefined));
+ // 上线:出站队列里这个机器人的微信消息(含上次没发完的)由这里发
+ this.unregister = this.outbox.register(this.botId, "weixin", (row, progress) => this.deliver(row, progress));
+ }
+
+ private async deliver(row: OutboxRow, progress: (n: number) => void): Promise<void> {
+ if (!this.client) throw new Later("微信渠道没有运行");
+ if ((this.store.getWeixinAccount(this.botId)?.pausedUntil ?? 0) > Date.now()) throw new Later("微信登录已过期,等重新扫码");
+ try {
+ await deliverWeixin(this.client, this.quota, row, progress);
+ } catch (e) {
+ if (e instanceof WeixinApiError && e.sessionExpired) throw new Later("微信登录已过期,等重新扫码");
+ throw e;
+ }
}
/**
- * 主动提醒:发给扫码登录的那个微信用户。需要他最近发过消息(有 context_token),
- * 并占用同一份回复配额;没有可用配额时放弃,返回 false。
+ * 主动给某人发一条通知(使用请求、批准结果、余额提醒):要他最近 24 小时内发过消息、还有配额,否则返回 false。
+ * 进出站队列(同一 id 只发一次),占用他的回复配额。
*/
- async notifyOwner(text: string): Promise<boolean> {
- return this.notify(this.store.getWeixinAccount(this.botId)?.ownerUserId ?? "", text);
+ tell(userId: string, text: string, id: string): boolean {
+ if (!this.client || !this.quota.open(userId) || this.quota.remaining(userId) <= 0) return false;
+ void this.outbox.send({ id, botId: this.botId, channel: "weixin", peerId: userId, kind: "notice", body: { text, raw: true } });
+ return true;
}
- /** 主动发给某个微信用户(如重启后的提醒):同样要有他最近的 context_token、占用同一份回复配额;发不出去返回 false */
+ /** 主动发给某个微信用户(余额提醒、重启后的提醒):同 tell;同样的内容一分钟内只发一次 */
async notify(userId: string, text: string): Promise<boolean> {
- const peer = userId ? this.store.getWeixinPeer(this.botId, userId) : undefined;
- if (!this.client || !peer?.contextToken || !this.quota.tryConsume(userId)) return false;
- await this.client.sendText(userId, text, peer.contextToken);
- return true;
+ return !!userId && this.tell(userId, text, `notice:${this.botId}:weixin:${stableId(`${userId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`);
+ }
+
+ /** 主动提醒:发给扫码登录的那个微信用户 */
+ async notifyOwner(text: string): Promise<boolean> {
+ return this.notify(this.store.getWeixinAccount(this.botId)?.ownerUserId ?? "", text);
}
async stop(): Promise<void> {
+ this.unregister?.();
+ this.unregister = undefined;
this.abort?.abort();
await this.loop?.catch(() => {});
this.loop = undefined;
@@ -315,7 +399,7 @@ export class WeixinChannel {
// 没处理掉但带 ack 的(前一条还在处理):先说一声,消息照常入队
const intercepted = this.runtime.interceptReply(ev);
if (intercepted.ack) {
- const ack = new WeixinReply(this.client!, userId, peer.contextToken, this.quota);
+ const ack = new WeixinReply(this.client!, userId, peer.contextToken, this.quota, { outbox: this.outbox, botId: this.botId, key: `${id}:ack`, ttlMs: SHORT_TTL_MS });
const p = ack.apply({ type: "text", text: intercepted.ack }).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));
this.pending.add(p);
void p.finally(() => this.pending.delete(p));
@@ -323,7 +407,7 @@ export class WeixinChannel {
if (intercepted.handled) return;
const media = mediaItems(m.item_list);
const p = this.queue.run(`weixin:${this.botId}:${userId}`, async () => {
- const reply = new WeixinReply(this.client!, userId, this.store.getWeixinPeer(this.botId, userId)?.contextToken ?? peer.contextToken, this.quota);
+ const reply = new WeixinReply(this.client!, userId, this.store.getWeixinPeer(this.botId, userId)?.contextToken ?? peer.contextToken, this.quota, { outbox: this.outbox, botId: this.botId, key: id });
try {
if (media.length) ev.parts = weixinParts(m.item_list, await this.download(media));
await this.runtime.handle(ev, reply);
@@ -352,5 +436,6 @@ export class WeixinChannel {
async idle(): Promise<void> {
while (this.pending.size) await Promise.all([...this.pending]);
+ await this.outbox.idle();
}
}
diff --git a/src/channels/weixin/quota.ts b/src/channels/weixin/quota.ts
index d290534..f1c0938 100644
--- a/src/channels/weixin/quota.ts
+++ b/src/channels/weixin/quota.ts
@@ -22,6 +22,16 @@ export class WeixinQuota {
return peer;
}
+ peer(userId: string): WeixinPeer | undefined {
+ return this.store.getWeixinPeer(this.botId, userId);
+ }
+
+ /** 会话凭证还在 24 小时窗口内(对方最近发过消息) */
+ open(userId: string): boolean {
+ const p = this.peer(userId);
+ return !!p?.contextToken && this.now() - p.windowStartedAt <= QUOTA_WINDOW_MS;
+ }
+
remaining(userId: string): number {
const p = this.store.getWeixinPeer(this.botId, userId);
if (!p) return 0;
diff --git a/src/core/access.ts b/src/core/access.ts
new file mode 100644
index 0000000..86ce673
--- /dev/null
+++ b/src/core/access.ts
@@ -0,0 +1,256 @@
+/**
+ * 谁能和机器人对话:默认只有主人。代理跑在用户自己的电脑上(甚至可能是完全权限),陌生人找到机器人也不能驱动它。
+ *
+ * - 主人:微信 = 扫码登录的那个微信;飞书(以及没拿到扫码者的微信)= 在应用里设的主人
+ * (第一个给机器人发消息的人会出现在信息面板的「使用请求」里,点「设为主人」)。
+ * - 其他人发消息:登记成使用请求,只回一句"还没被允许"(同一个人每小时最多一次),不进队列、不碰模型、不花钱;
+ * 请求出现在信息面板里,也会带配对码发给主人(每个机器人每小时最多 3 条),主人回复「同意 1234」即可。
+ * - 允许的人进允许名单,在机器人设置里能看到、能移除;被拒绝的人不再回复。
+ * - 本机网页控制台本来就可信;群聊目前没有渠道接入(飞书只收单聊,微信 iLink 没有群),保持原样不拦,接入群聊时再定规则。
+ */
+import crypto from "node:crypto";
+import type { InboundEvent } from "./types.js";
+import { eventText } from "./types.js";
+import type { AccessEntry, Store } from "../store/db.js";
+import { logger } from "../log.js";
+
+const log = logger("access");
+
+/** 陌生人收到的那一句 */
+export const REFUSAL_TEXT = "你还没有被允许使用这个机器人,已通知主人。主人同意后就可以直接对话了。";
+/** 同一个陌生人多久最多回一次 */
+export const REFUSE_EVERY_MS = 3600_000;
+/** 每个机器人每小时最多给主人发几条使用请求通知(其余只在应用里显示) */
+export const NOTICE_LIMIT = 3;
+const NOTICE_WINDOW_MS = 3600_000;
+export const APPROVED_TEXT = "主人已经同意了,现在可以直接和我对话。";
+
+export type AccessChannel = "weixin" | "feishu";
+export const ACCESS_CHANNELS: AccessChannel[] = ["weixin", "feishu"];
+const CHANNEL_LABEL: Record<string, string> = { weixin: "微信", feishu: "飞书", web: "网页" };
+
+/** 主动发一条通知(App 经渠道和出站队列发);发不出去(对方 24 小时内没说过话、渠道没开)返回 false */
+export type Notify = (to: { botId: string; channel: string; peerId: string }, text: string, id: string) => boolean;
+
+export interface Owner {
+ peerId: string;
+ /** login = 扫码登录的微信;app = 在应用里设的 */
+ via: "login" | "app";
+ entryId?: string;
+}
+
+/** 平台 id 太长:只留末尾几位,主人对得上就行 */
+export function shortPeer(id: string): string {
+ const s = id.replace(/@im\.wechat$/, "");
+ return s.length > 10 ? `…${s.slice(-6)}` : s;
+}
+
+export function whoText(e: Pick<AccessEntry, "channel" | "peerId" | "senderId" | "name">): string {
+ return `${CHANNEL_LABEL[e.channel] ?? e.channel}用户 ${e.name && e.name !== e.peerId ? e.name : shortPeer(e.senderId || e.peerId)}`;
+}
+
+const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+
+export class AccessControl {
+ constructor(
+ private store: Store,
+ private opts: { notify?: Notify; now?: () => number } = {},
+ ) {}
+
+ private now(): number {
+ return (this.opts.now ?? Date.now)();
+ }
+
+ /** 某个渠道的主人:微信优先用扫码登录的人,其余是在应用里设的 */
+ owner(botId: string, channel: string): Owner | undefined {
+ if (channel === "weixin") {
+ const o = this.store.getWeixinAccount(botId)?.ownerUserId;
+ if (o) return { peerId: o, via: "login" };
+ }
+ const e = this.store.listAccess({ botId, channel, status: "owner" })[0];
+ return e ? { peerId: e.peerId, via: "app", entryId: e.id } : undefined;
+ }
+
+ private isOwner(ev: InboundEvent): boolean {
+ if (ev.channel === "web") return true;
+ return this.owner(ev.botId, ev.channel)?.peerId === ev.conversation.id;
+ }
+
+ /** 只判断,不登记(runtime.handle 里的兜底检查) */
+ allowed(ev: InboundEvent): boolean {
+ // 本机界面本来就可信
+ if (ev.channel === "web") return true;
+ // 群聊:目前没有渠道接入群聊,保持原样;接入时要在这里加规则(例如只响应主人 @ 机器人)
+ if (ev.conversation.kind === "group") return true;
+ if (this.isOwner(ev)) return true;
+ const s = this.store.getAccess(ev.botId, ev.channel, ev.conversation.id)?.status;
+ return s === "allowed" || s === "owner";
+ }
+
+ /**
+ * 渠道入口(interceptReply 最前面):允许的直接放行;其他人登记成使用请求并通知主人(限频),
+ * 返回给他的一句话(同一个人每小时最多一次;被拒绝的人不回)。
+ */
+ admit(ev: InboundEvent): { ok: true } | { ok: false; reply?: string } {
+ if (this.allowed(ev)) return { ok: true };
+ const now = this.now();
+ let e = this.store.getAccess(ev.botId, ev.channel, ev.conversation.id);
+ if (e?.status === "denied") return { ok: false };
+ if (!e) {
+ e = this.store.putAccess({
+ id: crypto.randomUUID(),
+ botId: ev.botId,
+ channel: ev.channel,
+ peerId: ev.conversation.id,
+ senderId: ev.sender.id,
+ name: ev.sender.name ?? "",
+ status: "pending",
+ source: "request",
+ code: this.newCode(),
+ text: clip(eventText(ev).replace(/\s+/g, " "), 200),
+ requests: 1,
+ createdAt: now,
+ updatedAt: now,
+ decidedAt: 0,
+ decidedBy: "",
+ repliedAt: 0,
+ notifiedAt: 0,
+ });
+ log.info(`access request ${e.code}`, { bot: e.botId, channel: e.channel, peer: shortPeer(e.peerId) });
+ this.notifyOwners(e);
+ } else {
+ this.store.updateAccess(e.id, { requests: e.requests + 1, updatedAt: now });
+ }
+ if (e.repliedAt && now - e.repliedAt < REFUSE_EVERY_MS) return { ok: false };
+ this.store.updateAccess(e.id, { repliedAt: now });
+ return { ok: false, reply: REFUSAL_TEXT };
+ }
+
+ /** 把新请求带配对码发给各渠道的主人(每个机器人每小时最多 NOTICE_LIMIT 条;超出的只在应用里显示) */
+ private notifyOwners(e: AccessEntry): void {
+ const now = this.now();
+ if (this.store.accessNotifiedSince(e.botId, now - NOTICE_WINDOW_MS) >= NOTICE_LIMIT) {
+ log.info("access notice rate-limited", { bot: e.botId, code: e.code });
+ return;
+ }
+ const bot = this.store.getBot(e.botId);
+ const said = e.text ? `:「${clip(e.text, 60)}」` : "";
+ const text = `有人想使用机器人「${bot?.name ?? e.botId}」——${whoText(e)}${said}\n回复「同意 ${e.code}」允许,「拒绝 ${e.code}」拒绝;也可以在 AnyModelBot 的信息面板里处理。`;
+ let sent = false;
+ for (const ch of ACCESS_CHANNELS) {
+ const o = this.owner(e.botId, ch);
+ if (o && this.opts.notify?.({ botId: e.botId, channel: ch, peerId: o.peerId }, text, `access:${e.id}:${ch}`)) sent = true;
+ }
+ if (sent) this.store.updateAccess(e.id, { notifiedAt: now });
+ }
+
+ /** 4 位配对码,不和待处理的请求、待批准的工具审批撞 */
+ private newCode(): string {
+ const used = new Set([...this.store.pendingAccessCodes(), ...this.store.listApprovals({ status: "pending", limit: 500 }).map((r) => r.code)]);
+ for (let i = 0; i < 50; i++) {
+ const c = String(crypto.randomInt(0, 10000)).padStart(4, "0");
+ if (!used.has(c)) return c;
+ }
+ return String(crypto.randomInt(1000, 10000));
+ }
+
+ /**
+ * 主人在聊天里处理请求:「同意 1234」/「拒绝 1234」(也接受 允许/批准/y/n 等)。
+ * 只认主人(各渠道的主人和本机网页),只认这个机器人待处理请求的配对码;其余交给工具审批处理。
+ */
+ handleReply(ev: InboundEvent): { handled: boolean; ack?: string } {
+ const m = /^(同意|允许|批准|通过|y|yes|ok|拒绝|不同意|n|no)\s*[#::]?\s*(\d{4})$/i.exec(eventText(ev).trim());
+ if (!m || !this.isOwner(ev)) return { handled: false };
+ const e = this.store.pendingAccessByCode(ev.botId, m[2]);
+ if (!e) return { handled: false };
+ const allow = !/^(拒绝|不同意|n|no)$/i.test(m[1]);
+ this.decide(e.id, allow, `${ev.channel}:${ev.sender.id}`);
+ return { handled: true, ack: allow ? `✅ 已允许「${whoText(e)}」使用这个机器人` : `❌ 已拒绝「${whoText(e)}」` };
+ }
+
+ /** 允许或拒绝一个请求(被拒绝的也可以改成允许);允许时告诉对方一声 */
+ decide(id: string, allow: boolean, by: string): AccessEntry | undefined {
+ const e = this.store.getAccessById(id);
+ if (!e || (e.status !== "pending" && !(allow && e.status === "denied"))) return undefined;
+ const now = this.now();
+ this.store.updateAccess(id, { status: allow ? "allowed" : "denied", code: "", decidedAt: now, decidedBy: by, updatedAt: now });
+ log.info(`access ${allow ? "allowed" : "denied"}`, { bot: e.botId, channel: e.channel, peer: shortPeer(e.peerId), by });
+ if (allow) this.opts.notify?.({ botId: e.botId, channel: e.channel, peerId: e.peerId }, APPROVED_TEXT, `access:${id}:approved:${now}`);
+ return this.store.getAccessById(id);
+ }
+
+ /**
+ * 设为这个渠道的主人(飞书;或没拿到扫码者的微信)。原来的主人改为普通允许。
+ * 扫码登录的微信已经是主人时不能改(重新扫码就换了)。
+ */
+ setOwner(id: string, by: string): AccessEntry {
+ const e = this.store.getAccessById(id);
+ if (!e) throw new Error("记录不存在");
+ if (e.channel === "weixin" && this.store.getWeixinAccount(e.botId)?.ownerUserId) throw new Error("微信的主人是扫码登录的人;要换主人,请用那个微信重新扫码");
+ const now = this.now();
+ for (const o of this.store.listAccess({ botId: e.botId, channel: e.channel, status: "owner" })) {
+ if (o.id !== id) this.store.updateAccess(o.id, { status: "allowed", updatedAt: now });
+ }
+ const was = e.status;
+ this.store.updateAccess(id, { status: "owner", code: "", decidedAt: now, decidedBy: by, updatedAt: now });
+ log.info("access owner set", { bot: e.botId, channel: e.channel, peer: shortPeer(e.peerId), by });
+ if (was === "pending") this.opts.notify?.({ botId: e.botId, channel: e.channel, peerId: e.peerId }, "你已被设为这个机器人的主人。以后有人想使用它时,我会在这里告诉你。", `access:${id}:owner:${now}`);
+ return this.store.getAccessById(id)!;
+ }
+
+ /** 直接加入允许名单(迁移、换了扫码的微信、测试) */
+ allow(botId: string, channel: string, peerId: string, source: string): AccessEntry {
+ const now = this.now();
+ const cur = this.store.getAccess(botId, channel, peerId);
+ if (cur && (cur.status === "allowed" || cur.status === "owner")) return cur;
+ return this.store.putAccess({
+ id: cur?.id ?? crypto.randomUUID(),
+ botId,
+ channel,
+ peerId,
+ senderId: channel === "weixin" ? peerId : "",
+ name: "",
+ status: "allowed",
+ source,
+ code: "",
+ text: "",
+ requests: 0,
+ createdAt: now,
+ updatedAt: now,
+ decidedAt: now,
+ decidedBy: source,
+ repliedAt: 0,
+ notifiedAt: 0,
+ });
+ }
+
+ /** 移除(允许名单里的人、被拒绝的人、在应用里设的主人):之后他再发消息会重新申请 */
+ remove(id: string): boolean {
+ const e = this.store.getAccessById(id);
+ if (!e) return false;
+ this.store.deleteAccess(id);
+ log.info("access removed", { bot: e.botId, channel: e.channel, peer: shortPeer(e.peerId), was: e.status });
+ return true;
+ }
+
+ /** 界面与 /status:主人、名单、待处理的请求 */
+ view(botId: string) {
+ const all = this.store.listAccess({ botId });
+ const owners = Object.fromEntries(ACCESS_CHANNELS.map((ch) => [ch, this.owner(botId, ch) ?? null])) as Record<AccessChannel, Owner | null>;
+ return {
+ policy: "owner-allowlist" as const,
+ owners,
+ requests: all.filter((e) => e.status === "pending"),
+ entries: all.filter((e) => e.status !== "pending"),
+ };
+ }
+
+ /** /status 里的一行 */
+ policyLine(botId: string): string {
+ const v = this.view(botId);
+ const allowed = v.entries.filter((e) => e.status === "allowed").length;
+ const owners = ACCESS_CHANNELS.map((ch) => `${CHANNEL_LABEL[ch]}主人${v.owners[ch] ? ` ${shortPeer(v.owners[ch]!.peerId)}` : "未设置"}`).join(",");
+ const req = v.requests.length ? `;${v.requests.length} 个使用请求待处理(回复「同意 编号」或在应用的信息面板里处理)` : "";
+ return `谁能使用:只有主人和允许名单里的人(${owners};已允许 ${allowed} 人)${req}`;
+ }
+}
diff --git a/src/core/outbox.ts b/src/core/outbox.ts
new file mode 100644
index 0000000..4b5b177
--- /dev/null
+++ b/src/core/outbox.ts
@@ -0,0 +1,250 @@
+/**
+ * 持久化的出站队列:最终回复、文件、审批提示和重要通知先写进 sqlite,再发送。
+ * - 每条消息有确定的 id(由入站消息 id 推出来),同一 id 只写一次、只发一次;
+ * - 同一会话按写入顺序一条一条发,前一条没发完,后面的等着;
+ * - 临时失败按退避重试(5 秒起,翻倍到 5 分钟),渠道没在运行时等它上线;
+ * - 发不出去了(配额用完、超过 24 小时、过期、平台多次拒绝)标记 gone 并记下原因,界面里能看到;
+ * - 应用重启后接着发。流式的中间内容和"正在输入"不经过这里。
+ *
+ * 设计改编自 deepseek-ai/dsh-superagent-prototype(MIT,© 2026 DeepSeek Harness Team):src/app/outbox.ts 的回执 +
+ * src/app/effects.ts 的持久化副作用队列(按会话排队、Later 不计失败、指数退避、关机时留到下次启动),见 THIRD_PARTY_NOTICES.md。
+ */
+import crypto from "node:crypto";
+import type { OutboxBody, OutboxKind, OutboxRow, Store } from "../store/db.js";
+import { logger } from "../log.js";
+
+const log = logger("outbox");
+
+/** 暂时不能发(渠道没上线、登录过期等):稍后再试,不算失败 */
+export class Later extends Error {}
+/** 再也发不出去了:标记 gone,message 是给人看的原因 */
+export class Gone extends Error {}
+
+/** 普通消息最长等多久(微信的会话凭证 24 小时有效,飞书也不该再补发一天前的回复) */
+export const OUTBOX_TTL_MS = 24 * 3600_000;
+/** 平台明确拒绝(有错误码)的,试这么多次就放弃 */
+export const REJECTIONS_BEFORE_GONE = 5;
+
+export interface OutboxInput {
+ id: string;
+ botId: string;
+ channel: "weixin" | "feishu";
+ /** 微信:用户 id;飞书:单聊 chat_id */
+ peerId: string;
+ kind: OutboxKind;
+ body: OutboxBody;
+ /** 飞书:回复的消息 id */
+ replyTo?: string;
+ /** 多久之后不再发(默认 24 小时;ack、审批提示更短) */
+ ttlMs?: number;
+}
+
+/** 渠道的发送函数:成功返回;Later / Gone / 其他错误(临时失败,会重试)。progress 记下长文本已发出的分段数 */
+export type Deliver = (row: OutboxRow, progress: (n: number) => void) => Promise<void>;
+
+/** 平台给的确定 id(微信 client_id、飞书 uuid):同一条消息的同一段每次都一样,平台去重时不会重复 */
+export function stableId(id: string, part: number, len = 32): string {
+ return crypto.createHash("sha256").update(`${id}#${part}`).digest("hex").slice(0, len);
+}
+
+/**
+ * 一次回复里每条出站消息 id 的最后一段:最终回复按"第几个"(同一条入站只有一个最终回复,平台重复投递、模型答得不一样时也不会再发一遍),
+ * 其余按内容(不同的消息不会因为先后顺序不同撞上同一个 id 而被吞掉)。
+ */
+export class ReplyIds {
+ private finals = 0;
+ final(): string {
+ return `final${this.finals++ || ""}`;
+ }
+ of(kind: string, content: string): string {
+ return `${kind}-${stableId(content, 0, 12)}`;
+ }
+}
+
+export class Outbox {
+ private handlers = new Map<string, Deliver>();
+ /** 会话 → 正在进行的那次发送 */
+ private inflight = new Map<string, { id: string; done: Promise<void> }>();
+ private timer: NodeJS.Timeout | undefined;
+ private scheduled = false;
+ private started = false;
+ private stopped = false;
+ /** 一条消息发不出去了(界面提示、日志) */
+ onGone: ((row: OutboxRow) => void) | undefined;
+
+ constructor(
+ private store: Store,
+ private opts: { now?: () => number; retry?: readonly [number, number] } = {},
+ ) {}
+
+ private now(): number {
+ return (this.opts.now ?? Date.now)();
+ }
+
+ /** 渠道上线时登记自己的发送函数,返回注销函数(渠道停下时调用;没登记的消息等着) */
+ register(botId: string, channel: string, deliver: Deliver): () => void {
+ const key = `${botId}:${channel}`;
+ this.handlers.set(key, deliver);
+ this.kick();
+ return () => {
+ if (this.handlers.get(key) === deliver) this.handlers.delete(key);
+ };
+ }
+
+ /**
+ * 先写库再发。同一 id 已经写过就不再写(也不会再发一遍)。
+ * 等到这条消息的第一次发送结束(成功、失败待重试或放弃)才返回;排在同一会话前一条后面时立即返回。不抛错。
+ */
+ async send(input: OutboxInput): Promise<OutboxRow | undefined> {
+ const now = this.now();
+ const conversationId = `${input.botId}:${input.channel}:${input.peerId}`;
+ this.store.insertOutbox({
+ id: input.id,
+ botId: input.botId,
+ channel: input.channel,
+ conversationId,
+ peerId: input.peerId,
+ kind: input.kind,
+ body: input.body,
+ replyTo: input.replyTo ?? "",
+ due: now,
+ createdAt: now,
+ expiresAt: now + (input.ttlMs ?? OUTBOX_TTL_MS),
+ });
+ this.pump();
+ const f = this.inflight.get(conversationId);
+ if (f?.id === input.id) await f.done;
+ return this.store.getOutbox(input.id);
+ }
+
+ /** 开始发送(含上次没发完的);清理旧记录 */
+ start(): void {
+ this.started = true;
+ this.stopped = false;
+ try {
+ this.store.pruneOutbox(this.now());
+ // 重启了:等着退避的不用再等,马上试一次
+ this.store.resumeOutbox(this.now());
+ } catch (e) {
+ log.warn("prune failed", { message: (e as Error).message });
+ }
+ const left = this.store.pendingOutbox().length;
+ if (left) log.info(`resuming ${left} unsent message(s)`);
+ this.kick();
+ }
+
+ /** 不再开始新的发送,等正在发的结束(最多 waitMs);没发完的留在库里,下次启动接着发 */
+ async stop(waitMs = 5000): Promise<void> {
+ this.stopped = true;
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ const running = [...this.inflight.values()].map((f) => f.done);
+ if (!running.length) return;
+ let t: NodeJS.Timeout | undefined;
+ await Promise.race([Promise.allSettled(running), new Promise((r) => (t = setTimeout(r, waitMs)))]);
+ clearTimeout(t);
+ }
+
+ /** 等到没有正在进行的发送(到期待重试的不等) */
+ async idle(): Promise<void> {
+ for (;;) {
+ this.pump();
+ const running = [...this.inflight.values()].map((f) => f.done);
+ if (!running.length) return;
+ await Promise.allSettled(running);
+ }
+ }
+
+ /** 界面上"知道了" */
+ dismiss(id: string): boolean {
+ const row = this.store.getOutbox(id);
+ if (!row || row.status !== "gone") return false;
+ this.store.updateOutbox(id, { dismissed: true }, this.now());
+ return true;
+ }
+
+ private kick(): void {
+ if (this.scheduled) return;
+ this.scheduled = true;
+ queueMicrotask(() => {
+ this.scheduled = false;
+ this.pump();
+ });
+ }
+
+ /** 每个会话只看最早的一条没发出去的:到期且渠道在线就发,否则记下最早什么时候再看 */
+ private pump(): void {
+ if (!this.started || this.stopped) return;
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ const now = this.now();
+ let next = Infinity;
+ const heads = new Set<string>();
+ for (const row of this.store.pendingOutbox()) {
+ if (heads.has(row.conversationId)) continue;
+ heads.add(row.conversationId);
+ if (this.inflight.has(row.conversationId)) continue;
+ if (row.expiresAt <= now) {
+ this.gone(row, row.error ? `一直没能发出去(${row.error})` : "等待太久,已不再发送");
+ this.kick();
+ continue;
+ }
+ const deliver = this.handlers.get(`${row.botId}:${row.channel}`);
+ if (row.due > now || !deliver) {
+ // 渠道没上线:等它注册;到了过期时间也要醒来标记 gone
+ next = Math.min(next, deliver ? row.due : row.expiresAt);
+ continue;
+ }
+ this.attempt(row, deliver);
+ }
+ if (next < Infinity) {
+ this.timer = setTimeout(() => this.pump(), Math.max(20, next - now));
+ this.timer.unref?.();
+ }
+ }
+
+ private attempt(row: OutboxRow, deliver: Deliver): void {
+ const conv = row.conversationId;
+ const done = (async () => {
+ try {
+ await deliver(row, (n) => this.store.updateOutbox(row.id, { progress: n }, this.now()));
+ this.store.updateOutbox(row.id, { status: "sent", sentAt: this.now(), error: "" }, this.now());
+ } catch (e) {
+ this.failed(row, e);
+ }
+ })().finally(() => {
+ if (this.inflight.get(conv)?.done === done) this.inflight.delete(conv);
+ this.kick();
+ });
+ this.inflight.set(conv, { id: row.id, done });
+ }
+
+ private failed(row: OutboxRow, e: unknown): void {
+ const msg = String((e as Error)?.message ?? e).slice(0, 300);
+ const now = this.now();
+ if (e instanceof Gone) return this.gone(row, msg);
+ // 关机中:留到下次启动
+ if (this.stopped) return;
+ const [base, max] = this.opts.retry ?? [5000, 300_000];
+ if (e instanceof Later) {
+ this.store.updateOutbox(row.id, { due: now + base, error: msg }, now);
+ return;
+ }
+ const attempts = row.attempts + 1;
+ const rejected = (e as { rejected?: boolean })?.rejected === true;
+ if ((rejected && attempts >= REJECTIONS_BEFORE_GONE) || now >= row.expiresAt) return this.gone(row, `发送失败:${msg}`);
+ const delay = Math.min(max, base * 2 ** Math.min(attempts - 1, 16));
+ log.warn("send failed, will retry", { id: row.id, channel: row.channel, attempts, inMs: delay, message: msg });
+ this.store.updateOutbox(row.id, { attempts, error: msg, due: now + delay }, now);
+ }
+
+ private gone(row: OutboxRow, reason: string): void {
+ this.store.updateOutbox(row.id, { status: "gone", error: reason }, this.now());
+ log.warn("message gone", { id: row.id, channel: row.channel, kind: row.kind, reason });
+ try {
+ this.onGone?.({ ...row, status: "gone", error: reason });
+ } catch {
+ /* ignore */
+ }
+ }
+}
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index b075636..16a6b71 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -15,6 +15,7 @@ import { clearInflight, markInflight, takeNotice } from "./recovery.js";
import { pwshProbe, pwshStatusLine } from "../agent/pwsh.js";
import { isBotProviderModel } from "../modelflare.js";
import type { ApprovalRow } from "../store/db.js";
+import type { AccessControl } from "./access.js";
const log = logger("runtime");
@@ -96,6 +97,8 @@ export interface RuntimeOptions {
* 会话与界面里保存的仍是不带 provider 的 id。缺省原样发送。
*/
route?: (botId: string, model: string) => string;
+ /** 谁能和机器人对话(主人 + 允许名单);缺省不限制 */
+ access?: AccessControl;
}
const HELP = [
@@ -179,6 +182,11 @@ export class BotRuntime {
*/
async handle(ev: InboundEvent, out: ReplySession, opts: { signal?: AbortSignal } = {}): Promise<void> {
const { store } = this.opts;
+ // 兜底:不在允许名单里的人不建会话、不进模型(正常已在 interceptReply 拦下)
+ if (this.opts.access && !this.opts.access.allowed(ev)) {
+ log.warn("dropped a message from a sender who is not allowed", { bot: ev.botId, channel: ev.channel });
+ return;
+ }
const bot = store.getBot(ev.botId);
if (!bot) throw new Error(`unknown bot ${ev.botId}`);
const conv = store.ensureConversation(bot.id, ev.channel, ev.conversation.id, ev.sender.name || ev.sender.id, ev.conversation.kind === "group" ? "group" : "dm");
@@ -307,6 +315,11 @@ export class BotRuntime {
* handled=false 但带 ack:前一条还在处理,渠道先把 ack 发出去,消息照常入队。
*/
interceptReply(ev: InboundEvent): { handled: boolean; ack?: string } {
+ // 准入:不在允许名单里的人只收到一句提示(限频),不进队列、不碰模型;主人可以用「同意 1234」处理使用请求
+ const gate = this.opts.access?.admit(ev);
+ if (gate && !gate.ok) return { handled: true, ack: gate.reply };
+ const paired = this.opts.access?.handleReply(ev);
+ if (paired?.handled) return paired;
const text = eventText(ev);
const convId = `${ev.botId}:${ev.channel}:${ev.conversation.id}`;
// /status、/help 只读、不碰模型和代理进程:不进会话队列,不会排在一个卡住或正在启动代理的回合后面
@@ -351,7 +364,8 @@ export class BotRuntime {
const ps = a?.available ? pwshStatusLine(pwshProbe.snapshot()) : "";
const turn = a?.turnsInProgress.get(convId);
const busy = turn ? [busyLine(turn.since, turn.lastProgress, turn.activity.steps)] : [];
- return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
+ const who = this.opts.access ? [this.opts.access.policyLine(botId)] : [];
+ return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...who, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
}
/** 卡片按钮回调:批准/拒绝/选择选项。 */
diff --git a/src/diagnostics.ts b/src/diagnostics.ts
index bdddb40..3111d9a 100644
--- a/src/diagnostics.ts
+++ b/src/diagnostics.ts
@@ -357,10 +357,22 @@ export function diagnosticsStatus(app: App): Record<string, unknown> {
agent: app.agent.diagnostics(),
// Windows:代理执行命令用的 PowerShell(没有 7 时每条命令要二三十秒)
pwsh: pwshProbe.snapshot(),
+ outbox: outboxSummary(app),
last: app.lastDiagnostics,
};
}
+/** 出站队列:等着发的、最近 7 天没发出去的(只有数量和原因,不含消息内容) */
+function outboxSummary(app: App): Record<string, unknown> | undefined {
+ try {
+ const pending = app.store.listOutbox({ status: "pending", limit: 500 });
+ const gone = app.store.listOutbox({ status: "gone", since: Date.now() - 7 * 86400_000, limit: 500 });
+ return { pending: pending.length, retrying: pending.filter((r) => r.attempts > 0).length, lastError: pending.find((r) => r.error)?.error, gone7d: gone.length, lastGone: gone[0]?.error };
+ } catch {
+ return undefined;
+ }
+}
+
const ts = (t?: number) => (t ? new Date(t).toISOString() : "-");
function probeLine(name: string, p: ProbeResult): string {
@@ -389,6 +401,8 @@ export function diagnosticsReport(app: App, lines = 200): string {
}
const ps = pwshReportLine(s.pwsh);
if (ps) out.push(ps);
+ const ob = s.outbox;
+ if (ob) out.push(`[出站队列] 等待发送 ${ob.pending} 条(重试中 ${ob.retrying})${ob.lastError ? ` · 最近错误:${ob.lastError}` : ""} · 最近 7 天没发出去 ${ob.gone7d} 条${ob.lastGone ? ` · 最近一次:${ob.lastGone}` : ""}`);
const m = app.lastDiagnostics.model;
if (m) {
out.push("");
diff --git a/src/store/db.ts b/src/store/db.ts
index ade3886..ed0f9ae 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -88,6 +88,82 @@ export interface ApprovalRow {
decidedAt: number;
}
+/**
+ * 谁能和机器人对话(每个机器人、每个渠道):owner = 在应用里设的主人(微信的主人默认是扫码登录的人,不存在这里),
+ * allowed = 允许名单,pending = 等主人处理的使用请求,denied = 被拒绝(不再回复,主人可移除)。
+ * peerId 是单聊会话 id(微信 = 用户 id,飞书 = 单聊 chat_id)。
+ */
+export type AccessStatus = "owner" | "allowed" | "pending" | "denied";
+export interface AccessEntry {
+ id: string;
+ botId: string;
+ channel: string;
+ peerId: string;
+ /** 平台上的发送者 id(飞书 open_id;微信同 peerId) */
+ senderId: string;
+ name: string;
+ status: AccessStatus;
+ /** 怎么来的:request(发消息申请)、migration(升级前已在使用)、previous-owner(换了扫码的微信)、app(在应用里添加) */
+ source: string;
+ /** 待处理请求的配对码(主人回复「同意 1234」);处理后清空 */
+ code: string;
+ /** 第一条消息(截断),帮主人认出是谁 */
+ text: string;
+ requests: number;
+ createdAt: number;
+ updatedAt: number;
+ decidedAt: number;
+ decidedBy: string;
+ /** 上次给这个人回"还没被允许"的时间(限频) */
+ repliedAt: number;
+ /** 上次把这个请求通知给主人的时间(限频) */
+ notifiedAt: number;
+}
+
+export type OutboxStatus = "pending" | "sent" | "gone";
+/** 出站消息的内容:文本(最终回复、提示、通知)、文件、带按钮的卡片(飞书审批) */
+export interface OutboxBody {
+ text?: string;
+ /** 微信:原样发送,不过 Markdown 过滤(审批提示里的反引号要保留) */
+ raw?: boolean;
+ path?: string;
+ name?: string;
+ /** 飞书交互卡片 JSON(发不了时发 text) */
+ card?: Record<string, unknown>;
+ /** 飞书流式卡片:最终回复先写进这张卡片,失败再发文本 */
+ cardId?: string;
+ cardSeq?: number;
+ /** 卡片上已经是最终全文 */
+ shown?: boolean;
+}
+export type OutboxKind = "text" | "file" | "card" | "notice";
+/** 持久化的出站消息(见 core/outbox.ts) */
+export interface OutboxRow {
+ id: string;
+ seq: number;
+ botId: string;
+ channel: string;
+ /** 排序单位:同一会话按 seq 依次发送 */
+ conversationId: string;
+ peerId: string;
+ kind: OutboxKind;
+ body: OutboxBody;
+ /** 飞书:回复的消息 id */
+ replyTo: string;
+ status: OutboxStatus;
+ attempts: number;
+ /** 已经发出去的分段数(长文本分多条发,崩溃后从这里接着发) */
+ progress: number;
+ due: number;
+ /** 最近一次失败的原因;gone 时是发不出去的原因 */
+ error: string;
+ createdAt: number;
+ updatedAt: number;
+ expiresAt: number;
+ sentAt: number;
+ dismissed: boolean;
+}
+
type Row = Record<string, unknown>;
const SCHEMA = `
@@ -126,6 +202,23 @@ CREATE INDEX IF NOT EXISTS approvals_status ON approvals(status, expires_at);
CREATE TABLE IF NOT EXISTS agent_segments (
id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT NOT NULL, session_id TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '', handoff TEXT NOT NULL DEFAULT '', ended_at INTEGER NOT NULL);
+CREATE TABLE IF NOT EXISTS access (
+ id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, channel TEXT NOT NULL, peer_id TEXT NOT NULL,
+ sender_id TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '', status TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT '', code TEXT NOT NULL DEFAULT '', text TEXT NOT NULL DEFAULT '',
+ requests INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL,
+ decided_at INTEGER NOT NULL DEFAULT 0, decided_by TEXT NOT NULL DEFAULT '',
+ replied_at INTEGER NOT NULL DEFAULT 0, notified_at INTEGER NOT NULL DEFAULT 0);
+CREATE UNIQUE INDEX IF NOT EXISTS access_peer ON access(bot_id, channel, peer_id);
+CREATE TABLE IF NOT EXISTS outbox (
+ id TEXT PRIMARY KEY, seq INTEGER NOT NULL, bot_id TEXT NOT NULL, channel TEXT NOT NULL,
+ conversation_id TEXT NOT NULL, peer_id TEXT NOT NULL, kind TEXT NOT NULL, body TEXT NOT NULL,
+ reply_to TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
+ progress INTEGER NOT NULL DEFAULT 0, due INTEGER NOT NULL, error TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,
+ sent_at INTEGER NOT NULL DEFAULT 0, dismissed INTEGER NOT NULL DEFAULT 0);
+CREATE INDEX IF NOT EXISTS outbox_status ON outbox(status, seq);
+CREATE INDEX IF NOT EXISTS outbox_bot ON outbox(bot_id, status);
`;
/** 旧库补列(CREATE TABLE IF NOT EXISTS 不会改已有表)。 */
@@ -158,6 +251,31 @@ export class Store {
if (!cols.includes(col)) this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${col} ${def}`);
}
this.migrateComputerUseAuto();
+ this.migrateAccess();
+ }
+
+ /**
+ * 一次性迁移(引入允许名单时):已经和机器人有单聊会话的人自动加入允许名单(来源 migration,可在机器人设置里移除),
+ * 升级后不会被拦在外面。扫码登录的微信本来就是主人,不用加;群聊不受名单限制。
+ */
+ private migrateAccess(): void {
+ const KEY = "migration.access-allowlist";
+ if (this.getKV(KEY)) return;
+ const now = Date.now();
+ const rows = this.db.prepare("SELECT bot_id, channel, peer_id, title FROM conversations WHERE channel IN ('weixin', 'feishu') AND kind != 'group'").all() as Row[];
+ for (const r of rows) {
+ const botId = String(r.bot_id);
+ const channel = String(r.channel);
+ const peerId = String(r.peer_id);
+ if (channel === "weixin" && this.getWeixinAccount(botId)?.ownerUserId === peerId) continue;
+ this.db
+ .prepare(
+ `INSERT OR IGNORE INTO access(id, bot_id, channel, peer_id, sender_id, name, status, source, created_at, updated_at, decided_at, decided_by)
+ VALUES(?, ?, ?, ?, ?, ?, 'allowed', 'migration', ?, ?, ?, 'migration')`,
+ )
+ .run(randomUUID(), botId, channel, peerId, channel === "weixin" ? peerId : "", String(r.title ?? ""), now, now, now);
+ }
+ this.setKV(KEY, String(now));
}
/** 一次性迁移:电脑操作改为默认自动执行(旧的 always / readonly-free 审批设置一律改成 auto)。 */
@@ -250,6 +368,8 @@ export class Store {
this.db.prepare("DELETE FROM weixin_accounts WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM weixin_peers WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM agent_sessions WHERE bot_id = ?").run(id);
+ this.db.prepare("DELETE FROM access WHERE bot_id = ?").run(id);
+ this.db.prepare("DELETE FROM outbox WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM bots WHERE id = ?").run(id);
}
@@ -509,6 +629,154 @@ export class Store {
.run(status, decidedBy, result, Date.now(), id);
return Number(res.changes) > 0;
}
+
+ // ---------- access(允许名单与使用请求) ----------
+ private toAccess(r: Row): AccessEntry {
+ return {
+ id: String(r.id),
+ botId: String(r.bot_id),
+ channel: String(r.channel),
+ peerId: String(r.peer_id),
+ senderId: String(r.sender_id),
+ name: String(r.name),
+ status: String(r.status) as AccessStatus,
+ source: String(r.source),
+ code: String(r.code),
+ text: String(r.text),
+ requests: Number(r.requests),
+ createdAt: Number(r.created_at),
+ updatedAt: Number(r.updated_at),
+ decidedAt: Number(r.decided_at),
+ decidedBy: String(r.decided_by),
+ repliedAt: Number(r.replied_at),
+ notifiedAt: Number(r.notified_at),
+ };
+ }
+ getAccess(botId: string, channel: string, peerId: string): AccessEntry | undefined {
+ const r = this.db.prepare("SELECT * FROM access WHERE bot_id = ? AND channel = ? AND peer_id = ?").get(botId, channel, peerId) as Row | undefined;
+ return r ? this.toAccess(r) : undefined;
+ }
+ getAccessById(id: string): AccessEntry | undefined {
+ const r = this.db.prepare("SELECT * FROM access WHERE id = ?").get(id) as Row | undefined;
+ return r ? this.toAccess(r) : undefined;
+ }
+ listAccess(opts: { botId?: string; channel?: string; status?: AccessStatus } = {}): AccessEntry[] {
+ const where: string[] = [];
+ const args: string[] = [];
+ if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
+ if (opts.channel) (where.push("channel = ?"), args.push(opts.channel));
+ if (opts.status) (where.push("status = ?"), args.push(opts.status));
+ const sql = `SELECT * FROM access ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY created_at DESC LIMIT 500`;
+ return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toAccess(r));
+ }
+ /** 新建;同一机器人、渠道、会话已有一条时只改状态和来源 */
+ putAccess(e: AccessEntry): AccessEntry {
+ this.db
+ .prepare(
+ `INSERT INTO access(id, bot_id, channel, peer_id, sender_id, name, status, source, code, text, requests, created_at, updated_at, decided_at, decided_by, replied_at, notified_at)
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(bot_id, channel, peer_id) DO UPDATE SET status=excluded.status, source=excluded.source, code=excluded.code,
+ updated_at=excluded.updated_at, decided_at=excluded.decided_at, decided_by=excluded.decided_by`,
+ )
+ .run(e.id, e.botId, e.channel, e.peerId, e.senderId, e.name, e.status, e.source, e.code, e.text, e.requests, e.createdAt, e.updatedAt, e.decidedAt, e.decidedBy, e.repliedAt, e.notifiedAt);
+ return this.getAccess(e.botId, e.channel, e.peerId)!;
+ }
+ updateAccess(id: string, patch: Partial<Pick<AccessEntry, "status" | "source" | "code" | "requests" | "updatedAt" | "decidedAt" | "decidedBy" | "repliedAt" | "notifiedAt">>): void {
+ const cols: Record<string, string> = { status: "status", source: "source", code: "code", requests: "requests", updatedAt: "updated_at", decidedAt: "decided_at", decidedBy: "decided_by", repliedAt: "replied_at", notifiedAt: "notified_at" };
+ const keys = (Object.keys(patch) as Array<keyof typeof patch>).filter((k) => k in cols);
+ if (!keys.length) return;
+ this.db.prepare(`UPDATE access SET ${keys.map((k) => `${cols[k]} = ?`).join(", ")} WHERE id = ?`).run(...keys.map((k) => patch[k] as string | number), id);
+ }
+ deleteAccess(id: string): void {
+ this.db.prepare("DELETE FROM access WHERE id = ?").run(id);
+ }
+ pendingAccessByCode(botId: string, code: string): AccessEntry | undefined {
+ const r = this.db.prepare("SELECT * FROM access WHERE bot_id = ? AND code = ? AND status = 'pending' LIMIT 1").get(botId, code) as Row | undefined;
+ return r ? this.toAccess(r) : undefined;
+ }
+ /** 待处理请求占用的配对码(与审批码同是 4 位数字,不能撞) */
+ pendingAccessCodes(): string[] {
+ return (this.db.prepare("SELECT code FROM access WHERE status = 'pending' AND code != ''").all() as Row[]).map((r) => String(r.code));
+ }
+ /** since 之后通知过主人的请求数(限频) */
+ accessNotifiedSince(botId: string, since: number): number {
+ const r = this.db.prepare("SELECT COUNT(*) AS n FROM access WHERE bot_id = ? AND notified_at > 0 AND notified_at > ?").get(botId, since) as Row;
+ return Number(r.n);
+ }
+
+ // ---------- outbox(持久化的出站消息,见 core/outbox.ts) ----------
+ private toOutbox(r: Row): OutboxRow {
+ let body: OutboxBody = {};
+ try {
+ body = JSON.parse(String(r.body)) as OutboxBody;
+ } catch {
+ body = {};
+ }
+ return {
+ id: String(r.id),
+ seq: Number(r.seq),
+ botId: String(r.bot_id),
+ channel: String(r.channel),
+ conversationId: String(r.conversation_id),
+ peerId: String(r.peer_id),
+ kind: String(r.kind) as OutboxKind,
+ body,
+ replyTo: String(r.reply_to),
+ status: String(r.status) as OutboxStatus,
+ attempts: Number(r.attempts),
+ progress: Number(r.progress),
+ due: Number(r.due),
+ error: String(r.error),
+ createdAt: Number(r.created_at),
+ updatedAt: Number(r.updated_at),
+ expiresAt: Number(r.expires_at),
+ sentAt: Number(r.sent_at),
+ dismissed: Number(r.dismissed) === 1,
+ };
+ }
+ /** 同一 id 只写一次;返回是否是新写入的 */
+ insertOutbox(o: Pick<OutboxRow, "id" | "botId" | "channel" | "conversationId" | "peerId" | "kind" | "body" | "replyTo" | "due" | "createdAt" | "expiresAt">): boolean {
+ const res = this.db
+ .prepare(
+ `INSERT OR IGNORE INTO outbox(id, seq, bot_id, channel, conversation_id, peer_id, kind, body, reply_to, due, created_at, updated_at, expires_at)
+ VALUES(?, (SELECT IFNULL(MAX(seq), 0) + 1 FROM outbox), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(o.id, o.botId, o.channel, o.conversationId, o.peerId, o.kind, JSON.stringify(o.body), o.replyTo, o.due, o.createdAt, o.createdAt, o.expiresAt);
+ return Number(res.changes) > 0;
+ }
+ getOutbox(id: string): OutboxRow | undefined {
+ const r = this.db.prepare("SELECT * FROM outbox WHERE id = ?").get(id) as Row | undefined;
+ return r ? this.toOutbox(r) : undefined;
+ }
+ /** 还没发出去的,按写入顺序 */
+ pendingOutbox(limit = 1000): OutboxRow[] {
+ return (this.db.prepare("SELECT * FROM outbox WHERE status = 'pending' ORDER BY seq LIMIT ?").all(limit) as Row[]).map((r) => this.toOutbox(r));
+ }
+ updateOutbox(id: string, patch: Partial<Pick<OutboxRow, "status" | "attempts" | "progress" | "due" | "error" | "sentAt" | "dismissed">>, now = Date.now()): void {
+ const cols: Record<string, string> = { status: "status", attempts: "attempts", progress: "progress", due: "due", error: "error", sentAt: "sent_at", dismissed: "dismissed" };
+ const keys = (Object.keys(patch) as Array<keyof typeof patch>).filter((k) => k in cols);
+ if (!keys.length) return;
+ const vals = keys.map((k) => (typeof patch[k] === "boolean" ? (patch[k] ? 1 : 0) : (patch[k] as string | number)));
+ this.db.prepare(`UPDATE outbox SET ${keys.map((k) => `${cols[k]} = ?`).join(", ")}, updated_at = ? WHERE id = ?`).run(...vals, now, id);
+ }
+ listOutbox(opts: { botId?: string; status?: OutboxStatus; dismissed?: boolean; since?: number; limit?: number } = {}): OutboxRow[] {
+ const where: string[] = [];
+ const args: Array<string | number> = [];
+ if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
+ if (opts.status) (where.push("status = ?"), args.push(opts.status));
+ if (opts.dismissed !== undefined) (where.push("dismissed = ?"), args.push(opts.dismissed ? 1 : 0));
+ if (opts.since) (where.push("updated_at >= ?"), args.push(opts.since));
+ const sql = `SELECT * FROM outbox ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY seq DESC LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 100))}`;
+ return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toOutbox(r));
+ }
+ /** 启动时:等着退避重试的马上再试一次 */
+ resumeOutbox(now = Date.now()): number {
+ return Number(this.db.prepare("UPDATE outbox SET due = ? WHERE status = 'pending' AND due > ?").run(now, now).changes);
+ }
+ /** 清理:发出去的留 7 天(这期间同一 id 不会再发),发不出去的留 30 天 */
+ pruneOutbox(now = Date.now()): void {
+ this.db.prepare("DELETE FROM outbox WHERE (status = 'sent' AND updated_at < ?) OR (status = 'gone' AND updated_at < ?)").run(now - 7 * 86400_000, now - 30 * 86400_000);
+ }
}
function parseSettings(v: unknown): BotSettings {
diff --git a/src/web/server.ts b/src/web/server.ts
index 38f8b63..0b7bc27 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -20,6 +20,8 @@ import type { ApprovalRow } from "../store/db.js";
import { normalizeSettings } from "../agent/settings.js";
import { scopeLabel } from "../agent/memory.js";
import { pwshProbe, type PwshMode } from "../agent/pwsh.js";
+import { shortPeer, whoText } from "../core/access.js";
+import type { AccessEntry, OutboxRow } from "../store/db.js";
const log = logger("web");
const require = createRequire(import.meta.url);
@@ -140,6 +142,45 @@ function publicApproval(r: ApprovalRow) {
return { ...rest, questions };
}
+/** 允许名单 / 使用请求:界面要的字段(平台 id 只给末尾几位,界面不需要完整的) */
+function publicAccess(e: AccessEntry) {
+ return {
+ id: e.id,
+ channel: e.channel,
+ peer: shortPeer(e.peerId),
+ who: whoText(e),
+ status: e.status,
+ source: e.source,
+ code: e.code,
+ text: e.text,
+ requests: e.requests,
+ createdAt: e.createdAt,
+ updatedAt: e.updatedAt,
+ decidedAt: e.decidedAt,
+ };
+}
+
+/** 出站队列里等着重发或发不出去的消息:发给谁、内容摘要、原因 */
+function publicOutbox(app: App, r: OutboxRow) {
+ const owner = app.access.owner(r.botId, r.channel)?.peerId === r.peerId;
+ const e = owner ? undefined : app.store.getAccess(r.botId, r.channel, r.peerId);
+ const preview = r.kind === "file" ? `文件「${r.body.name ?? ""}」` : (r.body.text ?? "").replace(/\s+/g, " ").slice(0, 120);
+ return {
+ id: r.id,
+ channel: r.channel,
+ to: owner ? `${r.channel === "weixin" ? "微信" : "飞书"}主人` : whoText(e ?? { channel: r.channel, peerId: r.peerId, senderId: r.peerId, name: "" }),
+ kind: r.kind,
+ preview,
+ status: r.status,
+ attempts: r.attempts,
+ error: r.error,
+ createdAt: r.createdAt,
+ updatedAt: r.updatedAt,
+ due: r.due,
+ expiresAt: r.expiresAt,
+ };
+}
+
/** 账户操作的错误:Modelflare 返回的状态码原样带给界面(没有状态码的网络错误按 502) */
async function accountCall<T>(fn: () => Promise<T>): Promise<T> {
try {
@@ -615,6 +656,55 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
throw new HttpError(400, (e as Error).message);
}
}
+ // —— 谁能使用:主人、允许名单、使用请求 ——
+ if (sub === "access" && m === "GET") {
+ const v = app.access.view(id);
+ const owner = (ch: "weixin" | "feishu") => {
+ const o = v.owners[ch];
+ const e = o?.entryId ? app.store.getAccessById(o.entryId) : undefined;
+ return o ? { peer: shortPeer(o.peerId), who: e ? whoText(e) : whoText({ channel: ch, peerId: o.peerId, senderId: o.peerId, name: "" }), via: o.via, entryId: o.entryId ?? null } : null;
+ };
+ return send(res, 200, {
+ policy: v.policy,
+ owners: { weixin: owner("weixin"), feishu: owner("feishu") },
+ requests: v.requests.map(publicAccess),
+ entries: v.entries.filter((e) => e.status !== "owner").map(publicAccess),
+ });
+ }
+ if (seg[2] === "access" && seg.length === 5 && m === "POST") {
+ const entry = app.store.getAccessById(decodeURIComponent(seg[3]));
+ if (!entry || entry.botId !== id) throw new HttpError(404, "记录不存在");
+ if (seg[4] === "approve" || seg[4] === "deny") {
+ const r = app.access.decide(entry.id, seg[4] === "approve", "web");
+ if (!r) throw new HttpError(409, "这个请求已经处理过了");
+ return send(res, 200, { entry: publicAccess(r) });
+ }
+ if (seg[4] === "owner") {
+ try {
+ return send(res, 200, { entry: publicAccess(app.access.setOwner(entry.id, "web")) });
+ } catch (e) {
+ throw new HttpError(409, (e as Error).message);
+ }
+ }
+ }
+ if (seg[2] === "access" && seg.length === 4 && m === "DELETE") {
+ const entry = app.store.getAccessById(decodeURIComponent(seg[3]));
+ if (!entry || entry.botId !== id) throw new HttpError(404, "记录不存在");
+ app.access.remove(entry.id);
+ return send(res, 200, { ok: true });
+ }
+ // —— 出站队列:等着重发的、发不出去的(信息面板) ——
+ if (sub === "outbox" && m === "GET") {
+ const waiting = app.store.listOutbox({ botId: id, status: "pending", limit: 50 }).filter((r) => r.attempts > 0 || r.error);
+ const failed = app.store.listOutbox({ botId: id, status: "gone", dismissed: false, since: Date.now() - 7 * 86400_000, limit: 50 });
+ return send(res, 200, { waiting: waiting.map((r) => publicOutbox(app, r)), failed: failed.map((r) => publicOutbox(app, r)) });
+ }
+ if (seg[2] === "outbox" && seg.length === 5 && seg[4] === "dismiss" && m === "POST") {
+ const row = app.store.getOutbox(decodeURIComponent(seg[3]));
+ if (!row || row.botId !== id) throw new HttpError(404, "消息不存在");
+ if (!app.outbox.dismiss(row.id)) throw new HttpError(409, "这条消息还在发送");
+ return send(res, 200, { ok: true });
+ }
if (sub === "feishu" && m === "PUT") {
const b = await readJson(req);
const appId = String(b.appId ?? "").trim();
diff --git a/test/access.e2e.test.ts b/test/access.e2e.test.ts
new file mode 100644
index 0000000..b08ad83
--- /dev/null
+++ b/test/access.e2e.test.ts
@@ -0,0 +1,211 @@
+/**
+ * 准入端到端:mock iLink + 假飞书 + 真实 App/Web(外部模型端点模式)。
+ * 陌生人被拦(只回一句、不碰模型)→ 主人在微信里「同意 1234」或在应用里批准 → 对方能对话;拒绝、移除;
+ * 飞书在应用里设主人;升级前已在对话的人自动加入允许名单。
+ */
+import { describe, it, expect, beforeAll, afterAll } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { DatabaseSync } from "node:sqlite";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { APPROVED_TEXT, REFUSAL_TEXT } from "../src/core/access.js";
+import { FakeFeishu, feishuEvent, mockIlink, mockOpenAI, until } from "./helpers.js";
+
+let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+let ilink: Awaited<ReturnType<typeof mockIlink>>;
+let app: App;
+let base: string;
+const feishu = new FakeFeishu();
+const OWNER = "[email protected]";
+
+async function api(p: string, init: { method?: string; body?: unknown } = {}) {
+ const res = await fetch(base + "/amb/api" + p, {
+ method: init.method ?? "GET",
+ headers: init.body !== undefined ? { "content-type": "application/json" } : {},
+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
+ });
+ return { status: res.status, json: (await res.json().catch(() => ({}))) as any };
+}
+/** 发给某人的微信消息(按顺序) */
+const to = (user: string) => ilink.state.sent.filter((s) => s.to === user).map((s) => s.text);
+
+beforeAll(async () => {
+ llm = await mockOpenAI({ key: "gw-key" });
+ ilink = await mockIlink();
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-access-e2e-"));
+ // 升级前的库:已经有人在用(微信 old@、飞书 oc_old),还没有允许名单
+ const old = new DatabaseSync(path.join(dataDir, "anymodel.db"));
+ old.exec(`CREATE TABLE conversations (id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, channel TEXT NOT NULL, peer_id TEXT NOT NULL,
+ title TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`);
+ const conv = old.prepare("INSERT INTO conversations(id, bot_id, channel, peer_id, title, created_at, updated_at) VALUES(?, 'default', ?, ?, ?, 1, 1)");
+ conv.run("default:weixin:[email protected]", "weixin", "[email protected]", "[email protected]");
+ conv.run("default:feishu:oc_old", "feishu", "oc_old", "ou_old");
+ old.close();
+ const config = loadConfig({
+ dataDir,
+ env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: ilink.url, AMB_WEIXIN_CDN_BASE: ilink.cdnBase, AMB_FEISHU_THROTTLE_MS: "30", AMB_AGENT: "off" },
+ });
+ process.env.FEISHU_APP_ID = "cli_test";
+ process.env.FEISHU_APP_SECRET = "secret_test";
+ app = new App(config, { feishuTransport: () => feishu, weixinPollTimeoutMs: 2000, printQrToTerminal: false });
+ await app.start();
+ delete process.env.FEISHU_APP_ID;
+ delete process.env.FEISHU_APP_SECRET;
+ base = app.web!.url.replace(/\/$/, "");
+ // 扫码登录:扫码的是 [email protected]
+ await api("/bots/default/weixin/login", { method: "POST", body: {} });
+ await until(async () => (await api("/bots/default/channels")).json.weixin.state === "connected", 8000);
+});
+
+afterAll(async () => {
+ await app?.stop();
+ await llm?.close();
+ await ilink?.close();
+});
+
+describe("微信:只有主人和允许的人", () => {
+ it("扫码的人就是主人,直接能用", async () => {
+ ilink.push(OWNER, "你好");
+ await until(() => to(OWNER).length >= 1, 8000);
+ expect(to(OWNER)[0]).toBe("[mock-a] 你说:你好");
+ const acc = await api("/bots/default/access");
+ expect(acc.json.owners.weixin).toMatchObject({ via: "login" });
+ expect(acc.json.policy).toBe("owner-allowlist");
+ });
+
+ let code = "";
+ it("陌生人:只回一句、不碰模型;主人在微信里收到带配对码的通知;请求出现在信息面板", async () => {
+ const calls = llm.calls.length;
+ const ownerMsgs = to(OWNER).length;
+ ilink.push("[email protected]", "我是张三,想借用一下");
+ await until(() => to("[email protected]").length >= 1 && to(OWNER).length > ownerMsgs, 8000);
+ expect(to("[email protected]")).toEqual([REFUSAL_TEXT]);
+ const notice = to(OWNER).at(-1)!;
+ expect(notice).toContain("我是张三");
+ code = /同意 (\d{4})/.exec(notice)![1];
+ const acc = await api("/bots/default/access");
+ expect(acc.json.requests).toEqual([expect.objectContaining({ channel: "weixin", code, text: "我是张三,想借用一下", status: "pending", requests: 1 })]);
+ // 再发:不再回复、不再通知主人,模型一直没被调用
+ ilink.push("[email protected]", "在吗?");
+ await until(async () => (await api("/bots/default/access")).json.requests[0]?.requests === 2, 8000);
+ await app.channels.get("default")!.weixin!.idle();
+ expect(to("[email protected]")).toHaveLength(1);
+ expect(to(OWNER).at(-1)).toBe(notice);
+ expect(llm.calls.length).toBe(calls);
+ expect(app.store.getConversation("default:weixin:[email protected]")).toBeUndefined();
+ });
+
+ it("主人回复「同意 1234」:对方收到通知,之后能正常对话", async () => {
+ ilink.push(OWNER, `同意 ${code}`);
+ await until(() => to(OWNER).at(-1)!.startsWith("✅"), 8000);
+ expect(to(OWNER).at(-1)).toMatch(/^✅ 已允许「微信用户 .+」使用这个机器人$/);
+ await until(() => to("[email protected]").length >= 2, 8000);
+ expect(to("[email protected]")[1]).toBe(APPROVED_TEXT);
+ ilink.push("[email protected]", "现在呢");
+ await until(() => to("[email protected]").length >= 3, 8000);
+ expect(to("[email protected]")[2]).toBe("[mock-a] 你说:现在呢");
+ const acc = await api("/bots/default/access");
+ expect(acc.json.requests).toEqual([]);
+ expect(acc.json.entries).toEqual(expect.arrayContaining([expect.objectContaining({ channel: "weixin", status: "allowed", source: "request" })]));
+ });
+
+ it("在应用里拒绝:对方之后发什么都不回;在应用里批准、再移除:又被拦下", async () => {
+ ilink.push("[email protected]", "hi");
+ ilink.push("[email protected]", "hello");
+ await until(async () => (await api("/bots/default/access")).json.requests.length === 2, 8000);
+ const reqs = (await api("/bots/default/access")).json.requests as any[];
+ const li = reqs.find((r) => r.text === "hi");
+ const wang = reqs.find((r) => r.text === "hello");
+ expect((await api(`/bots/default/access/${li.id}/deny`, { method: "POST", body: {} })).json.entry.status).toBe("denied");
+ expect((await api(`/bots/default/access/${wang.id}/approve`, { method: "POST", body: {} })).json.entry.status).toBe("allowed");
+ expect((await api(`/bots/default/access/${wang.id}/approve`, { method: "POST", body: {} })).status).toBe(409);
+ await until(() => to("[email protected]").length >= 2, 8000);
+ expect(to("[email protected]")).toEqual([REFUSAL_TEXT, APPROVED_TEXT]);
+
+ const calls = llm.calls.length;
+ ilink.push("[email protected]", "再试试");
+ ilink.push("[email protected]", "我能用了吗");
+ await until(() => to("[email protected]").length >= 3, 8000);
+ await app.channels.get("default")!.weixin!.idle();
+ expect(to("[email protected]")).toEqual([REFUSAL_TEXT]);
+ expect(llm.calls.length).toBe(calls + 1);
+
+ expect((await api(`/bots/default/access/${wang.id}`, { method: "DELETE" })).status).toBe(200);
+ ilink.push("[email protected]", "还能用吗");
+ await until(async () => (await api("/bots/default/access")).json.requests.length === 1, 8000);
+ await app.channels.get("default")!.weixin!.idle();
+ expect(to("[email protected]")).toHaveLength(4);
+ expect(to("[email protected]")[3]).toBe(REFUSAL_TEXT);
+ expect(llm.calls.length).toBe(calls + 1);
+ });
+
+ it("/status 显示谁能使用", async () => {
+ ilink.push(OWNER, "/status");
+ await until(() => to(OWNER).at(-1)!.includes("当前模型"), 8000);
+ expect(to(OWNER).at(-1)).toMatch(/谁能使用:只有主人和允许名单里的人(微信主人 \S+,飞书主人未设置;已允许 \d+ 人);1 个使用请求待处理/);
+ });
+
+ it("升级:升级前已在对话的人自动在允许名单里,能继续用,可以移除", async () => {
+ const acc = await api("/bots/default/access");
+ const old = acc.json.entries.filter((e: any) => e.source === "migration");
+ expect(old.map((e: any) => e.channel).sort()).toEqual(["feishu", "weixin"]);
+ ilink.push("[email protected]", "我还能用吗");
+ await until(() => to("[email protected]").length >= 1, 8000);
+ expect(to("[email protected]")).toEqual(["[mock-a] 你说:我还能用吗"]);
+ });
+});
+
+describe("飞书:在应用里设主人", () => {
+ it("还没有主人:第一个发消息的人被拦下,在应用里「设为主人」后能用,并且收到后续请求的通知", async () => {
+ // 模拟过了一小时:上面的请求通知不占这里的限额
+ app.store.db.prepare("UPDATE access SET notified_at = 0").run();
+ const ch = app.channels.get("default")!.feishu!;
+ feishu.onMessage!(feishuEvent("我是老板", { chatId: "oc_boss", senderOpenId: "ou_boss" }));
+ await ch.idle();
+ expect(feishu.texts.at(-1)).toBe(REFUSAL_TEXT);
+ const req = (await api("/bots/default/access")).json.requests.find((r: any) => r.channel === "feishu");
+ expect(req).toMatchObject({ text: "我是老板", peer: "oc_boss" });
+ expect((await api("/bots/default/access")).json.owners.feishu).toBeNull();
+ const r = await api(`/bots/default/access/${req.id}/owner`, { method: "POST", body: {} });
+ expect(r.json.entry.status).toBe("owner");
+ await ch.idle();
+ expect(feishu.notices.at(-1)).toMatchObject({ chatId: "oc_boss", text: expect.stringContaining("主人") });
+ expect((await api("/bots/default/access")).json.owners.feishu).toMatchObject({ via: "app", peer: "oc_boss" });
+
+ feishu.onMessage!(feishuEvent("帮我看看", { chatId: "oc_boss", senderOpenId: "ou_boss" }));
+ await ch.idle();
+ expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:帮我看看");
+
+ // 同事来了:飞书主人和微信主人都收到配对码,主人在飞书里回复「允许 1234」
+ const ownerWx = to(OWNER).length;
+ feishu.onMessage!(feishuEvent("借用一下", { chatId: "oc_colleague", senderOpenId: "ou_colleague" }));
+ await ch.idle();
+ expect(feishu.texts.at(-1)).toBe(REFUSAL_TEXT);
+ const notice = feishu.notices.at(-1)!;
+ expect(notice.chatId).toBe("oc_boss");
+ const code = /同意 (\d{4})/.exec(notice.text)![1];
+ await until(() => to(OWNER).length > ownerWx, 8000);
+ expect(to(OWNER).at(-1)).toContain(`同意 ${code}`);
+ feishu.onMessage!(feishuEvent(`允许 ${code}`, { chatId: "oc_boss", senderOpenId: "ou_boss" }));
+ await ch.idle();
+ expect(feishu.texts.at(-1)).toMatch(/^✅ 已允许「飞书用户 .+」使用这个机器人$/);
+ expect(feishu.notices.at(-1)).toMatchObject({ chatId: "oc_colleague", text: APPROVED_TEXT });
+ feishu.onMessage!(feishuEvent("谢谢", { chatId: "oc_colleague", senderOpenId: "ou_colleague" }));
+ await ch.idle();
+ expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:谢谢");
+ });
+
+ it("升级前的飞书单聊照常能用", async () => {
+ const ch = app.channels.get("default")!.feishu!;
+ feishu.onMessage!(feishuEvent("老用户", { chatId: "oc_old", senderOpenId: "ou_old" }));
+ await ch.idle();
+ expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:老用户");
+ });
+
+ it("网页控制台不受限制", async () => {
+ const r = await api("/bots/default/chat", { method: "POST", body: { text: "控制台" } });
+ expect(r.json.reply).toBe("[mock-a] 你说:控制台");
+ });
+});
diff --git a/test/access.unit.test.ts b/test/access.unit.test.ts
new file mode 100644
index 0000000..e27189e
--- /dev/null
+++ b/test/access.unit.test.ts
@@ -0,0 +1,176 @@
+/**
+ * 谁能和机器人对话:主人、允许名单、使用请求(配对码、限频)、升级迁移。
+ */
+import { describe, it, expect } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { DatabaseSync } from "node:sqlite";
+import { Store } from "../src/store/db.js";
+import { AccessControl, NOTICE_LIMIT, REFUSAL_TEXT, REFUSE_EVERY_MS } from "../src/core/access.js";
+import { ApprovalCenter } from "../src/agent/approvals.js";
+import type { InboundEvent } from "../src/core/types.js";
+
+const ev = (channel: InboundEvent["channel"], peer: string, text: string, kind: "dm" | "group" = "dm"): InboundEvent => ({
+ id: Math.random().toString(36).slice(2),
+ channel,
+ botId: "b",
+ conversation: { kind, id: peer },
+ sender: { id: channel === "feishu" ? `ou_${peer}` : peer },
+ parts: [{ type: "text", text }],
+ replyHandle: {},
+ receivedAt: Date.now(),
+});
+
+function setup() {
+ const store = new Store(":memory:");
+ store.createBot({ id: "b", name: "小助手" });
+ store.saveWeixinAccount({ botId: "b", botToken: "t", ilinkBotId: "[email protected]", baseUrl: "http://x", ownerUserId: "[email protected]" });
+ let now = 1_000_000;
+ const sent: Array<{ channel: string; peerId: string; text: string; id: string }> = [];
+ const access = new AccessControl(store, { now: () => now, notify: (to, text, id) => (sent.push({ channel: to.channel, peerId: to.peerId, text, id }), true) });
+ return { store, access, sent, tick: (ms: number) => (now += ms) };
+}
+
+describe("AccessControl", () => {
+ it("owner, web console and group chats pass; a stranger gets one reply per hour and the owner one notice with a code", () => {
+ const { store, access, sent, tick } = setup();
+ expect(access.admit(ev("weixin", "[email protected]", "你好"))).toEqual({ ok: true });
+ expect(access.admit(ev("web", "console", "hi"))).toEqual({ ok: true });
+ expect(access.admit(ev("feishu", "oc_group", "hi", "group"))).toEqual({ ok: true });
+
+ expect(access.admit(ev("weixin", "[email protected]", "我是张三,想用一下"))).toEqual({ ok: false, reply: REFUSAL_TEXT });
+ const req = access.view("b").requests[0];
+ expect(req).toMatchObject({ channel: "weixin", peerId: "[email protected]", status: "pending", text: "我是张三,想用一下", requests: 1 });
+ expect(req.code).toMatch(/^\d{4}$/);
+ expect(sent).toHaveLength(1);
+ expect(sent[0]).toMatchObject({ channel: "weixin", peerId: "[email protected]", id: `access:${req.id}:weixin` });
+ expect(sent[0].text).toContain(`同意 ${req.code}`);
+ expect(sent[0].text).toContain("小助手");
+ expect(sent[0].text).toContain("我是张三");
+
+ // 一小时内再发:不回、不再通知主人
+ expect(access.admit(ev("weixin", "[email protected]", "在吗"))).toEqual({ ok: false });
+ expect(sent).toHaveLength(1);
+ expect(store.getAccessById(req.id)!.requests).toBe(2);
+ tick(REFUSE_EVERY_MS + 1);
+ expect(access.admit(ev("weixin", "[email protected]", "在吗"))).toEqual({ ok: false, reply: REFUSAL_TEXT });
+ expect(sent).toHaveLength(1);
+ });
+
+ it("notices to the owner are rate-limited per bot", () => {
+ const { access, sent, tick } = setup();
+ for (let i = 0; i < NOTICE_LIMIT + 2; i++) access.admit(ev("weixin", `s${i}@im.wechat`, "hi"));
+ expect(sent).toHaveLength(NOTICE_LIMIT);
+ expect(access.view("b").requests).toHaveLength(NOTICE_LIMIT + 2);
+ tick(3600_000 + 1);
+ access.admit(ev("weixin", "[email protected]", "hi"));
+ expect(sent).toHaveLength(NOTICE_LIMIT + 1);
+ });
+
+ it("the owner approves with 同意 <code> from WeChat; strangers and wrong codes fall through", () => {
+ const { access, sent } = setup();
+ access.admit(ev("weixin", "[email protected]", "hi"));
+ const { code, id } = access.view("b").requests[0];
+ // 不是主人:不处理(交给后面的工具审批)
+ expect(access.handleReply(ev("weixin", "[email protected]", `同意 ${code}`)).handled).toBe(false);
+ expect(access.handleReply(ev("weixin", "[email protected]", `同意 ${code === "0000" ? "0001" : "0000"}`)).handled).toBe(false);
+ const r = access.handleReply(ev("weixin", "[email protected]", `同意 ${code}`));
+ expect(r).toEqual({ handled: true, ack: "✅ 已允许「微信用户 s」使用这个机器人" });
+ expect(access.allowed(ev("weixin", "[email protected]", "x"))).toBe(true);
+ expect(access.view("b").entries.find((e) => e.id === id)).toMatchObject({ status: "allowed", code: "", decidedBy: "weixin:[email protected]" });
+ // 告诉对方一声
+ expect(sent.at(-1)).toMatchObject({ channel: "weixin", peerId: "[email protected]", text: expect.stringContaining("同意") });
+ // 已处理:同一个码不再认
+ expect(access.handleReply(ev("weixin", "[email protected]", `同意 ${code}`)).handled).toBe(false);
+ });
+
+ it("denied senders get no reply; removing them lets them ask again", () => {
+ const { access, tick } = setup();
+ access.admit(ev("weixin", "[email protected]", "hi"));
+ const { id } = access.view("b").requests[0];
+ expect(access.decide(id, false, "web")!.status).toBe("denied");
+ tick(5 * 3600_000);
+ expect(access.admit(ev("weixin", "[email protected]", "hi"))).toEqual({ ok: false });
+ expect(access.remove(id)).toBe(true);
+ expect(access.admit(ev("weixin", "[email protected]", "hi again"))).toEqual({ ok: false, reply: REFUSAL_TEXT });
+ expect(access.view("b").requests[0].text).toBe("hi again");
+ });
+
+ it("Feishu: the first sender can be made owner in the app; later requests reach that owner, who can approve in Feishu", () => {
+ const { access, sent } = setup();
+ expect(access.owner("b", "feishu")).toBeUndefined();
+ access.admit(ev("feishu", "oc_me", "我是主人"));
+ const mine = access.view("b").requests[0];
+ access.setOwner(mine.id, "web");
+ expect(access.owner("b", "feishu")).toEqual({ peerId: "oc_me", via: "app", entryId: mine.id });
+ expect(access.allowed(ev("feishu", "oc_me", "x"))).toBe(true);
+ expect(sent.at(-1)).toMatchObject({ channel: "feishu", peerId: "oc_me", text: expect.stringContaining("主人") });
+
+ access.admit(ev("feishu", "oc_colleague", "借用一下"));
+ const req = access.view("b").requests[0];
+ // 两个渠道的主人都收到
+ expect(sent.filter((s) => s.id.startsWith(`access:${req.id}`)).map((s) => s.channel).sort()).toEqual(["feishu", "weixin"]);
+ expect(access.handleReply(ev("feishu", "oc_me", `允许 ${req.code}`)).handled).toBe(true);
+ expect(access.allowed(ev("feishu", "oc_colleague", "x"))).toBe(true);
+
+ // 换主人:原来的主人变成普通允许
+ access.setOwner(req.id, "web");
+ expect(access.owner("b", "feishu")!.peerId).toBe("oc_colleague");
+ expect(access.view("b").entries.find((e) => e.peerId === "oc_me")!.status).toBe("allowed");
+ // 扫码登录的微信主人不能在应用里改
+ access.admit(ev("weixin", "[email protected]", "hi"));
+ expect(() => access.setOwner(access.view("b").requests[0].id, "web")).toThrow(/扫码/);
+ });
+
+ it("pairing codes and tool approval codes never collide", () => {
+ const { store, access } = setup();
+ const approvals = new ApprovalCenter(store);
+ for (let i = 0; i < 40; i++) {
+ access.admit(ev("weixin", `p${i}@im.wechat`, "hi"));
+ approvals.create({ kind: "approval", botId: "b", conversationId: "b:weixin:[email protected]", sessionId: "s", tool: "bash", detail: "", reason: "" });
+ }
+ const codes = [...store.pendingAccessCodes(), ...store.listApprovals({ status: "pending", limit: 500 }).map((r) => r.code)];
+ expect(new Set(codes).size).toBe(codes.length);
+ });
+
+ it("/status line names the policy, owners and pending requests", () => {
+ const { access } = setup();
+ access.allow("b", "weixin", "[email protected]", "app");
+ access.admit(ev("weixin", "[email protected]", "hi"));
+ expect(access.policyLine("b")).toBe("谁能使用:只有主人和允许名单里的人(微信主人 owner,飞书主人未设置;已允许 1 人);1 个使用请求待处理(回复「同意 编号」或在应用的信息面板里处理)");
+ });
+});
+
+describe("upgrade: people who already talk to a bot are allowed once", () => {
+ it("grandfathers existing DM peers (not the WeChat owner, not groups), only on the first open", () => {
+ const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "amb-access-")), "anymodel.db");
+ // 旧版本的库:只有会话和微信账号,没有 access 表
+ const old = new DatabaseSync(file);
+ old.exec(`CREATE TABLE conversations (id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, channel TEXT NOT NULL, peer_id TEXT NOT NULL,
+ title TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, kind TEXT NOT NULL DEFAULT 'dm');
+ CREATE TABLE weixin_accounts (bot_id TEXT PRIMARY KEY, bot_token TEXT NOT NULL, ilink_bot_id TEXT NOT NULL, base_url TEXT NOT NULL,
+ owner_user_id TEXT NOT NULL DEFAULT '', cursor TEXT NOT NULL DEFAULT '', paused_until INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL);`);
+ const conv = old.prepare("INSERT INTO conversations(id, bot_id, channel, peer_id, title, created_at, updated_at, kind) VALUES(?, 'b', ?, ?, ?, 1, 1, ?)");
+ conv.run("b:weixin:alice", "weixin", "[email protected]", "alice", "dm");
+ conv.run("b:weixin:owner", "weixin", "[email protected]", "owner", "dm");
+ conv.run("b:feishu:oc_1", "feishu", "oc_1", "ou_1", "dm");
+ conv.run("b:feishu:oc_g", "feishu", "oc_g", "群", "group");
+ conv.run("b:web:console", "web", "console", "控制台", "dm");
+ old.prepare("INSERT INTO weixin_accounts(bot_id, bot_token, ilink_bot_id, base_url, owner_user_id, updated_at) VALUES('b', 't', 'i', 'u', '[email protected]', 1)").run();
+ old.close();
+
+ let store = new Store(file);
+ const got = store.listAccess({ botId: "b" }).map((e) => [e.channel, e.peerId, e.status, e.source]).sort();
+ expect(got).toEqual([
+ ["feishu", "oc_1", "allowed", "migration"],
+ ["weixin", "[email protected]", "allowed", "migration"],
+ ]);
+ // 移除后不会在下次启动时又被加回来
+ store.deleteAccess(store.getAccess("b", "weixin", "[email protected]")!.id);
+ store.close();
+ store = new Store(file);
+ expect(store.getAccess("b", "weixin", "[email protected]")).toBeUndefined();
+ store.close();
+ });
+});
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index e222686..a9acb3f 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -531,6 +531,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");
const send = async (user: string, model: string) => {
const conv = app.store.ensureConversation("default", "weixin", user, user, "dm");
+ app.access.allow("default", "weixin", user, "test");
app.store.setConversationModel(conv.id, model);
const ops: any[] = [];
const ev = { id: `img-${user}`, channel: "weixin" as const, botId: "default", conversation: { kind: "dm" as const, id: user }, sender: { id: user }, parts: [{ type: "text" as const, text: "LOOKIMG" }, { type: "image" as const, data: png, mime: "image/png" }], replyHandle: {}, receivedAt: Date.now() };
@@ -715,6 +716,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
/** 用一个微信会话(可单独设模型)发一条消息:回复与这一轮的步骤 */
const turnOn = async (user: string, model: string, text: string, images: Buffer[] = []) => {
const conv = app.store.ensureConversation("default", "weixin", user, user, "dm");
+ app.access.allow("default", "weixin", user, "test");
app.store.setConversationModel(conv.id, model);
const ops: any[] = [];
const parts = [{ type: "text" as const, text }, ...images.map((data) => ({ type: "image" as const, data, mime: "image/png" }))];
diff --git a/test/e2e.test.ts b/test/e2e.test.ts
index f6ec9af..ffdf351 100644
--- a/test/e2e.test.ts
+++ b/test/e2e.test.ts
@@ -50,6 +50,10 @@ afterAll(async () => {
});
describe("飞书 E2E", () => {
+ // 只有主人和允许名单里的人能用(准入见 access-outbox.e2e.test.ts):这里的单聊都先放进允许名单
+ beforeAll(() => {
+ for (const chat of ["oc_chat1", "oc_m", "oc_other"]) app.access.allow("default", "feishu", chat, "test");
+ });
it("单聊:快速 ack + 流式卡片 + 历史持久化", async () => {
const ev = feishuEvent("你好");
const t0 = Date.now();
@@ -109,6 +113,9 @@ describe("微信 E2E", () => {
expect(fs.existsSync(path.join(dataDir, "weixin", "default-login-qr.png"))).toBe(true);
const acct = app.store.getWeixinAccount("default")!;
expect(acct.ilinkBotId).toBe("[email protected]");
+ expect(acct.ownerUserId).toBe("[email protected]");
+ // 扫码的是 [email protected];下面这些人先放进允许名单(准入见 access-outbox.e2e.test.ts)
+ for (const u of ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]) app.access.allow("default", "weixin", u, "test");
ilink.push("[email protected]", "**你好** 微信");
await until(() => ilink.state.sent.length >= 1, 8000);
diff --git a/test/fixtures/app-child.ts b/test/fixtures/app-child.ts
new file mode 100644
index 0000000..cf6baec
--- /dev/null
+++ b/test/fixtures/app-child.ts
@@ -0,0 +1,14 @@
+/**
+ * 崩溃测试用的子进程:起一个真实 App(外部模型端点 + mock iLink,不开网页),打印 READY 后一直运行,直到被 kill -9。
+ * 用法:node --import tsx test/fixtures/app-child.ts <dataDir> <llmUrl> <ilinkUrl> <cdnBase>
+ */
+import { App } from "../../src/app.js";
+import { loadConfig } from "../../src/config.js";
+
+const [dataDir, llmUrl, ilinkUrl, cdnBase] = process.argv.slice(2);
+const app = new App(
+ loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: `${llmUrl}/v1`, AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: ilinkUrl, AMB_WEIXIN_CDN_BASE: cdnBase, AMB_AGENT: "off" } }),
+ { weixinPollTimeoutMs: 2000, printQrToTerminal: false, noWeb: true },
+);
+await app.start();
+console.log("READY");
diff --git a/test/helpers.ts b/test/helpers.ts
index 40b5607..87259f8 100644
--- a/test/helpers.ts
+++ b/test/helpers.ts
@@ -111,13 +111,18 @@ export async function mockIlink() {
statusSeq: ["wait", "scaned", "confirmed"] as string[],
inbox: [] as any[],
sent: [] as Array<{ to: string; text: string; contextToken?: string; item?: any }>,
+ /** 与 sent 一一对应:每条消息的 client_id(出站队列给的是固定的) */
+ clientIds: [] as string[],
+ /** sendmessage 回 HTTP 500(模拟网络/服务端故障):sendDown 一直失败,failSend 失败接下来的 N 次 */
+ sendDown: false,
+ failSend: 0,
+ sendFailures: 0,
/** 假 CDN:encrypt_query_param → 密文(下载);上传的密文也存这里 */
cdn: new Map<string, Buffer>(),
cdnDownloads: [] as string[],
typing: [] as number[],
expireNext: false,
authSeen: [] as string[],
- cursor: 0,
};
let base = "";
const srv = await listen(async (req, res) => {
@@ -146,20 +151,29 @@ export async function mockIlink() {
return json({ status: s });
}
case "/ilink/bot/getupdates": {
- await body(req);
+ const b = await body(req);
if (state.expireNext) {
state.expireNext = false;
return json({ ret: -14, errcode: -14, errmsg: "session timeout" });
}
+ // 像真实 iLink 一样按游标投递:inbox 只追加,get_updates_buf = 已经拿到第几条;
+ // 客户端没处理完就停了(游标没前进),下次拉取会再拿到同样的消息
+ const from = Number(/^cur-(\d+)$/.exec(String(b.get_updates_buf ?? ""))?.[1] ?? 0);
const deadline = Date.now() + 300;
- while (!state.inbox.length && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10));
- const msgs = state.inbox.splice(0);
- return json({ ret: 0, msgs, get_updates_buf: `cur-${++state.cursor}` });
+ while (state.inbox.length <= from && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10));
+ const msgs = state.inbox.slice(from);
+ return json({ ret: 0, msgs, get_updates_buf: `cur-${from + msgs.length}` });
}
case "/ilink/bot/sendmessage": {
const b = await body(req);
+ if (state.sendDown || state.failSend > 0) {
+ if (state.failSend > 0) state.failSend--;
+ state.sendFailures++;
+ return res.writeHead(500).end();
+ }
const item = b.msg.item_list[0];
state.sent.push({ to: b.msg.to_user_id, text: item.text_item?.text ?? "", contextToken: b.msg.context_token, ...(item.text_item ? {} : { item }) });
+ state.clientIds.push(b.msg.client_id);
return json({ ret: 0 });
}
case "/ilink/bot/getuploadurl": {
@@ -235,10 +249,16 @@ export class FakeFeishu implements FeishuTransport {
if (this.failFinish) throw new Error("finish failed");
this.finished.add(cardId);
}
- async replyText(to: string, text: string) {
- this.calls.push({ op: "text", args: [to, text] });
+ async replyText(to: string, text: string, uuid?: string) {
+ this.calls.push({ op: "text", args: [to, text, uuid] });
this.texts.push(text);
}
+ /** 主动发到会话(使用请求通知、余额提醒) */
+ notices: Array<{ chatId: string; text: string; uuid?: string }> = [];
+ async sendText(chatId: string, text: string, uuid?: string) {
+ this.calls.push({ op: "send", args: [chatId, text, uuid] });
+ this.notices.push({ chatId, text, uuid });
+ }
}
export function feishuEvent(text: string, opts: Partial<FeishuMessageEvent> = {}): FeishuMessageEvent {
diff --git a/test/live-chat.test.ts b/test/live-chat.test.ts
index 4bc307f..72873e8 100644
--- a/test/live-chat.test.ts
+++ b/test/live-chat.test.ts
@@ -224,6 +224,7 @@ describe("网页对话:进行中的消息(纯对话)", () => {
it("/stop:微信等渠道的纯对话也能停(以前只停代理回合)", async () => {
const ev = (id: string, text: string): InboundEvent => ({ id, channel: "weixin", botId: "default", conversation: { kind: "dm", id: "wx-1" }, sender: { id: "wx-1" }, parts: [{ type: "text", text }], replyHandle: {}, receivedAt: Date.now() });
+ app.access.allow("default", "weixin", "wx-1", "test");
const out: string[] = [];
const before = calls.length;
const p = app.runtime.handle(ev("w1", "HOLD 微信"), { apply: async (op: OutboundOp) => void (op.type === "stream.finish" && out.push(op.text)) });
diff --git a/test/outbox.e2e.test.ts b/test/outbox.e2e.test.ts
new file mode 100644
index 0000000..bc7b887
--- /dev/null
+++ b/test/outbox.e2e.test.ts
@@ -0,0 +1,166 @@
+/**
+ * 出站队列端到端:mock iLink + 真实 App。
+ * - 回复发不出去时进程被 kill -9,重启后补发,而且只发一次;
+ * - 同一条入站消息重启后被重复投递:回复的 id 相同,不会再发一遍;
+ * - 重启后发现对方超过 24 小时没说话 / 本轮配额用完:标记 gone,信息面板能看到原因,可以"知道了"。
+ */
+import { describe, it, expect, beforeAll, afterAll, afterEach } from "vitest";
+import { spawn, type ChildProcess } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { DatabaseSync } from "node:sqlite";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { Store } from "../src/store/db.js";
+import { stableId } from "../src/core/outbox.js";
+import { mockIlink, mockOpenAI, until } from "./helpers.js";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const OWNER = "[email protected]";
+let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+let ilink: Awaited<ReturnType<typeof mockIlink>>;
+let dataDir: string;
+let app: App | undefined;
+let child: ChildProcess | undefined;
+
+const dbFile = () => path.join(dataDir, "anymodel.db");
+const config = () =>
+ loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: ilink.url, AMB_WEIXIN_CDN_BASE: ilink.cdnBase, AMB_AGENT: "off" } });
+async function startApp(): Promise<App> {
+ app = new App(config(), { weixinPollTimeoutMs: 2000, printQrToTerminal: false });
+ await app.start();
+ return app;
+}
+async function api(p: string, init: { method?: string; body?: unknown } = {}) {
+ const res = await fetch(app!.web!.url.replace(/\/$/, "") + "/amb/api" + p, {
+ method: init.method ?? "GET",
+ headers: init.body !== undefined ? { "content-type": "application/json" } : {},
+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
+ });
+ return { status: res.status, json: (await res.json().catch(() => ({}))) as any };
+}
+/** 不经 App 读库(子进程还在写时也能读,WAL) */
+function rows(): Array<{ id: string; status: string; attempts: number; error: string; body: string }> {
+ const db = new DatabaseSync(dbFile(), { readOnly: true });
+ try {
+ return db.prepare("SELECT id, status, attempts, error, body FROM outbox ORDER BY seq").all() as any;
+ } finally {
+ db.close();
+ }
+}
+const sentTo = (user: string, text: string) => ilink.state.sent.filter((s) => s.to === user && s.text.includes(text));
+
+beforeAll(async () => {
+ llm = await mockOpenAI({ key: "gw-key" });
+ ilink = await mockIlink();
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-outbox-e2e-"));
+ // 已经扫码登录过:扫码的是 [email protected]
+ const s = new Store(dbFile());
+ s.createBot({ id: "default", name: "我的助手", weixinEnabled: true });
+ s.saveWeixinAccount({ botId: "default", botToken: "tok", ilinkBotId: "[email protected]", baseUrl: ilink.url, ownerUserId: OWNER });
+ s.close();
+});
+
+afterEach(async () => {
+ child?.kill("SIGKILL");
+ child = undefined;
+ await app?.stop();
+ app = undefined;
+});
+
+afterAll(async () => {
+ await llm?.close();
+ await ilink?.close();
+});
+
+describe("出站队列:崩溃与重启", () => {
+ it("回复发不出去时进程被 kill -9:重启后补发,只发一次,再重启也不重发", async () => {
+ ilink.state.sendDown = true;
+ child = spawn(process.execPath, ["--import", "tsx", path.join(root, "test/fixtures/app-child.ts"), dataDir, llm.url, ilink.url, ilink.cdnBase], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
+ let out = "";
+ child.stdout!.on("data", (d) => (out += d));
+ child.stderr!.on("data", (d) => (out += d));
+ await until(() => out.includes("READY"), 30_000, 50);
+
+ ilink.push(OWNER, "崩溃前的问题");
+ await until(() => ilink.state.sendFailures >= 1, 15_000);
+ await until(() => rows().some((r) => r.attempts >= 1), 5000);
+ const [row] = rows();
+ expect(row).toMatchObject({ status: "pending", attempts: 1 });
+ // id 由入站消息推出:同一条入站只有一个最终回复
+ expect(row.id).toMatch(/^wx:default:m\d+:final$/);
+ expect(JSON.parse(row.body).text).toBe("[mock-a] 你说:崩溃前的问题");
+
+ // 崩溃:不给任何收尾的机会
+ const exited = new Promise((r) => child!.once("exit", r));
+ child.kill("SIGKILL");
+ await exited;
+ child = undefined;
+ ilink.state.sendDown = false;
+
+ await startApp();
+ await until(() => sentTo(OWNER, "崩溃前的问题").length >= 1, 10_000);
+ await app!.outbox.idle();
+ await new Promise((r) => setTimeout(r, 300));
+ const got = sentTo(OWNER, "崩溃前的问题");
+ expect(got).toHaveLength(1);
+ expect(ilink.state.clientIds[ilink.state.sent.indexOf(got[0])]).toBe(`amb:${stableId(row.id, 0)}`);
+ expect(app!.store.getOutbox(row.id)).toMatchObject({ status: "sent", attempts: 1 });
+
+ await app!.stop();
+ await startApp();
+ await new Promise((r) => setTimeout(r, 500));
+ await app!.outbox.idle();
+ expect(sentTo(OWNER, "崩溃前的问题")).toHaveLength(1);
+ }, 60_000);
+
+ it("同一条入站消息在重启后又被投递:模型可能再答一遍,但用户只收到一次回复", async () => {
+ await startApp();
+ const msg = { seq: 900, message_id: "dup-1", from_user_id: OWNER, to_user_id: "[email protected]", create_time_ms: Date.now(), message_type: 1, message_state: 2, context_token: "ctx-1", item_list: [{ type: 1, text_item: { text: "只答一次" } }] };
+ ilink.state.inbox.push(msg);
+ await until(() => sentTo(OWNER, "只答一次").length >= 1, 8000);
+ await app!.stop();
+ const calls = llm.calls.length;
+ await startApp();
+ ilink.state.inbox.push({ ...msg });
+ await until(() => llm.calls.length > calls, 8000);
+ await app!.channels.get("default")!.weixin!.idle();
+ await new Promise((r) => setTimeout(r, 300));
+ expect(sentTo(OWNER, "只答一次")).toHaveLength(1);
+ });
+
+ it("重启后对方的 24 小时窗口已过 / 配额已用完:标记 gone,信息面板能看到原因,可以「知道了」", async () => {
+ await startApp();
+ ilink.state.sendDown = true;
+ ilink.push(OWNER, "过期测试");
+ await until(() => rows().some((r) => JSON.parse(r.body).text?.includes("过期测试") && r.attempts >= 1), 8000);
+ app!.access.allow("default", "weixin", "[email protected]", "test");
+ await app!.stop();
+ // 关机期间:主人的窗口过了 24 小时;朋友那边还有一条没发出去的回复,而他这一轮的配额已经用完
+ const s = new Store(dbFile());
+ const owner = s.getWeixinPeer("default", OWNER)!;
+ s.upsertWeixinPeer({ ...owner, windowStartedAt: Date.now() - 25 * 3600_000 });
+ s.upsertWeixinPeer({ botId: "default", userId: "[email protected]", contextToken: "ctx-f", quotaRemaining: 0, windowStartedAt: Date.now() });
+ s.insertOutbox({ id: "wx:default:test-quota:0", botId: "default", channel: "weixin", conversationId: "default:weixin:[email protected]", peerId: "[email protected]", kind: "text", body: { text: "配额测试的回复" }, replyTo: "", due: Date.now(), createdAt: Date.now(), expiresAt: Date.now() + 3600_000 });
+ s.close();
+ ilink.state.sendDown = false;
+
+ await startApp();
+ await until(() => rows().filter((r) => r.status === "gone").length >= 2, 8000);
+ const box = await api("/bots/default/outbox");
+ const reasons = box.json.failed.map((f: any) => [f.to, f.preview, f.error]);
+ expect(reasons).toEqual(
+ expect.arrayContaining([
+ ["微信主人", "[mock-a] 你说:过期测试", expect.stringMatching(/超过 24 小时/)],
+ ["微信用户 friend", "配额测试的回复", expect.stringMatching(/本轮可发送条数已用完/)],
+ ]),
+ );
+ expect(sentTo(OWNER, "过期测试")).toHaveLength(0);
+ // 状态里也记了一笔
+ expect((await api("/status")).json.notices.some((n: any) => n.text.includes("没能发出去"))).toBe(true);
+ for (const f of box.json.failed) expect((await api(`/bots/default/outbox/${encodeURIComponent(f.id)}/dismiss`, { method: "POST", body: {} })).status).toBe(200);
+ expect((await api("/bots/default/outbox")).json.failed).toEqual([]);
+ });
+});
diff --git a/test/outbox.unit.test.ts b/test/outbox.unit.test.ts
new file mode 100644
index 0000000..9ab8996
--- /dev/null
+++ b/test/outbox.unit.test.ts
@@ -0,0 +1,213 @@
+/**
+ * 出站队列:先落库再发、同一 id 只发一次、按会话排队、退避重试、Later 不计失败、Gone 记下原因、过期、重启后接着发。
+ * 以及微信 / 飞书的发送函数(配额、24 小时窗口、分段续发、卡片降级)。
+ */
+import { describe, it, expect } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { Store, type OutboxRow } from "../src/store/db.js";
+import { Gone, Later, Outbox, REJECTIONS_BEFORE_GONE, stableId } from "../src/core/outbox.js";
+import { deliverWeixin } from "../src/channels/weixin/channel.js";
+import { WeixinQuota } from "../src/channels/weixin/quota.js";
+import { deliverFeishu } from "../src/channels/feishu/card.js";
+import { FakeFeishu, until } from "./helpers.js";
+
+const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "amb-outbox-"));
+const input = (id: string, text: string, peerId = "u1") => ({ id, botId: "b", channel: "weixin" as const, peerId, kind: "text" as const, body: { text } });
+
+describe("Outbox", () => {
+ it("writes before sending, sends once per id, keeps per-conversation order", async () => {
+ const store = new Store(":memory:");
+ const ob = new Outbox(store);
+ const sent: string[] = [];
+ let release: (() => void) | undefined;
+ ob.register("b", "weixin", async (row) => {
+ if (row.body.text === "slow") await new Promise<void>((r) => (release = r));
+ sent.push(`${row.peerId}:${row.body.text}`);
+ });
+ ob.start();
+ const first = ob.send(input("a", "slow"));
+ await until(() => !!release);
+ expect(store.getOutbox("a")!.status).toBe("pending");
+ // 同一会话:排在 slow 后面;别的会话不受影响
+ await ob.send(input("b", "second"));
+ await ob.send(input("c", "other", "u2"));
+ expect(sent).toEqual(["u2:other"]);
+ release!();
+ await first;
+ await ob.idle();
+ expect(sent).toEqual(["u2:other", "u1:slow", "u1:second"]);
+ // 同一 id 再写一遍:不再发
+ await ob.send(input("a", "slow"));
+ await ob.idle();
+ expect(sent).toHaveLength(3);
+ expect(store.getOutbox("a")).toMatchObject({ status: "sent", attempts: 0 });
+ });
+
+ it("transient failures back off and retry; a failing head holds back the rest of its conversation", async () => {
+ const store = new Store(":memory:");
+ const ob = new Outbox(store, { retry: [30, 200] });
+ let fails = 2;
+ const sent: string[] = [];
+ ob.register("b", "weixin", async (row) => {
+ if (row.body.text === "x" && fails-- > 0) throw new Error("ECONNRESET");
+ sent.push(row.body.text!);
+ });
+ ob.start();
+ const r = await ob.send(input("x", "x"));
+ expect(r).toMatchObject({ status: "pending", attempts: 1, error: "ECONNRESET" });
+ await ob.send(input("y", "y"));
+ expect(sent).toEqual([]);
+ await until(() => sent.length === 2, 3000);
+ expect(sent).toEqual(["x", "y"]);
+ expect(store.getOutbox("x")).toMatchObject({ status: "sent", attempts: 2, error: "" });
+ });
+
+ it("Later waits without counting; Gone and repeated rejections are kept with the reason", async () => {
+ const store = new Store(":memory:");
+ const ob = new Outbox(store, { retry: [20, 40] });
+ const gone: OutboxRow[] = [];
+ ob.onGone = (r) => gone.push(r);
+ let later = 3;
+ ob.register("b", "weixin", async (row) => {
+ if (row.body.text === "later" && later-- > 0) throw new Later("渠道没上线");
+ if (row.body.text === "gone") throw new Gone("本轮可发送条数已用完");
+ if (row.body.text === "rejected") throw Object.assign(new Error("sendmessage ret=-2"), { rejected: true });
+ });
+ ob.start();
+ await ob.send(input("l", "later"));
+ await ob.send(input("g", "gone", "u2"));
+ await ob.send(input("r", "rejected", "u3"));
+ await until(() => store.getOutbox("l")!.status === "sent" && store.getOutbox("r")!.status === "gone", 5000);
+ expect(store.getOutbox("l")!.attempts).toBe(0);
+ expect(store.getOutbox("g")).toMatchObject({ status: "gone", error: "本轮可发送条数已用完" });
+ expect(store.getOutbox("r")).toMatchObject({ status: "gone", attempts: REJECTIONS_BEFORE_GONE - 1 });
+ expect(store.getOutbox("r")!.error).toContain("ret=-2");
+ expect(gone.map((r) => r.id).sort()).toEqual(["g", "r"]);
+ // 界面"知道了"
+ expect(ob.dismiss("g")).toBe(true);
+ expect(store.listOutbox({ botId: "b", status: "gone", dismissed: false }).map((r) => r.id)).toEqual(["r"]);
+ });
+
+ it("waits for the channel to register; expired messages are marked gone and the next one goes", async () => {
+ let now = 1_000_000;
+ const store = new Store(":memory:");
+ const ob = new Outbox(store, { now: () => now });
+ ob.start();
+ await ob.send({ ...input("old", "过期的", "u1"), ttlMs: 1000 });
+ await ob.send(input("new", "新的", "u1"));
+ expect(store.getOutbox("old")!.status).toBe("pending");
+ now += 2000;
+ const sent: string[] = [];
+ ob.register("b", "weixin", async (row) => void sent.push(row.body.text!));
+ await ob.idle();
+ await until(() => sent.length === 1);
+ expect(store.getOutbox("old")!.status).toBe("gone");
+ expect(store.getOutbox("old")!.error).toMatch(/等待太久/);
+ expect(sent).toEqual(["新的"]);
+ });
+
+ it("survives a restart: unsent messages resume from their progress, sent ones are not repeated", async () => {
+ const file = path.join(tmp(), "o.db");
+ let store = new Store(file);
+ let ob = new Outbox(store, { retry: [60_000, 60_000] });
+ const got: string[] = [];
+ ob.register("b", "weixin", async (row, progress) => {
+ // 第一段发出去了,第二段时"断网"
+ got.push(`${row.body.text}#${row.progress}`);
+ progress(1);
+ throw new Error("socket hang up");
+ });
+ ob.start();
+ await ob.send(input("m1", "长回复"));
+ await ob.stop();
+ store.close();
+ // 重启:等着退避的马上再试,从第 2 段接着发
+ store = new Store(file);
+ ob = new Outbox(store, { retry: [60_000, 60_000] });
+ ob.register("b", "weixin", async (row) => void got.push(`${row.body.text}#${row.progress}`));
+ ob.start();
+ await ob.idle();
+ await until(() => store.getOutbox("m1")!.status === "sent");
+ expect(got).toEqual(["长回复#0", "长回复#1"]);
+ await ob.stop();
+ store.close();
+ store = new Store(file);
+ ob = new Outbox(store);
+ ob.register("b", "weixin", async () => void got.push("again"));
+ ob.start();
+ await ob.idle();
+ expect(got).toHaveLength(2);
+ store.close();
+ });
+});
+
+describe("deliverWeixin", () => {
+ const setup = (quotaRemaining = 10, ageMs = 0) => {
+ const store = new Store(":memory:");
+ store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining, windowStartedAt: Date.now() - ageMs });
+ const sent: Array<{ text: string; clientId?: string }> = [];
+ let failAt = -1;
+ const client = {
+ sendText: async (_u: string, text: string, _ctx: string, clientId?: string) => {
+ if (sent.length === failAt) throw new Error("fetch failed");
+ sent.push({ text, clientId });
+ },
+ } as any;
+ const quota = new WeixinQuota(store, "b");
+ const row = (text: string, progress = 0) => ({ id: "wx:b:m1:0", peerId: "u1", kind: "text", body: { text }, progress, attempts: 0 }) as OutboxRow;
+ return { store, sent, client, quota, row, fail: (n: number) => (failAt = n) };
+ };
+
+ it("splits long text, consumes quota only for what was sent, resumes from progress with the same client ids", async () => {
+ const { sent, client, quota, row, fail } = setup();
+ const text = "甲".repeat(3990) + "\n\n" + "乙".repeat(3990) + "\n\n" + "丙".repeat(100);
+ fail(1);
+ let progress = 0;
+ await expect(deliverWeixin(client, quota, row(text), (n) => (progress = n))).rejects.toThrow("fetch failed");
+ expect(progress).toBe(1);
+ expect(quota.remaining("u1")).toBe(9);
+ fail(-1);
+ await deliverWeixin(client, quota, row(text, progress), (n) => (progress = n));
+ expect(sent.map((s) => s.text[0])).toEqual(["甲", "乙", "丙"]);
+ expect(sent.map((s) => s.clientId)).toEqual([0, 1, 2].map((i) => stableId("wx:b:m1:0", i)));
+ expect(quota.remaining("u1")).toBe(7);
+ });
+
+ it("too little quota: truncates with a note; none left or the 24h window passed: gone with the reason", async () => {
+ const a = setup(1);
+ await deliverWeixin(a.client, a.quota, a.row("x".repeat(5000)), () => {});
+ expect(a.sent).toHaveLength(1);
+ expect(a.sent[0].text).toMatch(/已达到本轮可发送条数上限/);
+ await expect(deliverWeixin(a.client, a.quota, a.row("再来一条"), () => {})).rejects.toThrow(/本轮可发送条数已用完/);
+ const b = setup(10, 25 * 3600_000);
+ await expect(deliverWeixin(b.client, b.quota, b.row("晚了"), () => {})).rejects.toBeInstanceOf(Gone);
+ await expect(deliverWeixin(b.client, b.quota, b.row("晚了"), () => {})).rejects.toThrow(/超过 24 小时/);
+ expect(b.sent).toEqual([]);
+ });
+});
+
+describe("deliverFeishu", () => {
+ const row = (over: Partial<OutboxRow>) => ({ id: "fs:b:om_1:0", peerId: "oc_1", replyTo: "om_1", kind: "text", body: {}, progress: 0, attempts: 0, ...over }) as OutboxRow;
+
+ it("final reply goes into the streaming card; a retry after failure falls back to a text reply with a stable uuid", async () => {
+ const t = new FakeFeishu();
+ await deliverFeishu(t, row({ body: { text: "最终", cardId: "card1", cardSeq: 5 } }), () => {});
+ expect(t.calls.map((c) => [c.op, c.args[3] ?? c.args[1]])).toEqual([["update", 5], ["finish", 6]]);
+ expect(t.texts).toEqual([]);
+ const t2 = new FakeFeishu();
+ await deliverFeishu(t2, row({ body: { text: "最终", cardId: "card1", cardSeq: 5 }, attempts: 1 }), () => {});
+ expect(t2.calls.filter((c) => c.op !== "text")).toEqual([]);
+ expect(t2.calls[0].args).toEqual(["om_1", "最终", stableId("fs:b:om_1:0", 0)]);
+ });
+
+ it("notices go to the chat; a transport without proactive sends marks them gone", async () => {
+ const t = new FakeFeishu();
+ await deliverFeishu(t, row({ kind: "notice", body: { text: "有人想使用机器人" } }), () => {});
+ expect(t.notices).toEqual([{ chatId: "oc_1", text: "有人想使用机器人", uuid: stableId("fs:b:om_1:0", 0) }]);
+ const bare = new FakeFeishu() as any;
+ bare.sendText = undefined;
+ await expect(deliverFeishu(bare, row({ kind: "notice", body: { text: "x" } }), () => {})).rejects.toBeInstanceOf(Gone);
+ });
+});
diff --git a/test/recovery.test.ts b/test/recovery.test.ts
index c48d92b..c249da4 100644
--- a/test/recovery.test.ts
+++ b/test/recovery.test.ts
@@ -145,6 +145,8 @@ describe("App 启动时告诉用户", () => {
env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: ilink.url, AMB_WEIXIN_CDN_BASE: ilink.cdnBase, AMB_AGENT: "off" },
});
app = new App(config, { feishuTransport: () => feishu, weixinPollTimeoutMs: 1000, printQrToTerminal: false, noWeb: true });
+ // 只有主人和允许名单里的人能用:bob 上次就在用(这里的库是直接造的,没有经过升级迁移)
+ app.access.allow("default", "weixin", "[email protected]", "test");
await app.start();
});