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.

Phase 3c: delivery and attention budget

Marla332157bb582b
diff --git a/dsh-runtime/plugins/amb-tasks.mjs b/dsh-runtime/plugins/amb-tasks.mjs
index a2c322d..b54e2c7 100644
--- a/dsh-runtime/plugins/amb-tasks.mjs
+++ b/dsh-runtime/plugins/amb-tasks.mjs
@@ -86,6 +86,7 @@ export function apply(ctx) {
parameters: {
title: { type: 'string', required: true, description: 'Short title in the user\'s language.' },
brief: { type: 'string', required: true, description: 'What to do and what result to give, at most 1,500 characters. The user\'s words and the recent chat are added automatically.' },
+ anytime: { type: 'boolean', description: 'true only when the user asked to be told the moment it is done, even at night. Otherwise a result that is ready during their quiet hours waits until morning.' },
},
output: TEXT_OUT,
execute: tool('start'),
diff --git a/src/agent/settings.ts b/src/agent/settings.ts
index 3c85bdd..0ca9336 100644
--- a/src/agent/settings.ts
+++ b/src/agent/settings.ts
@@ -1,4 +1,5 @@
/** 每个机器人的身份与行为设置(存在 bots.settings JSON 列,网页可编辑)。 */
+import { DEFAULT_QUIET, minuteOf, type QuietHours } from "../core/quiet.js";
export type PermissionPreset = "readonly" | "workspace" | "full";
export type CuBackend = "cua" | "codex";
export type CuApproval = "auto" | "ask-input";
@@ -48,6 +49,10 @@ export interface BotSettings {
budget: { enabled: boolean; limitUsd: number };
/** 后台任务最多同时跑几个(聊天不占名额;见 tasks/slots.ts) */
taskSlots: number;
+ /** 免打扰(主人的时区):期间的后台结果、规则命中排到结束再发;聊天回复不受影响(core/delivery.ts) */
+ quietHours: QuietHours;
+ /** 微信续期提醒:24 小时窗口快关时,还有消息要发就请用户回一句 */
+ nudge: boolean;
}
export const DEFAULT_SETTINGS: BotSettings = {
@@ -60,6 +65,8 @@ export const DEFAULT_SETTINGS: BotSettings = {
avatar: "",
budget: { enabled: false, limitUsd: 5 },
taskSlots: 2,
+ quietHours: { ...DEFAULT_QUIET },
+ nudge: true,
};
export function normalizeSettings(raw: unknown): BotSettings {
@@ -69,6 +76,7 @@ export function normalizeSettings(raw: unknown): BotSettings {
const cu = r.computerUse && typeof r.computerUse === "object" ? r.computerUse : {};
const bg = r.budget && typeof r.budget === "object" ? r.budget : {};
const md = r.media && typeof r.media === "object" ? r.media : {};
+ const qh = r.quietHours && typeof r.quietHours === "object" ? r.quietHours : {};
const limit = Number(bg.limitUsd);
const slots = Number(r.taskSlots);
const b = (v: unknown, d: boolean) => (typeof v === "boolean" ? v : d);
@@ -95,6 +103,12 @@ export function normalizeSettings(raw: unknown): BotSettings {
limitUsd: Number.isFinite(limit) && limit >= 0 && limit <= 100_000 ? Math.round(limit * 100) / 100 : DEFAULT_SETTINGS.budget.limitUsd,
},
taskSlots: Number.isInteger(slots) && slots >= 1 && slots <= 8 ? slots : DEFAULT_SETTINGS.taskSlots,
+ quietHours: {
+ enabled: b(qh.enabled, DEFAULT_QUIET.enabled),
+ from: typeof qh.from === "string" && minuteOf(qh.from) !== undefined ? qh.from : DEFAULT_QUIET.from,
+ to: typeof qh.to === "string" && minuteOf(qh.to) !== undefined ? qh.to : DEFAULT_QUIET.to,
+ },
+ nudge: b(r.nudge, DEFAULT_SETTINGS.nudge),
};
}
diff --git a/src/app.ts b/src/app.ts
index 5587d81..c4b72b3 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -8,6 +8,7 @@ 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 { Delivery, type DeliveryOptions } from "./core/delivery.js";
import { AccessControl } from "./core/access.js";
import type { ChannelStatus } from "./core/types.js";
import { MagpieSupervisor } from "./magpie/supervisor.js";
@@ -43,7 +44,7 @@ import { MediaService, pickDefault } from "./agent/media.js";
import { COMPACT_ENDPOINT, serverCompactionEnabled, type CompactEndpoint } from "./agent/server-compaction.js";
import type { BotSettings } from "./agent/settings.js";
import { TaskService } from "./tasks/service.js";
-import { Attention, approvalItems, type AttentionItem } from "./tasks/attention.js";
+import { Attention, approvalItems, deliveryItem, type AttentionItem } from "./tasks/attention.js";
const log = logger("app");
@@ -98,6 +99,10 @@ export interface AppOptions {
printQrToTerminal?: boolean;
/** 写 <dataDir>/logs/app.log(默认 true) */
fileLog?: boolean;
+ /** 测试注入:主人的时区(免打扰、续期提醒;默认本机的) */
+ timeZone?: string;
+ /** 测试注入:主动消息的每天上限、合并间隔(core/delivery.ts) */
+ deliveryLimits?: Pick<DeliveryOptions, "dailyCap" | "coalesceMs">;
}
interface BotChannels {
@@ -117,6 +122,11 @@ export class App {
readonly channels = new Map<string, BotChannels>();
/** 持久化的出站队列:最终回复、文件、重要通知先落库再发,重启后接着发 */
readonly outbox: Outbox;
+ /**
+ * 主动消息的送达规则:免打扰、合并与摘要、每天上限、微信配额预留和续期提醒;没送到的进「需要你」(attentionItems)。
+ * 3b / 3d 经它登记占配额的东西和之后要发的东西
+ */
+ readonly delivery: Delivery;
/** 谁能和机器人对话:主人 + 允许名单 + 使用请求 */
readonly access: AccessControl;
/** 后台任务:自己的会话和文件夹,结果经出站队列回到请求它的会话 */
@@ -155,6 +165,7 @@ export class App {
});
this.store = new Store(path.join(config.dataDir, "anymodel.db"));
this.outbox = new Outbox(this.store);
+ this.delivery = new Delivery({ store: this.store, outbox: this.outbox, timeZone: opts.timeZone, ...opts.deliveryLimits });
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 });
@@ -217,7 +228,7 @@ export class App {
this.tasks = new TaskService({
store: this.store,
host: this.agent.taskHost(),
- outbox: this.outbox,
+ delivery: this.delivery,
approvals: this.agent.approvals,
onChange: () => this.attention.kick(),
defaultModel: () => this.config.llm.defaultModel,
@@ -225,11 +236,14 @@ export class App {
maxBackground: config.agent.maxBackground,
});
this.agent.tasks = this.tasks;
- // "需要你"的三份:在等的提问和审批、任务(失败、没送到)、渠道(微信登录过期)
+ // "需要你"的四份:在等的提问和审批、任务(失败、预算)、没送到的结果(出站队列)、渠道(微信登录过期)
this.attention.addSource(() => approvalItems(this.store, this.agent.approvals.pendingAll()));
this.attention.addSource(() => this.tasks.attention());
+ this.attention.addSource(() => this.delivery.attentionItems().map((d) => deliveryItem(d, this.store.getBot(d.botId)?.name ?? d.botId)));
this.attention.addSource(() => this.loginAttention());
this.agent.approvals.listen(() => this.attention.kick());
+ // 出站队列的变化(结果留着等微信、发出去了、放弃了):任务的"未送达"随之出现、消失
+ this.delivery.onChange(() => this.attention.kick());
this.runtime = new BotRuntime({
agent: this.agent,
store: this.store,
@@ -474,6 +488,7 @@ export class App {
const interrupted = takeInterrupted(this.store);
// 出站队列先开:渠道上线时登记发送函数,上次没发完的消息接着发
this.outbox.start();
+ this.delivery.start();
for (const bot of this.store.listBots()) await this.startBot(bot.id);
if (interrupted.length) void this.tellInterrupted(interrupted);
// 后台任务:上次没跑完的记为中断、带着恢复说明接着做(渠道已经上线,结果能发出去)
@@ -544,6 +559,7 @@ export class App {
this.account?.cancelLogin();
await this.web?.close();
// 不再开始新的发送,等正在发的结束;没发完的留在库里,下次启动接着发
+ this.delivery.stop();
await this.outbox.stop();
for (const id of [...this.channels.keys()]) await this.stopBot(id);
await this.agent.stop();
@@ -655,6 +671,7 @@ export class App {
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, this.outbox);
+ ch.feishu.delivery = this.delivery;
// 代理自己醒来的一轮(后台命令结束):经出站队列回复到这个会话最近收到的那条消息
const fs = ch.feishu;
this.runtime.registerReplier(bot.id, "feishu", (conv, handle, key) => (handle?.messageId ? { out: fs.followUp(conv.peerId, handle.messageId, key) } : undefined));
@@ -671,6 +688,7 @@ export class App {
cdnBaseUrl: this.config.weixin.cdnBaseUrl,
pollTimeoutMs: this.opts.weixinPollTimeoutMs,
outbox: this.outbox,
+ delivery: this.delivery,
});
ch.weixin.onExpired = () => {
this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在信息面板的「渠道」里重新扫码`);
diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.ts
index 93b586f..441272a 100644
--- a/src/channels/feishu/channel.ts
+++ b/src/channels/feishu/channel.ts
@@ -4,6 +4,7 @@ import type { BotRuntime } from "../../core/runtime.js";
import type { FeishuMessageEvent, FeishuTransport } from "./transport.js";
import { FeishuReply, deliverFeishu } from "./card.js";
import { Outbox, stableId } from "../../core/outbox.js";
+import type { Delivery } from "../../core/delivery.js";
import type { Store } from "../../store/db.js";
import { logger } from "../../log.js";
@@ -58,6 +59,8 @@ export class FeishuChannel {
readonly pending = new Set<Promise<void>>();
/** 出站队列(App 共用一个;没给时用内存库自己建一个) */
readonly outbox: Outbox;
+ /** 主动消息的送达规则(App 设):对方发消息时,排着的主动消息先发,合成一条摘要 */
+ delivery: Delivery | undefined;
private unregister: (() => void) | undefined;
constructor(
@@ -112,6 +115,9 @@ export class FeishuChannel {
replyHandle: { messageId: ev.messageId, chatId: ev.chatId },
receivedAt: Date.now(),
};
+ // 人在:排着的主动消息(免打扰、每天上限)不用再等,排在这次的回复前面
+ const delivery = this.delivery;
+ if (delivery) this.outbox.release(this.botId, "feishu", ev.chatId, (rows) => delivery.combine(rows));
// 审批/提问回复在入队前处理(正在进行的回合正等着它)
// 没处理掉但带 ack 的(前一条还在处理):先说一声,消息照常入队
const intercepted = this.runtime.interceptReply(inbound);
diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.ts
index 6d02d50..3bff4c7 100644
--- a/src/channels/weixin/channel.ts
+++ b/src/channels/weixin/channel.ts
@@ -8,6 +8,7 @@ import { Gone, Held, Later, Outbox, ReplyIds, stableId, type HeldGroup } from ".
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";
+import type { Delivery } from "../../core/delivery.js";
import { logger } from "../../log.js";
export const WEIXIN_CAPS: ChannelCapabilities = {
@@ -87,12 +88,21 @@ function transient(e: unknown): boolean {
return !(x?.syscall && ["open", "read", "stat", "scandir"].includes(x.syscall));
}
+/**
+ * 这条能用几条配额:主动消息(任务结果、续期提醒…)用全部剩下的;聊天回复要给主动消息留出 reserved 条(core/delivery.ts)
+ */
+function budgetOf(quota: WeixinQuota, userId: string, row: Pick<OutboxRow, "purpose">): number {
+ const left = quota.remaining(userId);
+ return row.purpose ? left : left - quota.reserved(userId);
+}
+
/** 能不能给这个人发:要有会话凭证、24 小时窗口没过、还有配额;不能就留着(Held),等他下次发消息;返回凭证 */
-function reachable(quota: WeixinQuota, userId: string): string {
+function reachable(quota: WeixinQuota, userId: string, row: Pick<OutboxRow, "purpose">): string {
const peer = quota.peer(userId);
- if (!peer?.contextToken) throw new Held("对方还没有给机器人发过消息,等他发消息后再发");
- if (!quota.open(userId)) throw new Held("对方超过 24 小时没有发消息,等他下次发消息时再发");
- if (quota.remaining(userId) <= 0) throw new Held("本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条),等他下次发消息时再发");
+ if (!peer?.contextToken) throw new Held("对方还没有给机器人发过消息,等他发消息后再发", "no_token");
+ if (!quota.open(userId)) throw new Held("对方超过 24 小时没有发消息,等他下次发消息时再发", "window_closed");
+ if (quota.remaining(userId) <= 0) throw new Held("本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条),等他下次发消息时再发", "quota");
+ if (budgetOf(quota, userId, row) <= 0) throw new Held("本轮剩下的条数留给后台任务的结果了,等他下次发消息时再发", "quota");
return peer.contextToken;
}
@@ -135,7 +145,7 @@ export function combineHeld(rows: OutboxRow[]): HeldGroup[] {
*/
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);
+ const token = reachable(quota, user, row);
if (row.kind === "file") {
const name = row.body.name ?? "文件";
if (row.progress === 0) {
@@ -157,7 +167,7 @@ export async function deliverWeixin(client: IlinkClient, quota: WeixinQuota, row
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);
+ const budget = budgetOf(quota, user, row);
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;
@@ -297,9 +307,12 @@ 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; outbox?: Outbox } = {},
+ private opts: { fetchImpl?: typeof fetch; cdnBaseUrl?: string; pollTimeoutMs?: number; retryDelayMs?: number; backoffMs?: number; outbox?: Outbox; delivery?: Delivery } = {},
) {
this.quota = new WeixinQuota(store, botId);
+ // 聊天回复给主动消息(进行中的任务的结果等)留出配额
+ const delivery = opts.delivery;
+ if (delivery) this.quota.reserver = (userId) => delivery.reserved(botId, "weixin", userId);
if (opts.outbox) this.outbox = opts.outbox;
else {
this.outbox = new Outbox(store);
@@ -427,9 +440,14 @@ export class WeixinChannel {
const id = String(m.message_id ?? m.client_id ?? `${m.from_user_id}:${m.seq}:${m.create_time_ms}`);
if (!this.dedup.firstSeen(id)) return;
const userId = m.from_user_id;
+ const delivery = this.opts.delivery;
+ // 回的是续期提醒(「ok」):先认出来(之后放出留着的消息,最近发的一条就不是提醒了)
+ const said = weixinParts(m.item_list).map((p) => (p.type === "text" ? p.text : "")).join("").trim();
+ const ack = said ? delivery?.ack(this.botId, "weixin", userId, said) : undefined;
const peer = this.quota.onInbound(userId, m.context_token ?? "");
- // 对方又发消息了(24 小时窗口和配额重新开始):之前留着没发的先发,合成「你不在时:…」,排在这次的回复前面
- this.outbox.release(this.botId, "weixin", userId, combineHeld);
+ // 对方又发消息了(24 小时窗口和配额重新开始):之前留着没发的、排着的主动消息先发,合成一条(「你不在时:…」或摘要),排在这次的回复前面
+ const released = this.outbox.release(this.botId, "weixin", userId, (rows) => (delivery ? delivery.combine(rows) : combineHeld(rows)));
+ if (ack) return this.acked(id, userId, peer.contextToken, said, released ? "" : ack);
const ev: InboundEvent = {
id,
channel: "weixin",
@@ -465,6 +483,20 @@ export class WeixinChannel {
void p.finally(() => this.pending.delete(p));
}
+ /**
+ * 对方回了续期提醒(「ok」):窗口已经重新开始,不进模型;记进会话历史,回一句(留着的消息刚放出去时它们就是回应,不再多说)
+ */
+ private acked(id: string, userId: string, contextToken: string, said: string, text: string): void {
+ const conv = this.store.ensureConversation(this.botId, "weixin", userId);
+ this.store.addMessage(conv.id, "user", said);
+ if (!text) return;
+ this.store.addMessage(conv.id, "assistant", text);
+ const reply = new WeixinReply(this.client!, userId, contextToken, this.quota, { outbox: this.outbox, botId: this.botId, key: `${id}:ack` });
+ const p = reply.apply({ type: "text", text }).catch((e) => this.log.warn("nudge ack failed", { message: (e as Error).message }));
+ this.pending.add(p);
+ void p.finally(() => this.pending.delete(p));
+ }
+
/** 逐个下载解密;失败的记下原因(消息照常处理,文字里会说明没下载成功) */
private async download(items: MessageItem[]): Promise<WeixinMediaResults> {
const out: WeixinMediaResults = new Map();
diff --git a/src/channels/weixin/quota.ts b/src/channels/weixin/quota.ts
index f1c0938..ba8c38f 100644
--- a/src/channels/weixin/quota.ts
+++ b/src/channels/weixin/quota.ts
@@ -8,8 +8,19 @@ export const QUOTA_PER_INBOUND = 10;
export const QUOTA_WINDOW_MS = 24 * 3600_000;
export class WeixinQuota {
+ /** 现在要给主动消息(任务结果等)留几条:聊天回复只能用 remaining − reserved(core/delivery.ts 设) */
+ reserver: ((userId: string) => number) | undefined;
+
constructor(private store: Store, private botId: string, private now: () => number = Date.now) {}
+ reserved(userId: string): number {
+ try {
+ return Math.max(0, this.reserver?.(userId) ?? 0);
+ } catch {
+ return 0;
+ }
+ }
+
onInbound(userId: string, contextToken: string): WeixinPeer {
const peer: WeixinPeer = {
botId: this.botId,
diff --git a/src/core/delivery.ts b/src/core/delivery.ts
new file mode 100644
index 0000000..9faae72
--- /dev/null
+++ b/src/core/delivery.ts
@@ -0,0 +1,530 @@
+/**
+ * 主动消息的送达规则(设计文档第 6 节「Transparency without noise」、决定 4 和 8)。机制在 outbox.ts,这里只定规则:
+ *
+ * - 免打扰(默认 22:00–08:00,主人的时区,每个机器人可关、可改时段):任务结果、失败、规则命中排到时段结束再发;
+ * 用户 10 分钟内刚发过消息(人醒着)或任务、规则要求马上告诉(anytime)时不拦。聊天里的回复从不推迟。
+ * - 合并:上一条主动消息发出不到 2 分钟时,新的排到 2 分钟后;同一时间到期的合成一条摘要,一项一行。
+ * - 每天上限(每个机器人每个会话):微信 3 条、飞书 5 条;超出的排到下一个早上,合成一条摘要。
+ * - 对方发消息时,留着的和排着的先发(outbox.release),排在这次的回复前面。
+ * - 微信配额预留:进行中的任务、排着的主动消息(以及 3b 的待答问题、3d 的执行中规则)各留 1 条,最多 3 条;
+ * 聊天回复只能用剩下的(deliverWeixin)。
+ * - 微信续期提醒:24 小时窗口关闭前约 2 小时,窗口关闭后还有东西要发给这个人时,发一句「回个 ok」;
+ * 每个窗口最多一次,免打扰时不发,用掉 10 条里的 1 条,可按机器人关掉;没有要发的就不发。
+ * - 没送到的(微信要对方先发消息、一直失败、放弃了)是「需要你」里的一项(attentionItems),原因没了就自己消失。
+ *
+ * 给 3b / 3d 的接口:addReserver(占配额)、addUpcoming(续期提醒里列出要来的规则)、attentionItems / act / onChange。
+ */
+import path from "node:path";
+import type { BotSettings } from "../agent/settings.js";
+import type { OutboxKind, OutboxPurpose, OutboxRow, Store } from "../store/db.js";
+import type { HeldGroup, Outbox } from "./outbox.js";
+import { DEFAULT_QUIET, fmtWhen, inQuiet, minuteOf, nextAt, quietEnd, quietStart, startOfDay, systemTimeZone, type QuietHours } from "./quiet.js";
+import { QUOTA_WINDOW_MS, WeixinQuota } from "../channels/weixin/quota.js";
+import { combineHeld, filterMarkdown } from "../channels/weixin/channel.js";
+import { logger } from "../log.js";
+
+const log = logger("delivery");
+
+/** 上一条主动消息发出不到这么久,新的就等到这时再发(期间来的合成一条) */
+export const COALESCE_MS = 2 * 60_000;
+/** 每个机器人每个会话每天最多几条主动消息;超出的合成一条摘要,排到下一个早上 */
+export const DAILY_CAP: Readonly<Record<string, number>> = { weixin: 3, feishu: 5 };
+/** 微信:给主动消息留的配额最多几条 */
+export const MAX_RESERVED = 3;
+/** 用户这么久之内发过消息:人醒着,免打扰不拦 */
+export const AWAKE_MS = 10 * 60_000;
+/** 续期提醒:窗口关闭前多久 */
+export const NUDGE_BEFORE_MS = 2 * 3600_000;
+/** 离窗口关闭不到这么久就不提醒了(来不及回) */
+export const NUDGE_LATEST_MS = 10 * 60_000;
+/** 续期提醒最长隔多久看一次 */
+const NUDGE_TICK_MS = 15 * 60_000;
+/** 「需要你」:试了这么多次还没发出去就算 */
+export const FAILS_FOR_ATTENTION = 3;
+/** 放弃了的、没处理掉的,在「需要你」里留多久 */
+const GONE_SHOWN_MS = 7 * 86400_000;
+/** 摘要一条最长多少字(微信一条 4000 字,留余地) */
+const DIGEST_MAX = 3500;
+
+/** 主动推送的用途(续期提醒由这里自己发) */
+export type PushPurpose = Exclude<OutboxPurpose, "" | "nudge">;
+
+export interface PushInput {
+ /** 确定的 id(同一 id 只发一次),如 task:<任务>:result:<run> */
+ id: string;
+ botId: string;
+ channel: "weixin" | "feishu";
+ /** 微信:用户 id;飞书:chat_id */
+ peerId: string;
+ purpose: PushPurpose;
+ /** 是什么:任务标题、规则名(摘要、续期提醒、「需要你」里用) */
+ subject: string;
+ /** 一句话(设计里的消息样式:一行,细节按需) */
+ text: string;
+ /** 跟在后面的文件 */
+ files?: string[];
+ /** 飞书:回复在哪条消息下;kind = notice 时直接发到会话 */
+ replyTo?: string;
+ kind?: Extract<OutboxKind, "text" | "notice">;
+ /** 飞书:交互卡片(任务提问的选项按钮),给了就发卡片,发不了时发 text */
+ card?: Record<string, unknown>;
+ /** 微信:原样发送,不过 Markdown 过滤(提问的编号选项、审批的命令) */
+ raw?: boolean;
+ /** 不受免打扰和每天上限限制(用户说了做完马上告诉他) */
+ anytime?: boolean;
+ /** 来自哪里:task:<id>、rule:<id> */
+ ref?: string;
+}
+
+/** 一个人(一个会话):机器人、渠道、对方 */
+export interface Peer {
+ botId: string;
+ channel: string;
+ peerId: string;
+ conversationId: string;
+}
+
+/** 接下来要发给这个人的一项(续期提醒里列出来):at 是预计的时间(不知道就不给) */
+export interface Upcoming {
+ label: string;
+ at?: number;
+ kind: "task" | "rule" | "reminder" | "message";
+}
+
+/** 这个人现在要给主动消息留几条配额(3b:待答问题;3d:执行中的规则) */
+export type Reserver = (p: Peer) => number;
+/** 窗口关闭(after)之后还要发给这个人的(3d:规则下次运行) */
+export type UpcomingSource = (p: Peer, after: number) => Upcoming[];
+
+/**
+ * 「需要你」里的一项:没送到的消息,按会话分组。held = 等对方在微信里发条消息(自己会好);failed = 一直失败或放弃了。
+ * 3b 的「需要你」视图读 attentionItems(),按钮调 act()。
+ */
+export interface AttentionItem {
+ id: string;
+ kind: "delivery";
+ state: "held" | "failed";
+ botId: string;
+ conversationId: string;
+ channel: string;
+ severity: "warn" | "error";
+ /** 第一行:1 条结果未送达微信 */
+ title: string;
+ /** 第二行(可能为空) */
+ line: string;
+ /** 从什么时候起 */
+ since: number;
+ /** 没送到的内容(「在这里查看」) */
+ messages: Array<{ id: string; text: string; at: number; ref: string }>;
+ actions: Array<"retry" | "dismiss">;
+}
+
+const CHANNEL_NAME: Record<string, string> = { weixin: "微信", feishu: "飞书" };
+const ACK = /^(ok|okay|k|好|好的|好滴|嗯|嗯嗯|收到|行|可以)[\s!!。.~~]*$/i;
+
+const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();
+const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+const peerOf = (botId: string, channel: string, peerId: string): Peer => ({ botId, channel, peerId, conversationId: `${botId}:${channel}:${peerId}` });
+
+/** 一条要不要人管:留着等对方、一直失败、放弃了且没在「需要你」里点不再提示(合进别的一条的,传那一条进来) */
+export function needsPerson(row: OutboxRow | undefined): boolean {
+ if (!row) return false;
+ return row.status === "held" || (row.status === "gone" && !row.seenAt) || (row.status === "pending" && row.attempts >= FAILS_FOR_ATTENTION);
+}
+
+/** 摘要:一条就是它自己;几条就是「N 个后台任务:」加一项一行 */
+export function digestText(items: Array<{ purpose: string; text: string }>): string {
+ if (items.length === 1) return items[0].text;
+ const all = (...k: string[]) => items.every((i) => k.includes(i.purpose));
+ const head = all("result", "failure") ? `${items.length} 个后台任务:` : all("rule", "reminder") ? `${items.length} 条提醒:` : `${items.length} 条消息:`;
+ return [head, ...items.map((i) => `· ${oneLine(i.text)}`)].join("\n");
+}
+
+/** 续期提醒的那句话:「接下来还有 2 条提醒要发给你(明早 8:00 天气、周一 9:00 周报)。回个「ok」我就能继续按时提醒你。」 */
+export function nudgeText(items: Upcoming[], now: number, tz: string): { text: string; noun: string } {
+ const all = (...k: string[]) => items.every((i) => k.includes(i.kind));
+ const noun = all("rule", "reminder") ? "提醒" : all("task") ? "结果" : "消息";
+ const list = items
+ .slice(0, 3)
+ .map((i) => (i.at ? `${fmtWhen(i.at, now, tz)} ` : "") + clip(oneLine(i.label), 20))
+ .join("、");
+ const tail = noun === "提醒" ? "回个「ok」我就能继续按时提醒你。" : "回个「ok」我就能继续发给你。";
+ return { text: `接下来还有 ${items.length} 条${noun}要发给你(${list}${items.length > 3 ? " 等" : ""})。${tail}`, noun };
+}
+
+/**
+ * 续期提醒什么时候发:窗口关闭前 2 小时;那时在免打扰里,就挪到免打扰结束(离关闭至少还有 30 分钟)
+ * 或开始前一分钟(窗口已经开了),哪个离 2 小时前近用哪个;都不行就不发(Infinity)
+ */
+export function nudgeAt(start: number, close: number, quiet: QuietHours, tz: string): number {
+ const target = close - NUDGE_BEFORE_MS;
+ if (!inQuiet(target, quiet, tz)) return target;
+ const after = quietEnd(target, quiet, tz);
+ const before = quietStart(target, quiet, tz) - 60_000;
+ const okAfter = after <= close - 3 * NUDGE_LATEST_MS;
+ const okBefore = before >= start;
+ if (okAfter && (!okBefore || after - target <= target - before)) return after;
+ if (okBefore) return before;
+ return Infinity;
+}
+
+export interface DeliveryOptions {
+ store: Store;
+ outbox: Outbox;
+ now?: () => number;
+ /** 主人的时区(默认本机的) */
+ timeZone?: string;
+ /** 测试注入:每天上限(默认 DAILY_CAP)、合并间隔(默认 COALESCE_MS) */
+ dailyCap?: Readonly<Record<string, number>>;
+ coalesceMs?: number;
+}
+
+export class Delivery {
+ private reservers = new Set<Reserver>();
+ private sources = new Set<UpcomingSource>();
+ private listeners = new Set<() => void>();
+ private timer: NodeJS.Timeout | undefined;
+ private running = false;
+ private emitting = false;
+ private offOutbox: (() => void) | undefined;
+
+ constructor(private o: DeliveryOptions) {
+ o.outbox.planner = { promote: (rows, now) => this.promote(rows, now) };
+ }
+
+ private get store(): Store {
+ return this.o.store;
+ }
+ private now(): number {
+ return (this.o.now ?? Date.now)();
+ }
+ get timeZone(): string {
+ return this.o.timeZone ?? systemTimeZone();
+ }
+
+ /** 这个机器人的免打扰时段与续期提醒开关 */
+ settingsOf(botId: string): { quiet: QuietHours; nudge: boolean } {
+ const s: Partial<BotSettings> | undefined = this.store.getBot(botId)?.settings;
+ return { quiet: s?.quietHours ?? DEFAULT_QUIET, nudge: s?.nudge ?? true };
+ }
+
+ /** 开始:续期提醒的定时器;出站队列的变化转给「需要你」 */
+ start(): void {
+ if (this.running) return;
+ this.running = true;
+ this.offOutbox = this.o.outbox.onChange(() => this.emit());
+ this.arm(1000);
+ }
+
+ stop(): void {
+ this.running = false;
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ this.offOutbox?.();
+ this.offOutbox = undefined;
+ }
+
+ // ---------- 推送 ----------
+
+ /** 主动推送(任务结果、失败;3d 的规则命中、提醒):按规则算出什么时候发,写进出站队列(同步落库) */
+ push(p: PushInput): { due: number; reason: string } {
+ const peer = peerOf(p.botId, p.channel, p.peerId);
+ const now = this.now();
+ const { due, reason } = this.plan(peer, p.purpose, !!p.anytime, now);
+ const common = { botId: p.botId, channel: p.channel, peerId: p.peerId, replyTo: p.replyTo ?? "", purpose: p.purpose, subject: clip(oneLine(p.subject), 60), ref: p.ref ?? "", due, reason };
+ const flag = p.anytime ? { anytime: true } : {};
+ const extra = { ...(p.card ? { card: p.card } : {}), ...(p.raw ? { raw: true } : {}) };
+ void this.o.outbox.send({ ...common, id: p.id, kind: p.card ? "card" : (p.kind ?? "text"), body: { text: p.text, ...extra, ...flag } });
+ (p.files ?? []).forEach((f, i) => void this.o.outbox.send({ ...common, id: `${p.id}:file:${i}`, kind: "file", body: { path: f, name: path.basename(f), ...flag } }));
+ if (due > now) log.info("proactive message scheduled", { id: p.id, channel: p.channel, reason, inMin: Math.round((due - now) / 60_000) });
+ return { due, reason };
+ }
+
+ /** 推了还没发出去的不用再发了(任务的提问在别处回答了):撤回 */
+ withdraw(id: string, reason: string): boolean {
+ return this.o.outbox.withdraw(id, reason);
+ }
+
+ /** 什么时候发:免打扰 → 每天上限 → 合并(离上一条不到 2 分钟就等,和排着的一起发) */
+ plan(p: Peer, purpose: OutboxPurpose, anytime: boolean, now: number): { due: number; reason: string } {
+ const { quiet } = this.settingsOf(p.botId);
+ const tz = this.timeZone;
+ const free = anytime || this.awake(p, now);
+ let due = now;
+ let reason = "";
+ if (!free && inQuiet(due, quiet, tz)) [due, reason] = [quietEnd(due, quiet, tz), "quiet_hours"];
+ if (!anytime) {
+ const capped = this.afterCap(p, due, quiet);
+ if (capped !== due) [due, reason] = [capped, "daily_cap"];
+ }
+ // 问题单独发,不合并
+ if (purpose === "question") return { due, reason: due > now ? reason : "" };
+ const last = this.store.lastPushAt(p.conversationId);
+ const gap = this.o.coalesceMs ?? COALESCE_MS;
+ if (last && due < last + gap) {
+ [due, reason] = [last + gap, reason || "coalesce"];
+ if (!free && inQuiet(due, quiet, tz)) [due, reason] = [quietEnd(due, quiet, tz), "quiet_hours"];
+ }
+ const with_ = this.store.scheduledPushes(p.conversationId).find((r) => r.purpose !== "question" && Math.abs(r.due - due) <= gap);
+ if (with_) [due, reason] = [Math.max(with_.due, now), with_.reason || reason];
+ return { due, reason: due > now ? reason : "" };
+ }
+
+ /** 这天到上限了就挪到下一个早上(免打扰结束的时间),直到有一天没满 */
+ private afterCap(p: Peer, due: number, quiet: QuietHours): number {
+ const tz = this.timeZone;
+ const cap = (this.o.dailyCap ?? DAILY_CAP)[p.channel] ?? 5;
+ const morning = minuteOf(quiet.to) ?? minuteOf(DEFAULT_QUIET.to)!;
+ for (let i = 0; i < 7; i++) {
+ const d0 = startOfDay(due, tz);
+ if (this.store.countPushes(p.conversationId, d0, nextAt(d0, 0, tz)) < cap) return due;
+ due = nextAt(due, morning, tz);
+ }
+ return due;
+ }
+
+ /** 用户刚发过消息(人醒着):免打扰不拦 */
+ private awake(p: Peer, now: number): boolean {
+ let last = this.store.lastUserMessageAt(p.conversationId);
+ if (p.channel === "weixin") last = Math.max(last, this.store.getWeixinPeer(p.botId, p.peerId)?.windowStartedAt ?? 0);
+ return last > now - AWAKE_MS && last <= now + 1000;
+ }
+
+ /** 排着的主动消息到时间了:还在免打扰里(设置改过)或这天满了就再排,否则合成一条 */
+ private promote(rows: OutboxRow[], now: number): { later: number; reason: string } | HeldGroup[] {
+ const r0 = rows[0];
+ if (!r0.purpose || r0.purpose === "nudge") return rows.map((r) => ({ rows: [r] }));
+ const p = peerOf(r0.botId, r0.channel, r0.peerId);
+ const { quiet } = this.settingsOf(p.botId);
+ const anytime = rows.every((r) => r.body.anytime);
+ if (!anytime && !this.awake(p, now) && inQuiet(now, quiet, this.timeZone)) return { later: quietEnd(now, quiet, this.timeZone), reason: "quiet_hours" };
+ if (!anytime) {
+ const capped = this.afterCap(p, now, quiet);
+ if (capped !== now) return { later: capped, reason: "daily_cap" };
+ }
+ return this.combine(rows);
+ }
+
+ /**
+ * 一起发的几条怎么合(到时间的一批、对方发消息时放出来的):有等对方的(held)就照「你不在时:…」合(微信);
+ * 只是排着的就合成摘要,文字一条(放得下就合),文件、问题、发了一半的照原样排在后面。飞书的摘要直接发到会话。
+ */
+ combine(rows: OutboxRow[]): HeldGroup[] {
+ if (!rows.length) return [];
+ if (rows.some((r) => r.status === "held")) return rows[0].channel === "weixin" ? combineHeld(rows) : rows.map((r) => ({ rows: [r] }));
+ const mergeable = (r: OutboxRow) => (r.kind === "text" || r.kind === "notice") && r.progress === 0 && !!r.purpose && r.purpose !== "question" && r.purpose !== "nudge" && !!(r.body.text ?? "").trim();
+ const groups: HeldGroup[] = [];
+ let cur: OutboxRow[] = [];
+ let len = 0;
+ const flush = () => {
+ if (cur.length) groups.push(this.digestGroup(cur));
+ cur = [];
+ len = 0;
+ };
+ for (const r of rows.filter(mergeable)) {
+ const n = this.textOf(r).length + 4;
+ if (cur.length && len + n > DIGEST_MAX) flush();
+ cur.push(r);
+ len += n;
+ }
+ flush();
+ return [...groups, ...rows.filter((r) => !mergeable(r)).map((r) => ({ rows: [r] }))];
+ }
+
+ private textOf(r: OutboxRow): string {
+ const t = r.body.text ?? "";
+ return r.channel === "weixin" && !r.body.raw ? filterMarkdown(t) : t.trim();
+ }
+
+ private digestGroup(rows: OutboxRow[]): HeldGroup {
+ if (rows.length === 1) return { rows };
+ const text = digestText(rows.map((r) => ({ purpose: r.purpose, text: this.textOf(r) })));
+ return { rows, body: { text, raw: true, digest: true }, ...(rows[0].channel === "feishu" ? { kind: "notice" as const, replyTo: "" } : {}) };
+ }
+
+ // ---------- 微信配额预留 ----------
+
+ /** 登记一种占配额的东西(返回注销函数):3b 的待答问题、3d 的执行中规则 */
+ addReserver(fn: Reserver): () => void {
+ this.reservers.add(fn);
+ return () => this.reservers.delete(fn);
+ }
+
+ /** 这个人现在要给主动消息留几条:排着的主动消息 1 条,加上登记的(进行中的任务各 1 条…),最多 3 条 */
+ reserved(botId: string, channel: string, peerId: string): number {
+ const p = peerOf(botId, channel, peerId);
+ let n = this.store.scheduledPushes(p.conversationId).length ? 1 : 0;
+ for (const fn of this.reservers) {
+ try {
+ n += Math.max(0, Math.floor(fn(p) || 0));
+ } catch (e) {
+ log.warn("reserver failed", { message: (e as Error).message });
+ }
+ }
+ return Math.min(MAX_RESERVED, n);
+ }
+
+ // ---------- 续期提醒 ----------
+
+ /** 登记"之后还要发给这个人的"来源(返回注销函数):3d 的规则下次运行 */
+ addUpcoming(fn: UpcomingSource): () => void {
+ this.sources.add(fn);
+ return () => this.sources.delete(fn);
+ }
+
+ /** after(窗口关闭)之后还要发给这个人的:排到那之后的、留着的主动消息,加上登记的(进行中的任务…),按时间排 */
+ upcoming(p: Peer, after: number): Upcoming[] {
+ const out: Upcoming[] = [];
+ for (const r of this.store.waitingOutbox(p.conversationId)) {
+ if (r.kind === "file" || !r.purpose || r.purpose === "nudge") continue;
+ if (r.status === "scheduled" && r.due < after) continue;
+ const kind = r.purpose === "result" || r.purpose === "failure" ? "task" : r.purpose === "rule" ? "rule" : r.purpose === "reminder" ? "reminder" : "message";
+ out.push({ label: r.subject || oneLine(r.body.text ?? ""), ...(r.status === "scheduled" ? { at: r.due } : {}), kind });
+ }
+ for (const fn of this.sources) {
+ try {
+ out.push(...fn(p, after));
+ } catch (e) {
+ log.warn("upcoming source failed", { message: (e as Error).message });
+ }
+ }
+ return out.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity));
+ }
+
+ /** 续期提醒的 id:每个窗口一个(同一 id 只发一次) */
+ static nudgeId(botId: string, userId: string, windowStartedAt: number): string {
+ return `nudge:${botId}:${userId}:${windowStartedAt}`;
+ }
+
+ /** 看一遍所有开着的微信窗口:到了提醒时间、有东西要发、还有配额、不在免打扰里就发一句;之后定好下次看的时间 */
+ tick(): void {
+ if (!this.running) return;
+ const now = this.now();
+ const tz = this.timeZone;
+ let next = now + NUDGE_TICK_MS;
+ for (const bot of this.store.listBots()) {
+ const st = this.settingsOf(bot.id);
+ if (!bot.weixinEnabled || !st.nudge) continue;
+ const quota = new WeixinQuota(this.store, bot.id, () => now);
+ for (const peer of this.store.listWeixinPeers(bot.id)) {
+ const close = peer.windowStartedAt + QUOTA_WINDOW_MS;
+ if (!peer.contextToken || close <= now + NUDGE_LATEST_MS) continue;
+ const at = nudgeAt(peer.windowStartedAt, close, st.quiet, tz);
+ if (at > now) {
+ next = Math.min(next, at);
+ continue;
+ }
+ if (inQuiet(now, st.quiet, tz)) continue;
+ const id = Delivery.nudgeId(bot.id, peer.userId, peer.windowStartedAt);
+ if (this.store.getOutbox(id) || quota.remaining(peer.userId) <= 0) continue;
+ const p = peerOf(bot.id, "weixin", peer.userId);
+ const items = this.upcoming(p, close);
+ if (!items.length) continue;
+ const { text, noun } = nudgeText(items, now, tz);
+ void this.o.outbox.send({ id, botId: bot.id, channel: "weixin", peerId: peer.userId, kind: "text", body: { text, raw: true }, purpose: "nudge", subject: noun, ttlMs: close - now });
+ if (this.store.getConversation(p.conversationId)) this.store.addMessage(p.conversationId, "assistant", text);
+ log.info("weixin window nudge", { bot: bot.id, items: items.length, closesInMin: Math.round((close - now) / 60_000) });
+ }
+ }
+ this.arm(next - now);
+ }
+
+ private arm(ms: number): void {
+ clearTimeout(this.timer);
+ if (!this.running) return;
+ this.timer = setTimeout(() => this.tick(), Math.min(NUDGE_TICK_MS, Math.max(1000, ms)));
+ this.timer.unref?.();
+ }
+
+ /**
+ * 对方回了「ok」一类的话,而机器人最近发的一条是还没回过的续期提醒:不进模型,返回要回的那句(否则 undefined)。
+ * 渠道先调这个,再放出留着的消息。
+ */
+ ack(botId: string, channel: string, peerId: string, text: string): string | undefined {
+ if (!ACK.test(text.trim())) return undefined;
+ const last = this.store.lastSentOutbox(`${botId}:${channel}:${peerId}`);
+ if (!last || last.purpose !== "nudge" || last.reason === "acked" || this.now() - last.sentAt > QUOTA_WINDOW_MS + NUDGE_BEFORE_MS) return undefined;
+ this.store.updateOutbox(last.id, { reason: "acked" }, this.now());
+ return last.subject === "提醒" ? "好的,到时提醒你。" : "好的,到时发给你。";
+ }
+
+ // ---------- 需要你 ----------
+
+ /** 「需要你」有变化时通知(3b:刷新视图、托盘计数、桌面通知) */
+ onChange(fn: () => void): () => void {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+
+ private emit(): void {
+ if (this.emitting || !this.listeners.size) return;
+ this.emitting = true;
+ queueMicrotask(() => {
+ this.emitting = false;
+ for (const fn of this.listeners) {
+ try {
+ fn();
+ } catch (e) {
+ log.warn("attention listener failed", { message: (e as Error).message });
+ }
+ }
+ });
+ }
+
+ /**
+ * 没送到、要人管的消息,按会话分两种:等对方在微信里发条消息的(自己会好,没有按钮),一直失败或放弃了的(重试、不再提示)。
+ * 只算主动推的结果和提醒:聊天里的回复对方下次发消息时会补上(不单列,产品负责人否掉过「没发出去的消息」),
+ * 续期提醒没送到就算了,提问在「需要你」里本来就有一行。
+ */
+ attentionItems(botId?: string): AttentionItem[] {
+ const now = this.now();
+ const rows = this.store
+ .undeliveredOutbox({ botId, minAttempts: FAILS_FOR_ATTENTION, since: now - GONE_SHOWN_MS })
+ .filter((r) => r.purpose !== "" && r.purpose !== "nudge" && r.purpose !== "question");
+ const groups = new Map<string, OutboxRow[]>();
+ for (const r of rows) {
+ const key = `delivery:${r.conversationId}:${r.status === "held" ? "held" : "failed"}`;
+ groups.set(key, [...(groups.get(key) ?? []), r]);
+ }
+ const items: AttentionItem[] = [];
+ for (const [id, list] of groups) {
+ const r0 = list[0];
+ const held = r0.status === "held";
+ const ch = CHANNEL_NAME[r0.channel] ?? r0.channel;
+ // 合成过的一条按里面的条数算;文件不单算
+ const parts = list.flatMap((r) => [r, ...(r.body.digest || r.body.away ? this.store.mergedOutbox(r.id) : [])]).filter((r) => r.kind !== "file");
+ const n = Math.max(1, parts.length);
+ const noun = parts.length && parts.every((r) => r.purpose === "result" || r.purpose === "failure") ? "条结果" : "条消息";
+ items.push({
+ id,
+ kind: "delivery",
+ state: held ? "held" : "failed",
+ botId: r0.botId,
+ conversationId: r0.conversationId,
+ channel: r0.channel,
+ severity: held ? "warn" : "error",
+ title: held ? `${n} ${noun}未送达${ch}` : `${n} ${noun}没能发到${ch}`,
+ line: held ? `在${ch}里发条消息就能收到` : list.some((r) => r.status === "pending") ? "还在重试" : "",
+ since: Math.min(...list.map((r) => r.createdAt)),
+ messages: list.map((r) => ({ id: r.id, text: r.kind === "file" ? `[文件 ${r.body.name ?? ""}]` : (r.body.text ?? ""), at: r.createdAt, ref: r.ref })),
+ actions: held ? [] : list.some((r) => r.status === "gone") ? ["retry", "dismiss"] : ["retry"],
+ });
+ }
+ return items.sort((a, b) => a.since - b.since);
+ }
+
+ /** 「需要你」里的按钮:retry 再发一次;dismiss 不再提示(只对放弃了的) */
+ act(id: string, action: "retry" | "dismiss"): boolean {
+ const item = this.attentionItems().find((i) => i.id === id);
+ if (!item || !item.actions.includes(action)) return false;
+ const now = this.now();
+ for (const m of item.messages) {
+ const row = this.store.getOutbox(m.id);
+ if (!row) continue;
+ if (action === "retry") this.o.outbox.retry(m.id);
+ else if (row.status === "gone") this.store.updateOutbox(m.id, { seenAt: now }, now);
+ }
+ this.emit();
+ return true;
+ }
+}
diff --git a/src/core/outbox.ts b/src/core/outbox.ts
index 547f2ea..e7ec804 100644
--- a/src/core/outbox.ts
+++ b/src/core/outbox.ts
@@ -5,6 +5,8 @@
* - 临时失败按退避重试(5 秒起,翻倍到 5 分钟),渠道没在运行时等它上线;
* - 要等对方先发消息才能发的(微信:超过 24 小时没说话、本轮配额用完)留着(held),对方下次发消息时按原来的顺序先发出去,
* 能合并的合成一条「你不在时:…」,排在这次的回复前面;
+ * - 主动消息(任务结果等,规则见 delivery.ts)可以排到某个时间再发(scheduled:免打扰、每天上限、合并),不挡同一会话里的回复;
+ * 到时间时同一会话一起到期的交给 planner 合成一条摘要;对方先发了消息就和留着的一起先发;
* - 再也发不出去了(平台多次拒绝、等待太久)标记 gone 并记下原因,只记在日志和诊断信息里;
* - 应用重启后接着发。流式的中间内容和"正在输入"不经过这里。
*
@@ -12,7 +14,7 @@
* 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 type { OutboxBody, OutboxKind, OutboxPurpose, OutboxRow, Store } from "../store/db.js";
import { logger } from "../log.js";
const log = logger("outbox");
@@ -21,8 +23,18 @@ const log = logger("outbox");
export class Later extends Error {}
/** 再也发不出去了:标记 gone,message 是原因(日志、诊断信息) */
export class Gone extends Error {}
-/** 要等对方先发消息才能发(微信 24 小时窗口已过、本轮配额用完):留着,对方下次发消息时再发(见 release) */
-export class Held extends Error {}
+/** 要等对方先发消息才能发(微信 24 小时窗口已过、本轮配额用完):留着,对方下次发消息时再发(见 release);code 是原因 */
+export class Held extends Error {
+ constructor(
+ message: string,
+ readonly code: "window_closed" | "quota" | "no_token" = "window_closed",
+ ) {
+ super(message);
+ }
+}
+
+/** 定时器最长睡多久:电脑睡眠时定时器不走,醒来后最多这么久就会重新看一遍 */
+const MAX_SLEEP_MS = 5 * 60_000;
/** 普通消息最长等多久(微信的会话凭证 24 小时有效,飞书也不该再补发一天前的回复) */
export const OUTBOX_TTL_MS = 24 * 3600_000;
@@ -41,14 +53,32 @@ export interface OutboxInput {
body: OutboxBody;
/** 飞书:回复的消息 id */
replyTo?: string;
- /** 多久之后不再发(默认 24 小时;ack、审批提示更短) */
+ /** 多久之后不再发(默认 24 小时;ack、审批提示更短);排着的从到期时算起 */
ttlMs?: number;
+ /** 主动推送的用途(见 delivery.ts);不给 = 对话里的回复 */
+ purpose?: OutboxPurpose;
+ subject?: string;
+ ref?: string;
+ /** 什么时候发:晚于现在就先排着(scheduled),不挡同一会话里的回复 */
+ due?: number;
+ /** 排着的原因 */
+ reason?: string;
}
-/** 对方发消息后一起发的一组留着的消息:body 给了就合成这一条发,否则这组只有一条、照原样发 */
+/**
+ * 一起发的一组消息:body 给了就合成这一条发(kind、replyTo 给了也换掉,比如飞书的摘要改成直接发到会话),
+ * 否则这组只有一条、照原样发
+ */
export interface HeldGroup {
rows: OutboxRow[];
body?: OutboxBody;
+ kind?: OutboxKind;
+ replyTo?: string;
+}
+
+/** 排着的消息到时间了(同一会话的一批):返回 later 就再排到那时,否则返回怎么合成 */
+export interface OutboxPlanner {
+ promote(rows: OutboxRow[], now: number): { later: number; reason: string } | HeldGroup[];
}
/** 渠道的发送函数:成功返回;Later / Gone / 其他错误(临时失败,会重试)。progress 记下长文本已发出的分段数 */
@@ -81,12 +111,39 @@ export class Outbox {
private scheduled = false;
private started = false;
private stopped = false;
+ private listeners = new Set<(row: OutboxRow) => void>();
+ /** 排着的消息到时间时怎么办(delivery.ts 设);没有就一条一条照原样发 */
+ planner: OutboxPlanner | undefined;
constructor(
private store: Store,
private opts: { now?: () => number; retry?: readonly [number, number] } = {},
) {}
+ /** 消息的状态变了(发出去、留着、放弃、排着的放出来):「需要你」据此刷新 */
+ onChange(fn: (row: OutboxRow) => void): () => void {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+
+ private changed(id: string): void {
+ if (!this.listeners.size) return;
+ const row = this.store.getOutbox(id);
+ if (!row) return;
+ for (const fn of this.listeners) {
+ try {
+ fn(row);
+ } catch (e) {
+ log.warn("outbox listener failed", { message: (e as Error).message });
+ }
+ }
+ }
+
+ /** 时间可能跳了(电脑睡醒、改了时钟):马上再看一遍 */
+ wake(): void {
+ this.kick();
+ }
+
private now(): number {
return (this.opts.now ?? Date.now)();
}
@@ -108,7 +165,9 @@ export class Outbox {
async send(input: OutboxInput): Promise<OutboxRow | undefined> {
const now = this.now();
const conversationId = `${input.botId}:${input.channel}:${input.peerId}`;
- this.store.insertOutbox({
+ const due = Math.max(now, input.due ?? now);
+ const later = due > now;
+ const fresh = this.store.insertOutbox({
id: input.id,
botId: input.botId,
channel: input.channel,
@@ -117,10 +176,20 @@ export class Outbox {
kind: input.kind,
body: input.body,
replyTo: input.replyTo ?? "",
- due: now,
+ due,
createdAt: now,
- expiresAt: now + (input.ttlMs ?? OUTBOX_TTL_MS),
+ expiresAt: due + (input.ttlMs ?? OUTBOX_TTL_MS),
+ status: later ? "scheduled" : "pending",
+ purpose: input.purpose ?? "",
+ subject: input.subject ?? "",
+ ref: input.ref ?? "",
+ reason: later ? (input.reason ?? "") : "",
});
+ if (later) {
+ if (fresh) this.changed(input.id);
+ this.kick();
+ return this.store.getOutbox(input.id);
+ }
this.pump();
const f = this.inflight.get(conversationId);
if (f?.id === input.id) await f.done;
@@ -132,7 +201,7 @@ export class Outbox {
this.started = true;
this.stopped = false;
try {
- for (const r of this.store.listOutbox({ status: "held", limit: 500 })) if (r.expiresAt <= this.now()) this.gone(r, "等待太久,已不再发送");
+ for (const st of ["held", "scheduled"] as const) for (const r of this.store.listOutbox({ status: st, limit: 500 })) if (r.expiresAt <= this.now()) this.gone(r, "等待太久,已不再发送");
this.store.pruneOutbox(this.now());
// 重启了:等着退避的不用再等,马上试一次
this.store.resumeOutbox(this.now());
@@ -167,24 +236,71 @@ export class Outbox {
}
/**
- * 对方又发消息了:留着给他的消息放回队列,按原来的顺序排在这次回复的前面。
+ * 对方又发消息了:留着给他的消息和排着的主动消息放回队列,按原来的顺序排在这次回复的前面。
* combine 决定哪几条合成一条发(每组第一条换成合并后的内容,其余标记 merged);不给就一条一条发。过期的不再发。
*/
release(botId: string, channel: string, peerId: string, combine?: (rows: OutboxRow[]) => HeldGroup[]): number {
- const held = this.store.heldOutbox(`${botId}:${channel}:${peerId}`);
- if (!held.length) return 0;
+ const conv = `${botId}:${channel}:${peerId}`;
+ // 还没发出去的续期提醒:对方已经发消息了,不用再提醒
+ for (const r of this.store.pendingOutbox().filter((x) => x.conversationId === conv && x.purpose === "nudge")) if (!this.inflight.has(conv)) this.gone(r, "对方已经发消息了");
+ const waiting = this.store.waitingOutbox(conv);
+ if (!waiting.length) return 0;
const now = this.now();
- const live = held.filter((r) => r.expiresAt > now || (this.gone(r, "等待太久,已不再发送"), false));
- for (const g of combine ? combine(live) : live.map((r): HeldGroup => ({ rows: [r] }))) {
- const [first, ...rest] = g.rows;
- this.store.updateOutbox(first.id, { status: "pending", due: now, error: "", ...(g.body ? { body: g.body, progress: 0 } : {}) }, now);
- for (const r of rest) this.store.updateOutbox(r.id, { status: "merged" }, now);
- }
- if (live.length) log.info(`releasing ${live.length} held message(s)`, { bot: botId, channel });
+ const live = waiting.filter((r) => r.expiresAt > now || (this.gone(r, "等待太久,已不再发送"), false));
+ this.apply(combine ? combine(live) : live.map((r): HeldGroup => ({ rows: [r] })), now, "inbound");
+ if (live.length) log.info(`releasing ${live.length} waiting message(s)`, { bot: botId, channel });
this.kick();
return live.length;
}
+ /** 每组第一条放回队列(换成合并后的内容),其余标记 merged;排着的从现在起重新算有效期 */
+ private apply(groups: HeldGroup[], now: number, reason: string): void {
+ for (const g of groups) {
+ const [first, ...rest] = g.rows;
+ if (!first) continue;
+ this.store.updateOutbox(
+ first.id,
+ {
+ status: "pending",
+ due: now,
+ error: "",
+ reason,
+ ...(first.status === "scheduled" ? { expiresAt: now + Math.max(OUTBOX_TTL_MS, first.expiresAt - first.due) } : {}),
+ ...(g.body ? { body: g.body, progress: 0 } : {}),
+ ...(g.kind ? { kind: g.kind } : {}),
+ ...(g.replyTo !== undefined ? { replyTo: g.replyTo } : {}),
+ },
+ now,
+ );
+ for (const r of rest) this.store.updateOutbox(r.id, { status: "merged", mergedInto: first.id, reason }, now);
+ this.changed(first.id);
+ }
+ }
+
+ /** 排着的主动消息到时间了:同一会话的一批交给 planner(再排到以后 / 合成一条),放回队列 */
+ private promote(now: number): void {
+ const due = this.store.dueScheduledOutbox(now);
+ if (!due.length) return;
+ const byConv = new Map<string, OutboxRow[]>();
+ for (const r of due) byConv.set(r.conversationId, [...(byConv.get(r.conversationId) ?? []), r]);
+ for (const rows of byConv.values()) {
+ const live = rows.filter((r) => r.expiresAt > now || (this.gone(r, "等待太久,已不再发送"), false));
+ if (!live.length) continue;
+ let plan: ReturnType<OutboxPlanner["promote"]> = live.map((r) => ({ rows: [r] }));
+ try {
+ if (this.planner) plan = this.planner.promote(live, now);
+ } catch (e) {
+ log.warn("outbox planner failed", { message: (e as Error).message });
+ }
+ if ("later" in plan) {
+ const at = Math.max(plan.later, now + 1000);
+ for (const r of live) this.store.updateOutbox(r.id, { due: at, reason: plan.reason, expiresAt: Math.max(r.expiresAt, at + OUTBOX_TTL_MS) }, now);
+ continue;
+ }
+ this.apply(plan, now, live[0].reason);
+ }
+ }
+
private kick(): void {
if (this.scheduled) return;
this.scheduled = true;
@@ -200,7 +316,8 @@ export class Outbox {
clearTimeout(this.timer);
this.timer = undefined;
const now = this.now();
- let next = Infinity;
+ this.promote(now);
+ let next = this.store.nextScheduledDue() || Infinity;
const heads = new Set<string>();
for (const row of this.store.pendingOutbox()) {
if (heads.has(row.conversationId)) continue;
@@ -220,7 +337,7 @@ export class Outbox {
this.attempt(row, deliver);
}
if (next < Infinity) {
- this.timer = setTimeout(() => this.pump(), Math.max(20, next - now));
+ this.timer = setTimeout(() => this.pump(), Math.min(MAX_SLEEP_MS, Math.max(20, next - now)));
this.timer.unref?.();
}
}
@@ -234,6 +351,7 @@ export class Outbox {
} catch (e) {
this.failed(row, e);
}
+ this.changed(row.id);
})().finally(() => {
if (this.inflight.get(conv)?.done === done) this.inflight.delete(conv);
this.kick();
@@ -245,7 +363,7 @@ export class Outbox {
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 (e instanceof Held) return this.hold(row, msg);
+ if (e instanceof Held) return this.hold(row, msg, e.code);
// 关机中:留到下次启动
if (this.stopped) return;
const [base, max] = this.opts.retry ?? [5000, 300_000];
@@ -261,15 +379,47 @@ export class Outbox {
this.store.updateOutbox(row.id, { attempts, error: msg, due: now + delay }, now);
}
- /** 留着等对方发消息:不算失败;普通消息最多留 HOLD_TTL_MS,短命的(ack、审批提示)照旧按自己的期限 */
- private hold(row: OutboxRow, reason: string): void {
- const expiresAt = row.expiresAt - row.createdAt >= OUTBOX_TTL_MS ? Math.max(row.expiresAt, row.createdAt + HOLD_TTL_MS) : row.expiresAt;
- this.store.updateOutbox(row.id, { status: "held", error: reason, expiresAt }, this.now());
+ /**
+ * 留着等对方发消息:不算失败;普通消息和主动消息从现在起最多留 HOLD_TTL_MS,短命的(ack、审批提示)照旧按自己的期限。
+ * 续期提醒发不出去就算了
+ */
+ private hold(row: OutboxRow, reason: string, code = ""): void {
+ if (row.purpose === "nudge") return this.gone(row, reason);
+ const long = row.purpose !== "" || row.expiresAt - row.createdAt >= OUTBOX_TTL_MS;
+ const expiresAt = long ? Math.max(row.expiresAt, (row.purpose ? this.now() : row.createdAt) + HOLD_TTL_MS) : row.expiresAt;
+ this.store.updateOutbox(row.id, { status: "held", error: reason, reason: code, expiresAt }, this.now());
log.info("message held until the user writes again", { id: row.id, channel: row.channel, kind: row.kind, reason });
}
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 });
+ this.changed(row.id);
+ }
+
+ /**
+ * 不用再发了(任务的提问已经在别处回答了、任务停了):还没发出去的(排着、留着、等着重试)标记 gone,记作看过(不算没送到);
+ * 正在发的不管。返回撤回了没有
+ */
+ withdraw(id: string, reason: string): boolean {
+ const row = this.store.getOutbox(id);
+ if (!row || (row.status !== "pending" && row.status !== "scheduled" && row.status !== "held")) return false;
+ if (this.inflight.get(row.conversationId)?.id === id) return false;
+ const now = this.now();
+ this.store.updateOutbox(id, { status: "gone", error: reason, seenAt: now }, now);
+ log.info("message withdrawn", { id, channel: row.channel, reason });
+ this.changed(id);
+ return true;
+ }
+
+ /** 「需要你」里点了重试:放弃了的从现在起再试,一直失败的马上再试一次 */
+ retry(id: string): boolean {
+ const row = this.store.getOutbox(id);
+ if (!row || (row.status !== "gone" && row.status !== "pending")) return false;
+ const now = this.now();
+ this.store.updateOutbox(id, { status: "pending", due: now, attempts: 0, error: "", expiresAt: Math.max(row.expiresAt, now + OUTBOX_TTL_MS) }, now);
+ this.changed(id);
+ this.kick();
+ return true;
}
}
diff --git a/src/core/quiet.ts b/src/core/quiet.ts
new file mode 100644
index 0000000..246d763
--- /dev/null
+++ b/src/core/quiet.ts
@@ -0,0 +1,126 @@
+/**
+ * 主人的本地时间与免打扰时段(设计文档第 6 节、决定 4):默认 22:00–08:00,按主人的时区(本机的 IANA 时区)算,
+ * 跨午夜的时段也行。夏令时切换那天按本地钟面时间对齐。
+ */
+
+export interface QuietHours {
+ enabled: boolean;
+ /** "22:00" */
+ from: string;
+ /** "08:00" */
+ to: string;
+}
+
+export const DEFAULT_QUIET: QuietHours = { enabled: true, from: "22:00", to: "08:00" };
+
+const MIN = 60_000;
+const DAY = 1440;
+
+/** 本机的时区(主人的时区) */
+export function systemTimeZone(): string {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+ } catch {
+ return "UTC";
+ }
+}
+
+/** "22:00" → 1320;格式不对返回 undefined */
+export function minuteOf(hhmm: string): number | undefined {
+ const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(hhmm);
+ return m ? Number(m[1]) * 60 + Number(m[2]) : undefined;
+}
+
+const fmts = new Map<string, Intl.DateTimeFormat>();
+function fmt(tz: string): Intl.DateTimeFormat {
+ let f = fmts.get(tz);
+ if (!f) {
+ f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", weekday: "short" });
+ fmts.set(tz, f);
+ }
+ return f;
+}
+
+const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
+
+/** ts 在 tz 里的日期、星期(0 = 周日)和一天里的第几分钟(带秒的小数) */
+export function localParts(ts: number, tz: string): { y: number; mo: number; d: number; weekday: number; minute: number } {
+ const p: Record<string, string> = {};
+ for (const x of fmt(tz).formatToParts(ts)) p[x.type] = x.value;
+ const ms = ((ts % 1000) + 1000) % 1000;
+ return {
+ y: Number(p.year),
+ mo: Number(p.month),
+ d: Number(p.day),
+ weekday: WEEKDAYS.indexOf(p.weekday),
+ minute: Number(p.hour) * 60 + Number(p.minute) + (Number(p.second) + ms / 1000) / 60,
+ };
+}
+
+/** ts 之后(不含)第一次到本地 minute 分的时刻 */
+export function nextAt(ts: number, minute: number, tz: string): number {
+ let delta = minute - localParts(ts, tz).minute;
+ if (delta <= 0) delta += DAY;
+ let t = ts + Math.round(delta * MIN);
+ // 夏令时那天差一小时:按钟面时间再对一次
+ const off = minute - Math.round(localParts(t, tz).minute);
+ if (off && Math.abs(off) <= 120) t += off * MIN;
+ return t;
+}
+
+/** ts 及之前最后一次到本地 minute 分的时刻 */
+export function prevAt(ts: number, minute: number, tz: string): number {
+ const t = nextAt(ts - DAY * MIN, minute, tz);
+ return t > ts ? nextAt(ts - 2 * DAY * MIN, minute, tz) : t;
+}
+
+/** 本地这一天的 0 点 */
+export function startOfDay(ts: number, tz: string): number {
+ return prevAt(ts, 0, tz);
+}
+
+function range(q: QuietHours): [number, number] | undefined {
+ const s = minuteOf(q.from);
+ const e = minuteOf(q.to);
+ if (!q.enabled || s === undefined || e === undefined || s === e) return undefined;
+ return [s, e];
+}
+
+/** ts 在免打扰时段里 */
+export function inQuiet(ts: number, q: QuietHours, tz: string): boolean {
+ const r = range(q);
+ if (!r) return false;
+ const m = localParts(ts, tz).minute;
+ return r[0] < r[1] ? m >= r[0] && m < r[1] : m >= r[0] || m < r[1];
+}
+
+/** 在免打扰时段里时:这段结束的时刻;不在时就是 ts */
+export function quietEnd(ts: number, q: QuietHours, tz: string): number {
+ const r = range(q);
+ return r && inQuiet(ts, q, tz) ? nextAt(ts, r[1], tz) : ts;
+}
+
+/** 在免打扰时段里时:这段开始的时刻;不在时就是 ts */
+export function quietStart(ts: number, q: QuietHours, tz: string): number {
+ const r = range(q);
+ return r && inQuiet(ts, q, tz) ? prevAt(ts, r[0], tz) : ts;
+}
+
+/** 最早能发主动消息的时刻:ts 不在免打扰时段里就是 ts,在就是这段结束时 */
+export function allowedAt(ts: number, q: QuietHours, tz: string): number {
+ return quietEnd(ts, q, tz);
+}
+
+const CN_WEEK = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
+
+/** 给用户看的时间:今天 21:30、今晚 22:00、明早 8:00、明天 15:00、周一 9:00、11月3日 9:00 */
+export function fmtWhen(at: number, now: number, tz: string): string {
+ const a = localParts(at, tz);
+ const m = Math.floor(a.minute);
+ const hm = `${Math.floor(m / 60)}:${String(m % 60).padStart(2, "0")}`;
+ const days = Math.round((startOfDay(at, tz) - startOfDay(now, tz)) / (DAY * MIN));
+ if (days <= 0) return `${m >= 18 * 60 ? "今晚" : "今天"} ${hm}`;
+ if (days === 1) return `${m < 12 * 60 ? "明早" : "明天"} ${hm}`;
+ if (days < 7) return `${CN_WEEK[a.weekday]} ${hm}`;
+ return `${a.mo}月${a.d}日 ${hm}`;
+}
diff --git a/src/store/db.ts b/src/store/db.ts
index e5c3bc6..0d15641 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -126,8 +126,16 @@ export interface AccessEntry {
notifiedAt: number;
}
-/** pending 等着发;held 等对方先发消息(微信);sent 发出去了;merged 合进别的一条发出去了;gone 再也发不出去 */
-export type OutboxStatus = "pending" | "held" | "sent" | "merged" | "gone";
+/**
+ * pending 等着发;scheduled 主动消息排到某个时间再发(免打扰、每天上限、合并);held 等对方先发消息(微信);
+ * sent 发出去了;merged 合进别的一条发出去了;gone 再也发不出去
+ */
+export type OutboxStatus = "pending" | "scheduled" | "held" | "sent" | "merged" | "gone";
+/**
+ * 主动推送的用途(设计文档第 6 节):任务结果、任务失败、规则命中、固定提醒、问题(3b)、微信续期提醒;
+ * 空 = 对话里的回复、提示和系统通知(从不推迟)
+ */
+export type OutboxPurpose = "" | "result" | "failure" | "rule" | "reminder" | "question" | "nudge";
/** 出站消息的内容:文本(最终回复、提示、通知)、文件、带按钮的卡片(飞书审批) */
export interface OutboxBody {
text?: string;
@@ -144,6 +152,10 @@ export interface OutboxBody {
shown?: boolean;
/** 已经是合成的「你不在时:…」(再被留着时不再加前缀) */
away?: boolean;
+ /** 几条主动消息合成的摘要 */
+ digest?: boolean;
+ /** 不受免打扰和每天上限限制(任务或规则要求马上告诉用户) */
+ anytime?: boolean;
}
export type OutboxKind = "text" | "file" | "card" | "notice";
/** 持久化的出站消息(见 core/outbox.ts) */
@@ -170,6 +182,18 @@ export interface OutboxRow {
updatedAt: number;
expiresAt: number;
sentAt: number;
+ /** 主动推送的用途;空 = 回复 */
+ purpose: OutboxPurpose;
+ /** 推的是什么(任务标题、规则名):摘要、续期提醒和「需要你」里用 */
+ subject: string;
+ /** 来自哪里:task:<id>、rule:<id> */
+ ref: string;
+ /** 排着 / 留着的原因:quiet_hours、daily_cap、coalesce、window_closed、quota、no_token;对方发消息时放出来的是 inbound */
+ reason: string;
+ /** merged:合进了哪一条 */
+ mergedInto: string;
+ /** 发不出去的,在「需要你」里被处理掉的时间 */
+ seenAt: number;
}
/**
@@ -210,6 +234,8 @@ export interface TaskRow {
/** done | stopped | archived */
endReason: string;
stoppedBy: string;
+ /** 结果不受免打扰和每天上限限制(用户说了做完马上告诉他) */
+ anytime: boolean;
createdAt: number;
updatedAt: number;
}
@@ -365,6 +391,7 @@ CREATE TABLE IF NOT EXISTS outbox (
sent_at 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 INDEX IF NOT EXISTS outbox_conv ON outbox(conversation_id, status);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
origin_message_id INTEGER NOT NULL DEFAULT 0, origin_ref TEXT NOT NULL DEFAULT '',
@@ -398,6 +425,15 @@ const COLUMNS: Array<[string, string, string]> = [
["conversations", "kind", "TEXT NOT NULL DEFAULT 'dm'"],
// 代理回合的活动记录(JSON 数组,见 agent/activity.ts);只在助手消息上
["messages", "activity", "TEXT NOT NULL DEFAULT ''"],
+ // 主动消息的送达规则(core/delivery.ts)
+ ["outbox", "purpose", "TEXT NOT NULL DEFAULT ''"],
+ ["outbox", "subject", "TEXT NOT NULL DEFAULT ''"],
+ ["outbox", "ref", "TEXT NOT NULL DEFAULT ''"],
+ ["outbox", "reason", "TEXT NOT NULL DEFAULT ''"],
+ ["outbox", "merged_into", "TEXT NOT NULL DEFAULT ''"],
+ ["outbox", "seen_at", "INTEGER NOT NULL DEFAULT 0"],
+ // 任务的结果不受免打扰限制(用户说了做完马上告诉他)
+ ["tasks", "anytime", "INTEGER NOT NULL DEFAULT 0"],
// 后台任务的提问与审批(3b):属于哪个任务、哪个 run;blocking = 有 DSH 调用在等它
["approvals", "task_id", "TEXT NOT NULL DEFAULT ''"],
["approvals", "run_id", "TEXT NOT NULL DEFAULT ''"],
@@ -604,6 +640,11 @@ export class Store {
this.db.prepare("UPDATE conversations SET updated_at = ? WHERE id = ?").run(now, conversationId);
return Number(res.lastInsertRowid);
}
+ /** 这个会话里用户最近一次发消息的时间(没有返回 0) */
+ lastUserMessageAt(conversationId: string): number {
+ const r = this.db.prepare("SELECT MAX(created_at) AS at FROM messages WHERE conversation_id = ? AND role = 'user'").get(conversationId) as Row;
+ return Number(r?.at ?? 0) || 0;
+ }
listMessages(conversationId: string, limit = 500): Message[] {
const rows = this.db
.prepare(
@@ -914,16 +955,28 @@ export class Store {
updatedAt: Number(r.updated_at),
expiresAt: Number(r.expires_at),
sentAt: Number(r.sent_at),
+ purpose: String(r.purpose ?? "") as OutboxPurpose,
+ subject: String(r.subject ?? ""),
+ ref: String(r.ref ?? ""),
+ reason: String(r.reason ?? ""),
+ mergedInto: String(r.merged_into ?? ""),
+ seenAt: Number(r.seen_at ?? 0),
};
}
/** 同一 id 只写一次;返回是否是新写入的 */
- insertOutbox(o: Pick<OutboxRow, "id" | "botId" | "channel" | "conversationId" | "peerId" | "kind" | "body" | "replyTo" | "due" | "createdAt" | "expiresAt">): boolean {
+ insertOutbox(
+ o: Pick<OutboxRow, "id" | "botId" | "channel" | "conversationId" | "peerId" | "kind" | "body" | "replyTo" | "due" | "createdAt" | "expiresAt"> &
+ Partial<Pick<OutboxRow, "status" | "purpose" | "subject" | "ref" | "reason">>,
+ ): 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), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `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, status, purpose, subject, ref, reason)
+ 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);
+ .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,
+ o.status ?? "pending", o.purpose ?? "", o.subject ?? "", o.ref ?? "", o.reason ?? "",
+ );
return Number(res.changes) > 0;
}
getOutbox(id: string): OutboxRow | undefined {
@@ -934,8 +987,15 @@ export class Store {
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" | "expiresAt" | "body">>, now = Date.now()): void {
- const cols: Record<string, string> = { status: "status", attempts: "attempts", progress: "progress", due: "due", error: "error", sentAt: "sent_at", expiresAt: "expires_at", body: "body" };
+ updateOutbox(
+ id: string,
+ patch: Partial<Pick<OutboxRow, "status" | "attempts" | "progress" | "due" | "error" | "sentAt" | "expiresAt" | "body" | "kind" | "replyTo" | "reason" | "mergedInto" | "seenAt">>,
+ now = Date.now(),
+ ): void {
+ const cols: Record<string, string> = {
+ status: "status", attempts: "attempts", progress: "progress", due: "due", error: "error", sentAt: "sent_at", expiresAt: "expires_at", body: "body",
+ kind: "kind", replyTo: "reply_to", reason: "reason", mergedInto: "merged_into", seenAt: "seen_at",
+ };
const keys = (Object.keys(patch) as Array<keyof typeof patch>).filter((k) => k in cols);
if (!keys.length) return;
const vals = keys.map((k) => (k === "body" ? JSON.stringify(patch.body) : (patch[k] as string | number)));
@@ -959,6 +1019,67 @@ export class Store {
heldOutbox(conversationId: string): OutboxRow[] {
return (this.db.prepare("SELECT * FROM outbox WHERE conversation_id = ? AND status = 'held' ORDER BY seq").all(conversationId) as Row[]).map((r) => this.toOutbox(r));
}
+ /** 这个会话还没发出去、在等的:留着的(等对方发消息)和排着的(主动消息等时间),按写入顺序 */
+ waitingOutbox(conversationId: string): OutboxRow[] {
+ return (this.db.prepare("SELECT * FROM outbox WHERE conversation_id = ? AND status IN ('held', 'scheduled') ORDER BY seq").all(conversationId) as Row[]).map((r) => this.toOutbox(r));
+ }
+ /** 排着的主动消息里到时间了的,按写入顺序 */
+ dueScheduledOutbox(now: number): OutboxRow[] {
+ return (this.db.prepare("SELECT * FROM outbox WHERE status = 'scheduled' AND due <= ? ORDER BY seq").all(now) as Row[]).map((r) => this.toOutbox(r));
+ }
+ /** 排着的主动消息里最早的时间(没有返回 0) */
+ nextScheduledDue(): number {
+ const r = this.db.prepare("SELECT MIN(due) AS due FROM outbox WHERE status = 'scheduled'").get() as Row;
+ return Number(r?.due ?? 0) || 0;
+ }
+ /** 这个会话排着的主动消息(不含文件),按时间 */
+ scheduledPushes(conversationId: string): OutboxRow[] {
+ return (this.db.prepare("SELECT * FROM outbox WHERE conversation_id = ? AND status = 'scheduled' AND kind != 'file' AND purpose NOT IN ('', 'nudge') ORDER BY due, seq").all(conversationId) as Row[]).map((r) =>
+ this.toOutbox(r),
+ );
+ }
+ /**
+ * 这个会话在 [since, until) 里推送出去(或正要推送、留着)的主动消息条数:一条摘要算一条,文件、续期提醒、
+ * 对方发消息时一起放出来的不算(每天上限)
+ */
+ countPushes(conversationId: string, since: number, until: number): number {
+ const r = this.db
+ .prepare(
+ `SELECT COUNT(*) AS n FROM outbox WHERE conversation_id = ? AND status IN ('pending', 'sent', 'held') AND kind != 'file'
+ AND purpose NOT IN ('', 'nudge') AND reason != 'inbound' AND due >= ? AND due < ?`,
+ )
+ .get(conversationId, since, until) as Row;
+ return Number(r.n);
+ }
+ /** 这个会话最近一次推送主动消息的时间(合并窗口;没有返回 0) */
+ lastPushAt(conversationId: string): number {
+ const r = this.db
+ .prepare("SELECT MAX(due) AS due FROM outbox WHERE conversation_id = ? AND status IN ('pending', 'sent', 'held') AND kind != 'file' AND purpose NOT IN ('', 'nudge')")
+ .get(conversationId) as Row;
+ return Number(r?.due ?? 0) || 0;
+ }
+ /** 这个会话最近发出去的一条 */
+ lastSentOutbox(conversationId: string): OutboxRow | undefined {
+ const r = this.db.prepare("SELECT * FROM outbox WHERE conversation_id = ? AND status = 'sent' ORDER BY seq DESC LIMIT 1").get(conversationId) as Row | undefined;
+ return r ? this.toOutbox(r) : undefined;
+ }
+ /** 合进这一条的那几条 */
+ mergedOutbox(id: string): OutboxRow[] {
+ return (this.db.prepare("SELECT * FROM outbox WHERE merged_into = ? ORDER BY seq").all(id) as Row[]).map((r) => this.toOutbox(r));
+ }
+ /** 一条消息实际的去向:合进别的一条的,看那一条 */
+ carrierOutbox(id: string): OutboxRow | undefined {
+ let row = this.getOutbox(id);
+ for (let i = 0; row && row.status === "merged" && row.mergedInto && i < 8; i++) row = this.getOutbox(row.mergedInto);
+ return row;
+ }
+ /** 没送到、要人管的:留着的、一直失败的(试了 minAttempts 次还在试)、放弃了还没处理掉的(since 之后) */
+ undeliveredOutbox(o: { botId?: string; minAttempts: number; since: number }): OutboxRow[] {
+ const where = ["(status = 'held' OR (status = 'pending' AND attempts >= ?) OR (status = 'gone' AND seen_at = 0 AND updated_at >= ?))", "purpose != 'nudge'"];
+ const args: Array<string | number> = [o.minAttempts, o.since];
+ if (o.botId) (where.push("bot_id = ?"), args.push(o.botId));
+ return (this.db.prepare(`SELECT * FROM outbox WHERE ${where.join(" AND ")} ORDER BY seq`).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);
@@ -988,17 +1109,18 @@ export class Store {
endedAt: Number(r.ended_at),
endReason: String(r.end_reason),
stoppedBy: String(r.stopped_by),
+ anytime: Number(r.anytime ?? 0) === 1,
createdAt: Number(r.created_at),
updatedAt: Number(r.updated_at),
};
}
- insertTask(t: Omit<TaskRow, "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy">): TaskRow {
+ insertTask(t: Omit<TaskRow, "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy" | "anytime"> & { anytime?: boolean }): TaskRow {
this.db
.prepare(
- `INSERT INTO tasks(id, bot_id, conversation_id, origin_message_id, origin_ref, title, brief, session_id, folder, model, permission, budget_usd, created_at, updated_at)
- VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT INTO tasks(id, bot_id, conversation_id, origin_message_id, origin_ref, title, brief, session_id, folder, model, permission, budget_usd, anytime, created_at, updated_at)
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
- .run(t.id, t.botId, t.conversationId, t.originMessageId, t.originRef, t.title, t.brief, t.sessionId, t.folder, t.model, t.permission, t.budgetUsd, t.createdAt, t.updatedAt);
+ .run(t.id, t.botId, t.conversationId, t.originMessageId, t.originRef, t.title, t.brief, t.sessionId, t.folder, t.model, t.permission, t.budgetUsd, t.anytime ? 1 : 0, t.createdAt, t.updatedAt);
return this.getTask(t.id)!;
}
getTask(id: string): TaskRow | undefined {
diff --git a/src/tasks/attention.ts b/src/tasks/attention.ts
index a6e6ad8..3dd499a 100644
--- a/src/tasks/attention.ts
+++ b/src/tasks/attention.ts
@@ -9,17 +9,18 @@
*/
import type { ApprovalRow, Store } from "../store/db.js";
import { questionsOf, type QuestionItem } from "../agent/approvals.js";
+import type { AttentionItem as DeliveryItem } from "../core/delivery.js";
import { logger } from "../log.js";
const log = logger("attention");
/** question / approval:在等你回答、批准;failed:任务失败了;delivery:结果没送到;login:渠道登录过期了 */
export type AttentionKind = "question" | "approval" | "failed" | "delivery" | "login";
-/** answer、approve、deny、retry、stop、seen(知道了)、relogin(去重新扫码)、open(打开对话) */
-export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "seen" | "relogin" | "open";
+/** answer、approve、deny、retry(任务再试 / 消息再发)、stop、dismiss(不再提示)、relogin(去重新扫码)、open(打开对话) */
+export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open";
export interface AttentionItem {
- /** 稳定 id:approval:<id>、task:<id>、login:<bot>:<渠道> */
+ /** 稳定 id:approval:<id>、task:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道> */
id: string;
kind: AttentionKind;
botId: string;
@@ -196,6 +197,28 @@ export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[
});
}
+/**
+ * 出站队列那一份(core/delivery.ts):没送到的结果,一个会话一行。「1 条结果未送达微信 · 在微信里发条消息就能收到」,
+ * 第二行是没送到的那几句(在这里就能看到);一直失败的可以重试、放弃了的可以不再提示
+ */
+export function deliveryItem(d: DeliveryItem, botName: string): AttentionItem {
+ const text = d.messages.map((m) => m.text.replace(/\s+/g, " ").trim()).filter(Boolean).join(" / ");
+ return {
+ id: d.id,
+ kind: "delivery",
+ botId: d.botId,
+ botName,
+ subject: d.title,
+ status: d.line,
+ line: text.length > 300 ? text.slice(0, 299) + "…" : text,
+ since: d.since,
+ severity: d.severity === "error" ? "err" : "warn",
+ actions: d.actions,
+ conversationId: d.conversationId,
+ channel: d.channel,
+ };
+}
+
/** 列表变没变:id + 状态 + 第二行 */
function signature(items: AttentionItem[]): string {
return items.map((it) => `${it.id}|${it.status}|${it.line}`).join("\n");
diff --git a/src/tasks/service.ts b/src/tasks/service.ts
index 42aef15..ce34d47 100644
--- a/src/tasks/service.ts
+++ b/src/tasks/service.ts
@@ -5,8 +5,9 @@
* amb-tasks 插件给这些会话限定工具、加任务规则和 task_report。
* - run 是一段工作:排队 → 跑(占名额)→ 收尾(会话空了但还有后台命令或子代理:settling,仍占名额)→ 结束。
* 名额见 slots.ts;聊天从不占名额(人的通道)。
- * - 一轮结束、会话安静下来时按代理最近的 Report 结束这个 run:done / failed 的那一句经出站队列发回请求它的会话
- * (微信在 24 小时窗口内,飞书回复在请求那条消息下),网页写进会话历史。没有 Report 就提醒一次,还没有就算失败。
+ * - 一轮结束、会话安静下来时按代理最近的 Report 结束这个 run:done / failed 的那一句按主动消息的规则(core/delivery.ts:
+ * 免打扰、合并、每天上限、微信窗口)发回请求它的会话(飞书回复在请求那条消息下),网页写进会话历史。
+ * 没有 Report 就提醒一次,还没有就算失败。进行中的任务给微信留配额,也算续期提醒里"之后还要发的"。
* - 宿主欠会话的每条输入都落库(交出去时记 DSH 收件 id,会话里出现这条用户消息时记 taken)。应用重启或代理进程退出时,
* 跑着的 run 记为 interrupted,给任务排一个恢复 run:先交一条恢复说明,没被会话收下的输入再交一次,收下过的不再交。
* - 停止只停这个任务(指令通道:取消这一轮、停它的后台命令、之后的工具调用一律拒绝),聊天和别的任务照常。
@@ -19,7 +20,7 @@
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
-import type { Outbox } from "../core/outbox.js";
+import { needsPerson, type Delivery } from "../core/delivery.js";
import { ActivityLog, type ActivityStep } from "../agent/activity.js";
import { ResumeFailed, deliverables } from "../agent/host.js";
import { answerLine, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";
@@ -80,8 +81,8 @@ export interface TaskNotification {
export interface TaskServiceOptions {
store: Store;
host: TaskHost;
- /** 微信、飞书的结果经出站队列发(没有就只写进会话历史) */
- outbox?: Outbox;
+ /** 微信、飞书的结果按主动消息的规则经出站队列发(没有就只写进会话历史);任务的提问也经它推 */
+ delivery?: Delivery;
/** 任务的提问、任务会话里的审批(没有就不能问用户) */
approvals?: TaskApprovals;
/** 机器人没设模型时用的默认模型 */
@@ -187,7 +188,13 @@ export class TaskService {
private dropped = new Set<string>();
private unlisten: (() => void) | undefined;
- constructor(private o: TaskServiceOptions) {}
+ constructor(private o: TaskServiceOptions) {
+ // 进行中的任务:给微信留 1 条配额(聊天回复不会把它挤掉),续期提醒里也算"之后还要发的"
+ o.delivery?.addReserver((p) => this.working(p.conversationId).length);
+ // 推给用户、还没回答的提问(审批):再留 1 条(设计第 6 节:任务、待答问题各占 1 条,一共最多 3 条)
+ o.delivery?.addReserver((p) => (o.approvals?.pending(p.conversationId).some((r) => r.taskId) ? 1 : 0));
+ o.delivery?.addUpcoming((p) => this.working(p.conversationId).map((t) => ({ label: t.title, kind: "task" as const })));
+ }
private get store(): Store {
return this.o.store;
@@ -275,7 +282,7 @@ export class TaskService {
// ---------- 建任务、追加、停止 ----------
/** 新任务(聊天代理的 task_start):用户原话、说明、最近的对话、附件和记忆快照作为第一条输入,排进队列 */
- create(o: { botId: string; conversationId: string; title: string; brief: string; budgetUsd?: number }): { task?: TaskRow; error?: string } {
+ create(o: { botId: string; conversationId: string; title: string; brief: string; budgetUsd?: number; anytime?: boolean }): { task?: TaskRow; error?: string } {
const conv = this.store.getConversation(o.conversationId);
const bot = this.store.getBot(o.botId);
if (!conv || !bot) return { error: "conversation not found" };
@@ -308,6 +315,7 @@ export class TaskService {
model: conv.model || bot.defaultModel || this.o.defaultModel?.() || "",
permission: st.permission,
budgetUsd: o.budgetUsd && o.budgetUsd > 0 ? Math.min(o.budgetUsd, 100) : 1,
+ anytime: !!o.anytime,
createdAt: now,
updatedAt: now,
});
@@ -696,9 +704,9 @@ export class TaskService {
// ---------- 送达 ----------
/**
- * 把结果(或失败)发回请求它的会话:微信、飞书经出站队列(id 固定:task:<任务>:result|failure:<run>,同一 id 只发一次;
- * 微信在发送时才查 24 小时窗口和配额),飞书回复在请求那条消息下;网页只写进会话历史。同时写进会话历史,
- * 给聊天代理留一张便条。交过的 run 不再交(重启后补送也一样)。
+ * 把结果(或失败)发回请求它的会话:微信、飞书按主动消息的规则推送(id 固定:task:<任务>:result|failure:<run>,同一 id 只发一次;
+ * 免打扰时排到早上、几条一起到的合成摘要,微信在发送时才查 24 小时窗口和配额),飞书回复在请求那条消息下;
+ * 网页只写进会话历史。同时写进会话历史,给聊天代理留一张便条。交过的 run 不再交(重启后补送也一样)。
*/
private deliver(task: TaskRow, runId: string, outcome: "done" | "failed", report: TaskReport | undefined, error: string): void {
const run = this.store.getRun(runId);
@@ -713,21 +721,31 @@ export class TaskService {
const msg = oneLine(report?.message ?? "");
const text = outcome === "done" ? clip(msg, MESSAGE_MAX) || `「${task.title}」做好了。` : `⚠️「${task.title}」没做完:${clip(msg || error || "没有给出结果", MESSAGE_MAX)}`;
const files = outcome === "done" ? this.files(task, report?.files ?? []) : [];
- if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.outbox) this.post(conv, task, id, text, files);
+ if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.delivery) this.post(conv, task, id, purpose, text, files);
this.store.addMessage(conv.id, "assistant", files.length && conv.channel === "web" ? `${text}\n\n${files.map((f) => `- ${path.relative(this.o.host.workspace(task.botId), f)}`).join("\n")}` : text);
this.store.updateRun(runId, { delivery: id });
this.note(conv.id, outcome === "done" ? `[后台任务「${task.title}」已完成,已把结果发给用户] ${text}` : `[后台任务「${task.title}」失败了,已告诉用户] ${text}`);
}
- /** 微信、飞书:写进出站队列(同步落库;渠道没上线时等它上线) */
- private post(conv: Conversation, task: TaskRow, id: string, text: string, files: string[]): void {
- const outbox = this.o.outbox!;
+ /** 微信、飞书:按主动消息的规则写进出站队列(同步落库;渠道没上线时等它上线) */
+ private post(conv: Conversation, task: TaskRow, id: string, purpose: "result" | "failure", text: string, files: string[]): void {
const channel = conv.channel as "weixin" | "feishu";
const replyTo = channel === "feishu" ? task.originRef || replyHandle(this.store, conv.id).messageId || "" : "";
- const base = { botId: task.botId, channel, peerId: conv.peerId, replyTo };
- void outbox.send({ ...base, id, kind: channel === "feishu" && !replyTo ? "notice" : "text", body: { text } });
- if (channel === "feishu" && !replyTo) return;
- files.forEach((f, i) => void outbox.send({ ...base, id: `${id}:file:${i}`, kind: "file", body: { path: f, name: path.basename(f) } }));
+ const notice = channel === "feishu" && !replyTo;
+ this.o.delivery!.push({
+ id,
+ botId: task.botId,
+ channel,
+ peerId: conv.peerId,
+ purpose,
+ subject: task.title,
+ text,
+ files: notice ? [] : files,
+ replyTo,
+ kind: notice ? "notice" : "text",
+ anytime: task.anytime,
+ ref: `task:${task.id}`,
+ });
}
/** task_report 里的文件:先按任务文件夹找,再按工作区找;只交工作区里真实存在的文件 */
@@ -792,7 +810,7 @@ export class TaskService {
const a = (b?.args ?? {}) as Record<string, unknown>;
switch (String(b?.op ?? "")) {
case "start": {
- const r = this.create({ botId, conversationId: conv.id, title: String(a.title ?? ""), brief: String(a.brief ?? ""), budgetUsd: Number(a.budget_usd) || undefined });
+ const r = this.create({ botId, conversationId: conv.id, title: String(a.title ?? ""), brief: String(a.brief ?? ""), budgetUsd: Number(a.budget_usd) || undefined, anytime: a.anytime === true });
if (!r.task) return { error: r.error };
return {
text: `Started background task ${r.task.id} 「${r.task.title}」 in folder ${r.task.folder}. In your reply, tell the user in one sentence what now runs in the background and that they will hear back when it is done; they can keep chatting. Do not do the task yourself.`,
@@ -856,6 +874,8 @@ export class TaskService {
const task = this.store.getTask(row.taskId);
if (!task) return;
if (e.type === "decided" && row.kind === "question" && !row.blocking && row.status === "answered" && task.endReason !== "stopped") this.answered(task, row);
+ // 有了决定(在桌面上回答了、批了,任务停了):推给用户还没发出去的那条(排到早上、等微信窗口)不用再发了
+ if (e.type === "decided") this.o.delivery?.withdraw(askId(row), `已${row.status === "answered" ? "回答" : "处理"}`);
this.changed(task.id);
// 等批准时让出的名额:有了决定,排队的可能要等它了
if (e.type === "decided" && row.blocking) this.pump();
@@ -872,12 +892,13 @@ export class TaskService {
/**
* 推给请求它的会话(微信、飞书;网页的提问卡片就在对话里):一个会话同时只推一个,前一个没回答,后面的只在"需要你"里等,
- * 微信里光回编号才不会认错。出站 id 固定(askId),同一条只推一次;发不出去(微信窗口关了)由出站队列留着。
+ * 微信里光回编号才不会认错。按主动消息的规则推(core/delivery.ts:免打扰、每天上限;问题不合并):排着的、留着的都算推了。
+ * 出站 id 固定(askId),同一条只推一次;发不出去(微信窗口关了)由出站队列留着。
*/
private pushNext(conversationId: string): void {
const a = this.o.approvals;
- const outbox = this.o.outbox;
- if (!a || !outbox || !this.started) return;
+ const delivery = this.o.delivery;
+ if (!a || !delivery || !this.started) return;
const conv = this.store.getConversation(conversationId);
if (!conv || (conv.channel !== "weixin" && conv.channel !== "feishu")) return;
const rows = a.pending(conversationId).filter((r) => r.taskId).sort((x, y) => x.createdAt - y.createdAt);
@@ -887,15 +908,15 @@ export class TaskService {
const task = row ? this.store.getTask(row.taskId) : undefined;
if (!row || !task || task.endReason === "stopped") return;
const text = taskPromptText(row, task.title);
- const base = { id: askId(row), botId: task.botId, channel: conv.channel as "weixin" | "feishu", peerId: conv.peerId };
- if (conv.channel === "weixin") void outbox.send({ ...base, kind: "text", body: { text, raw: true } });
+ const base = { id: askId(row), botId: task.botId, channel: conv.channel as "weixin" | "feishu", peerId: conv.peerId, purpose: "question" as const, subject: task.title, text, ref: `task:${task.id}` };
+ if (conv.channel === "weixin") delivery.push({ ...base, raw: true });
else {
const replyTo = task.originRef || replyHandle(this.store, conv.id).messageId || "";
const buttons = promptButtons(row);
const title = row.kind === "approval" ? `需批准(任务「${task.title}」)` : `「${task.title}」想问你`;
const body = row.kind === "approval" ? (row.detail ? "`" + row.detail.slice(0, 300) + "`" : row.tool) : (questionsOf(row)[0]?.question ?? row.detail);
- if (replyTo && buttons) void outbox.send({ ...base, kind: "card", replyTo, body: { text, card: actionCardSpec(title, body, buttons) } });
- else void outbox.send({ ...base, kind: replyTo ? "text" : "notice", replyTo, body: { text } });
+ if (replyTo && buttons) delivery.push({ ...base, replyTo, card: actionCardSpec(title, body, buttons) });
+ else delivery.push({ ...base, replyTo, kind: replyTo ? "text" : "notice" });
}
if (row.kind === "question") this.store.addMessage(conv.id, "assistant", text);
log.info("pushed a background task's prompt", { task: task.id, kind: row.kind, channel: conv.channel });
@@ -916,16 +937,7 @@ export class TaskService {
};
}
- /** 没送到的结果:用户在"需要你"里看过了(知道了),不再算需要他 */
- seenDelivery(taskId: string): boolean {
- const run = this.store.latestRun(taskId);
- if (!run?.delivery || /:(dropped|seen)$/.test(run.delivery)) return false;
- this.store.updateRun(run.id, { delivery: `${run.delivery}:seen` });
- this.changed(taskId);
- return true;
- }
-
- /** "需要你"里任务那一份:失败、没送到、预算用完(提问和审批由审批中心那一份给) */
+ /** "需要你"里任务那一份:失败、预算用完(提问和审批由审批中心那一份给,没送到的由出站队列那一份给:core/delivery.ts) */
attention(): AttentionItem[] {
const out: AttentionItem[] = [];
const since = this.now() - 7 * 86400_000;
@@ -933,14 +945,14 @@ export class TaskService {
for (const t of tasks) {
const run = this.store.latestRun(t.id);
const st = this.stage(t, run);
- if (st.key !== "failed" && st.key !== "needs-you/delivery" && st.key !== "needs-you/budget") continue;
+ if (st.key !== "failed" && st.key !== "needs-you/budget") continue;
const bot = this.store.getBot(t.botId);
const conv = this.store.getConversation(t.conversationId);
const r = run?.report ?? t.report;
const line = st.key === "failed" ? r?.message || run?.error || "没有给出结果" : r?.message || r?.summary.split("\n")[0] || "";
out.push({
id: `task:${t.id}`,
- kind: st.key === "needs-you/delivery" ? "delivery" : "failed",
+ kind: "failed",
botId: t.botId,
botName: bot?.name ?? t.botId,
subject: t.title,
@@ -948,7 +960,7 @@ export class TaskService {
line: clip(oneLine(line), 200),
since: run?.endedAt || t.updatedAt,
severity: st.key === "failed" ? "err" : "warn",
- actions: st.key === "needs-you/delivery" ? ["seen"] : ["retry", "stop"],
+ actions: ["retry", "stop"],
conversationId: t.conversationId,
channel: conv?.channel ?? "",
taskId: t.id,
@@ -960,12 +972,13 @@ export class TaskService {
// ---------- 查看 ----------
private stage(task: TaskRow, run = this.store.latestRun(task.id)): Stage {
- const delivery = run?.delivery && !/:(dropped|seen)$/.test(run.delivery) ? this.o.store.getOutbox(run.delivery) : undefined;
+ // 结果没送到:留着等对方发消息、一直失败、放弃了(合进摘要的看那一条);排着等早上的、在「需要你」里不再提示的不算
+ const delivery = run?.delivery && !run.delivery.endsWith(":dropped") ? this.o.store.carrierOutbox(run.delivery) : undefined;
// 它在等的:任务会话(或子代理)里的审批、它报的提问
const now = this.now();
const rows = this.store.listApprovals({ status: "pending", botId: task.botId, limit: 200 }).filter((a) => (a.taskId === task.id || a.sessionId === task.sessionId) && (a.expiresAt === 0 || a.expiresAt > now));
const waiting = rows.some((a) => a.kind === "approval") ? "approval" : rows.length ? "answer" : undefined;
- return taskStage({ stopped: task.endReason === "stopped", undelivered: delivery?.status === "gone", waiting, run });
+ return taskStage({ stopped: task.endReason === "stopped", undelivered: needsPerson(delivery), waiting, run });
}
view(task: TaskRow): TaskView {
diff --git a/src/web/server.ts b/src/web/server.ts
index 44c5d59..ee70647 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -451,9 +451,9 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
ok = Array.isArray(b.answers)
? app.agent.approvals.answer(item.approvalId!, { answers: b.answers.map((a: any) => ({ id: String(a.id), selected: (a.selected ?? []).map(String), ...(a.custom ? { custom: String(a.custom) } : {}) })) }, "web")
: app.agent.approvals.answerText(item.approvalId!, String(b.text ?? ""), "web");
- } else if (action === "retry") ok = !(await app.tasks.retry(item.taskId!)).error;
+ } else if (item.kind === "delivery" && (action === "retry" || action === "dismiss")) ok = app.delivery.act(item.id, action);
+ else if (action === "retry") ok = !(await app.tasks.retry(item.taskId!)).error;
else if (action === "stop") ok = await app.tasks.stopTask(item.taskId!, "web");
- else if (action === "seen") ok = app.tasks.seenDelivery(item.taskId!);
if (!ok) throw new HttpError(409, "没能完成,可能已经处理过了");
app.attention.kick();
return send(res, 200, { ok: true, items: app.attention.list() });
@@ -657,6 +657,8 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
...(b.avatar !== undefined ? { avatar: b.avatar } : {}),
...(b.computerUse !== undefined ? { computerUse: { ...cur.computerUse, ...b.computerUse } } : {}),
...(b.media !== undefined ? { media: { ...cur.media, ...b.media } } : {}),
+ ...(b.quietHours !== undefined ? { quietHours: { ...cur.quietHours, ...b.quietHours } } : {}),
+ ...(b.nudge !== undefined ? { nudge: b.nudge } : {}),
memory: { ...cur.memory, ...(b.memory ?? {}) },
steward: { ...cur.steward, ...(b.steward ?? {}) },
});
diff --git a/test/delivery.e2e.test.ts b/test/delivery.e2e.test.ts
new file mode 100644
index 0000000..2a9a49a
--- /dev/null
+++ b/test/delivery.e2e.test.ts
@@ -0,0 +1,192 @@
+/**
+ * 主动消息的送达规则(3c)端到端:mock iLink + 真实 App(真实的出站队列、微信渠道、后台任务服务),钟是假的(只假 Date,拨着走),
+ * 时区是上海。主人在微信里用自己的机器人。
+ * - 退出演示:23:00 做好的结果 08:00 才发;微信窗口已经关了时留着、出现在「需要你」里,主人下次发消息时排在回复前面先到;
+ * - 免打扰里做好的几条到早上合成一条摘要;夜里的聊天回复照常马上回;
+ * - 续期提醒:窗口关闭前约 2 小时、还有任务在跑时发一次,只发一次;没有要发的就不发;回「ok」不进模型。
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { Store } from "../src/store/db.js";
+import { mockIlink, mockOpenAI, until } from "./helpers.js";
+
+const OWNER = "[email protected]";
+const FRIEND = "[email protected]";
+const CONV = `default:weixin:${OWNER}`;
+/** 上海时间 → 时间戳 */
+const at = (s: string) => Date.parse(`${s}:00+08:00`);
+
+let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+let ilink: Awaited<ReturnType<typeof mockIlink>>;
+let dataDir: string;
+let app: App;
+let n = 0;
+
+/** 拨钟:出站队列和续期提醒马上重新看一遍 */
+async function clock(t: string): Promise<void> {
+ vi.setSystemTime(at(t));
+ app.outbox.wake();
+ app.delivery.tick();
+ await settle();
+}
+async function settle(): Promise<void> {
+ await new Promise((r) => setTimeout(r, 50));
+ await app.channels.get("default")!.weixin!.idle();
+}
+/** 发给某人的消息(从 from 条之后) */
+const to = (user: string, from = 0) => ilink.state.sent.slice(from).filter((s) => s.to === user).map((s) => s.text);
+/** 主人发一条消息,等到回复 */
+async function say(user: string, text: string): Promise<string[]> {
+ const from = ilink.state.sent.length;
+ ilink.push(user, text);
+ await until(() => to(user, from).some((t) => t.includes(`你说:${text}`)), 8000);
+ await settle();
+ return to(user, from);
+}
+/** 一个后台任务做完了(结果是 message):写进库,让任务服务把结果发出去 */
+function finish(title: string, message: string): string {
+ const id = `t_e2e${++n}`;
+ const now = Date.now();
+ app.store.insertTask({ id, botId: "default", conversationId: CONV, originMessageId: 0, originRef: "", title, brief: title, sessionId: `task-${id}`, folder: `tasks/x-${id}`, model: "", permission: "workspace", budgetUsd: 1, createdAt: now, updatedAt: now });
+ app.store.insertRun({ id: `r_${id}`, botId: "default", taskId: id, sessionId: `task-${id}`, cause: "launch", queuedAt: now });
+ app.store.updateRun(`r_${id}`, { state: "ended", outcome: "done", startedAt: now, endedAt: now, report: { state: "done", summary: "", message, at: now } });
+ app.store.updateTask(id, { endedAt: now, endReason: "done", report: { state: "done", summary: "", message, at: now } });
+ // 应用重启时任务服务会补送结束了却没送出的结果;这里用同一条路
+ app.tasks.start();
+ return id;
+}
+const stage = (id: string) => app.tasks.get(id)!.stage.label;
+
+beforeAll(async () => {
+ vi.useFakeTimers({ toFake: ["Date"], shouldAdvanceTime: true });
+ vi.setSystemTime(at("2026-11-06T21:00"));
+ llm = await mockOpenAI({ key: "gw-key" });
+ ilink = await mockIlink();
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-delivery-e2e-"));
+ const s = new Store(path.join(dataDir, "anymodel.db"));
+ s.createBot({ id: "default", name: "小蓝", weixinEnabled: true });
+ s.saveWeixinAccount({ botId: "default", botToken: "tok", ilinkBotId: "[email protected]", baseUrl: ilink.url, ownerUserId: OWNER });
+ s.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_AGENT: "off" } });
+ app = new App(config, { weixinPollTimeoutMs: 1000, printQrToTerminal: false, timeZone: "Asia/Shanghai" });
+ await app.start();
+ app.access.allow("default", "weixin", FRIEND, "test");
+});
+
+afterAll(async () => {
+ await app?.stop();
+ await llm?.close();
+ await ilink?.close();
+ vi.useRealTimers();
+});
+
+describe("退出演示:免打扰与微信窗口", () => {
+ it("23:00 做好的结果 08:00 才发;夜里的聊天照常马上回", async () => {
+ // 周五 21:00 主人说了句话(窗口到周六 21:00)
+ expect(await say(OWNER, "晚上好")).toEqual(["[mock-a] 你说:晚上好"]);
+ await clock("2026-11-06T23:00");
+ const from = ilink.state.sent.length;
+ const t = finish("GPU 价格调研", "GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800。");
+ await settle();
+ expect(to(OWNER, from)).toEqual([]);
+ expect(stage(t)).toBe("已完成");
+ // 健康:排着等早上,「需要你」里什么都没有
+ expect(app.delivery.attentionItems()).toEqual([]);
+ // 朋友夜里发消息:回复照常马上回(聊天回复从不推迟)
+ expect(await say(FRIEND, "睡了吗")).toEqual(["[mock-a] 你说:睡了吗"]);
+ await clock("2026-11-07T07:59");
+ expect(to(OWNER, from)).toEqual([]);
+ await clock("2026-11-07T08:00");
+ await until(() => to(OWNER, from).length >= 1, 5000);
+ expect(to(OWNER, from)).toEqual(["GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800。"]);
+ await clock("2026-11-07T09:00");
+ expect(to(OWNER, from)).toHaveLength(1);
+ });
+
+ it("窗口已经关了:留着,出现在「需要你」里;主人下次发消息时排在回复前面先到,只到一次", async () => {
+ // 周六 23:00 又做好一个;主人周五 21:00 之后再没说话,窗口周六 21:00 已经关了
+ await clock("2026-11-07T23:00");
+ const from = ilink.state.sent.length;
+ const t = finish("季度报告", "季度报告做好了,在 tasks 文件夹里。");
+ await clock("2026-11-08T08:00");
+ await until(() => app.store.getOutbox(`task:${t}:result:r_${t}`)?.status === "held", 5000);
+ expect(to(OWNER, from)).toEqual([]);
+ expect(stage(t)).toBe("未送达");
+ const items = app.delivery.attentionItems();
+ expect(items).toHaveLength(1);
+ expect(items[0]).toMatchObject({ kind: "delivery", botId: "default", title: "1 条结果未送达微信", line: "在微信里发条消息就能收到", severity: "warn" });
+ expect(items[0].messages.map((m) => m.text)).toEqual(["季度报告做好了,在 tasks 文件夹里。"]);
+ // 「需要你」里就这一行(任务那一份不重复列),没送到的那句在这里就能看到
+ expect(app.attention.list().map((x) => [x.kind, x.subject, x.status, x.line, x.actions])).toEqual([["delivery", "1 条结果未送达微信", "在微信里发条消息就能收到", "季度报告做好了,在 tasks 文件夹里。", []]]);
+ // 主人周日 09:00 发消息:先收到留着的结果,再收到这次的回复
+ await clock("2026-11-08T09:00");
+ expect(await say(OWNER, "早")).toEqual(["你不在时:季度报告做好了,在 tasks 文件夹里。", "[mock-a] 你说:早"]);
+ expect(app.delivery.attentionItems()).toEqual([]);
+ expect(app.attention.list()).toEqual([]);
+ expect(stage(t)).toBe("已完成");
+ expect(await say(OWNER, "好的")).toEqual(["[mock-a] 你说:好的"]);
+ });
+
+ it("免打扰里做好的几条,到早上合成一条摘要", async () => {
+ // 窗口从周日 09:00 开到周一 09:00
+ await clock("2026-11-08T23:00");
+ const from = ilink.state.sent.length;
+ finish("周报", "周报写好了。");
+ await clock("2026-11-08T23:40");
+ finish("发票整理", "发票整理好了,一共 12 张。");
+ await clock("2026-11-09T02:00");
+ finish("域名续费", "⚠️「域名续费」没做完:支付页要登录。");
+ await clock("2026-11-09T07:00");
+ expect(to(OWNER, from)).toEqual([]);
+ await clock("2026-11-09T08:00");
+ await until(() => to(OWNER, from).length >= 1, 5000);
+ await settle();
+ expect(to(OWNER, from)).toEqual(["3 个后台任务:\n· 周报写好了。\n· 发票整理好了,一共 12 张。\n· ⚠️「域名续费」没做完:支付页要登录。"]);
+ });
+});
+
+describe("续期提醒", () => {
+ it("窗口关闭前约 2 小时、还有任务在跑:提醒一次,只一次;回「ok」不进模型;没东西要发的人收不到", async () => {
+ // 周一 10:00 主人和朋友都说了话:窗口到周二 10:00,提醒时间周二 08:00
+ await clock("2026-11-09T10:00");
+ await say(OWNER, "帮我后台调研 Y");
+ await say(FRIEND, "在吗");
+ const now = Date.now();
+ app.store.insertTask({ id: "t_live", botId: "default", conversationId: CONV, originMessageId: 0, originRef: "", title: "调研 Y", brief: "", sessionId: "task-t_live", folder: "tasks/y", model: "", permission: "workspace", budgetUsd: 1, createdAt: now, updatedAt: now });
+ app.store.insertRun({ id: "r_live", botId: "default", taskId: "t_live", sessionId: "task-t_live", cause: "launch", queuedAt: now });
+ app.store.updateRun("r_live", { state: "running", startedAt: now });
+ // 进行中的任务给它留了一条配额
+ expect(app.delivery.reserved("default", "weixin", OWNER)).toBe(1);
+ const from = ilink.state.sent.length;
+ await clock("2026-11-10T07:59");
+ expect(to(OWNER, from)).toEqual([]);
+ await clock("2026-11-10T08:00");
+ await until(() => to(OWNER, from).length >= 1, 5000);
+ const nudge = "接下来还有 1 条结果要发给你(调研 Y)。回个「ok」我就能继续发给你。";
+ expect(to(OWNER, from)).toEqual([nudge]);
+ await clock("2026-11-10T08:30");
+ await clock("2026-11-10T09:30");
+ expect(to(OWNER, from)).toEqual([nudge]);
+ // 朋友那边没有要发的:什么都没收到
+ expect(to(FRIEND, from)).toEqual([]);
+ // 主人回「ok」:窗口重新开始,回一句,不进模型
+ const calls = llm.calls.length;
+ ilink.push(OWNER, "ok");
+ await until(() => to(OWNER, from).length >= 2, 5000);
+ await settle();
+ expect(to(OWNER, from)).toEqual([nudge, "好的,到时发给你。"]);
+ expect(llm.calls.length).toBe(calls);
+ expect(app.store.listMessages(CONV).slice(-3).map((m) => [m.role, m.content])).toEqual([["assistant", nudge], ["user", "ok"], ["assistant", "好的,到时发给你。"]]);
+ // 任务做完了、结果发了:下一个窗口快关时没有要发的,不再提醒
+ app.store.updateRun("r_live", { state: "ended", outcome: "done", endedAt: Date.now(), delivery: "x:dropped" });
+ app.store.updateTask("t_live", { endedAt: Date.now(), endReason: "done" });
+ const later = ilink.state.sent.length;
+ await clock("2026-11-11T07:40");
+ await clock("2026-11-11T08:30");
+ expect(to(OWNER, later)).toEqual([]);
+ });
+});
diff --git a/test/delivery.unit.test.ts b/test/delivery.unit.test.ts
new file mode 100644
index 0000000..266dabe
--- /dev/null
+++ b/test/delivery.unit.test.ts
@@ -0,0 +1,474 @@
+/**
+ * 主动消息的送达规则(3c):免打扰时段的时间计算(时区、跨午夜、夏令时)、什么时候发(免打扰、人醒着、anytime、合并、每天上限)、
+ * 到时间时合成摘要、对方发消息时一起放出来、微信配额预留、续期提醒(时间、只发一次、没东西不发、免打扰不发、关掉、配额、「ok」)、
+ * 「需要你」里的未送达(只有不健康的才有)。时钟都是注入的。
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { Store, type OutboxRow } from "../src/store/db.js";
+import { Outbox } from "../src/core/outbox.js";
+import { Delivery, digestText, nudgeAt, nudgeText, type PushInput } from "../src/core/delivery.js";
+import { DEFAULT_QUIET, fmtWhen, inQuiet, minuteOf, nextAt, quietEnd, startOfDay } from "../src/core/quiet.js";
+import { deliverWeixin } from "../src/channels/weixin/channel.js";
+import { WeixinQuota } from "../src/channels/weixin/quota.js";
+import { normalizeSettings } from "../src/agent/settings.js";
+import { Held } from "../src/core/outbox.js";
+
+const TZ = "Asia/Shanghai";
+/** 上海时间 "2026-11-06T23:00" → 时间戳 */
+const at = (s: string) => Date.parse(`${s}${s.length === 16 ? ":00" : ""}+08:00`);
+const H = 3600_000;
+
+describe("免打扰时段:主人的时区", () => {
+ const q = DEFAULT_QUIET;
+ it("22:00–08:00 跨午夜,左闭右开", () => {
+ expect(minuteOf("22:00")).toBe(1320);
+ expect(minuteOf("24:00")).toBeUndefined();
+ expect(["21:59", "22:00", "23:30", "03:00", "07:59", "08:00", "12:00"].map((t) => inQuiet(at(`2026-11-06T${t}`), q, TZ))).toEqual([false, true, true, true, true, false, false]);
+ });
+ it("结束时间:当晚的到第二天 8 点,凌晨的到当天 8 点;不在时段里就是现在", () => {
+ expect(quietEnd(at("2026-11-06T23:00"), q, TZ)).toBe(at("2026-11-07T08:00"));
+ expect(quietEnd(at("2026-11-07T03:10"), q, TZ)).toBe(at("2026-11-07T08:00"));
+ expect(quietEnd(at("2026-11-07T09:00"), q, TZ)).toBe(at("2026-11-07T09:00"));
+ });
+ it("同一天里的时段、关掉、起止相同都行", () => {
+ const noon = { enabled: true, from: "12:00", to: "13:30" };
+ expect([inQuiet(at("2026-11-06T12:10"), noon, TZ), inQuiet(at("2026-11-06T13:30"), noon, TZ)]).toEqual([true, false]);
+ expect(quietEnd(at("2026-11-06T12:10"), noon, TZ)).toBe(at("2026-11-06T13:30"));
+ expect(inQuiet(at("2026-11-06T23:00"), { ...q, enabled: false }, TZ)).toBe(false);
+ expect(inQuiet(at("2026-11-06T23:00"), { enabled: true, from: "08:00", to: "08:00" }, TZ)).toBe(false);
+ });
+ it("按时区算:纽约的 23:00 是上海的中午", () => {
+ const t = Date.parse("2026-11-06T23:00:00-05:00");
+ expect(inQuiet(t, q, "America/New_York")).toBe(true);
+ expect(inQuiet(t, q, TZ)).toBe(false);
+ expect(quietEnd(t, q, "America/New_York")).toBe(Date.parse("2026-11-07T08:00:00-05:00"));
+ });
+ it("夏令时那天按钟面时间:纽约 3 月 8 日凌晨跳过一小时,早上 8 点照样是 8 点", () => {
+ const t = Date.parse("2026-03-07T23:00:00-05:00");
+ expect(quietEnd(t, q, "America/New_York")).toBe(Date.parse("2026-03-08T08:00:00-04:00"));
+ expect(nextAt(Date.parse("2026-11-01T00:30:00-04:00"), 8 * 60, "America/New_York")).toBe(Date.parse("2026-11-01T08:00:00-05:00"));
+ });
+ it("一天的开始;给用户看的时间", () => {
+ expect(startOfDay(at("2026-11-06T23:00"), TZ)).toBe(at("2026-11-06T00:00"));
+ const now = at("2026-11-07T08:00");
+ expect(fmtWhen(at("2026-11-07T09:30"), now, TZ)).toBe("今天 9:30");
+ expect(fmtWhen(at("2026-11-07T21:00"), now, TZ)).toBe("今晚 21:00");
+ expect(fmtWhen(at("2026-11-08T08:00"), now, TZ)).toBe("明早 8:00");
+ expect(fmtWhen(at("2026-11-08T15:00"), now, TZ)).toBe("明天 15:00");
+ expect(fmtWhen(at("2026-11-09T09:00"), now, TZ)).toBe("周一 9:00");
+ expect(fmtWhen(at("2026-11-20T09:00"), now, TZ)).toBe("11月20日 9:00");
+ });
+});
+
+describe("消息样式", () => {
+ it("摘要:一条就是它自己;后台任务、提醒、混在一起各有一句开头,一项一行", () => {
+ expect(digestText([{ purpose: "result", text: "GPU 价格调研好了" }])).toBe("GPU 价格调研好了");
+ expect(digestText([{ purpose: "result", text: "A 好了" }, { purpose: "failure", text: "⚠️「B」没做完:打不开" }])).toBe("2 个后台任务:\n· A 好了\n· ⚠️「B」没做完:打不开");
+ expect(digestText([{ purpose: "rule", text: "X 降价到 ¥199" }, { purpose: "rule", text: "仓库 Y 的 issue #12 有新回复" }])).toBe("2 条提醒:\n· X 降价到 ¥199\n· 仓库 Y 的 issue #12 有新回复");
+ expect(digestText([{ purpose: "rule", text: "a" }, { purpose: "result", text: "b\n第二行" }])).toBe("2 条消息:\n· a\n· b 第二行");
+ });
+ it("续期提醒:产品负责人给的那句话;任务的;多于 3 项", () => {
+ const now = at("2026-11-07T08:00");
+ const rules = [
+ { label: "天气", at: at("2026-11-08T08:00"), kind: "rule" as const },
+ { label: "周报", at: at("2026-11-09T09:00"), kind: "rule" as const },
+ ];
+ expect(nudgeText(rules, now, TZ)).toEqual({ text: "接下来还有 2 条提醒要发给你(明早 8:00 天气、周一 9:00 周报)。回个「ok」我就能继续按时提醒你。", noun: "提醒" });
+ expect(nudgeText([{ label: "GPU 价格调研", kind: "task" }], now, TZ).text).toBe("接下来还有 1 条结果要发给你(GPU 价格调研)。回个「ok」我就能继续发给你。");
+ const many = nudgeText([...rules, { label: "GPU", kind: "task" }, { label: "D", kind: "task" }], now, TZ).text;
+ expect(many).toBe("接下来还有 4 条消息要发给你(明早 8:00 天气、周一 9:00 周报、GPU 等)。回个「ok」我就能继续发给你。");
+ });
+ it("续期提醒的时间:关闭前 2 小时;那时在免打扰里就挪到结束时或开始前,哪个近用哪个", () => {
+ const q = DEFAULT_QUIET;
+ // 10:00 发的消息,第二天 10:00 关:8:00 刚好不在免打扰里
+ expect(nudgeAt(at("2026-11-06T10:00"), at("2026-11-07T10:00"), q, TZ)).toBe(at("2026-11-07T08:00"));
+ // 9:00 关:7:00 在免打扰里,8:00 结束(离关闭还有 1 小时)比前一晚 21:59 近
+ expect(nudgeAt(at("2026-11-06T09:00"), at("2026-11-07T09:00"), q, TZ)).toBe(at("2026-11-07T08:00"));
+ // 凌晨 1:00 关:23:00 在免打扰里,结束时已经关了,只能在 21:59
+ expect(nudgeAt(at("2026-11-06T01:00"), at("2026-11-07T01:00"), q, TZ)).toBe(at("2026-11-06T21:59"));
+ // 7:40 关:结束时离关闭不到 30 分钟,前一晚 21:59
+ expect(nudgeAt(at("2026-11-06T07:40"), at("2026-11-07T07:40"), q, TZ)).toBe(at("2026-11-06T21:59"));
+ expect(nudgeAt(at("2026-11-06T09:00"), at("2026-11-07T09:00"), { ...q, enabled: false }, TZ)).toBe(at("2026-11-07T07:00"));
+ });
+});
+
+/** 一个机器人、一个时钟、一个出站队列(发送函数只记下来)和送达规则 */
+function rig(start: string) {
+ let now = at(start);
+ const store = new Store(":memory:");
+ store.createBot({ id: "b", name: "小蓝", weixinEnabled: true });
+ const outbox = new Outbox(store, { now: () => now, retry: [10, 20] });
+ const delivery = new Delivery({ store, outbox, now: () => now, timeZone: TZ });
+ const sent: OutboxRow[] = [];
+ let fail: ((row: OutboxRow) => Error | undefined) | undefined;
+ for (const ch of ["weixin", "feishu"])
+ outbox.register("b", ch, async (row) => {
+ const e = fail?.(row);
+ if (e) throw e;
+ sent.push(row);
+ });
+ outbox.start();
+ delivery.start();
+ const push = (id: string, text: string, o: Partial<PushInput> = {}) => delivery.push({ id, botId: "b", channel: "weixin", peerId: "u1", purpose: "result", subject: id, text, ...o });
+ const settle = async () => {
+ for (let i = 0; i < 3; i++) {
+ await outbox.idle();
+ await new Promise((r) => setImmediate(r));
+ }
+ };
+ /** 拨钟,让出站队列重新看一遍 */
+ const go = async (t: string) => {
+ now = at(t);
+ outbox.wake();
+ await new Promise((r) => setImmediate(r));
+ await settle();
+ };
+ return {
+ store,
+ outbox,
+ delivery,
+ sent,
+ push,
+ settle,
+ go,
+ texts: () => sent.map((r) => r.body.text),
+ now: () => now,
+ setNow: (t: number) => (now = t),
+ onFail: (f: typeof fail) => (fail = f),
+ settings: (patch: Record<string, unknown>) => {
+ const b = store.getBot("b")!;
+ store.updateBot("b", { settings: normalizeSettings({ ...b.settings, ...patch }) });
+ },
+ close: () => {
+ delivery.stop();
+ void outbox.stop();
+ store.close();
+ },
+ };
+}
+
+describe("什么时候发", () => {
+ let r: ReturnType<typeof rig>;
+ afterEach(() => r.close());
+
+ it("23:00 的结果排到 08:00;聊天回复从不推迟", async () => {
+ r = rig("2026-11-06T23:00");
+ expect(r.push("t1", "GPU 价格调研好了")).toEqual({ due: at("2026-11-07T08:00"), reason: "quiet_hours" });
+ await r.outbox.send({ id: "reply", botId: "b", channel: "weixin", peerId: "u1", kind: "text", body: { text: "这是聊天回复" } });
+ await r.settle();
+ expect(r.texts()).toEqual(["这是聊天回复"]);
+ expect(r.store.getOutbox("t1")).toMatchObject({ status: "scheduled", reason: "quiet_hours" });
+ await r.go("2026-11-07T07:59");
+ expect(r.texts()).toEqual(["这是聊天回复"]);
+ await r.go("2026-11-07T08:00");
+ expect(r.texts()).toEqual(["这是聊天回复", "GPU 价格调研好了"]);
+ expect(r.store.getOutbox("t1")).toMatchObject({ status: "sent" });
+ });
+
+ it("不受限的情况:任务说了马上告诉(anytime)、人 10 分钟内刚发过消息、免打扰关掉了", async () => {
+ r = rig("2026-11-06T23:00");
+ expect(r.push("a", "马上要的", { anytime: true }).reason).toBe("");
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u2", contextToken: "c", quotaRemaining: 10, windowStartedAt: at("2026-11-06T22:55") });
+ expect(r.push("b", "人醒着", { peerId: "u2" }).reason).toBe("");
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u3", contextToken: "c", quotaRemaining: 10, windowStartedAt: at("2026-11-06T22:45") });
+ expect(r.push("c", "15 分钟前说过话", { peerId: "u3" }).reason).toBe("quiet_hours");
+ r.settings({ quietHours: { enabled: false } });
+ expect(r.push("d", "关掉了", { peerId: "u4" }).reason).toBe("");
+ r.settings({ quietHours: { enabled: true, from: "23:30", to: "07:00" } });
+ expect(r.push("e", "时段改了", { peerId: "u5" }).reason).toBe("");
+ });
+
+ it("合并:上一条发出不到 2 分钟,后来的排到 2 分钟后,合成一条摘要(一项一行)", async () => {
+ r = rig("2026-11-06T10:00");
+ r.push("a", "A 好了");
+ await r.settle();
+ r.setNow(at("2026-11-06T10:00") + 30_000);
+ expect(r.push("b", "B 好了")).toEqual({ due: at("2026-11-06T10:02"), reason: "coalesce" });
+ r.setNow(at("2026-11-06T10:01"));
+ expect(r.push("c", "C 好了").due).toBe(at("2026-11-06T10:02"));
+ await r.go("2026-11-06T10:02");
+ expect(r.texts()).toEqual(["A 好了", "2 个后台任务:\n· B 好了\n· C 好了"]);
+ expect(r.store.getOutbox("c")).toMatchObject({ status: "merged", mergedInto: "b" });
+ expect(r.store.getOutbox("b")!.body).toMatchObject({ digest: true });
+ // 过了 2 分钟的照常马上发
+ await r.go("2026-11-06T10:30");
+ r.push("d", "D 好了");
+ await r.settle();
+ expect(r.texts().at(-1)).toBe("D 好了");
+ });
+
+ it("免打扰里到的几条到早上合成一条;文件排在摘要后面", async () => {
+ r = rig("2026-11-06T23:00");
+ r.push("a", "A 好了", { files: ["/w/a.pdf"] });
+ r.setNow(at("2026-11-07T02:00"));
+ r.push("b", "⚠️「B」没做完:页面要登录", { purpose: "failure" });
+ r.setNow(at("2026-11-07T07:59"));
+ r.push("c", "C 好了");
+ await r.go("2026-11-07T08:00");
+ expect(r.sent.map((x) => (x.kind === "file" ? `[${x.body.name}]` : x.body.text))).toEqual(["3 个后台任务:\n· A 好了\n· ⚠️「B」没做完:页面要登录\n· C 好了", "[a.pdf]"]);
+ });
+
+ it("每天上限:微信 3 条,第 4 条起排到第二天早上合成一条;飞书 5 条", async () => {
+ r = rig("2026-11-06T09:00");
+ for (const [i, t] of ["09:00", "11:00", "13:00"].entries()) {
+ await r.go(`2026-11-06T${t}`);
+ r.push(`w${i}`, `第 ${i + 1} 条`);
+ await r.settle();
+ }
+ await r.go("2026-11-06T15:00");
+ expect(r.push("w3", "第 4 条")).toEqual({ due: at("2026-11-07T08:00"), reason: "daily_cap" });
+ await r.go("2026-11-06T18:00");
+ expect(r.push("w4", "第 5 条").due).toBe(at("2026-11-07T08:00"));
+ // 飞书单独算,5 条
+ for (let i = 0; i < 5; i++) {
+ await r.go(`2026-11-06T1${i}:30`);
+ expect(r.push(`f${i}`, `飞书 ${i + 1}`, { channel: "feishu", peerId: "oc_1", kind: "notice" }).reason).toBe("");
+ await r.settle();
+ }
+ expect(r.push("f5", "飞书 6", { channel: "feishu", peerId: "oc_1", kind: "notice" }).reason).toBe("daily_cap");
+ await r.go("2026-11-07T08:00");
+ expect(r.texts().filter((t) => !t!.startsWith("飞书"))).toEqual(["第 1 条", "第 2 条", "第 3 条", "2 个后台任务:\n· 第 4 条\n· 第 5 条"]);
+ expect(r.texts().at(-1)).toBe("飞书 6");
+ });
+
+ it("到时间时再看一遍:设置改了还在免打扰里就再排", async () => {
+ r = rig("2026-11-06T23:00");
+ r.push("a", "A 好了");
+ r.settings({ quietHours: { enabled: true, from: "22:00", to: "09:00" } });
+ await r.go("2026-11-07T08:00");
+ expect(r.texts()).toEqual([]);
+ expect(r.store.getOutbox("a")).toMatchObject({ status: "scheduled", due: at("2026-11-07T09:00") });
+ await r.go("2026-11-07T09:00");
+ expect(r.texts()).toEqual(["A 好了"]);
+ });
+
+ it("对方发消息时排着的不用再等:一起放出来,合成摘要(不是「你不在时」);有等对方的就是「你不在时」", async () => {
+ r = rig("2026-11-06T23:00");
+ r.push("a", "A 好了");
+ r.push("b", "B 好了");
+ expect(r.outbox.release("b", "weixin", "u1", (rows) => r.delivery.combine(rows))).toBe(2);
+ await r.settle();
+ expect(r.texts()).toEqual(["2 个后台任务:\n· A 好了\n· B 好了"]);
+ // 一条留着(窗口关了)、一条排着:合成「你不在时」
+ r.onFail((row) => (row.id === "c" ? new Held("窗口关了") : undefined));
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u2", contextToken: "c", quotaRemaining: 10, windowStartedAt: at("2026-11-05T09:00") });
+ await r.go("2026-11-07T10:00");
+ r.push("c", "C 好了", { peerId: "u2" });
+ await r.settle();
+ expect(r.store.getOutbox("c")).toMatchObject({ status: "held", reason: "window_closed" });
+ r.setNow(at("2026-11-07T10:00") + 60_000);
+ r.push("d", "D 好了", { peerId: "u2" });
+ r.onFail(undefined);
+ r.outbox.release("b", "weixin", "u2", (rows) => r.delivery.combine(rows));
+ await r.settle();
+ expect(r.texts().at(-1)).toBe("你不在时:\nC 好了\n\nD 好了");
+ });
+
+ it("飞书:摘要直接发到会话(不回复在某一条下面);问题不合并", async () => {
+ r = rig("2026-11-06T23:00");
+ r.push("a", "A 好了", { channel: "feishu", peerId: "oc_1", replyTo: "om_a" });
+ r.push("b", "B 好了", { channel: "feishu", peerId: "oc_1", replyTo: "om_b" });
+ r.push("q", "❓ 中文还是英文?", { channel: "feishu", peerId: "oc_1", purpose: "question" });
+ await r.go("2026-11-07T08:00");
+ expect(r.sent.map((x) => [x.kind, x.replyTo, x.body.text])).toEqual([
+ ["notice", "", "2 个后台任务:\n· A 好了\n· B 好了"],
+ ["text", "", "❓ 中文还是英文?"],
+ ]);
+ });
+});
+
+describe("微信配额预留", () => {
+ const setup = (remaining: number, reserved: number) => {
+ const store = new Store(":memory:");
+ store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: remaining, windowStartedAt: Date.now() });
+ const sent: string[] = [];
+ const client = { sendText: async (_u: string, text: string) => void sent.push(text) } as any;
+ const quota = new WeixinQuota(store, "b");
+ quota.reserver = () => reserved;
+ const row = (text: string, purpose = "") => ({ id: "r", peerId: "u1", kind: "text", body: { text }, progress: 0, attempts: 0, purpose }) as OutboxRow;
+ return { sent, client, quota, row };
+ };
+ it("聊天回复只能用剩下的减去留给后台任务的;后台任务的结果用全部剩下的", async () => {
+ const a = setup(4, 3);
+ await deliverWeixin(a.client, a.quota, a.row("x".repeat(9000)), () => {});
+ expect(a.sent).toHaveLength(1);
+ expect(a.sent[0]).toMatch(/已达到本轮可发送条数上限/);
+ await expect(deliverWeixin(a.client, a.quota, a.row("再说一句"), () => {})).rejects.toMatchObject({ code: "quota" });
+ await deliverWeixin(a.client, a.quota, a.row("GPU 价格调研好了", "result"), () => {});
+ expect(a.sent.at(-1)).toBe("GPU 价格调研好了");
+ expect(a.quota.remaining("u1")).toBe(2);
+ });
+
+ it("留几条:进行中的任务各 1 条(登记的)、排着的主动消息 1 条,最多 3 条", () => {
+ const r = rig("2026-11-06T23:00");
+ let live = 0;
+ r.delivery.addReserver(() => live);
+ expect(r.delivery.reserved("b", "weixin", "u1")).toBe(0);
+ live = 1;
+ expect(r.delivery.reserved("b", "weixin", "u1")).toBe(1);
+ r.push("a", "A 好了");
+ expect(r.delivery.reserved("b", "weixin", "u1")).toBe(2);
+ live = 5;
+ expect(r.delivery.reserved("b", "weixin", "u1")).toBe(3);
+ expect(r.delivery.reserved("b", "weixin", "someone-else")).toBe(3);
+ r.close();
+ });
+});
+
+describe("续期提醒(「回个 ok」)", () => {
+ let r: ReturnType<typeof rig>;
+ afterEach(() => r.close());
+ /** 用户周五 10:00 发了最后一条消息:窗口周六 10:00 关,提醒在周六 08:00 */
+ beforeEach(() => {
+ r = rig("2026-11-06T10:00");
+ r.store.ensureConversation("b", "weixin", "u1");
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: 6, windowStartedAt: at("2026-11-06T10:00") });
+ });
+ const rules = () => [
+ { label: "天气", at: at("2026-11-08T08:00"), kind: "rule" as const },
+ { label: "周报", at: at("2026-11-09T09:00"), kind: "rule" as const },
+ ];
+
+ it("关闭前约 2 小时、窗口关闭后还有要发的:发一句,只发一次;用掉一条配额;回「ok」不进模型", async () => {
+ r.delivery.addUpcoming(() => rules());
+ await r.go("2026-11-07T07:59");
+ r.delivery.tick();
+ await r.settle();
+ expect(r.texts()).toEqual([]);
+ await r.go("2026-11-07T08:00");
+ r.delivery.tick();
+ await r.settle();
+ expect(r.texts()).toEqual(["接下来还有 2 条提醒要发给你(明早 8:00 天气、周一 9:00 周报)。回个「ok」我就能继续按时提醒你。"]);
+ expect(r.sent[0]).toMatchObject({ purpose: "nudge", id: Delivery.nudgeId("b", "u1", at("2026-11-06T10:00")) });
+ expect(r.store.listMessages("b:weixin:u1").at(-1)!.content).toBe(r.texts()[0]);
+ await r.go("2026-11-07T09:00");
+ r.delivery.tick();
+ await r.settle();
+ expect(r.sent).toHaveLength(1);
+ // 回「ok」:认出来,回一句;再回一次就是普通聊天了
+ expect(r.delivery.ack("b", "weixin", "u1", "今天天气怎么样")).toBeUndefined();
+ expect(r.delivery.ack("b", "weixin", "u1", "OK!")).toBe("好的,到时提醒你。");
+ expect(r.delivery.ack("b", "weixin", "u1", "ok")).toBeUndefined();
+ });
+
+ it("没有要发的就什么都不发;窗口关闭前就会送到的(排在 08:00 的)不算", async () => {
+ await r.go("2026-11-06T23:00");
+ r.push("t", "GPU 好了");
+ expect(r.store.getOutbox("t")).toMatchObject({ status: "scheduled", due: at("2026-11-07T08:00") });
+ // 拨到 08:00,先看提醒(出站队列还没把它发出去)
+ r.setNow(at("2026-11-07T08:00"));
+ r.delivery.tick();
+ await r.settle();
+ expect(r.sent.filter((x) => x.purpose === "nudge")).toEqual([]);
+ expect(r.delivery.upcoming({ botId: "b", channel: "weixin", peerId: "u1", conversationId: "b:weixin:u1" }, at("2026-11-07T10:00"))).toEqual([]);
+ });
+
+ it("进行中的任务算(TaskService 登记的);排在窗口关闭之后的主动消息算", async () => {
+ r.delivery.addUpcoming((p) => (p.peerId === "u1" ? [{ label: "GPU 价格调研", kind: "task" }] : []));
+ await r.go("2026-11-07T08:00");
+ r.delivery.tick();
+ await r.settle();
+ expect(r.texts()).toEqual(["接下来还有 1 条结果要发给你(GPU 价格调研)。回个「ok」我就能继续发给你。"]);
+ expect(r.delivery.ack("b", "weixin", "u1", "好的")).toBe("好的,到时发给你。");
+ // 下一个窗口:一条排到周一的结果也算
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: 6, windowStartedAt: at("2026-11-07T10:00") });
+ await r.outbox.send({ id: "later", botId: "b", channel: "weixin", peerId: "u1", kind: "text", body: { text: "周报" }, purpose: "result", subject: "周报", due: at("2026-11-09T09:00") });
+ await r.go("2026-11-08T08:00");
+ r.delivery.tick();
+ await r.settle();
+ expect(r.texts().at(-1)).toBe("接下来还有 2 条结果要发给你(明早 9:00 周报、GPU 价格调研)。回个「ok」我就能继续发给你。");
+ });
+
+ it("免打扰时不发;按机器人关掉;配额用完、窗口已关不发", async () => {
+ r.delivery.addUpcoming(() => rules());
+ // 窗口凌晨 1:00 关:提醒挪到前一晚 21:59;22:30 才看到时已经在免打扰里,不发
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: 6, windowStartedAt: at("2026-11-06T01:00") });
+ await r.go("2026-11-06T22:30");
+ r.delivery.tick();
+ await r.settle();
+ expect(r.sent).toEqual([]);
+ await r.go("2026-11-06T21:59");
+ r.settings({ nudge: false });
+ r.delivery.tick();
+ await r.settle();
+ expect(r.sent).toEqual([]);
+ r.settings({ nudge: true });
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: 0, windowStartedAt: at("2026-11-06T01:00") });
+ r.delivery.tick();
+ await r.settle();
+ expect(r.sent).toEqual([]);
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: 3, windowStartedAt: at("2026-11-06T01:00") });
+ r.delivery.tick();
+ await r.settle();
+ expect(r.sent).toHaveLength(1);
+ // 发不出去(窗口刚好关了):不留着,下个窗口也不补发
+ await r.go("2026-11-07T08:00");
+ r.store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: 6, windowStartedAt: at("2026-11-06T10:00") });
+ r.onFail(() => new Held("窗口关了"));
+ r.delivery.tick();
+ await r.settle();
+ expect(r.store.getOutbox(Delivery.nudgeId("b", "u1", at("2026-11-06T10:00")))).toMatchObject({ status: "gone" });
+ expect(r.delivery.attentionItems()).toEqual([]);
+ });
+});
+
+describe("「需要你」里的未送达", () => {
+ let r: ReturnType<typeof rig>;
+ afterEach(() => r.close());
+
+ it("健康的什么都没有:发出去的、排着等早上的", async () => {
+ r = rig("2026-11-06T23:00");
+ r.push("a", "A 好了");
+ r.push("b", "B 好了", { anytime: true });
+ await r.settle();
+ expect(r.delivery.attentionItems()).toEqual([]);
+ });
+
+ it("微信窗口关了:一项「1 条结果未送达微信」,对方发消息后自己消失", async () => {
+ r = rig("2026-11-06T10:00");
+ let changes = 0;
+ r.delivery.onChange(() => changes++);
+ r.onFail(() => new Held("对方超过 24 小时没有发消息", "window_closed"));
+ r.push("a", "GPU 价格调研好了");
+ await r.settle();
+ await new Promise((x) => setImmediate(x));
+ const [item] = r.delivery.attentionItems();
+ expect(item).toMatchObject({ id: "delivery:b:weixin:u1:held", kind: "delivery", state: "held", severity: "warn", title: "1 条结果未送达微信", line: "在微信里发条消息就能收到", actions: [] });
+ expect(item.messages).toEqual([{ id: "a", text: "GPU 价格调研好了", at: at("2026-11-06T10:00"), ref: "" }]);
+ expect(changes).toBeGreaterThan(0);
+ r.onFail(undefined);
+ r.outbox.release("b", "weixin", "u1", (rows) => r.delivery.combine(rows));
+ await r.settle();
+ expect(r.delivery.attentionItems()).toEqual([]);
+ });
+
+ it("一直失败(试了 3 次):还在重试;放弃了:可以重试、可以不再提示;短命的提示和续期提醒不算", async () => {
+ r = rig("2026-11-06T10:00");
+ r.onFail(() => new Error("HTTP 500"));
+ r.push("f", "A 好了", { channel: "feishu", peerId: "oc_1", replyTo: "om_1" });
+ await r.outbox.send({ id: "ack", botId: "b", channel: "feishu", peerId: "oc_1", kind: "text", body: { text: "收到" }, ttlMs: 600_000 });
+ for (let i = 1; i <= 3; i++) await r.go(`2026-11-06T10:0${i}`);
+ expect(r.store.getOutbox("f")!.attempts).toBeGreaterThanOrEqual(3);
+ expect(r.delivery.attentionItems()).toMatchObject([{ state: "failed", severity: "error", title: "1 条结果没能发到飞书", line: "还在重试", actions: ["retry"] }]);
+ r.store.updateOutbox("f", { status: "gone", error: "发送失败" });
+ const [item] = r.delivery.attentionItems();
+ expect(item.actions).toEqual(["retry", "dismiss"]);
+ expect(r.delivery.act(item.id, "dismiss")).toBe(true);
+ expect(r.delivery.attentionItems()).toEqual([]);
+ r.store.updateOutbox("f", { seenAt: 0 });
+ r.onFail(undefined);
+ expect(r.delivery.act(item.id, "retry")).toBe(true);
+ await r.settle();
+ expect(r.store.getOutbox("f")).toMatchObject({ status: "sent" });
+ expect(r.delivery.attentionItems()).toEqual([]);
+ });
+
+ it("合成的一条按里面的条数算", async () => {
+ r = rig("2026-11-06T23:00");
+ r.push("a", "A 好了");
+ r.push("b", "B 好了");
+ r.onFail(() => new Held("窗口关了", "window_closed"));
+ await r.go("2026-11-07T08:00");
+ expect(r.delivery.attentionItems().map((i) => i.title)).toEqual(["2 条结果未送达微信"]);
+ });
+});
diff --git a/test/tasks.integration.test.ts b/test/tasks.integration.test.ts
index 4453954..2c680fd 100644
--- a/test/tasks.integration.test.ts
+++ b/test/tasks.integration.test.ts
@@ -90,6 +90,8 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
new App(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_DEFAULT_MODEL: "mock-agent", AMB_AGENT_PREWARM: "0" } }), {
printQrToTerminal: false,
weixinPollTimeoutMs: 1000,
+ // 这里测任务本身:所有测试共用主人的一个会话,主动消息的每天上限和合并(3c,见 delivery 的测试)不拦
+ deliveryLimits: { dailyCap: { weixin: 1000 }, coalesceMs: 0 },
});
beforeAll(async () => {
@@ -118,7 +120,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-"));
app = makeApp();
// 主人已经扫码登录;渠道连到 mock iLink
- app.store.createBot({ id: "default", name: "小蓝", weixinEnabled: true, settings: { avatar: "blue" } as any });
+ app.store.createBot({ id: "default", name: "小蓝", weixinEnabled: true, settings: { avatar: "blue", quietHours: { enabled: false, from: "22:00", to: "08:00" } } as any });
app.store.saveWeixinAccount({ botId: "default", botToken: "tok", ilinkBotId: "[email protected]", baseUrl: ilink.url, ownerUserId: OWNER });
await app.start();
base = app.web!.url.replace(/\/+$/, "");
diff --git a/test/tasks.unit.test.ts b/test/tasks.unit.test.ts
index fe066ad..5739830 100644
--- a/test/tasks.unit.test.ts
+++ b/test/tasks.unit.test.ts
@@ -16,6 +16,7 @@ import { AgentHost, ResumeFailed } from "../src/agent/host.js";
import { DEFAULT_SETTINGS, normalizeSettings } from "../src/agent/settings.js";
import { NUDGE, TASK_RULES, recoveryNote, taskBrief } from "../src/agent/prompts/index.js";
import { Outbox } from "../src/core/outbox.js";
+import { Delivery } from "../src/core/delivery.js";
import { Store } from "../src/store/db.js";
const flush = async (n = 5) => {
@@ -161,7 +162,7 @@ describe("TaskService(假宿主)", () => {
let ws: string;
const CONV = "b:weixin:owner";
- const make = () => new TaskService({ store, host, outbox, approvals, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });
+ const make = () => new TaskService({ store, host, delivery: new Delivery({ store, outbox }), approvals, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });
beforeEach(() => {
ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-unit-"));
store = new Store(":memory:");
@@ -273,7 +274,7 @@ describe("TaskService(假宿主)", () => {
expect(report(t.sessionId, "needs_you").error).toMatch(/needs a question/);
expect(report(t.sessionId, "maybe").error).toMatch(/state must be progress, needs_you, done or failed/);
svc.stop();
- const bare = new TaskService({ store, host, outbox, defaultModel: () => "m" });
+ const bare = new TaskService({ store, host, delivery: new Delivery({ store, outbox }), defaultModel: () => "m" });
bare.start();
const u = bare.create({ botId: "b", conversationId: CONV, title: "U", brief: "" }).task!;
await flush();
@@ -468,7 +469,7 @@ describe("TaskService(假宿主)", () => {
expect(approvals.pending(web.id).map((r) => r.taskId)).toEqual([w.id]);
});
- it("「需要你」里任务的那一份:失败的(重试、停止),没送到的(知道了);重试开一个 retry run", async () => {
+ it("「需要你」里任务的那一份:失败的(重试、停止);没送到的不在这里(出站队列那一份);重试开一个 retry run", async () => {
const t = start();
await flush();
await turn(t.sessionId, () => void report(t.sessionId, "failed", "X 云的价格页要登录"));
@@ -481,9 +482,10 @@ describe("TaskService(假宿主)", () => {
expect(svc.attention()).toEqual([]);
await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
store.updateOutbox(store.latestRun(t.id)!.delivery, { status: "gone", error: "窗口关了" });
- expect(svc.attention().map((x) => [x.kind, x.status, x.line, x.actions])).toEqual([["delivery", "未送达", "好了", ["seen"]]]);
- expect(svc.seenDelivery(t.id)).toBe(true);
+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/delivery");
expect(svc.attention()).toEqual([]);
+ // 在「需要你」里点了不再提示(出站队列记作看过):任务回到已完成
+ store.updateOutbox(store.latestRun(t.id)!.delivery, { seenAt: Date.now() });
expect(svc.get(t.id)!.stage.key).toBe("ready");
});
@@ -737,6 +739,70 @@ describe("TaskService(假宿主)", () => {
expect(svc.get(t.id)!.stage).toMatchObject({ key: "needs-you/delivery", label: "未送达", group: "needs" });
});
+ it("3c:结果留着等对方在微信里发消息、一直发不出去、合进的摘要留着:未送达;排着等早上的:已完成", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ const id = store.listRuns({ taskId: t.id })[0].delivery;
+ const stage = () => svc.get(t.id)!.stage.key;
+ store.updateOutbox(id, { status: "scheduled", due: Date.now() + 8 * 3600_000 });
+ expect(stage()).toBe("ready");
+ store.updateOutbox(id, { status: "held", reason: "window_closed" });
+ expect(stage()).toBe("needs-you/delivery");
+ store.updateOutbox(id, { status: "pending", attempts: 3 });
+ expect(stage()).toBe("needs-you/delivery");
+ store.insertOutbox({ id: "digest", botId: "b", channel: "weixin", conversationId: CONV, peerId: "owner", kind: "text", body: { text: "2 个后台任务:…" }, replyTo: "", due: 0, createdAt: 0, expiresAt: Date.now() + 3600_000, status: "held" });
+ store.updateOutbox(id, { status: "merged", mergedInto: "digest" });
+ expect(stage()).toBe("needs-you/delivery");
+ store.updateOutbox("digest", { status: "sent" });
+ expect(stage()).toBe("ready");
+ });
+
+ it("3c:进行中的任务给微信留 1 条配额,续期提醒里也算;task_start 的 anytime 让结果不受免打扰限制", async () => {
+ const delivery = new Delivery({ store, outbox });
+ svc.stop();
+ svc = new TaskService({ store, host, delivery, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });
+ svc.start();
+ const t = start();
+ await flush();
+ const peer = { botId: "b", channel: "weixin", peerId: "owner", conversationId: CONV };
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(1);
+ expect(delivery.upcoming(peer, Date.now())).toEqual([{ label: "GPU 价格调研", kind: "task" }]);
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(0);
+ store.setAgentSession(CONV, "b", "chat-1");
+ const r = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "start", args: { title: "夜里也要", brief: "做完马上告诉我", anytime: true } });
+ expect(r.error ?? "").toBe("");
+ const night = store.listTasks({ conversationId: CONV }).find((x) => x.title === "夜里也要")!;
+ expect(night.anytime).toBe(true);
+ expect(store.getTask(t.id)!.anytime).toBe(false);
+ });
+
+ it("3b + 3c:任务的提问按主动消息的规则推(免打扰时排到早上);没回答前给微信多留 1 条配额;在桌面上回答了,排着的那条撤回", async () => {
+ // 主人的时区 23:00,主人 10 分钟内没说过话:在免打扰里
+ const at = Date.UTC(2026, 10, 6, 23, 0);
+ const delivery = new Delivery({ store, outbox, timeZone: "UTC", now: () => at });
+ svc.stop();
+ svc = new TaskService({ store, host, delivery, approvals, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });
+ svc.start();
+ const t = start();
+ await flush();
+ await ask(t.sessionId);
+ const [row] = asks();
+ expect(row).toMatchObject({ kind: "text", status: "scheduled", purpose: "question", reason: "quiet_hours", due: Date.UTC(2026, 10, 7, 8, 0), subject: "GPU 价格调研", ref: `task:${t.id}` });
+ expect(row.body.raw).toBe(true);
+ // 排着的提问 1 条 + 待答的提问 1 条(任务在等回答,不算进行中)
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(2);
+ const [q] = approvals.pendingForTask(t.id);
+ expect(approvals.answerText(q.id, "2", "web")).toBe(true);
+ await flush();
+ // 早上不会再问一个已经回答了的问题;也不算没送到
+ expect(store.getOutbox(row.id)).toMatchObject({ status: "gone", error: "已回答" });
+ expect(store.getOutbox(row.id)!.seenAt).toBeGreaterThan(0);
+ expect(svc.get(t.id)!.stage.group).toBe("working");
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(1);
+ });
+
it("任务会话里阻塞着的审批:阶段是等你批准", async () => {
const t = start();
await flush();
diff --git a/ui/css/settings.css b/ui/css/settings.css
index b4a36df..17c8806 100644
--- a/ui/css/settings.css
+++ b/ui/css/settings.css
@@ -38,6 +38,9 @@
.mf-state { display: inline-flex; align-items: center; gap: var(--space-1-5); font-size: var(--fs-sm); color: var(--fg-2); }
.balance { font-size: var(--fs-lg); font-weight: var(--fw-semibold); font-variant-numeric: tabular-nums; }
.balance.low { color: var(--red); }
+/* 免打扰的起止:两个整点选择 + 中间一条短横,开关和它们隔开一点 */
+.settings .row .range-dash { color: var(--muted); font-variant-numeric: tabular-nums; }
+.settings .row .ctl .pick ~ .switch { margin-left: var(--space-2); }
.settings input.field.num-in { width: 96px; --field-h: var(--ctl-md); text-align: right; font-variant-numeric: tabular-nums; }
/* 用量:近 N 天的日柱状图 + 模型排行 */
diff --git a/ui/design/gallery.js b/ui/design/gallery.js
index 56b4b5f..bdf2870 100644
--- a/ui/design/gallery.js
+++ b/ui/design/gallery.js
@@ -572,7 +572,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场
<${NeedsRow} count=${3} onClick=${() => {}} /><${NeedsRow} count=${2} on onClick=${() => {}} /><${NeedsRow} count=${0} />
</div>`}
<//>
- <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你批准 / 失败 / 登录过期">
+ <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你批准 / 未送达 / 失败 / 登录过期">
${() => html`<div class="list needs-list">${NEEDS.map((it) => html`<${NeedItem} item=${it} multiBot onAct=${async () => {}} />`)}</div>`}
<//>
<//>
@@ -602,6 +602,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场
const NEEDS = [
{ id: "q", kind: "question", botName: "小蓝", subject: "GPU 价格调研", status: "等你回答", line: "报告用中文还是英文?", since: Date.now() - 2 * 60_000, severity: "warn", questions: [{ id: "a", question: "报告用中文还是英文?", options: [{ label: "中文" }, { label: "英文" }] }] },
{ id: "a", kind: "approval", botName: "小蓝", subject: "清理旧构建", status: "等你批准", line: "rm -rf build/", since: Date.now() - 5 * 60_000, severity: "warn" },
+ { id: "d", kind: "delivery", botName: "小蓝", subject: "1 条结果未送达微信", status: "在微信里发条消息就能收到", line: "季度报告做好了,在 tasks 文件夹里。", since: Date.now() - 20 * 60_000, severity: "warn", actions: [] },
{ id: "f", kind: "failed", botName: "红魔", subject: "季度报告", status: "失败", line: "X 云的价格页要登录,我进不去", since: Date.now() - 40 * 60_000, severity: "err" },
{ id: "l", kind: "login", botName: "绿草", subject: "微信登录已过期", status: "", line: "", since: Date.now() - 3 * 3600_000, severity: "err" },
];
diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.js
index 2644d91..10ff102 100644
--- a/ui/screens/bot-settings.js
+++ b/ui/screens/bot-settings.js
@@ -10,6 +10,12 @@ import { PERMS, FULL_WARNING, confirmPermission } from "../lib/perms.js";
import { CHANNEL_NAME, SOURCE_LABEL } from "../lib/access.js";
import { fmtAgo } from "../lib/format.js";
+/** 免打扰的起止:整点 */
+const HOURS = Array.from({ length: 24 }, (_, h) => {
+ const v = `${String(h).padStart(2, "0")}:00`;
+ return [v, v];
+});
+
function Row({ id, name, sub, title, children, off }) {
return html`<div class=${`row${off ? " off" : ""}`} id=${`bot-${id}`} title=${title}>
<div class="who"><div class="name">${name}</div>${sub && html`<div class="sub">${sub}</div>`}</div>
@@ -272,6 +278,21 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod
<//>
</div>
+ <div class="list-head">主动消息</div>
+ <div class="list">
+ <${Row} id="quiet" name="免打扰" sub="后台结果留到结束后再发">
+ ${s.quietHours.enabled && html`<${MenuButton} label="免打扰开始" value=${s.quietHours.from} width=${120} options=${HOURS}
+ onChange=${(v) => put({ quietHours: { from: v } })} />
+ <span class="range-dash">–</span>
+ <${MenuButton} label="免打扰结束" value=${s.quietHours.to} width=${120} options=${HOURS}
+ onChange=${(v) => put({ quietHours: { to: v } })} />`}
+ <${Switch} label="免打扰" value=${s.quietHours.enabled} onChange=${(v) => put({ quietHours: { enabled: v } })} />
+ <//>
+ ${bot.weixinEnabled && html`<${Row} id="nudge" name="微信续期提醒" sub="还有消息要发时,24 小时到期前请你回一句">
+ <${Switch} label="微信续期提醒" value=${s.nudge} onChange=${(v) => put({ nudge: v })} />
+ <//>`}
+ </div>
+
<div class="list-head">电脑操作</div>
<div class="list">
<${Row} id="computer" name="电脑操作" sub=${cu ? cu.reason : ""} title=${cu && cu.notice}>
diff --git a/ui/screens/needs-you.js b/ui/screens/needs-you.js
index 9940f0c..f885d53 100644
--- a/ui/screens/needs-you.js
+++ b/ui/screens/needs-you.js
@@ -66,7 +66,8 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin }) {
<${Button} loading=${busy === "deny"} disabled=${!!busy} onClick=${() => act("deny")}>拒绝<//>`}
${item.kind === "failed" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>重试<//>
<button type="button" class="text danger" disabled=${!!busy} onClick=${() => act("stop")}>停止</button>`}
- ${item.kind === "delivery" && html`<${Button} loading=${busy === "seen"} disabled=${!!busy} onClick=${() => act("seen")}>知道了<//>`}
+ ${item.kind === "delivery" && item.actions.includes("retry") && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>重试<//>`}
+ ${item.kind === "delivery" && item.actions.includes("dismiss") && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>不再提示</button>`}
${item.kind === "login" && html`<${Button} onClick=${() => onRelogin?.(item.botId)}>重新扫码<//>`}
</div>
${writing && html`<div class="need-reply">