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.

Merge origin/master into feat/p3d-rules (bilingual rules UI)

Marla8093b3622c91
diff --cc electron/main.ts
index 1d87abd,041a283..2a0a720
--- a/electron/main.ts
+++ b/electron/main.ts
@@@ -6,9 -6,10 +6,10 @@@
* - 托盘:显示 / 开机自启 / 退出;关闭窗口=隐藏到托盘(可在设置 → 常规里改为退出);退出时干净关闭 magpie
* - 「需要你」:托盘提示和角标是件数(没事时什么都不加),新的一件在窗口不在前台时发一条系统通知(每件最多一次)
* - 设置页里的开机自启、缩放、打开数据目录经 core.desktop 回调到这里(同进程,无需 preload/IPC)
+ * - 托盘菜单和对话框跟着应用语言(src/i18n):跟随系统时取系统首选语言,界面里换了语言托盘菜单立刻重建
* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。
*/
- import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, net, powerMonitor, shell, dialog, safeStorage } from "electron";
-import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, nativeTheme, net, shell, dialog, safeStorage } from "electron";
++import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, nativeTheme, net, powerMonitor, shell, dialog, safeStorage } from "electron";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
@@@ -207,10 -242,7 +242,10 @@@ async function boot(): Promise<void>
fetch: ((input: string | URL | Request, init?: RequestInit) => net.fetch(input instanceof URL ? input.href : input, init)) as typeof fetch,
};
await core.start();
- if (!core.web) throw new Error("管理界面未启动");
+ if (!core.web) throw new Error(t("desktop.uiNotStarted"));
+ // 规则的定时器:电脑醒来、解锁时马上重新看一遍(睡着时错过的按宽限期补跑一次或记为跳过)
+ powerMonitor.on("resume", () => core?.tasks.scheduler.wake());
+ powerMonitor.on("unlock-screen", () => core?.tasks.scheduler.wake());
entryUrl = `${core.web.url.replace(/\/$/, "")}/?token=${encodeURIComponent(config.ui.token)}`;
log.info(`数据目录:${dataDir}`);
log.info(`管理界面:${core.web.url}`);
diff --cc src/agent/approvals.ts
index 1aa4956,63dffeb..dc1bcd9
--- a/src/agent/approvals.ts
+++ b/src/agent/approvals.ts
@@@ -268,10 -266,10 +269,10 @@@ export class ApprovalCenter
* - 任务的提问是机器人最后一条消息:只认选项编号或选项原文
*/
handleReply(conversationId: string, text: string, by: string, ctx: ReplyContext = {}): ReplyResult {
- const t = text.trim();
- if (!t || t.startsWith("/")) return { handled: false };
+ const msg = text.trim();
+ if (!msg || msg.startsWith("/")) return { handled: false };
const all = this.pending(conversationId);
- const chat = all.filter((r) => !r.taskId);
+ const chat = all.filter((r) => !r.taskId && !r.ruleId);
const task = all.filter((r) => r.taskId);
// 引用了任务的提示
const quote = ctx.quote;
diff --cc src/agent/manager.ts
index 0eda731,e2455a5..3766daa
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@@ -12,8 -12,8 +12,9 @@@ import type { MediaModel, MediaPlan, Me
import { APPROVAL_TTL_MS, ApprovalCenter, TASK_APPROVAL_TTL_MS, type QuestionItem } from "./approvals.js";
import { MemoryError, MemoryStore, type Scope } from "./memory.js";
import type { TaskHost, TaskService } from "../tasks/service.js";
+import { RULE_APPROVAL_TTL_MS } from "../tasks/rules.js";
import { DEFAULT_SETTINGS, type BotSettings, type MediaConfirm } from "./settings.js";
+ import { t, tl } from "../i18n/index.js";
import {
HANDOFF_SYSTEM,
REVIEW_SYSTEM,
diff --cc src/app.ts
index 1e1567a,a6a3605..9bde72e
--- a/src/app.ts
+++ b/src/app.ts
@@@ -44,8 -44,7 +44,9 @@@ import { MediaService, pickDefault } fr
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 { RuleEvents } from "./tasks/rule-events.js";
+import { lockDataDir, type DataDirLock } from "./store/lock.js";
+ import { detached, setLangPref, t } from "./i18n/index.js";
import { Attention, approvalItems, deliveryItem, type AttentionItem } from "./tasks/attention.js";
const log = logger("app");
@@@ -149,10 -149,10 +153,12 @@@ export class App
private picksTimer: NodeJS.Timeout | undefined;
private modelInfoCache: { at: number; data: Record<string, ModelInfo> } | undefined;
private modelInfoLoading: Promise<Record<string, ModelInfo>> | undefined;
+ /** 数据目录锁(命令行、Docker:同一个数据目录只能一个宿主,调度器开始之前拿) */
+ private lock: DataDirLock | undefined;
constructor(readonly config: AppConfig, readonly opts: AppOptions = {}) {
+ // 应用语言(托盘菜单、后台和发到微信 / 飞书的系统消息用它;界面请求用请求自己的语言,见 src/i18n)
+ setLangPref(config.ui.lang);
// 日志文件:<dataDir>/logs/app.log(打包后的桌面版看不到 stdout,故障排查全靠它)
if (opts.fileLog !== false) initFileLog(path.join(config.dataDir, "logs"));
registerSecret(config.ui.token);
diff --cc src/i18n/messages/app.ts
index 0000000,f4b7adf..9cd1953
mode 000000,100644..100644
--- a/src/i18n/messages/app.ts
+++ b/src/i18n/messages/app.ts
@@@ -1,0 -1,42 +1,47 @@@
+ // app:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。
+ import type { Catalog } from "../types.js";
+
+ export const zh = {
+ external_mode: "外部模型端点模式下不管理 Modelflare 连接",
+ bot_not_found: "机器人不存在",
+ magpie_failed: "magpie 启动失败:{message}",
+ // 第一次启动时建的机器人(按当时的语言)
+ default_bot_name: "我的助手",
+ default_bot_prompt: "你是一个乐于助人的中文助手,回答简洁准确。",
+ feishu_failed: "机器人「{name}」飞书长连接启动失败:{message}",
+ weixin_expired: "机器人「{name}」微信登录已过期,请在信息面板的「渠道」里重新扫码",
+ weixin_connected: "机器人「{name}」微信已连接",
+ // 收到的消息里图片 / 文件 / 语音的占位(core/types.ts eventText)
+ media_image: "图片",
+ media_file: "文件",
+ media_video: "视频",
+ media_quoted_image: "引用的图片",
+ media_quoted_file: "引用的文件",
+ media_quoted_video: "引用的视频",
+ media_voice: "[语音]",
+ media_not_downloaded: "{label}(未能下载:{error})",
++ // 数据目录锁(store/lock.ts):同一个数据目录只能有一个宿主
++ data_dir_locked: "数据目录 {dir} 正被另一个 anymodel bot 进程使用({who})。先退出它,或者换一个数据目录(AMB_DATA_DIR)。",
++ data_dir_locked_remote: "{host} 上的 pid {pid}",
+ } satisfies Catalog;
+
+ export const en: Catalog<typeof zh> = {
+ external_mode: "Modelflare connections aren't managed when using an external model endpoint",
+ bot_not_found: "Bot not found",
+ magpie_failed: "magpie failed to start: {message}",
+ default_bot_name: "My Assistant",
+ default_bot_prompt: "You are a helpful assistant. Answer concisely and accurately.",
+ feishu_failed: "Bot \"{name}\": Feishu long connection failed to start: {message}",
+ weixin_expired: "Bot \"{name}\": WeChat sign-in expired. Scan the QR code again under Channels in the info panel",
+ weixin_connected: "Bot \"{name}\": WeChat connected",
+ media_image: "Image",
+ media_file: "File",
+ media_video: "Video",
+ media_quoted_image: "Quoted image",
+ media_quoted_file: "Quoted file",
+ media_quoted_video: "Quoted video",
+ media_voice: "[Voice]",
+ media_not_downloaded: "{label} (couldn't download: {error})",
++ data_dir_locked: "Another anymodel bot process ({who}) is using the data directory {dir}. Quit it, or use another data directory (AMB_DATA_DIR).",
++ data_dir_locked_remote: "pid {pid} on {host}",
+ };
diff --cc src/i18n/messages/index.ts
index 0000000,f9c3936..a689bf8
mode 000000,100644..100644
--- a/src/i18n/messages/index.ts
+++ b/src/i18n/messages/index.ts
@@@ -1,0 -1,17 +1,18 @@@
+ // 服务端文案的命名空间。新增命名空间:在这里加一行,键 = "命名空间.键"。
+ import * as web from "./web.js";
+ import * as desktop from "./desktop.js";
+ import * as app from "./app.js";
+ import * as diag from "./diag.js";
+ import * as modelflare from "./modelflare.js";
+ import * as account from "./account.js";
+ import * as magpie from "./magpie.js";
+ import * as channel from "./channel.js";
+ import * as runtime from "./runtime.js";
+ import * as agent from "./agent.js";
+ import * as approvals from "./approvals.js";
+ import * as media from "./media.js";
+ import * as cu from "./cu.js";
+ import * as pwsh from "./pwsh.js";
++import * as rules from "./rules.js";
+
-export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh };
++export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh, rules };
diff --cc src/i18n/messages/rules.ts
index 0000000,0000000..3243792
new file mode 100644
--- /dev/null
+++ b/src/i18n/messages/rules.ts
@@@ -1,0 -1,0 +1,180 @@@
++// rules(3d):zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。
++// 用户看得到的规则文字:时间表的话、状态、运行记录的一行、「需要你」、推送的暂停那句、建规则时建议的回复、接口的报错。
++// 给模型看的(规则段、第一条输入、工具说明和工具返回里的指示)不在这里。
++import type { Catalog } from "../types.js";
++
++export const zh = {
++ // 时间表的话(tasks/schedule.ts describe)
++ daily: "每天 {time}",
++ weekdays: "每个工作日 {time}",
++ weekends: "每个周末 {time}",
++ weekly: "每{days} {time}",
++ daysSep: "、",
++ everyMin: { other: "每 {count} 分钟" },
++ everyHour: { other: "每 {count} 小时" },
++ once: "{date} {time}",
++ cron: "cron {cron}",
++ withZone: "{text}({tz})",
++ event: "事件 {source}",
++ // 状态(tasks/rules.ts ruleState)
++ statePaused: "已暂停",
++ stateOff: "已关闭",
++ stateDone: "已结束",
++ stateRemind: "提醒",
++ stateObserve: "观察中",
++ stateAct: "执行中",
++ // 运行记录的一行(tasks/rules.ts runLine)
++ queued: "排队中",
++ running: "正在运行",
++ skipped: "跳过:{why}",
++ failed: "失败:{why}",
++ interrupted: "中断:应用重启了",
++ stopped: "已停止",
++ budget: "预算用完",
++ reminded: "已提醒:“{text}”",
++ sent: "已发送:“{text}”",
++ pending: "待发送:“{text}”",
++ unsent: "未送达:“{text}”",
++ wouldSend: "本会发送:“{text}”",
++ wouldDo: "本会做:{text}",
++ wouldQuiet: "本会保持安静",
++ wouldQuietNote: "本会保持安静:{note}",
++ quiet: "保持安静",
++ quietNote: "保持安静:{note}",
++ needsApproval: "需要批准:{what}",
++ permReadOnly: "只读",
++ permWorkspace: "可写工作区",
++ // 跳过、失败的原因(存的是代码,显示时再翻)
++ whyAppOff: "电脑没开",
++ whyBusy: "一直在忙",
++ whyOverlap: "上次还没跑完",
++ whyRestart: "应用重启了",
++ whyTimeout: "超时",
++ whyApprovalTimeout: "批准超时",
++ whyNoReport: "没有给出结果",
++ whyModelErrors: "模型一直出错",
++ whyAgentFailed: "代理没能启动",
++ whyAgentUnavailable: "代理不可用",
++ // 「需要你」
++ subject: "规则「{title}」",
++ failingPaused: { other: "连续失败 {count} 次,已暂停" },
++ failing: { other: "连续失败 {count} 次" },
++ // 推送:连续失败暂停了(执行中的规则)
++ pausedPush: "⚠️ 规则「{title}」连续失败 {count} 次,已暂停:{why}",
++ // 建规则时建议给用户的那句(经聊天代理转述)
++ createdReply: "已建好规则:{when} {title}。先观察几天,只记录不打扰你;在「任务」里可以改成执行。",
++ remindReply: "好,{when} 提醒你。",
++ weixinNote: "微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。",
++ // /tasks、/stop 编号
++ listHead: "规则:",
++ listLine: "{n}. {when} {title} · {state}",
++ stopHint: "发 /stop 编号 可停止。",
++ turnedOff: "已关闭规则「{title}」。",
++ // 接口和编辑的报错
++ notFound: "规则不存在",
++ runNotFound: "没有这次运行",
++ badSchedule: "时间表不对",
++ badMode: "模式只能是关、观察或执行",
++ createFailed: "没能建好",
++ saveFailed: "没能保存",
++ nameEmpty: "名称不能为空",
++ wordsEmpty: "规则不能为空",
++ messageEmpty: "提醒的话不能为空",
++ noConversation: "没有这个会话",
++ eventNoSchedule: "这条规则由事件触发,没有时间表",
++ remindNoObserve: "提醒没有观察模式",
++ isOff: "规则关着",
++ isRunning: "正在运行",
++ // 时间表的报错(tasks/schedule.ts normalizeSchedule)
++ needTime: "缺少时间",
++ pastTime: "这个时间已经过了",
++ timeFormat: "时间要写成 08:00 这样",
++ pickDays: "选一天或几天",
++ minEvery: "间隔至少 {min} 分钟",
++ maxEvery: "间隔最长 7 天",
++ cronFields: "cron 要写 5 段:分 时 日 月 星期",
++ unknownSchedule: "不认识的时间表",
++} satisfies Catalog;
++
++export const en: Catalog<typeof zh> = {
++ daily: "Daily {time}",
++ weekdays: "Weekdays {time}",
++ weekends: "Weekends {time}",
++ weekly: "Every {days} {time}",
++ daysSep: ", ",
++ everyMin: { other: "Every {count} min" },
++ everyHour: { one: "Every hour", other: "Every {count} hours" },
++ once: "{date} {time}",
++ cron: "cron {cron}",
++ withZone: "{text} ({tz})",
++ event: "Event {source}",
++ statePaused: "Paused",
++ stateOff: "Off",
++ stateDone: "Done",
++ stateRemind: "Reminder",
++ stateObserve: "Observing",
++ stateAct: "Acting",
++ queued: "Queued",
++ running: "Running",
++ skipped: "Skipped: {why}",
++ failed: "Failed: {why}",
++ interrupted: "Interrupted: the app restarted",
++ stopped: "Stopped",
++ budget: "Budget used up",
++ reminded: "Reminded: “{text}”",
++ sent: "Sent: “{text}”",
++ pending: "Waiting to send: “{text}”",
++ unsent: "Not delivered: “{text}”",
++ wouldSend: "Would send: “{text}”",
++ wouldDo: "Would do: {text}",
++ wouldQuiet: "Would stay quiet",
++ wouldQuietNote: "Would stay quiet: {note}",
++ quiet: "Stayed quiet",
++ quietNote: "Stayed quiet: {note}",
++ needsApproval: "Needs approval: {what}",
++ permReadOnly: "Read-only",
++ permWorkspace: "Can write the workspace",
++ whyAppOff: "the computer was off",
++ whyBusy: "no free slot",
++ whyOverlap: "the last run was still going",
++ whyRestart: "the app restarted",
++ whyTimeout: "timed out",
++ whyApprovalTimeout: "approval timed out",
++ whyNoReport: "no result",
++ whyModelErrors: "the model kept failing",
++ whyAgentFailed: "the agent didn't start",
++ whyAgentUnavailable: "the agent is unavailable",
++ subject: "Rule “{title}”",
++ failingPaused: { one: "Failed {count} time in a row, paused", other: "Failed {count} times in a row, paused" },
++ failing: { one: "Failed {count} time in a row", other: "Failed {count} times in a row" },
++ pausedPush: "⚠️ Rule “{title}” failed {count} times in a row and is paused: {why}",
++ createdReply: "Rule set: {title}, {when}. It watches quietly for a few days; switch it to act under Tasks.",
++ remindReply: "OK, reminder set for {when}.",
++ weixinNote: "WeChat lets the bot message you only within 24 hours of your last message. Otherwise it arrives with your next message and shows on the desktop.",
++ listHead: "Rules:",
++ listLine: "{n}. {when} {title} · {state}",
++ stopHint: "Send /stop <number> to stop one.",
++ turnedOff: "Rule “{title}” is off.",
++ notFound: "Rule not found",
++ runNotFound: "No such run",
++ badSchedule: "Invalid schedule",
++ badMode: "Mode must be off, observe or act",
++ createFailed: "Couldn't create the rule",
++ saveFailed: "Couldn't save",
++ nameEmpty: "Name can't be empty",
++ wordsEmpty: "The rule can't be empty",
++ messageEmpty: "The reminder text can't be empty",
++ noConversation: "No such conversation",
++ eventNoSchedule: "This rule runs on events and has no schedule",
++ remindNoObserve: "Reminders have no observe mode",
++ isOff: "The rule is off",
++ isRunning: "Already running",
++ needTime: "Pick a time",
++ pastTime: "That time has passed",
++ timeFormat: "Write the time like 08:00",
++ pickDays: "Pick one or more days",
++ minEvery: "The interval must be at least {min} minutes",
++ maxEvery: "The interval can be at most 7 days",
++ cronFields: "cron needs 5 fields: minute hour day month weekday",
++ unknownSchedule: "Unknown schedule",
++};
diff --cc src/i18n/messages/runtime.ts
index 0000000,e32e26f..a55d4b2
mode 000000,100644..100644
--- a/src/i18n/messages/runtime.ts
+++ b/src/i18n/messages/runtime.ts
@@@ -1,0 -1,144 +1,144 @@@
+ // runtime:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。
+ import type { Catalog } from "../types.js";
+
+ export const zh = {
+ help: [
+ "可用命令:",
+ "/model — 列出可用模型(带编号)",
+ "/model <编号或模型名> — 切换当前会话的模型",
+ "/reset — 清空当前会话的上下文(代理模式下同时开启新的代理会话;长期记忆保留)",
+ "/new — 开始新的一段对话:旧对话归档并生成交接便条,长期记忆保留",
+ "/status — 查看当前模型、代理状态和正在处理的消息走到了哪一步",
+ "/stop — 中止正在处理的消息(只停这个会话,机器人的其它会话照常进行)",
- "/tasks — 列出这个会话的后台任务",
- "/stop <编号> — 停止 /tasks 里的一个后台任务",
++ "/tasks — 列出这个会话的后台任务和规则",
++ "/stop <编号> — 停止 /tasks 里的一个后台任务或规则",
+ "/help — 显示本帮助",
+ ].join("\n"),
+ noModels: "没有可用模型:请先连接 Modelflare(设置 → Modelflare)",
+ startingNote: "(代理还在启动,这条消息先由模型直接回答;启动完成后会自动用回代理。)",
+ emptyReply: "(模型没有返回内容)",
+ interrupted: "⚠️ 生成中断:{error}",
+ modelFailed: "⚠️ 模型调用失败({model}):{error}",
+ // /status
+ autoModel: "(自动:第一个可用模型)",
+ modeAgent: "代理模式(DeepSeek Harness,{sandbox})",
+ sandboxWorkspace: "工作区沙箱",
+ sandboxReadonly: "只读沙箱",
+ sandboxFull: "完全权限:不经沙箱",
+ fullWarning: "注意:完全权限下命令以你的用户身份直接运行,可以读写你电脑上的任何文件(包括 AnyModelBot 自己的数据);只有递归删除仍会先问你。在机器人设置里可以改回「工作区可写」。",
+ backgroundTasks: "后台任务:{list}",
+ backgroundTask: "「{title}」{stage}",
+ modeChat: "纯对话模式",
+ pendingApproval: "待批准 {code}",
+ pendingQuestion: "待回答 {code}",
+ cuCodex: "Codex 桥",
+ cuOn: "已启用",
+ cuOff: "未启用",
+ cuLine: "电脑操作:{backend},{state}——{reason}",
+ busy: "本会话上一条消息还在处理(已 {s} 秒),新消息会排在它后面",
+ currentModel: "当前模型:{model}{suffix}",
+ convSetting: "(会话设置)",
+ runMode: "运行方式:{mode}",
+ pending: "未决:{list}",
+ listSep: ",",
+ // 卡片按钮
+ requestMissing: "请求不存在",
+ requestDone: "请求 {code} 已处理或已过期",
+ approvedOnce: "已批准 {code}(仅本次)",
+ rejected: "已拒绝 {code}",
+ expired: "已过期",
+ submitted: "已提交",
+ submitFailed: "提交失败",
+ unknownAction: "未知操作",
+ allowOnce: "允许(仅本次)",
+ deny: "拒绝",
+ // 代理回合
+ agentReady: "代理已就绪,正在处理…",
+ agentStarting: "代理正在启动…{elapsed}{first}",
+ agentStartingElapsed: "(已 {s} 秒)",
+ agentStartingFirst: "首次启动可能需要几分钟。",
+ doneNoText: "(已完成,没有文字回复)",
+ agentFailed: "⚠️ 代理执行失败:{error}",
+ // 命令
+ resetDone: "✅ 已清空本会话上下文",
+ newAgentOnly: "⚠️ /new 只在代理模式下可用;纯对话模式请用 /reset",
+ alreadyNew: "当前已经是新的一段对话",
+ newFailed: "⚠️ 开新段失败:{error}",
+ newDone: "✅ 已开始新的一段对话(旧对话已归档并留下交接便条,长期记忆保留)",
+ modelListFailed: "⚠️ 获取模型列表失败:{error}",
+ modelListEmpty: "暂无可用模型:请先连接 Modelflare(设置 → Modelflare)。",
+ modelListHead: "可用模型(回复 /model 编号 切换):",
+ modelCurrent: " ← 当前",
+ modelReset: "✅ 已恢复为机器人默认模型",
+ modelNotFound: "⚠️ 找不到模型「{name}」,发送 /model 查看列表",
+ modelSwitched: "✅ 本会话已切换到 {model}",
+ } satisfies Catalog;
+
+ export const en: Catalog<typeof zh> = {
+ help: [
+ "Commands:",
+ "/model — list available models (numbered)",
+ "/model <number or name> — switch the model for this conversation",
+ "/reset — clear this conversation's context (in agent mode, also starts a new agent session; long-term memory is kept)",
+ "/new — start a new conversation: the old one is archived with a handoff note; long-term memory is kept",
+ "/status — show the current model, the agent's state and how far the message in progress has got",
+ "/stop — stop the message in progress (only this conversation; the bot's other conversations carry on)",
- "/tasks — list this conversation's background tasks",
- "/stop <number> — stop one of the background tasks listed by /tasks",
++ "/tasks — list this conversation's background tasks and rules",
++ "/stop <number> — stop a background task or rule listed by /tasks",
+ "/help — show this help",
+ ].join("\n"),
+ noModels: "No models available: connect Modelflare first (Settings → Modelflare)",
+ startingNote: "(The agent is still starting, so the model answered this message directly; the agent takes over automatically once it's ready.)",
+ emptyReply: "(The model returned nothing)",
+ interrupted: "⚠️ Generation interrupted: {error}",
+ modelFailed: "⚠️ Model call failed ({model}): {error}",
+ autoModel: "(auto: first available model)",
+ modeAgent: "agent mode (DeepSeek Harness, {sandbox})",
+ sandboxWorkspace: "workspace sandbox",
+ sandboxReadonly: "read-only sandbox",
+ sandboxFull: "full access: no sandbox",
+ fullWarning: "Note: with full access, commands run directly as your user and can read and change any file on your computer (including AnyModelBot's own data); only recursive deletes still ask first. You can switch back to \"Workspace write\" in bot settings.",
+ backgroundTasks: "Background tasks: {list}",
+ backgroundTask: "\"{title}\" {stage}",
+ modeChat: "chat-only mode",
+ pendingApproval: "awaiting approval {code}",
+ pendingQuestion: "awaiting answer {code}",
+ cuCodex: "Codex bridge",
+ cuOn: "on",
+ cuOff: "off",
+ cuLine: "Computer use: {backend}, {state} — {reason}",
+ busy: "The previous message in this conversation is still being processed ({s}s so far); new messages queue behind it",
+ currentModel: "Current model: {model}{suffix}",
+ convSetting: " (conversation setting)",
+ runMode: "Mode: {mode}",
+ pending: "Pending: {list}",
+ listSep: ", ",
+ requestMissing: "Request not found",
+ requestDone: "Request {code} was already handled or has expired",
+ approvedOnce: "Approved {code} (this time only)",
+ rejected: "Denied {code}",
+ expired: "Expired",
+ submitted: "Submitted",
+ submitFailed: "Couldn't submit",
+ unknownAction: "Unknown action",
+ allowOnce: "Allow (this time only)",
+ deny: "Deny",
+ agentReady: "Agent ready, working on it…",
+ agentStarting: "Agent starting…{elapsed}{first}",
+ agentStartingElapsed: " ({s}s so far)",
+ agentStartingFirst: " The first start can take a few minutes.",
+ doneNoText: "(Done, no text reply)",
+ agentFailed: "⚠️ Agent run failed: {error}",
+ resetDone: "✅ Cleared this conversation's context",
+ newAgentOnly: "⚠️ /new only works in agent mode; in chat-only mode use /reset",
+ alreadyNew: "This is already a new conversation",
+ newFailed: "⚠️ Couldn't start a new conversation: {error}",
+ newDone: "✅ Started a new conversation (the old one is archived with a handoff note; long-term memory is kept)",
+ modelListFailed: "⚠️ Couldn't get the model list: {error}",
+ modelListEmpty: "No models available: connect Modelflare first (Settings → Modelflare).",
+ modelListHead: "Available models (reply /model <number> to switch):",
+ modelCurrent: " ← current",
+ modelReset: "✅ Back to the bot's default model",
+ modelNotFound: "⚠️ No model \"{name}\"; send /model to see the list",
+ modelSwitched: "✅ This conversation now uses {model}",
+ };
diff --cc src/store/lock.ts
index f813408,0000000..4ee2021
mode 100644,000000..100644
--- a/src/store/lock.ts
+++ b/src/store/lock.ts
@@@ -1,127 -1,0 +1,129 @@@
+/**
+ * 数据目录锁(设计文档第 11 节「Two hosts open the same data dir」):同一个数据目录只能有一个宿主在跑,
+ * 不然两个调度器会把同一条规则跑两遍、两个渠道连接抢同一个微信。桌面版本来就有 Electron 的单实例锁;
+ * 命令行和 Docker 靠这个,在调度器开始之前拿到。
+ *
+ * 锁是 <dataDir>/anymodel.lock:{pid, host, at}。拿锁时:没有、或是自己的(同一进程重启 App),直接拿;
+ * 那个进程已经不在了(崩溃、kill -9),或者心跳停了 3 分钟以上(断电重启后进程号被别的程序占了、另一台机器上的宿主没了),接管。
+ * 心跳:拿着锁的每分钟碰一下文件(两个容器挂同一个卷时只能靠它)。
+ */
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { logger } from "../log.js";
++import { t } from "../i18n/index.js";
+
+const log = logger("lock");
+
+export const LOCK_FILE = "anymodel.lock";
+/** 心跳:拿着锁的多久碰一下文件;别的机器上的锁多久没碰算没人了 */
+export const HEARTBEAT_MS = 60_000;
+export const STALE_MS = 3 * 60_000;
+
+export class DataDirLocked extends Error {
+ constructor(
+ readonly dataDir: string,
+ readonly holder: { pid: number; host: string },
+ ) {
- super(`数据目录 ${dataDir} 正被另一个 anymodel bot 进程使用(${holder.host === os.hostname() ? "" : `${holder.host} 上的 `}pid ${holder.pid})。先退出它,或者换一个数据目录(AMB_DATA_DIR)。`);
++ const who = holder.host === os.hostname() ? `pid ${holder.pid}` : t("app.data_dir_locked_remote", { host: holder.host, pid: holder.pid });
++ super(t("app.data_dir_locked", { dir: dataDir, who }));
+ this.name = "DataDirLocked";
+ }
+}
+
+interface Holder {
+ pid: number;
+ host: string;
+ at: number;
+ /** 这一次拿锁的标记(同一进程里先后两个 App:只放自己拿的那把) */
+ token: string;
+}
+
+function alive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ // EPERM:进程在,只是不是我们的
+ return (e as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+function read(file: string): Holder | undefined {
+ try {
+ const j = JSON.parse(fs.readFileSync(file, "utf8"));
+ return Number(j?.pid) > 0 ? { pid: Number(j.pid), host: String(j.host ?? ""), at: Number(j.at) || 0, token: String(j.token ?? "") } : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** 拿着的锁:release() 放掉(只放自己的) */
+export interface DataDirLock {
+ file: string;
+ release(): void;
+}
+
+/** 拿数据目录锁;被另一个活着的进程拿着时抛 DataDirLocked */
+export function lockDataDir(dataDir: string, o: { now?: () => number; heartbeatMs?: number } = {}): DataDirLock {
+ const now = o.now ?? Date.now;
+ const file = path.join(dataDir, LOCK_FILE);
+ fs.mkdirSync(dataDir, { recursive: true });
+ const me: Holder = { pid: process.pid, host: os.hostname(), at: now(), token: randomUUID() };
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ fs.writeFileSync(file, JSON.stringify(me), { flag: "wx", mode: 0o600 });
+ break;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
+ }
+ const h = read(file);
+ const mtime = (() => {
+ try {
+ return fs.statSync(file).mtimeMs;
+ } catch {
+ return 0;
+ }
+ })();
+ const mine = h && h.pid === me.pid && h.host === me.host;
+ // 同一台机器:进程不在了就接管;进程号还在但心跳停了 3 分钟以上也接管(崩溃或断电重启后,旧进程号可能被别的程序用了)
+ const stale = !!h && now() - Math.max(h.at, mtime) > STALE_MS;
+ const gone = !h || stale || (h.host === me.host && !alive(h.pid));
+ if (!mine && !gone) throw new DataDirLocked(dataDir, h!);
+ if (h && !mine) log.warn("taking over a stale data dir lock", { pid: h.pid, host: h.host });
+ try {
+ fs.rmSync(file, { force: true });
+ } catch {
+ /* 下一轮再试 */
+ }
+ }
+ if (read(file)?.token !== me.token) throw new DataDirLocked(dataDir, read(file) ?? me);
+ // 心跳:另一台机器上的宿主据此判断这把锁还有没有人
+ const beat = setInterval(() => {
+ try {
+ const t = new Date(now());
+ fs.utimesSync(file, t, t);
+ } catch {
+ /* 文件没了:下次启动重新拿 */
+ }
+ }, o.heartbeatMs ?? HEARTBEAT_MS);
+ beat.unref?.();
+ let released = false;
+ return {
+ file,
+ release() {
+ if (released) return;
+ released = true;
+ clearInterval(beat);
+ const h = read(file);
+ if (h?.token === me.token) {
+ try {
+ fs.rmSync(file, { force: true });
+ } catch {
+ /* ignore */
+ }
+ }
+ },
+ };
+}
diff --cc src/tasks/attention.ts
index 16c66a0,3dd499a..d4f0dd9
--- a/src/tasks/attention.ts
+++ b/src/tasks/attention.ts
@@@ -11,6 -11,6 +11,7 @@@ import type { ApprovalRow, Store } fro
import { questionsOf, type QuestionItem } from "../agent/approvals.js";
import type { AttentionItem as DeliveryItem } from "../core/delivery.js";
import { logger } from "../log.js";
++import { t } from "../i18n/index.js";
const log = logger("attention");
@@@ -184,7 -181,7 +185,7 @@@ export function approvalItems(store: St
kind: r.kind,
botId: r.botId,
botName: store.getBot(r.botId)?.name ?? r.botId,
- subject: task?.title ?? (rule ? `规则「${rule.title}」` : (CHANNEL[channel] ?? "对话")),
- subject: task?.title ?? CHANNEL[channel] ?? "对话",
++ subject: task?.title ?? (rule ? t("rules.subject", { title: rule.title }) : (CHANNEL[channel] ?? "对话")),
status: r.kind === "approval" ? "等你批准" : "等你回答",
line: line.length > 300 ? line.slice(0, 299) + "…" : line,
since: r.createdAt,
diff --cc src/tasks/rules.ts
index 32dd8c3,0000000..075d365
mode 100644,000000..100644
--- a/src/tasks/rules.ts
+++ b/src/tasks/rules.ts
@@@ -1,168 -1,0 +1,221 @@@
+/**
+ * 规则(3d)的纯函数部分:状态、给人看的一行、每种模式的权限和去掉的工具。写库的是任务服务(service.ts,唯一的写入者)。
+ *
+ * 状态(第一条符合的为准):暂停了(连续失败 3 次)→ 已暂停;关了 → 已关闭;一次性的跑过了 → 已结束;提醒 → 提醒;
+ * 观察中(含改了原话后先观察的那一次)→ 观察中;其余 → 执行中。状态是"点 + 文字":红 = 暂停,绿 = 执行中、提醒,灰 = 观察、关闭、结束。
++ * 给人看的文字跟着语言(src/i18n 的 rules.*);跳过、失败的原因存成代码(RUN_ERROR),显示时再翻。
+ */
+import type { OutboxRow, RuleMode, RuleRow, RunRow } from "../store/db.js";
++import { lang as currentLang, tl, type Lang, type MessageKey } from "../i18n/index.js";
+import { describe } from "./schedule.js";
+
+/** 连续失败几次自动暂停 */
+export const RULE_FAILS_TO_PAUSE = 3;
+/** 连续失败几次出现在「需要你」里 */
+export const RULE_FAILS_TO_SHOW = 2;
+/** 观察几次好的之后提示改为执行 */
+export const RULE_HINT_AFTER = 3;
+/** 改了原话之后先观察几次(产品负责人:1 次) */
+export const RULE_OBSERVE_AFTER_EDIT = 1;
+/** 每个机器人最多几条规则 */
+export const MAX_RULES = 30;
+/** 一次运行最长多久(不算等批准的时间) */
+export const RULE_RUN_CAP_MS = 15 * 60_000;
+/** 执行时的审批在「需要你」里等多久,过了就拒绝、这次运行失败 */
+export const RULE_APPROVAL_TTL_MS = 3600_000;
+
+/**
+ * 规则会话去掉的工具(只去掉注册了的;插件按 tools.restrict 的规矩过滤)。观察:能改变什么的都去掉,记忆只留 recall;
+ * 执行:上限是可写工作区(决定 12),电脑操作和生图、生视频不给(设计第 7 节:除非规则上开了,3d 不做这个开关)。
+ */
+const COMMON_DENY = ["present", "ask_user_question", "task_start", "task_message", "task_list", "rule_create", "rule_update", "generate_image", "generate_video", "media_models", "media_docs"];
+export const RULE_DENY: Readonly<Record<"observe" | "act", string[]>> = {
+ observe: [...COMMON_DENY, "remember", "forget"],
+ act: COMMON_DENY,
+};
+/** 按前缀拒绝的工具(MCP 的电脑操作,名字随平台变化,没法列全) */
+export const RULE_DENY_PREFIX = ["mcp__computer-use__"];
+
+/** 这次运行用的模式:改了原话后先观察 observeLeft 次 */
+export function runMode(rule: Pick<RuleRow, "mode" | "observeLeft" | "kind">): "observe" | "act" {
+ if (rule.kind === "remind") return "act";
+ return rule.mode === "act" && rule.observeLeft <= 0 ? "act" : "observe";
+}
+
+/** DSH 的沙箱:观察只读;执行是机器人的预设和可写工作区里取小的(完全权限的机器人也一样,决定 12) */
+export function rulePermission(mode: "observe" | "act", botPreset: string): "read-only" | "workspace-write" {
+ return mode === "observe" || botPreset === "readonly" ? "read-only" : "workspace-write";
+}
+
+export interface RuleState {
+ key: "paused" | "off" | "done" | "remind" | "observe" | "act";
+ label: string;
+ /** 状态点:err 红、ok 绿、空 = 灰 */
+ dot: "" | "ok" | "err";
+}
+
- export function ruleState(rule: RuleRow, live = false): RuleState {
- if (rule.pausedReason) return { key: "paused", label: "已暂停", dot: "err" };
- if (rule.mode === "off") return { key: "off", label: "已关闭", dot: "" };
- if (!live && !rule.nextRunAt && rule.trigger.kind === "schedule") return { key: "done", label: "已结束", dot: "" };
- if (rule.kind === "remind") return { key: "remind", label: "提醒", dot: "ok" };
- if (runMode(rule) === "observe") return { key: "observe", label: "观察中", dot: "" };
- return { key: "act", label: "执行中", dot: "ok" };
++export function ruleState(rule: RuleRow, live = false, l: Lang = currentLang()): RuleState {
++ const s = (key: RuleState["key"], label: MessageKey, dot: RuleState["dot"]): RuleState => ({ key, label: tl(l, label), dot });
++ if (rule.pausedReason) return s("paused", "rules.statePaused", "err");
++ if (rule.mode === "off") return s("off", "rules.stateOff", "");
++ if (!live && !rule.nextRunAt && rule.trigger.kind === "schedule") return s("done", "rules.stateDone", "");
++ if (rule.kind === "remind") return s("remind", "rules.stateRemind", "ok");
++ if (runMode(rule) === "observe") return s("observe", "rules.stateObserve", "");
++ return s("act", "rules.stateAct", "ok");
+}
+
+/** 规则在界面上的样子 */
+export interface RuleView {
+ id: string;
+ botId: string;
+ conversationId: string;
+ channel: string;
+ title: string;
+ instruction: string;
+ message: string;
+ kind: RuleRow["kind"];
+ trigger: RuleRow["trigger"];
+ /** 时间表的话:每天 08:00;事件触发的是来源 */
+ when: string;
+ mode: RuleMode;
+ /** 改了原话后还要先观察几次 */
+ observeLeft: number;
+ state: RuleState;
+ nextRunAt: number;
+ /** 最近一次:时间、结果、一行 */
+ last?: { at: number; outcome: string; line: string };
+ /** 已观察 3 次(这一版)、可以改为执行 */
+ hint: boolean;
+ /** 这一版好好观察过几次 */
+ observed: number;
+ failures: number;
+ folder: string;
+ version: number;
+ createdAt: number;
+ updatedAt: number;
+ /** 正在跑(或排队)的那一次 */
+ live?: { runId: string; state: string; since: number };
+}
+
- export function whenOf(rule: Pick<RuleRow, "trigger">, withZone = false): string {
- return rule.trigger.kind === "schedule" ? describe(rule.trigger.schedule, withZone) : `事件 ${rule.trigger.source}`;
++export function whenOf(rule: Pick<RuleRow, "trigger">, withZone = false, l: Lang = currentLang()): string {
++ return rule.trigger.kind === "schedule" ? describe(rule.trigger.schedule, withZone, l) : tl(l, "rules.event", { source: rule.trigger.source });
++}
++
++/** 跳过、失败的原因:存进 runs.error 的代码(显示时按语言翻,见 errorText) */
++export const RUN_ERROR = {
++ appOff: "app_off",
++ busy: "busy",
++ overlap: "overlap",
++ restart: "restart",
++ timeout: "timeout",
++ approvalTimeout: "approval_timeout",
++} as const;
++
++/** 原因 → 词条:规则自己的代码,和任务、规则共用的那套 run 写进去的说法(3a) */
++const WHY: Record<string, MessageKey> = {
++ app_off: "rules.whyAppOff",
++ busy: "rules.whyBusy",
++ overlap: "rules.whyOverlap",
++ restart: "rules.whyRestart",
++ timeout: "rules.whyTimeout",
++ approval_timeout: "rules.whyApprovalTimeout",
++ 没有给出结果: "rules.whyNoReport",
++ 模型一直出错: "rules.whyModelErrors",
++ 代理没能启动: "rules.whyAgentFailed",
++ 代理不可用: "rules.whyAgentUnavailable",
++};
++
++/** 存下来的原因给人看:认得的翻成当前语言,其余(模型自己说的)原样 */
++export function errorText(error: string, l: Lang = currentLang()): string {
++ const key = WHY[error];
++ return key ? tl(l, key) : error;
++}
++
++/** 观察时要批准、被自动拒绝的事:在 runs.would 里一行一个,带这个前缀(显示时翻成「需要批准:…」) */
++export const WOULD_APPROVAL = "approval: ";
++
++/** runs.would 给人看:需要批准的那几行按语言翻,模型写的原样 */
++export function wouldText(would: string, l: Lang = currentLang()): string {
++ return would
++ .split("\n")
++ .map((x) => (x.startsWith(WOULD_APPROVAL) ? tl(l, "rules.needsApproval", { what: x.slice(WOULD_APPROVAL.length) }) : x))
++ .join("\n");
++}
++
++/** DSH 的沙箱 → 给人看的权限 */
++export function permissionText(p: string, l: Lang = currentLang()): string {
++ return p === "read-only" ? tl(l, "rules.permReadOnly") : p === "workspace-write" ? tl(l, "rules.permWorkspace") : "";
+}
+
+const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();
+
+/** 出站队列里那一条的送达状态(合进摘要的看那一条)→ 已发送 / 待发送 / 未送达 */
- function sentWord(row: OutboxRow | undefined): string {
- if (!row || row.status === "sent" || row.status === "merged") return "已发送";
- if (row.status === "held" || row.status === "gone" || row.attempts >= 3) return "未送达";
- return "待发送";
++function sentKey(row: OutboxRow | undefined): "rules.sent" | "rules.unsent" | "rules.pending" {
++ if (!row || row.status === "sent" || row.status === "merged") return "rules.sent";
++ if (row.status === "held" || row.status === "gone" || row.attempts >= 3) return "rules.unsent";
++ return "rules.pending";
+}
+
+/**
+ * 运行记录的一行(设计第 6 节「Auditing a rule」):
+ * 观察:本会发送:“…” / 本会做:… / 本会保持安静;执行:已发送:“…”(待发送、未送达)/ 保持安静;提醒:已提醒:“…”;
+ * 失败:…;跳过:电脑没开;中断。
+ */
- export function runLine(run: RunRow, kind: RuleRow["kind"], carrier?: OutboxRow): string {
- if (run.state === "queued") return "排队中";
- if (run.state !== "ended") return "正在运行";
++export function runLine(run: RunRow, kind: RuleRow["kind"], carrier?: OutboxRow, l: Lang = currentLang()): string {
++ if (run.state === "queued") return tl(l, "rules.queued");
++ if (run.state !== "ended") return tl(l, "rules.running");
+ const r = run.report;
+ const msg = oneLine(r?.message ?? "");
+ const note = oneLine(r?.summary.split("\n")[0] ?? "");
+ switch (run.outcome) {
+ case "skipped":
- return `跳过:${run.error || "电脑没开"}`;
++ return tl(l, "rules.skipped", { why: errorText(run.error || RUN_ERROR.appOff, l) });
+ case "failed":
- return `失败:${clip(oneLine(r?.message || run.error || "没有给出结果"), 120)}`;
++ return tl(l, "rules.failed", { why: clip(oneLine(r?.message || errorText(run.error || "没有给出结果", l)), 120) });
+ case "interrupted":
- return "中断:应用重启了";
++ return tl(l, "rules.interrupted");
+ case "stopped":
- return "已停止";
++ return tl(l, "rules.stopped");
+ case "budget":
- return "预算用完";
++ return tl(l, "rules.budget");
+ case "done":
+ break;
+ default:
+ return run.outcome;
+ }
- if (kind === "remind") return `${sentWord(carrier) === "已发送" ? "已提醒" : sentWord(carrier)}:“${clip(msg, 120)}”`;
- const would = oneLine(run.would || r?.would || "");
++ const text = clip(msg, 120);
++ if (kind === "remind") {
++ const key = sentKey(carrier);
++ return tl(l, key === "rules.sent" ? "rules.reminded" : key, { text });
++ }
++ const would = oneLine(wouldText(run.would || r?.would || "", l));
+ if (run.mode === "observe") {
- if (msg) return `本会发送:“${clip(msg, 120)}”`;
- if (would) return `本会做:${clip(would, 120)}`;
- return note ? `本会保持安静:${clip(note, 60)}` : "本会保持安静";
++ if (msg) return tl(l, "rules.wouldSend", { text });
++ if (would) return tl(l, "rules.wouldDo", { text: clip(would, 120) });
++ return note ? tl(l, "rules.wouldQuietNote", { note: clip(note, 60) }) : tl(l, "rules.wouldQuiet");
+ }
- if (msg) return `${sentWord(carrier)}:“${clip(msg, 120)}”`;
- return note ? `保持安静:${clip(note, 60)}` : "保持安静";
++ if (msg) return tl(l, sentKey(carrier), { text });
++ return note ? tl(l, "rules.quietNote", { note: clip(note, 60) }) : tl(l, "rules.quiet");
+}
+
+/** 运行记录里的一项(界面展开看报告、步骤、版本和权限) */
+export interface RuleRunView {
+ id: string;
+ at: number;
+ mode: string;
+ cause: string;
+ state: string;
+ outcome: string;
+ line: string;
+ summary: string;
+ message: string;
+ would: string;
+ error: string;
+ version: number;
+ /** 那次的权限:只读 / 可写工作区 */
+ permission: string;
+ steps: number;
+ startedAt: number;
+ endedAt: number;
+}
diff --cc src/tasks/schedule.ts
index bae4676,0000000..93a4d61
mode 100644,000000..100644
--- a/src/tasks/schedule.ts
+++ b/src/tasks/schedule.ts
@@@ -1,335 -1,0 +1,344 @@@
+/**
+ * 规则的时间表(设计文档第 4 节):once(at)、daily(time, days?)、weekly(days, time)、every(N 分钟,N ≥ 15)、cron(高级)。
+ * 时区是建规则时本机的 IANA 时区,存在时间表里;按本地钟面时间算,夏令时那天:跳过的那一小时里的时刻顺延到跳过之后
+ * (02:30 → 03:30),重复的那一小时取第一次。every 按绝对时间,从起点一格一格往后排。
+ *
+ * - nextRun:after 之后(不含)第一次到点;latestRun:t 及之前最后一次到点(错过的补跑只补最近的一次)。
+ * - graceOf:错过多久之内还补跑一次(间隔的一半和 2 小时取小的);更早的记为跳过,从不补一串。
+ * - parseSchedule:聊天代理给的一行("daily 08:00"、"weekly mon,thu 09:00"、"every 30m"、"once 2026-11-02 15:00"、"cron 0 8 * * 1-5")。
- * - describe:给用户看的话:每天 08:00、每个工作日 08:00、每周一、周四 09:00、每 30 分钟、11月2日 15:00。
++ * - describe:给用户看的话(跟着语言,src/i18n 的 rules.*):每天 08:00、每个工作日 08:00、每周一、周四 09:00、每 30 分钟、11月2日 15:00;
++ * 英文 Daily 08:00、Weekdays 08:00、Every Mon, Thu 09:00、Every 30 min、Nov 2 15:00。
+ */
+import { localParts, minuteOf } from "../core/quiet.js";
++import { lang as currentLang, tl, type Lang } from "../i18n/index.js";
+
+export type Schedule =
+ | { kind: "once"; at: number; tz: string }
+ /** days:0 = 周日;没有 = 每天 */
+ | { kind: "daily"; time: string; days?: number[]; tz: string }
+ | { kind: "weekly"; time: string; days: number[]; tz: string }
+ /** from:第一次的时间(之后每 minutes 分钟一次) */
+ | { kind: "every"; minutes: number; from: number; tz: string }
+ | { kind: "cron"; cron: string; tz: string };
+
+/** every 最短间隔 */
+export const MIN_EVERY_MIN = 15;
+/** 错过之后最多多久内还补跑 */
+export const MAX_GRACE_MS = 2 * 3600_000;
+
+const MIN = 60_000;
+const DAY_MS = 86_400_000;
+
+/** ts 在 tz 里的钟面时间(当作 UTC 的毫秒数)减去 ts:这一刻的时区偏移 */
+function offsetAt(ts: number, tz: string): number {
+ const p = localParts(ts, tz);
+ const wall = Date.UTC(p.y, p.mo - 1, p.d) + p.minute * MIN;
+ return Math.round((wall - ts) / MIN) * MIN;
+}
+
+/**
+ * 本地日期 y-mo-d 的第 minute 分钟是哪一刻。夏令时:重复的那一小时取第一次;跳过的那一小时里的时刻顺延到跳过之后
+ * (按切换前的偏移算,和 Temporal 的 compatible 一样)。
+ */
+export function localTime(y: number, mo: number, d: number, minute: number, tz: string): number {
+ const guess = Date.UTC(y, mo - 1, d) + minute * MIN;
+ const before = guess - offsetAt(guess - DAY_MS / 2, tz);
+ const after = guess - offsetAt(guess + DAY_MS / 2, tz);
+ const ok = (t: number) => {
+ const p = localParts(t, tz);
+ return p.y === y && p.mo === mo && p.d === d && Math.floor(p.minute) === minute;
+ };
+ const valid = [before, after].filter(ok);
+ return valid.length ? Math.min(...valid) : before;
+}
+
+/** 从 ts 所在的本地日期起第 i 天(i 可以是负数):年、月、日、星期 */
+function dayAt(ts: number, i: number, tz: string): { y: number; mo: number; d: number; weekday: number } {
+ const p = localParts(ts, tz);
+ const u = new Date(Date.UTC(p.y, p.mo - 1, p.d + i));
+ return { y: u.getUTCFullYear(), mo: u.getUTCMonth() + 1, d: u.getUTCDate(), weekday: u.getUTCDay() };
+}
+
+// ---------- cron(分 时 日 月 星期;* , - /) ----------
+
+interface Cron {
+ minutes: number[];
+ hours: number[];
+ dom: Set<number>;
+ months: Set<number>;
+ dow: Set<number>;
+ domAny: boolean;
+ dowAny: boolean;
+}
+
+function cronField(f: string, lo: number, hi: number): number[] | undefined {
+ const out = new Set<number>();
+ for (const part of f.split(",")) {
+ const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
+ if (!m) return undefined;
+ const step = m[4] ? Number(m[4]) : 1;
+ const a = m[1] === "*" ? lo : Number(m[2]);
+ const b = m[1] === "*" ? hi : m[3] !== undefined ? Number(m[3]) : m[4] ? hi : a;
+ if (!(step >= 1) || a < lo || b > hi || a > b) return undefined;
+ for (let v = a; v <= b; v += step) out.add(v);
+ }
+ return [...out].sort((x, y) => x - y);
+}
+
+export function parseCron(expr: string): Cron | undefined {
+ const f = expr.trim().split(/\s+/);
+ if (f.length !== 5) return undefined;
+ const minutes = cronField(f[0], 0, 59);
+ const hours = cronField(f[1], 0, 23);
+ const dom = cronField(f[2], 1, 31);
+ const months = cronField(f[3], 1, 12);
+ // 星期 0–7,7 也是周日
+ const dow = cronField(f[4], 0, 7);
+ if (!minutes || !hours || !dom || !months || !dow) return undefined;
+ return {
+ minutes,
+ hours,
+ dom: new Set(dom),
+ months: new Set(months),
+ dow: new Set(dow.map((x) => x % 7)),
+ domAny: f[2] === "*",
+ dowAny: f[4] === "*",
+ };
+}
+
+/** 这一天合不合 cron 的日、月、星期(日和星期都限定时,满足一个就行,和 cron 一样) */
+function cronDay(c: Cron, day: { mo: number; d: number; weekday: number }): boolean {
+ if (!c.months.has(day.mo)) return false;
+ const dom = c.dom.has(day.d);
+ const dow = c.dow.has(day.weekday);
+ if (c.domAny && c.dowAny) return true;
+ if (c.domAny) return dow;
+ if (c.dowAny) return dom;
+ return dom || dow;
+}
+
+// ---------- 下一次、上一次 ----------
+
+/** 这一天里到点的分钟(本地),从小到大;这一天不跑就是空的 */
+function minutesOn(s: Schedule, day: { mo: number; d: number; weekday: number }, cron?: Cron): number[] {
+ if (s.kind === "daily" || s.kind === "weekly") {
+ const m = minuteOf(s.time);
+ if (m === undefined) return [];
+ if (s.days?.length && !s.days.includes(day.weekday)) return [];
+ return [m];
+ }
+ if (s.kind === "cron" && cron) {
+ if (!cronDay(cron, day)) return [];
+ return cron.hours.flatMap((h) => cron.minutes.map((m) => h * 60 + m));
+ }
+ return [];
+}
+
+/** 按日历找的那几种(每天、每周、cron)最多往前、往后看多少天 */
+const SCAN_DAYS = 400;
+
+/** after 之后(不含)第一次到点;没有了(once 已经过了)就是 undefined */
+export function nextRun(s: Schedule, after: number): number | undefined {
+ if (s.kind === "once") return s.at > after ? s.at : undefined;
+ if (s.kind === "every") {
+ const step = s.minutes * MIN;
+ if (after < s.from) return s.from;
+ return s.from + (Math.floor((after - s.from) / step) + 1) * step;
+ }
+ const cron = s.kind === "cron" ? parseCron(s.cron) : undefined;
+ if (s.kind === "cron" && !cron) return undefined;
+ for (let i = 0; i <= SCAN_DAYS; i++) {
+ const day = dayAt(after, i, s.tz);
+ for (const m of minutesOn(s, day, cron)) {
+ const t = localTime(day.y, day.mo, day.d, m, s.tz);
+ if (t > after) return t;
+ }
+ }
+ return undefined;
+}
+
+/** t 及之前最后一次到点(不早于 since);没有就是 undefined */
+export function latestRun(s: Schedule, t: number, since = -Infinity): number | undefined {
+ if (s.kind === "once") return s.at <= t && s.at >= since ? s.at : undefined;
+ if (s.kind === "every") {
+ if (t < s.from) return undefined;
+ const step = s.minutes * MIN;
+ const v = s.from + Math.floor((t - s.from) / step) * step;
+ return v >= since ? v : undefined;
+ }
+ const cron = s.kind === "cron" ? parseCron(s.cron) : undefined;
+ if (s.kind === "cron" && !cron) return undefined;
+ for (let i = 0; i >= -SCAN_DAYS; i--) {
+ const day = dayAt(t, i, s.tz);
+ const list = minutesOn(s, day, cron);
+ for (let k = list.length - 1; k >= 0; k--) {
+ const v = localTime(day.y, day.mo, day.d, list[k], s.tz);
+ if (v <= t) return v >= since ? v : undefined;
+ }
+ // 这一天整个都在 since 之前(多留一天给时区偏移):再往前也不会有
+ if (Date.UTC(day.y, day.mo - 1, day.d) < since - DAY_MS) return undefined;
+ }
+ return undefined;
+}
+
+/** 大约多久跑一次(毫秒):every 是间隔,cron 看从 ref 起的两次之间,其余一天或更长 */
+export function intervalOf(s: Schedule, ref: number): number {
+ if (s.kind === "every") return s.minutes * MIN;
+ if (s.kind === "cron") {
+ const a = nextRun(s, ref);
+ const b = a === undefined ? undefined : nextRun(s, a);
+ return a !== undefined && b !== undefined ? b - a : DAY_MS;
+ }
+ return DAY_MS;
+}
+
+/** 错过多久之内还补跑一次:间隔的一半和 2 小时取小的 */
+export function graceOf(s: Schedule, ref: number): number {
+ return Math.min(MAX_GRACE_MS, intervalOf(s, ref) / 2);
+}
+
+// ---------- 校验、解析、给人看的话 ----------
+
+const DAY_NAMES: Record<string, number> = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, 日: 0, 天: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6 };
+
+function dayList(text: string): number[] | undefined {
+ const out = new Set<number>();
+ for (const raw of text.split(/[,,、\s]+/).filter(Boolean)) {
+ const w = raw.toLowerCase().replace(/^(周|星期|礼拜)/, "").slice(0, 3);
+ const n = /^\d$/.test(w) ? Number(w) % 7 : DAY_NAMES[w];
+ if (n === undefined) return undefined;
+ out.add(n);
+ }
+ return out.size ? [...out].sort((a, b) => a - b) : undefined;
+}
+
+const hhmm = (s: string): string | undefined => {
+ const m = /^(\d{1,2})[::](\d{2})$/.exec(s.trim());
+ if (!m) return undefined;
+ const t = `${m[1].padStart(2, "0")}:${m[2]}`;
+ return minuteOf(t) !== undefined ? t : undefined;
+};
+
+/**
+ * 校验界面或接口给的结构化时间表(JSON),补上时区;有错时 error 是给人看的一句话。
+ * now:once 不能在过去;every 没给起点就从下一个整分钟起。
+ */
- export function normalizeSchedule(raw: unknown, tz: string, now: number): { schedule?: Schedule; error?: string } {
++export function normalizeSchedule(raw: unknown, tz: string, now: number, l: Lang = currentLang()): { schedule?: Schedule; error?: string } {
+ const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
+ const zone = typeof r.tz === "string" && validZone(r.tz) ? r.tz : tz;
+ switch (r.kind) {
+ case "once": {
+ const at = Number(r.at);
- if (!Number.isFinite(at) || at <= 0) return { error: "缺少时间" };
- if (at <= now) return { error: "这个时间已经过了" };
++ if (!Number.isFinite(at) || at <= 0) return { error: tl(l, "rules.needTime") };
++ if (at <= now) return { error: tl(l, "rules.pastTime") };
+ return { schedule: { kind: "once", at: Math.floor(at / MIN) * MIN, tz: zone } };
+ }
+ case "daily":
+ case "weekly": {
+ const time = hhmm(String(r.time ?? ""));
- if (!time) return { error: "时间要写成 08:00 这样" };
++ if (!time) return { error: tl(l, "rules.timeFormat") };
+ const days = Array.isArray(r.days) ? [...new Set(r.days.map((d) => Number(d) % 7).filter((d) => Number.isInteger(d) && d >= 0))].sort((a, b) => a - b) : [];
- if (r.kind === "weekly" && !days.length) return { error: "选一天或几天" };
++ if (r.kind === "weekly" && !days.length) return { error: tl(l, "rules.pickDays") };
+ if (r.kind === "weekly") return { schedule: { kind: "weekly", time, days, tz: zone } };
+ return { schedule: { kind: "daily", time, ...(days.length && days.length < 7 ? { days } : {}), tz: zone } };
+ }
+ case "every": {
+ const minutes = Math.round(Number(r.minutes));
- if (!Number.isFinite(minutes) || minutes < MIN_EVERY_MIN) return { error: `间隔至少 ${MIN_EVERY_MIN} 分钟` };
- if (minutes > 7 * 1440) return { error: "间隔最长 7 天" };
++ if (!Number.isFinite(minutes) || minutes < MIN_EVERY_MIN) return { error: tl(l, "rules.minEvery", { min: MIN_EVERY_MIN }) };
++ if (minutes > 7 * 1440) return { error: tl(l, "rules.maxEvery") };
+ const from = Number(r.from) > 0 ? Number(r.from) : Math.ceil((now + 1) / MIN) * MIN;
+ return { schedule: { kind: "every", minutes, from, tz: zone } };
+ }
+ case "cron": {
+ const cron = String(r.cron ?? "").trim().replace(/\s+/g, " ");
- if (!parseCron(cron)) return { error: "cron 要写 5 段:分 时 日 月 星期" };
++ if (!parseCron(cron)) return { error: tl(l, "rules.cronFields") };
+ return { schedule: { kind: "cron", cron, tz: zone } };
+ }
+ default:
- return { error: "不认识的时间表" };
++ return { error: tl(l, "rules.unknownSchedule") };
+ }
+}
+
+export function validZone(tz: string): boolean {
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * 聊天代理给的一行(rule_create 的 schedule):once 2026-11-02 15:00 | daily 08:00 | weekdays 08:00 | weekly mon,thu 09:00 |
+ * every 30m(或 2h、30 minutes) | cron 0 8 * * 1-5。时间是 tz 里的本地时间。
+ */
+export function parseSchedule(text: string, tz: string, now: number): { schedule?: Schedule; error?: string } {
+ const t = text.trim().replace(/\s+/g, " ");
+ const [head, ...rest] = t.split(" ");
+ const tail = rest.join(" ");
+ const kind = head.toLowerCase();
+ const bad = { error: `Unrecognized schedule "${t}". Use one of: once YYYY-MM-DD HH:MM | daily HH:MM | weekdays HH:MM | weekly mon,thu HH:MM | every 30m | cron M H DOM MON DOW` };
+ if (kind === "daily" || kind === "weekdays" || kind === "weekends") {
+ const time = hhmm(tail);
+ if (!time) return bad;
- return normalizeSchedule({ kind: "daily", time, days: kind === "weekdays" ? [1, 2, 3, 4, 5] : kind === "weekends" ? [0, 6] : [] }, tz, now);
++ return normalizeSchedule({ kind: "daily", time, days: kind === "weekdays" ? [1, 2, 3, 4, 5] : kind === "weekends" ? [0, 6] : [] }, tz, now, "en");
+ }
+ if (kind === "weekly") {
+ const m = /^(.+?) (\d{1,2}[::]\d{2})$/.exec(tail);
+ const days = m ? dayList(m[1]) : undefined;
+ if (!m || !days) return bad;
- return normalizeSchedule({ kind: "weekly", time: m[2], days }, tz, now);
++ return normalizeSchedule({ kind: "weekly", time: m[2], days }, tz, now, "en");
+ }
+ if (kind === "every") {
+ const m = /^(\d+)\s*(m|min|mins|minute|minutes|h|hr|hour|hours)$/i.exec(tail);
+ if (!m) return bad;
+ const n = Number(m[1]) * (/^h/i.test(m[2]) ? 60 : 1);
- const r = normalizeSchedule({ kind: "every", minutes: n }, tz, now);
++ const r = normalizeSchedule({ kind: "every", minutes: n }, tz, now, "en");
+ return r.error ? { error: `every needs at least ${MIN_EVERY_MIN} minutes` } : r;
+ }
+ if (kind === "once") {
+ const m = /^(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}[::]\d{2})$/.exec(tail);
+ const time = m ? hhmm(m[4]) : undefined;
+ if (!m || !time) return bad;
+ const at = localTime(Number(m[1]), Number(m[2]), Number(m[3]), minuteOf(time)!, tz);
- const r = normalizeSchedule({ kind: "once", at }, tz, now);
++ const r = normalizeSchedule({ kind: "once", at }, tz, now, "en");
+ return r.error ? { error: `That time (${tail}, ${tz}) has already passed.` } : r;
+ }
+ if (kind === "cron") {
- const r = normalizeSchedule({ kind: "cron", cron: tail }, tz, now);
++ const r = normalizeSchedule({ kind: "cron", cron: tail }, tz, now, "en");
+ return r.error ? { error: "cron needs 5 fields: minute hour day-of-month month day-of-week" } : r;
+ }
+ return bad;
+}
+
- const WEEK = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
+const pad = (n: number) => String(n).padStart(2, "0");
+
- function daysText(days: number[] | undefined): string {
- if (!days?.length || days.length === 7) return "每天";
++/** 星期几的短名(周一 / Mon):2026-11-01 是周日 */
++const dayName = (d: number, l: Lang) => new Intl.DateTimeFormat(l, { weekday: "short", timeZone: "UTC" }).format(Date.UTC(2026, 10, 1 + d));
++
++function daysText(days: number[] | undefined, time: string, l: Lang): string {
++ if (!days?.length || days.length === 7) return tl(l, "rules.daily", { time });
+ const key = days.join(",");
- if (key === "1,2,3,4,5") return "每个工作日";
- if (key === "0,6") return "每个周末";
++ if (key === "1,2,3,4,5") return tl(l, "rules.weekdays", { time });
++ if (key === "0,6") return tl(l, "rules.weekends", { time });
+ // 周一在前、周日在最后
- return "每" + [...days].sort((a, b) => ((a + 6) % 7) - ((b + 6) % 7)).map((d) => WEEK[d]).join("、");
++ const list = [...days].sort((a, b) => ((a + 6) % 7) - ((b + 6) % 7)).map((d) => dayName(d, l));
++ return tl(l, "rules.weekly", { days: list.join(tl(l, "rules.daysSep")), time });
+}
+
- /** 给用户看的时间表:每天 08:00、每个工作日 08:00、每周一、周四 09:00、每 30 分钟、11月2日 15:00;withZone 时带上时区 */
- export function describe(s: Schedule, withZone = false): string {
++/**
++ * 给用户看的时间表:每天 08:00、每个工作日 08:00、每周一、周四 09:00、每 30 分钟、11月2日 15:00;withZone 时带上时区。
++ * l:语言(默认当前的;给模型看的第一条输入固定用简体中文)
++ */
++export function describe(s: Schedule, withZone = false, l: Lang = currentLang()): string {
+ let text: string;
+ if (s.kind === "once") {
+ const p = localParts(s.at, s.tz);
+ const m = Math.floor(p.minute);
- text = `${p.mo}月${p.d}日 ${pad(Math.floor(m / 60))}:${pad(m % 60)}`;
- } else if (s.kind === "daily" || s.kind === "weekly") text = `${daysText(s.days)} ${s.time}`;
- else if (s.kind === "every") text = s.minutes % 60 === 0 ? `每 ${s.minutes / 60} 小时` : `每 ${s.minutes} 分钟`;
- else text = `cron ${s.cron}`;
- return withZone ? `${text}(${s.tz})` : text;
++ const date = new Intl.DateTimeFormat(l, { month: l === "en" ? "short" : "long", day: "numeric", timeZone: s.tz }).format(s.at);
++ text = tl(l, "rules.once", { date, time: `${pad(Math.floor(m / 60))}:${pad(m % 60)}` });
++ } else if (s.kind === "daily" || s.kind === "weekly") text = daysText(s.days, s.time, l);
++ else if (s.kind === "every") text = s.minutes % 60 === 0 ? tl(l, "rules.everyHour", { count: s.minutes / 60 }) : tl(l, "rules.everyMin", { count: s.minutes });
++ else text = tl(l, "rules.cron", { cron: s.cron });
++ return withZone ? tl(l, "rules.withZone", { text, tz: s.tz }) : text;
+}
diff --cc src/tasks/service.ts
index 9870862,ce34d47..fbcb088
--- a/src/tasks/service.ts
+++ b/src/tasks/service.ts
@@@ -29,35 -25,13 +29,41 @@@ import { ActivityLog, type ActivitySte
import { ResumeFailed, deliverables } from "../agent/host.js";
import { answerLine, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";
import { actionCardSpec } from "../channels/feishu/transport.js";
-import { NUDGE, attachmentsOf, rebrief, recoveryNote, retryNote, taskBrief } from "../agent/prompts/index.js";
+import { NUDGE, RULE_NUDGE, RULE_RERUN, RULE_RESULT_SYSTEM, attachmentsOf, rebrief, recoveryNote, retryNote, ruleBrief, ruleResultInput, ruleRules, taskBrief } from "../agent/prompts/index.js";
import type { BotSettings } from "../agent/settings.js";
-import type { ApprovalRow, Conversation, InputKind, RunCause, RunInputRow, RunOutcome, RunRow, Store, TaskReport, TaskRow } from "../store/db.js";
+import type { ApprovalRow, Conversation, InputKind, RuleKind, RuleMode, RuleRow, RuleTrigger, RunCause, RunInputRow, RunOutcome, RunRow, Store, TaskReport, TaskRow } from "../store/db.js";
import type { AttentionItem } from "./attention.js";
import { logger } from "../log.js";
+import { localParts, systemTimeZone } from "../core/quiet.js";
++import { t } from "../i18n/index.js";
import { DEFAULT_MAX_BACKGROUND, pickRuns, priorityOf } from "./slots.js";
import { taskStage, type Stage } from "./stage.js";
+import { MAX_GRACE_MS, graceOf, nextRun, latestRun, parseSchedule, type Schedule } from "./schedule.js";
+import { Scheduler } from "./scheduler.js";
+import { matchesFilter, type RuleEvent } from "./rule-events.js";
+import {
+ MAX_RULES,
+ RULE_APPROVAL_TTL_MS,
+ RULE_DENY,
+ RULE_DENY_PREFIX,
+ RULE_FAILS_TO_PAUSE,
+ RULE_FAILS_TO_SHOW,
+ RULE_HINT_AFTER,
+ RULE_OBSERVE_AFTER_EDIT,
+ RULE_RUN_CAP_MS,
++ RUN_ERROR,
++ WOULD_APPROVAL,
++ errorText,
++ permissionText,
+ ruleState,
+ rulePermission,
+ runLine,
+ runMode,
+ whenOf,
++ wouldText,
+ type RuleRunView,
+ type RuleView,
+} from "./rules.js";
const log = logger("tasks");
@@@ -188,19 -147,9 +194,18 @@@ interface Live
}
const hex = (n: number) => crypto.randomBytes(n).toString("hex");
++/** 翻译(updateRule 里有叫 t 的局部变量) */
++const tr = t;
const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();
+const pad2 = (n: number) => String(n).padStart(2, "0");
+/** 给模型看的时间:11月1日 08:00(规则的时区) */
+function stamp(ts: number, tz: string): string {
+ const p = localParts(ts, tz);
+ const m = Math.floor(p.minute);
+ return `${p.mo}月${p.d}日 ${pad2(Math.floor(m / 60))}:${pad2(m % 60)}`;
+}
- /** 规则发到微信时,建规则的回复里要说的那句(设计第 6 节「Be honest when a rule is created」) */
- export const WEIXIN_RULE_NOTE = "微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。";
-
/** 文件夹名里的 slug:标题里的字母数字(中文标题就是 task) */
export function slugOf(title: string): string {
const s = title
@@@ -1141,30 -1037,16 +1146,30 @@@ export class TaskService
/** /tasks:这个会话的任务,带编号(/stop 编号 用同一个顺序) */
listText(conversationId: string): string {
const list = this.list({ conversationId, limit: 10, since: this.now() - 7 * 86400_000 });
- if (!list.length) return "没有后台任务。";
+ const rules = this.activeRules(conversationId);
+ if (!list.length && !rules.length) return "没有后台任务。";
const lines = list.map((t, i) => `${i + 1}. ${t.title} · ${t.stage.label}${t.latest ? `:${clip(t.latest, 40)}` : ""}`);
- const working = list.findIndex((t) => t.stage.group === "working");
- return ["后台任务:", ...lines, ...(working >= 0 ? ["发 /stop 编号 可停止。"] : [])].join("\n");
+ // 规则接着编号(/stop 编号 关掉它)
- const ruleLines = rules.map((r, i) => `${list.length + i + 1}. ${r.when} ${r.title} · ${r.state.label}`);
- const working = list.findIndex((t) => t.stage.group === "working");
- return [...(list.length ? ["后台任务:", ...lines] : []), ...(rules.length ? ["规则:", ...ruleLines] : []), ...(working >= 0 || rules.length ? ["发 /stop 编号 可停止。"] : [])].join("\n");
++ const ruleLines = rules.map((r, i) => t("rules.listLine", { n: list.length + i + 1, when: r.when, title: r.title, state: r.state.label }));
++ const working = list.findIndex((x) => x.stage.group === "working");
++ return [...(list.length ? ["后台任务:", ...lines] : []), ...(rules.length ? [t("rules.listHead"), ...ruleLines] : []), ...(working >= 0 || rules.length ? [t("rules.stopHint")] : [])].join("\n");
+ }
+
+ /** /tasks 里列出的规则:开着的(关了的、跑完了的一次性规则不列) */
+ private activeRules(conversationId: string): RuleView[] {
+ return this.listRules({ conversationId }).filter((r) => r.state.key !== "off" && r.state.key !== "done");
}
/** /stop 编号:立即记为停止(停会话在后台进行),返回给用户的话 */
stopByIndex(conversationId: string, n: number, by: string): string {
const list = this.list({ conversationId, limit: 10, since: this.now() - 7 * 86400_000 });
const t = list[n - 1];
+ const rule = t ? undefined : this.activeRules(conversationId)[n - 1 - list.length];
+ if (rule) {
+ this.updateRule(rule.id, { mode: "off" });
+ log.info("rule turned off from chat", { rule: rule.id, by });
- return `已关闭规则「${rule.title}」。`;
++ return tr("rules.turnedOff", { title: rule.title });
+ }
if (!t) return `没有第 ${n} 个后台任务,发 /tasks 查看。`;
if (t.stage.group !== "working") return `「${t.title}」${t.stage.label}。`;
void this.stopTask(t.id, by);
@@@ -1183,689 -1065,6 +1188,692 @@@
/* ignore */
}
}
+
+ // ---------- 规则(3d) ----------
+
+ private get timeZone(): string {
+ return this.o.timeZone ?? systemTimeZone();
+ }
+
+ /** 主模型:发到的那个会话的模型 → 机器人的默认 → 应用的默认(和任务一样) */
+ private mainModel(rule: RuleRow): string {
+ const conv = this.store.getConversation(rule.conversationId);
+ return conv?.model || this.store.getBot(rule.botId)?.defaultModel || this.o.defaultModel?.() || "";
+ }
+
+ /** 检查用的模型:机器人的小模型(没设就是主模型;产品负责人的决定 5) */
+ private checkModel(rule: RuleRow): string {
+ return this.o.host.settings(rule.botId).utilityModel || this.mainModel(rule);
+ }
+
+ /** 发到这个会话、会主动发消息的规则(执行中的检查和提醒,没暂停):给微信留配额、续期提醒里列出来 */
+ private pushingRules(conversationId: string): RuleRow[] {
+ return this.store
+ .listRules({ conversationId })
+ .filter((r) => r.mode !== "off" && !r.pausedReason && runMode(r) === "act" && (r.nextRunAt > 0 || r.trigger.kind === "event"));
+ }
+
+ /** 这条规则有没有还没结束的 run(排队、在跑、收尾) */
+ private ruleBusy(ruleId: string): boolean {
+ return this.store.listRuns({ ruleId, states: ["queued", "running", "settling"], limit: 1 }).length > 0;
+ }
+
+ /** 时间表的下一次(关着、暂停了、事件触发的没有) */
+ private nextFor(rule: Pick<RuleRow, "trigger" | "mode" | "pausedReason">, now: number): number {
+ if (rule.mode === "off" || rule.pausedReason || rule.trigger.kind !== "schedule") return 0;
+ return nextRun(rule.trigger.schedule, now) ?? 0;
+ }
+
+ private graceFor(rule: RuleRow, at: number): number {
+ return rule.trigger.kind === "schedule" ? graceOf(rule.trigger.schedule, at) : MAX_GRACE_MS;
+ }
+
+ /**
+ * 新规则(聊天代理的 rule_create、界面):检查从观察开始;固定提醒没什么要判断的,直接执行(决定 6),
+ * 不受免打扰限制(时间是用户定的)。时间表或事件触发二选一。
+ */
+ createRule(o: { botId: string; conversationId: string; title: string; instruction: string; kind?: RuleKind; message?: string; schedule?: Schedule; trigger?: RuleTrigger }): { rule?: RuleRow; error?: string } {
+ const conv = this.store.getConversation(o.conversationId);
+ if (!conv || conv.botId !== o.botId || !this.store.getBot(o.botId)) return { error: "conversation not found" };
+ const kind: RuleKind = o.kind === "remind" ? "remind" : "check";
+ const title = clip(oneLine(o.title), 40);
+ const message = clip(oneLine(o.message ?? ""), MESSAGE_MAX);
+ // 提醒:界面里只写那句话时,它也是原话
+ const instruction = (o.instruction.trim() || (kind === "remind" ? message : "")).slice(0, 2000);
+ if (!title) return { error: "title is required" };
+ if (!instruction) return { error: "instruction is required: the user's words" };
+ if (kind === "remind" && !message) return { error: "a reminder needs message: the exact line to send" };
+ const trigger: RuleTrigger | undefined = o.trigger ?? (o.schedule ? { kind: "schedule", schedule: o.schedule } : undefined);
+ if (!trigger || (trigger.kind === "event" && !trigger.source.trim())) return { error: "schedule is required" };
+ if (kind === "remind" && trigger.kind !== "schedule") return { error: "a reminder needs a schedule" };
+ if (this.store.listRules({ botId: o.botId }).length >= MAX_RULES) return { error: `This bot already has ${MAX_RULES} rules; delete one first.` };
+ const now = this.now();
+ const id = `rl_${hex(6)}`;
+ const mode: RuleMode = kind === "remind" ? "act" : "observe";
+ const rule = this.store.insertRule({
+ id,
+ botId: o.botId,
+ conversationId: conv.id,
+ title,
+ instruction,
+ message: kind === "remind" ? message : "",
+ kind,
+ trigger,
+ mode,
+ folder: `rules/${slugOf(title).replace(/^task$/, "rule")}-${id.slice(3, 9)}`,
+ nextRunAt: this.nextFor({ trigger, mode, pausedReason: "" }, now),
+ anytime: kind === "remind",
+ createdAt: now,
+ updatedAt: now,
+ });
+ log.info("rule created", { bot: o.botId, rule: id, kind, trigger: trigger.kind, conversationId: conv.id });
+ this.ruleChanged(id);
+ return { rule };
+ }
+
+ /**
+ * 改规则(界面、rule_update)。改原话:版本加 1;执行中的检查先观察 1 次再回到执行(决定 7)。只改时间表:模式不变。
+ * 改模式:重新开的清掉连续失败和暂停。正在跑的那次照它开始时的版本跑完。
+ */
+ updateRule(id: string, patch: { title?: string; instruction?: string; message?: string; schedule?: Schedule; mode?: RuleMode; conversationId?: string }): { rule?: RuleRow; error?: string } {
+ const rule = this.store.getRule(id);
+ if (!rule) return { error: "rule not found" };
+ const now = this.now();
+ const next: Partial<RuleRow> = { updatedAt: now };
+ if (patch.title !== undefined) {
+ const t = clip(oneLine(patch.title), 40);
- if (!t) return { error: "名称不能为空" };
++ if (!t) return { error: tr("rules.nameEmpty") };
+ next.title = t;
+ }
+ let reworded = false;
+ if (patch.instruction !== undefined) {
+ const t = patch.instruction.trim().slice(0, 2000);
- if (!t) return { error: "规则不能为空" };
++ if (!t) return { error: tr("rules.wordsEmpty") };
+ if (t !== rule.instruction) (next.instruction = t), (reworded = true);
+ }
+ if (patch.message !== undefined && rule.kind === "remind") {
+ const m = clip(oneLine(patch.message), MESSAGE_MAX);
- if (!m) return { error: "提醒的话不能为空" };
++ if (!m) return { error: tr("rules.messageEmpty") };
+ if (m !== rule.message) (next.message = m), (reworded = true);
+ }
+ if (patch.conversationId !== undefined && patch.conversationId !== rule.conversationId) {
+ const c = this.store.getConversation(patch.conversationId);
- if (!c || c.botId !== rule.botId) return { error: "没有这个会话" };
++ if (!c || c.botId !== rule.botId) return { error: tr("rules.noConversation") };
+ next.conversationId = c.id;
+ }
+ let trigger = rule.trigger;
+ if (patch.schedule) {
- if (rule.trigger.kind !== "schedule") return { error: "这条规则由事件触发,没有时间表" };
++ if (rule.trigger.kind !== "schedule") return { error: tr("rules.eventNoSchedule") };
+ trigger = next.trigger = { kind: "schedule", schedule: patch.schedule };
+ }
+ let mode = rule.mode;
+ if (patch.mode !== undefined && patch.mode !== rule.mode) {
- if (rule.kind === "remind" && patch.mode === "observe") return { error: "提醒没有观察模式" };
++ if (rule.kind === "remind" && patch.mode === "observe") return { error: tr("rules.remindNoObserve") };
+ mode = next.mode = patch.mode;
+ next.observeLeft = 0;
+ }
+ if (reworded) {
+ next.version = rule.version + 1;
+ if (rule.kind === "check" && mode === "act") next.observeLeft = RULE_OBSERVE_AFTER_EDIT;
+ }
+ // 重新开(关着、暂停了 → 开着):连续失败清零
+ const reopened = patch.mode !== undefined && mode !== "off" && (rule.mode === "off" || !!rule.pausedReason || patch.mode !== rule.mode);
+ if (reopened) (next.failures = 0), (next.pausedReason = "");
+ if (next.trigger || next.mode !== undefined || reopened) next.nextRunAt = this.nextFor({ trigger, mode, pausedReason: reopened ? "" : rule.pausedReason }, now);
+ this.store.updateRule(id, next);
+ log.info("rule updated", { rule: id, fields: Object.keys(next).filter((k) => k !== "updatedAt") });
+ this.ruleChanged(id);
+ return { rule: this.store.getRule(id) };
+ }
+
+ /** 暂停的规则重新开(「需要你」里的重试):清掉连续失败,接着按时间表跑,并马上跑一次 */
+ resumeRule(id: string): { error?: string } {
+ const rule = this.store.getRule(id);
+ if (!rule) return { error: "rule not found" };
+ if (rule.pausedReason || rule.failures) {
+ const mode = rule.mode === "off" ? (rule.kind === "remind" ? "act" : "observe") : rule.mode;
+ this.store.updateRule(id, { failures: 0, pausedReason: "", mode, nextRunAt: this.nextFor({ trigger: rule.trigger, mode, pausedReason: "" }, this.now()), updatedAt: this.now() });
+ }
+ return this.runRuleNow(id);
+ }
+
+ /** 立即运行(界面):按规则现在的模式跑一次(人要求的:排在前面) */
+ runRuleNow(id: string): { error?: string } {
+ const rule = this.store.getRule(id);
+ if (!rule) return { error: "rule not found" };
- if (rule.mode === "off") return { error: "规则关着" };
- if (this.ruleBusy(id)) return { error: "正在运行" };
++ if (rule.mode === "off") return { error: tr("rules.isOff") };
++ if (this.ruleBusy(id)) return { error: tr("rules.isRunning") };
+ this.fireRule(rule, "manual", this.now());
+ this.pump();
+ return {};
+ }
+
+ /** 删掉规则:正在跑的那次停掉,等着的批准作废,运行记录一起删 */
+ async deleteRule(id: string): Promise<boolean> {
+ const rule = this.store.getRule(id);
+ if (!rule) return false;
+ for (const a of this.o.approvals?.pendingAll().filter((x) => x.ruleId === id) ?? []) this.o.approvals!.cancel(a.id, "deleted");
+ const l = [...this.live.values()].find((x) => x.ruleId === id);
+ if (l) this.forget(l);
+ this.store.deleteRule(id);
+ if (l) await this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);
+ log.info("rule deleted", { rule: id });
+ this.ruleChanged(id);
+ this.pump();
+ return true;
+ }
+
+ private ruleChanged(id: string): void {
+ this.changed(id);
+ this.scheduler.wake();
+ }
+
+ /**
+ * 定时器到点(也在启动时、电脑醒来时):每条到点的规则把 next_run_at 往后挪,最近该跑的那次在宽限期内就跑一次,
+ * 更早错过的记一条「跳过:电脑没开」,从不补一串。上一次还没跑完的,这次跳过。
+ */
+ fireDue(now = this.now()): void {
+ if (!this.started || this.closing) return;
+ for (const rule of this.store.dueRules(now)) {
+ if (this.dropped.has(rule.botId) || rule.trigger.kind !== "schedule") continue;
+ const s = rule.trigger.schedule;
+ const due = rule.nextRunAt;
+ const last = latestRun(s, now, due) ?? due;
+ this.store.updateRule(rule.id, { nextRunAt: nextRun(s, now) ?? 0 });
+ if (now - last > graceOf(s, last)) {
- this.skipRun(rule, due, "电脑没开");
++ this.skipRun(rule, due, RUN_ERROR.appOff);
+ continue;
+ }
- if (last > due) this.skipRun(rule, due, "电脑没开");
++ if (last > due) this.skipRun(rule, due, RUN_ERROR.appOff);
+ this.fireRule(rule, "schedule", last);
+ }
+ this.pump();
+ }
+
+ /**
+ * 事件到了(RuleEvents.emit,见 rule-events.ts):来源相同、过滤条件对得上的开着的规则各开一个 run,和定时的走同一条路。
+ * 以后用户配置的 workload 在这里接进来。返回开了 run 的规则 id。
+ */
+ emitRuleEvent(source: string, event: RuleEvent): string[] {
+ if (!this.started || this.closing) return [];
+ const out: string[] = [];
+ const now = this.now();
+ for (const rule of this.store.listRules()) {
+ if (rule.trigger.kind !== "event" || rule.trigger.source !== source || rule.mode === "off" || rule.pausedReason || this.dropped.has(rule.botId)) continue;
+ if (!matchesFilter(rule.trigger.filter, event)) continue;
+ if (this.fireRule(rule, "event", now, { source, event })) out.push(rule.id);
+ }
+ if (out.length) {
+ log.info("rule event", { source, rules: out.length });
+ this.pump();
+ }
+ return out;
+ }
+
+ /**
+ * 开一次:提醒直接发那句话(不进模型、不占名额);检查排一个 run(新会话,第一条输入是规则、原话、最近 3 次的结果)。
+ * 上一次还没结束:到点的、事件来的这次跳过。
+ */
+ private fireRule(rule: RuleRow, cause: RunCause, at: number, event?: { source: string; event: RuleEvent }): RunRow | undefined {
+ if (this.ruleBusy(rule.id)) {
- if (cause === "schedule" || cause === "event") this.skipRun(rule, at, "上次还没跑完");
++ if (cause === "schedule" || cause === "event") this.skipRun(rule, at, RUN_ERROR.overlap);
+ return undefined;
+ }
+ if (rule.kind === "remind") return this.remind(rule, cause, at);
+ const mode = runMode(rule);
+ const id = `r_${hex(6)}`;
+ const run = this.store.insertRun({ id, botId: rule.botId, taskId: "", ruleId: rule.id, ruleVersion: rule.version, mode, sessionId: `rule-${rule.id}-${id.slice(2)}`, cause, queuedAt: at });
+ this.store.insertInput({ id: `i_${hex(6)}`, taskId: "", ruleId: rule.id, runId: id, kind: "schedule", text: this.ruleBriefFor(rule, mode, event), fromPerson: cause === "manual", createdAt: this.now() });
+ this.changed(rule.id);
+ return run;
+ }
+
+ /** 第一条输入:规则、用户原话、最近 3 次的结果(连续性靠它,每次是新会话)、事件、记忆快照、这次是观察还是执行 */
+ private ruleBriefFor(rule: RuleRow, mode: "observe" | "act", event?: { source: string; event: RuleEvent }): string {
+ const tz = rule.trigger.kind === "schedule" ? rule.trigger.schedule.tz : this.timeZone;
+ const recent = this.store
+ .ruleRuns(rule.id, { limit: 10 })
+ .filter((r) => r.state === "ended" && r.report)
+ .slice(0, 3)
+ .reverse()
+ .map((r) => {
+ const msg = oneLine(r.report!.message ?? "");
+ const head = r.outcome === "failed" ? "失败" : msg ? `${r.mode === "observe" ? "本会告诉用户" : "告诉了用户"}:${msg}` : "没有告诉用户";
+ return { at: stamp(r.queuedAt, tz), line: [head, oneLine(r.report!.summary)].filter(Boolean).join("。") };
+ });
+ const st = this.o.host.settings(rule.botId);
+ let payload = "";
+ try {
+ payload = event ? JSON.stringify(event.event) : "";
+ } catch {
+ payload = "{}";
+ }
+ return ruleBrief({
+ title: rule.title,
- when: whenOf(rule),
++ // 第一条输入是给模型的,和别的提示词一样固定用简体中文
++ when: whenOf(rule, false, "zh-CN"),
+ instruction: rule.instruction,
+ mode,
+ recent,
+ ...(event ? { event: { source: event.source, payload } } : {}),
+ memory: st.memory.enabled ? this.o.host.memoryPrefix(rule.botId, rule.conversationId) : undefined,
+ });
+ }
+
+ /** 固定提醒:到点把那句话发出去,记一条运行记录(不进模型) */
+ private remind(rule: RuleRow, cause: RunCause, at: number): RunRow {
+ const now = this.now();
+ const id = `r_${hex(6)}`;
+ this.store.insertEndedRun({ id, botId: rule.botId, ruleId: rule.id, ruleVersion: rule.version, mode: "act", cause, outcome: "done", error: "", queuedAt: at, endedAt: now });
+ this.store.updateRun(id, { startedAt: now, report: { state: "done", summary: "", message: rule.message, at: now } });
+ this.deliverRule(rule, id, "reminder", rule.message);
+ log.info("reminder sent", { rule: rule.id, run: id });
+ this.changed(rule.id);
+ return this.store.getRun(id)!;
+ }
+
- /** 记一条跳过(电脑没开、一直在忙、上次还没跑完) */
++ /** 记一条跳过(电脑没开、一直在忙、上次还没跑完:why 是 RUN_ERROR 里的代码) */
+ private skipRun(rule: RuleRow, at: number, why: string): void {
+ this.store.insertEndedRun({ id: `r_${hex(6)}`, botId: rule.botId, ruleId: rule.id, ruleVersion: rule.version, mode: runMode(rule), cause: "schedule", outcome: "skipped", error: why, queuedAt: at, endedAt: this.now() });
+ log.info("rule run skipped", { rule: rule.id, at, why });
+ this.changed(rule.id);
+ }
+
+ /** 排着的规则 run 等名额超过宽限期:跳过(「一直在忙」);规则删了的作废。返回 true = 不用再排了 */
+ private skipStale(run: RunRow): boolean {
+ const rule = this.store.getRule(run.ruleId);
+ const now = this.now();
+ if (!rule) {
+ this.store.updateRun(run.id, { state: "ended", outcome: "stopped", endedAt: now });
+ return true;
+ }
+ if (now - run.queuedAt <= this.graceFor(rule, run.queuedAt)) return false;
- this.store.updateRun(run.id, { state: "ended", outcome: "skipped", error: "一直在忙", endedAt: now });
++ this.store.updateRun(run.id, { state: "ended", outcome: "skipped", error: RUN_ERROR.busy, endedAt: now });
+ log.info("rule run skipped: no free slot within its grace period", { rule: rule.id, run: run.id });
+ this.changed(rule.id);
+ return true;
+ }
+
+ /** 开始规则的一个 run:新会话,工作目录是规则的文件夹,检查用小模型;观察只读,执行最多可写工作区 */
+ private async startRuleRun(run: RunRow): Promise<void> {
+ const rule = this.store.getRule(run.ruleId);
+ const now = this.now();
+ if (!rule) {
+ this.store.updateRun(run.id, { state: "ended", outcome: "stopped", endedAt: now });
+ return;
+ }
+ const mode = run.mode === "act" ? "act" : "observe";
+ const permission = rulePermission(mode, this.o.host.settings(rule.botId).permission);
+ this.store.updateRun(run.id, { state: "running", startedAt: now, permission });
+ const model = this.checkModel(rule);
+ const l: Live = {
+ runId: run.id,
+ taskId: "",
+ ruleId: rule.id,
+ mode,
+ folder: path.join(this.o.host.workspace(rule.botId), rule.folder),
+ model: model && this.o.route ? this.o.route(rule.botId, model) : model,
+ botId: rule.botId,
+ sessionId: run.sessionId,
+ activity: new ActivityLog(undefined, model),
+ busy: false,
+ starting: false,
+ checking: false,
+ settling: false,
+ nudged: false,
+ retries: 0,
+ seen: new Set(),
+ tokensIn: 0,
+ tokensOut: 0,
+ would: [],
+ };
+ this.live.set(run.id, l);
+ this.bySession.set(run.sessionId, l);
+ this.armCap(l, this.o.ruleRunCapMs ?? RULE_RUN_CAP_MS);
+ this.changed(rule.id);
+ const inputs = this.store.openRunInputs(run.id);
+ await this.deliver_(l, inputs.length ? inputs : [this.inputFor(l, "nudge", RULE_NUDGE)]);
+ }
+
+ /** 一次运行的时间上限:到了就停掉会话,这次算失败(在等批准时不算,批准最多等 1 小时) */
+ private armCap(l: Live, ms: number): void {
+ clearTimeout(l.capTimer);
+ l.capTimer = setTimeout(() => {
+ l.capTimer = undefined;
+ if (this.live.get(l.runId) !== l) return;
+ if (this.o.approvals?.pendingAll().some((a) => a.ruleId && a.runId === l.runId)) return this.armCap(l, 60_000);
+ log.warn("rule run hit its time cap; stopping it", { rule: l.ruleId, run: l.runId });
- l.activity.end("超时");
- this.end(l, "failed", undefined, "超时");
++ l.activity.end(t("rules.whyTimeout"));
++ this.end(l, "failed", undefined, RUN_ERROR.timeout);
+ void this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);
+ }, ms);
+ l.capTimer.unref?.();
+ }
+
+ /** 规则会话的 task_report:done(带 message = 要告诉用户的一句,不带 = 保持安静)、failed、progress;没有 needs_you */
+ private ruleReport(l: Live, b: any): { text?: string; error?: string } {
+ const state = String(b?.state ?? "");
+ if (state !== "progress" && state !== "done" && state !== "failed") return { error: "state must be progress, done or failed (a rule run cannot ask the user)" };
+ const message = typeof b?.message === "string" ? oneLine(b.message) : "";
+ const would = typeof b?.would === "string" ? clip(b.would.trim(), 1000) : "";
+ const report: TaskReport = {
+ state,
+ summary: clip(String(b?.summary ?? "").trim(), 2000),
+ ...(message ? { message: clip(message, MESSAGE_MAX) } : {}),
+ ...(would ? { would } : {}),
+ at: this.now(),
+ };
+ this.store.updateRun(l.runId, { report });
+ if (state !== "progress") l.final = report;
+ this.changed(l.ruleId);
+ if (state === "progress") return { text: "Progress recorded (it is not sent). Continue the check." };
+ if (state === "failed") return { text: "Recorded. End your turn now." };
+ if (!message) return { text: "Recorded: the user hears nothing this time. End your turn now." };
+ return { text: l.mode === "observe" ? "Recorded as what you would have said (observe mode: nothing is sent). End your turn now." : "Recorded. End your turn now: the app sends your message to the user." };
+ }
+
+ /** 结束规则的 run:存下步骤、报告、本会做的事;之后按结果更新规则(连续失败、先观察的次数)、送出那一句 */
+ private endRule(l: Live, outcome: RunOutcome, report?: TaskReport, error = ""): void {
+ this.forget(l);
+ const now = this.now();
- const would = [report?.would ?? "", ...(l.would ?? []).map((d) => `需要批准:${d}`)].filter(Boolean).join("\n");
++ const would = [report?.would ?? "", ...(l.would ?? []).map((d) => `${WOULD_APPROVAL}${d}`)].filter(Boolean).join("\n");
+ this.store.updateRun(l.runId, { state: "ended", outcome, report, would, error, endedAt: now, activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });
+ for (const a of this.o.approvals?.pendingAll().filter((x) => x.ruleId && x.runId === l.runId) ?? []) this.o.approvals!.cancel(a.id, "run ended");
+ const rule = this.store.getRule(l.ruleId);
+ if (rule) this.afterRuleRun(rule, l.runId, l.mode, outcome, report, error);
+ log.info("rule run ended", { rule: l.ruleId, run: l.runId, mode: l.mode, outcome, ...(error ? { error } : {}) });
+ this.changed(l.ruleId);
+ this.pump();
+ }
+
+ /**
+ * 一次运行之后:成功清零连续失败,改了原话后先观察的那一次跑完了就回到执行;有要说的那一句(观察时是「本会发送」)用主模型写,
+ * 执行时发出去。失败加 1,连续 3 次自动暂停:执行中的规则推一句 ⚠️,观察中的只在「需要你」里。
+ */
+ private afterRuleRun(rule: RuleRow, runId: string, mode: "observe" | "act", outcome: RunOutcome, report: TaskReport | undefined, error: string): void {
+ const run = this.store.getRun(runId);
+ if (outcome === "done") {
+ const patch: Partial<RuleRow> = { failures: 0 };
+ if (mode === "observe" && rule.mode === "act" && rule.observeLeft > 0 && run?.ruleVersion === rule.version) patch.observeLeft = rule.observeLeft - 1;
+ this.store.updateRule(rule.id, patch);
+ if (report?.message) void this.ruleResult(rule, runId, mode, report);
+ return;
+ }
+ if (outcome !== "failed") return;
+ const failures = rule.failures + 1;
+ if (failures < RULE_FAILS_TO_PAUSE) return void this.store.updateRule(rule.id, { failures });
+ this.store.updateRule(rule.id, { failures, pausedReason: "failures", nextRunAt: 0 });
+ log.warn("rule paused after failing in a row", { rule: rule.id, failures });
+ if (rule.mode === "act") {
- const why = clip(oneLine(report?.message || error || "没有给出结果"), 200);
- this.deliverRule(rule, runId, "failure", `⚠️ 规则「${rule.title}」连续失败 ${failures} 次,已暂停:${why}`);
++ // 后台推送:应用的语言
++ const why = clip(oneLine(report?.message || errorText(error || "没有给出结果")), 200);
++ this.deliverRule(rule, runId, "failure", t("rules.pausedPush", { title: rule.title, count: failures, why }));
+ }
+ }
+
+ /** 那一句用主模型写(检查用的小模型只给草稿);执行时发出去。主模型不可用就用草稿 */
+ private async ruleResult(rule: RuleRow, runId: string, mode: "observe" | "act", report: TaskReport): Promise<void> {
+ let message = report.message ?? "";
+ const main = this.mainModel(rule);
+ if (this.o.complete && main && this.checkModel(rule) !== main) {
+ try {
+ const out = await this.o.complete(rule.botId, main, RULE_RESULT_SYSTEM, ruleResultInput({ instruction: rule.instruction, summary: report.summary, draft: message }));
+ const line = clip(oneLine(out).replace(/^["“「]+|["”」]+$/g, ""), MESSAGE_MAX);
+ if (line) message = line;
+ } catch (e) {
+ log.warn("writing the rule result with the main model failed; sending the draft", { rule: rule.id, message: (e as Error).message.slice(0, 200) });
+ }
+ if (message !== report.message) this.store.updateRun(runId, { report: { ...report, message } });
+ }
+ const fresh = this.store.getRule(rule.id);
+ if (mode === "act" && fresh) this.deliverRule(fresh, runId, "rule", message);
+ this.changed(rule.id);
+ }
+
+ /**
+ * 送出规则的那一句(命中、提醒、暂停):微信、飞书按主动消息的规则经出站队列(id 固定:rule:<规则>:<run>,同一 id 只发一次),
+ * 飞书直接发到会话;同时写进会话历史,给聊天代理留张便条。交过的 run 不再交。
+ */
+ private deliverRule(rule: RuleRow, runId: string, purpose: "rule" | "reminder" | "failure", text: string): void {
+ const run = this.store.getRun(runId);
+ if (!run || run.delivery) return;
+ const id = purpose === "failure" ? `rule:${rule.id}:paused:${runId}` : `rule:${rule.id}:${runId}`;
+ const conv = this.store.getConversation(rule.conversationId);
+ if (!conv) return void this.store.updateRun(runId, { delivery: `${id}:dropped` });
+ if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.delivery) {
+ this.o.delivery.push({
+ id,
+ botId: rule.botId,
+ channel: conv.channel,
+ peerId: conv.peerId,
+ purpose,
+ subject: rule.title,
+ text,
+ kind: conv.channel === "feishu" ? "notice" : "text",
+ anytime: rule.anytime,
+ ref: `rule:${rule.id}`,
+ });
+ }
+ this.store.addMessage(conv.id, "assistant", text);
+ this.store.updateRun(runId, { delivery: id });
+ this.note(conv.id, purpose === "failure" ? `[规则「${rule.title}」暂停了,已告诉用户] ${text}` : `[规则「${rule.title}」发给了用户] ${text}`);
+ log.info("rule message handed over", { rule: rule.id, run: runId, purpose, channel: conv.channel });
+ }
+
+ /** 启动:结束了、要发却还没交出去的(交之前应用退出了)补交;只看两天之内的 */
+ private redeliverRules(): void {
+ const since = this.now() - 2 * 86400_000;
+ for (const rule of this.store.listRules()) {
+ for (const r of this.store.ruleRuns(rule.id, { limit: 5 })) {
+ if (r.state !== "ended" || r.delivery || r.endedAt < since || r.outcome !== "done" || r.mode !== "act" || !r.report?.message) continue;
+ this.deliverRule(rule, r.id, rule.kind === "remind" ? "reminder" : "rule", r.report.message);
+ }
+ }
+ }
+
+ /**
+ * 重启时被打断的规则 run(已记为 interrupted):还在宽限期内、不是重跑过的,就用新会话再跑一次(照原样交第一条输入,
+ * 前面加一句说明);否则记为跳过(设计 3.restart 第 7 条)。
+ */
+ private recoverRule(run: RunRow): void {
+ const rule = this.store.getRule(run.ruleId);
+ if (!rule) return;
+ const fresh = this.now() - run.queuedAt <= this.graceFor(rule, run.queuedAt);
+ if (run.cause === "recover" || !fresh || rule.mode === "off" || rule.pausedReason || this.ruleBusy(rule.id)) {
- this.store.updateRun(run.id, { outcome: "skipped", error: "应用重启了" });
++ this.store.updateRun(run.id, { outcome: "skipped", error: RUN_ERROR.restart });
+ this.changed(rule.id);
+ return;
+ }
+ const id = `r_${hex(6)}`;
+ const mode = run.mode === "act" ? "act" : "observe";
+ this.store.insertRun({ id, botId: rule.botId, taskId: "", ruleId: rule.id, ruleVersion: run.ruleVersion, mode, sessionId: `rule-${rule.id}-${id.slice(2)}`, cause: "recover", queuedAt: run.queuedAt });
+ const brief = this.store.runInputs(run.id).find((i) => i.kind === "schedule")?.text ?? this.ruleBriefFor(rule, mode);
+ this.store.insertInput({ id: `i_${hex(6)}`, taskId: "", ruleId: rule.id, runId: id, kind: "schedule", text: `${RULE_RERUN}\n\n${brief}`, fromPerson: false, createdAt: this.now() });
+ log.info("rule run interrupted by a restart; running it again", { rule: rule.id, run: run.id, rerun: id });
+ this.changed(rule.id);
+ }
+
+ /** 插件(/dsh/task-config):规则会话的配置——观察只读、去掉能改变什么的工具;执行最多可写工作区。宿主说了算 */
+ sessionConfig(b: any): { kind?: string; mode?: string; deny?: string[]; denyPrefix?: string[]; section?: string; permission?: string; error?: string } {
+ const l = this.bySession.get(String(b?.sessionId ?? ""));
+ if (!l?.ruleId) return { error: "not a rule session the app is running" };
+ return { kind: "rule", mode: l.mode, deny: RULE_DENY[l.mode], denyPrefix: RULE_DENY_PREFIX, section: ruleRules(l.mode), permission: rulePermission(l.mode, this.o.host.settings(l.botId).permission) };
+ }
+
+ /** 规则会话(或它的子代理)属于哪条规则、哪次运行、这次是观察还是执行(审批落到哪里、观察时自动拒绝) */
+ ruleOfSession(sessionId: string, root?: string): { ruleId: string; runId: string; conversationId: string; mode: "observe" | "act" } | undefined {
+ const l = this.bySession.get(sessionId) ?? (root ? this.bySession.get(root) : undefined);
+ if (!l?.ruleId) return undefined;
+ const rule = this.store.getRule(l.ruleId);
+ return rule ? { ruleId: rule.id, runId: l.runId, conversationId: rule.conversationId, mode: l.mode } : undefined;
+ }
+
+ /** 观察时要批准的事:自动拒绝,记成「需要批准:…」 */
+ wouldNeedApproval(runId: string, detail: string): void {
+ const l = this.live.get(runId);
+ if (!l?.ruleId) return;
+ (l.would ??= []).push(clip(oneLine(detail || "一个操作"), 200));
+ log.info("rule run in observe mode asked for approval; rejected and recorded", { rule: l.ruleId, run: runId });
+ }
+
+ /** 规则执行时的审批:有了决定刷新;1 小时没人管(过期)就拒绝,这次运行失败(设计第 7 节) */
+ private onRuleApproval(e: ApprovalEvent): void {
+ const row = e.row;
+ this.changed(row.ruleId);
+ if (e.type !== "decided" || row.status !== "expired" || row.decidedBy !== "timeout") return;
+ const l = this.live.get(row.runId);
+ if (!l) return;
+ void this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);
- this.end(l, "failed", undefined, "批准超时");
++ this.end(l, "failed", undefined, RUN_ERROR.approvalTimeout);
+ }
+
+ // ---------- 规则:聊天代理的工具 ----------
+
+ /** rule_create:用户原话、一行时间表、检查还是提醒 */
+ private ruleCreateTool(conv: Conversation, a: Record<string, unknown>): { text?: string; error?: string } {
+ const s = parseSchedule(String(a.schedule ?? ""), this.timeZone, this.now());
+ if (!s.schedule) return { error: s.error };
+ const kind: RuleKind = a.kind === "remind" ? "remind" : "check";
+ const r = this.createRule({ botId: conv.botId, conversationId: conv.id, title: String(a.title ?? ""), instruction: String(a.instruction ?? ""), kind, message: String(a.message ?? ""), schedule: s.schedule });
+ if (!r.rule) return { error: r.error };
++ // 建议给用户的那几句按应用的语言(模型照着说,聊天的语言不同时它会自己换);其余是给模型的指示
+ const when = whenOf(r.rule);
- const wx = conv.channel === "weixin" ? ` This chat is WeChat, so also say: 「${WEIXIN_RULE_NOTE}」` : "";
- if (kind === "remind") return { text: `Created reminder ${r.rule.id}: ${when} the user gets 「${r.rule.message}」. Confirm in one sentence, e.g. 「好,${when} 提醒你。」${wx}` };
++ const wx = conv.channel === "weixin" ? ` This chat is WeChat, so also say: 「${t("rules.weixinNote")}」` : "";
++ if (kind === "remind") return { text: `Created reminder ${r.rule.id}: ${when} the user gets 「${r.rule.message}」. Confirm in one sentence, e.g. 「${t("rules.remindReply", { when })}」${wx}` };
+ return {
- text: `Created rule ${r.rule.id} 「${r.rule.title}」 (${when}) in observe mode: it only records what it would say until the user switches it to act. Tell the user in one sentence: 「已建好规则:${when} ${r.rule.title}。先观察几天,只记录不打扰你;在「任务」里可以改成执行。」${wx}`,
++ text: `Created rule ${r.rule.id} 「${r.rule.title}」 (${when}) in observe mode: it only records what it would say until the user switches it to act. Tell the user in one sentence: 「${t("rules.createdReply", { when, title: r.rule.title })}」${wx}`,
+ };
+ }
+
+ /** rule_update:改模式(执行 / 观察 / 关)、原话、时间表,或删掉 */
+ private async ruleUpdateTool(conv: Conversation, a: Record<string, unknown>): Promise<{ text?: string; error?: string }> {
+ const ref = String(a.rule ?? "").trim();
+ const list = this.store.listRules({ conversationId: conv.id });
+ const rule = list.find((r) => r.id === ref) ?? (ref ? list.find((r) => r.title.includes(ref) || ref.includes(r.title)) : undefined);
+ if (!rule) return { error: `No rule matches "${ref}". Call task_list to see them.` };
+ if (a.delete === true) {
+ await this.deleteRule(rule.id);
+ return { text: `Deleted rule 「${rule.title}」. Tell the user in one short sentence.` };
+ }
+ const patch: Parameters<TaskService["updateRule"]>[1] = {};
+ if (a.mode !== undefined) {
+ if (a.mode !== "observe" && a.mode !== "act" && a.mode !== "off") return { error: "mode must be observe, act or off" };
+ patch.mode = a.mode;
+ }
+ if (typeof a.instruction === "string" && a.instruction.trim()) patch[rule.kind === "remind" ? "message" : "instruction"] = a.instruction;
+ if (typeof a.schedule === "string" && a.schedule.trim()) {
+ const s = parseSchedule(a.schedule, rule.trigger.kind === "schedule" ? rule.trigger.schedule.tz : this.timeZone, this.now());
+ if (!s.schedule) return { error: s.error };
+ patch.schedule = s.schedule;
+ }
+ if (!Object.keys(patch).length) return { error: "Nothing to change: give mode, instruction, schedule or delete." };
+ const r = this.updateRule(rule.id, patch);
+ if (!r.rule) return { error: r.error };
+ const v = this.ruleView(r.rule);
+ const extra = r.rule.observeLeft > 0 && runMode(r.rule) === "observe" && r.rule.mode === "act" ? " The instruction changed, so its next run only observes; then it acts again." : "";
+ return { text: `Updated rule 「${v.title}」: ${v.when}, ${v.state.label}.${extra} Tell the user in one short sentence.` };
+ }
+
+ // ---------- 规则:查看 ----------
+
+ /** 出站队列里那一句现在怎样了(合进摘要的看那一条) */
+ private carrier(run: RunRow) {
+ return run.delivery && !run.delivery.endsWith(":dropped") ? this.store.carrierOutbox(run.delivery) : undefined;
+ }
+
+ ruleView(rule: RuleRow): RuleView {
+ const live = this.store.listRuns({ ruleId: rule.id, states: ["queued", "running", "settling"], limit: 1 })[0];
+ const last = this.store.ruleRuns(rule.id, { limit: 5 }).find((r) => r.state === "ended");
+ const observed = rule.kind === "check" ? this.store.ruleRuns(rule.id, { mode: "observe", outcome: "done", version: rule.version, limit: RULE_HINT_AFTER }).length : 0;
+ return {
+ id: rule.id,
+ botId: rule.botId,
+ conversationId: rule.conversationId,
+ channel: this.store.getConversation(rule.conversationId)?.channel ?? "",
+ title: rule.title,
+ instruction: rule.instruction,
+ message: rule.message,
+ kind: rule.kind,
+ trigger: rule.trigger,
+ when: whenOf(rule),
+ mode: rule.mode,
+ observeLeft: rule.observeLeft,
+ state: ruleState(rule, !!live),
+ nextRunAt: rule.nextRunAt,
+ ...(last ? { last: { at: last.queuedAt, outcome: last.outcome, line: runLine(last, rule.kind, this.carrier(last)) } } : {}),
+ hint: rule.kind === "check" && rule.mode === "observe" && !rule.pausedReason && observed >= RULE_HINT_AFTER,
+ observed,
+ failures: rule.failures,
+ folder: rule.folder,
+ version: rule.version,
+ createdAt: rule.createdAt,
+ updatedAt: rule.updatedAt,
+ ...(live ? { live: { runId: live.id, state: live.state, since: live.startedAt || live.queuedAt } } : {}),
+ };
+ }
+
+ listRules(o: { botId?: string; conversationId?: string } = {}): RuleView[] {
+ return this.store.listRules(o).map((r) => this.ruleView(r));
+ }
+
+ getRuleView(id: string): RuleView | undefined {
+ const r = this.store.getRule(id);
+ return r ? this.ruleView(r) : undefined;
+ }
+
+ /** 运行记录(新→旧,一次一行):时间、模式、结果、一行话;展开看报告、步骤、版本和权限 */
+ ruleLog(ruleId: string, o: { before?: number; limit?: number } = {}): RuleRunView[] {
+ const rule = this.store.getRule(ruleId);
+ if (!rule) return [];
+ return this.store.ruleRuns(ruleId, { before: o.before, limit: o.limit ?? 20 }).map((r) => ({
+ id: r.id,
+ at: r.queuedAt,
+ mode: r.mode,
+ cause: r.cause,
+ state: r.state,
+ outcome: r.outcome,
+ line: runLine(r, rule.kind, this.carrier(r)),
+ summary: r.report?.summary ?? "",
+ message: r.report?.message ?? "",
- would: r.would || r.report?.would || "",
- error: r.error,
++ would: wouldText(r.would || r.report?.would || ""),
++ error: errorText(r.error),
+ version: r.ruleVersion,
- permission: r.permission === "read-only" ? "只读" : r.permission === "workspace-write" ? "可写工作区" : "",
++ permission: permissionText(r.permission),
+ steps: r.startedAt && r.outcome !== "skipped" ? this.activity(r.id).length : 0,
+ startedAt: r.startedAt,
+ endedAt: r.endedAt,
+ }));
+ }
+
+ /**
+ * 「需要你」里规则那一份:连续失败 3 次暂停了的(红),连续失败 2 次的(黄)。原因没了(重试成功、关掉、删掉)就消失。
+ * 规则执行时的审批由审批中心那一份给。
+ */
+ ruleAttention(): AttentionItem[] {
+ const out: AttentionItem[] = [];
+ for (const rule of this.store.listRules()) {
+ const paused = !!rule.pausedReason;
+ if (!paused && (rule.mode === "off" || rule.failures < RULE_FAILS_TO_SHOW)) continue;
+ const last = this.store.ruleRuns(rule.id, { limit: 1, outcome: "failed" })[0];
+ const conv = this.store.getConversation(rule.conversationId);
+ out.push({
+ id: `rule:${rule.id}`,
+ kind: "rule",
+ botId: rule.botId,
+ botName: this.store.getBot(rule.botId)?.name ?? rule.botId,
- subject: `规则「${rule.title}」`,
- status: paused ? `连续失败 ${rule.failures} 次,已暂停` : `连续失败 ${rule.failures} 次`,
- line: clip(oneLine(last?.report?.message || last?.error || ""), 200),
++ subject: t("rules.subject", { title: rule.title }),
++ status: t(paused ? "rules.failingPaused" : "rules.failing", { count: rule.failures }),
++ line: last ? clip(oneLine(last.report?.message || errorText(last.error || "没有给出结果")), 200) : "",
+ since: last?.endedAt || rule.updatedAt,
+ severity: paused ? "err" : "warn",
+ actions: ["retry"],
+ conversationId: rule.conversationId,
+ channel: conv?.channel ?? "",
+ ruleId: rule.id,
+ });
+ }
+ return out;
+ }
}
/** task_report 的 question:一句问题(字符串或 {question, options, multiSelect}),选项最多 6 个 */
diff --cc src/web/server.ts
index af73bca,c8cbffb..8880bfd
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@@ -19,10 -19,11 +19,12 @@@ import { connectionFromPids } from "../
import type { ApprovalRow, Store } from "../store/db.js";
import { normalizeSettings } from "../agent/settings.js";
import { scopeLabel } from "../agent/memory.js";
- import { pwshProbe, type PwshMode } from "../agent/pwsh.js";
+ import { pwshProbe, type PwshMode, type PwshStatus } from "../agent/pwsh.js";
import { peerName, shortPeer, whoText } from "../core/access.js";
-import type { AccessEntry } from "../store/db.js";
+import type { AccessEntry, RuleMode } from "../store/db.js";
+import { normalizeSchedule, type Schedule } from "../tasks/schedule.js";
+ import { GUIDE_STEPS, deriveGuide, isGuideStep, mergeGuide, normalizeGuide, type GuideState } from "../guide.js";
+ import { normalizeLang, requestLang, setLangPref, t, type LangPref } from "../i18n/index.js";
const log = logger("web");
const require = createRequire(import.meta.url);
@@@ -488,69 -502,6 +504,69 @@@ export async function startWebServer(ap
const ok = await app.tasks.stopTask(task.id, "web");
if (!ok) throw new HttpError(409, "任务已经停止了");
return send(res, 200, { task: app.tasks.get(task.id) });
+ }
+ throw new HttpError(404, "not found");
+ }
+ // —— 规则(3d):列表、新建、改(原话、时间表、模式、发到哪)、删、立即运行、运行记录与一次运行的步骤 ——
+ if (seg[0] === "rules") {
+ const scheduleOf = (raw: unknown, tz: string): Schedule => {
+ const r = normalizeSchedule(raw, tz, Date.now());
- if (!r.schedule) throw new HttpError(400, r.error ?? "时间表不对");
++ if (!r.schedule) throw new HttpError(400, r.error ?? t("rules.badSchedule"));
+ return r.schedule;
+ };
+ if (seg.length === 1 && m === "GET") {
+ return send(res, 200, { rules: app.tasks.listRules({ botId: url.searchParams.get("bot") || undefined, conversationId: url.searchParams.get("conversation") || undefined }) });
+ }
+ if (seg.length === 1 && m === "POST") {
+ const b = await readJson(req);
+ const r = app.tasks.createRule({
+ botId: String(b.botId ?? ""),
+ conversationId: String(b.conversationId ?? ""),
+ title: String(b.title ?? ""),
+ instruction: String(b.instruction ?? ""),
+ kind: b.kind === "remind" ? "remind" : "check",
+ message: String(b.message ?? ""),
+ schedule: scheduleOf(b.schedule, app.delivery.timeZone),
+ });
- if (!r.rule) throw new HttpError(400, r.error ?? "没能建好");
++ if (!r.rule) throw new HttpError(400, r.error ?? t("rules.createFailed"));
+ return send(res, 200, { rule: app.tasks.getRuleView(r.rule.id) });
+ }
+ const rule = seg[1] ? app.store.getRule(decodeURIComponent(seg[1])) : undefined;
- if (!rule) throw new HttpError(404, "规则不存在");
++ if (!rule) throw new HttpError(404, t("rules.notFound"));
+ if (seg.length === 2 && m === "GET") return send(res, 200, { rule: app.tasks.getRuleView(rule.id) });
+ if (seg.length === 2 && m === "PUT") {
+ const b = await readJson(req);
+ const patch: Parameters<typeof app.tasks.updateRule>[1] = {};
+ if (b.title !== undefined) patch.title = String(b.title);
+ if (b.instruction !== undefined) patch.instruction = String(b.instruction);
+ if (b.message !== undefined) patch.message = String(b.message);
+ if (b.conversationId !== undefined) patch.conversationId = String(b.conversationId);
+ if (b.mode !== undefined) {
- if (!["off", "observe", "act"].includes(b.mode)) throw new HttpError(400, "模式只能是关、观察或执行");
++ if (!["off", "observe", "act"].includes(b.mode)) throw new HttpError(400, t("rules.badMode"));
+ patch.mode = b.mode as RuleMode;
+ }
+ if (b.schedule !== undefined) patch.schedule = scheduleOf(b.schedule, rule.trigger.kind === "schedule" ? rule.trigger.schedule.tz : app.delivery.timeZone);
+ const r = app.tasks.updateRule(rule.id, patch);
- if (!r.rule) throw new HttpError(400, r.error ?? "没能保存");
++ if (!r.rule) throw new HttpError(400, r.error ?? t("rules.saveFailed"));
+ return send(res, 200, { rule: app.tasks.getRuleView(rule.id) });
+ }
+ if (seg.length === 2 && m === "DELETE") {
+ await app.tasks.deleteRule(rule.id);
+ return send(res, 200, { ok: true });
+ }
+ if (seg.length === 3 && seg[2] === "run" && m === "POST") {
+ const r = rule.pausedReason ? app.tasks.resumeRule(rule.id) : app.tasks.runRuleNow(rule.id);
+ if (r.error) throw new HttpError(409, r.error);
+ return send(res, 200, { rule: app.tasks.getRuleView(rule.id) });
+ }
+ if (seg.length === 3 && seg[2] === "runs" && m === "GET") {
+ const before = Number(url.searchParams.get("before")) || undefined;
+ return send(res, 200, { runs: app.tasks.ruleLog(rule.id, { before, limit: Math.min(100, Number(url.searchParams.get("limit")) || 20) }) });
+ }
+ if (seg.length === 5 && seg[2] === "runs" && seg[4] === "activity" && m === "GET") {
+ const run = app.store.getRun(decodeURIComponent(seg[3]));
- if (!run || run.ruleId !== rule.id) throw new HttpError(404, "没有这次运行");
++ if (!run || run.ruleId !== rule.id) throw new HttpError(404, t("rules.runNotFound"));
+ return send(res, 200, { steps: app.tasks.activity(run.id) });
}
throw new HttpError(404, "not found");
}
diff --cc test/rules.integration.test.ts
index 671b25a,0000000..1c65ed3
mode 100644,000000..100644
--- a/test/rules.integration.test.ts
+++ b/test/rules.integration.test.ts
@@@ -1,279 -1,0 +1,288 @@@
+/**
+ * 规则(3d)端到端:真实 DSH 子进程 + 脚本化的模型 + mock iLink(主人在微信里和自己的机器人聊)。
+ * 退出演示:微信里说「每天 08:00 看 X 价格」,聊天代理 rule_create 建好规则(观察);「三天」到点各跑一次(把 next_run_at 拨到现在、
+ * 叫醒定时器),运行记录读得懂,什么都没发;提示改为执行;改了之后命中时推一句,只推一次。
+ * 另外:每次运行一个新会话;观察只读(写不了文件),执行可写工作区;规则会话的工具(观察去掉能改变什么的);检查用小模型、
+ * 那一句用主模型写;观察时要批准的自动拒绝、记下来,「需要你」里没有;事件触发走同一条路。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import http from "node:http";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { locateDshRuntime } from "../src/agent/host.js";
+import { findAppRoot } from "../src/magpie/supervisor.js";
+import { RULE_RESULT_SYSTEM } from "../src/agent/prompts/index.js";
+import { listen, mockIlink } from "./helpers.js";
+
+const runtime = locateDshRuntime(findAppRoot());
+const hasBwrap = fs.existsSync("/usr/bin/bwrap");
+
+async function body(req: http.IncomingMessage): Promise<any> {
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
+}
+const textOf = (c: any): string => (typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => (typeof p === "string" ? p : (p?.text ?? ""))).join("") : "");
+type Step = { tool?: { name: string; args: any }; text?: string };
+
+describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (real DSH, WeChat)", () => {
+ const OWNER = "[email protected]";
+ const CONV = `default:weixin:${OWNER}`;
+ let app: App;
+ let dataDir: string;
+ let llm: Awaited<ReturnType<typeof listen>>;
+ let ilink: Awaited<ReturnType<typeof mockIlink>>;
+ let base = "";
+ /** 每个模型请求:模型、工具名、系统提示词、用户消息、是不是规则会话 */
+ const calls: Array<{ model: string; tools: string[]; system: string; users: string[]; rule: boolean }> = [];
+
+ /** 规则会话:按第一条输入里的规则走;聊天会话:按最后一条带记号的用户消息走 */
+ function plan(messages: any[], tools: string[], system: string): Step {
+ let last = -1;
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user" && !/^Current runtime context/.test(textOf(messages[i].content))) { last = i; break; }
+ const user = textOf(messages[last]?.content);
+ const done = messages.slice(last + 1).filter((m) => m.role === "tool").length;
+ const outs = messages.slice(last + 1).filter((m) => m.role === "tool").map((m) => textOf(m.content)).join("|");
+ if (!system.includes("# 规则(优先于上面的聊天规则)")) {
+ if (/RULE PRICE/.test(user))
+ return done ? { text: "ACK-RULE:已建好规则:每天 08:00 看 X 价格。先观察几天,只记录不打扰你。" } : { tool: { name: "rule_create", args: { title: "看 X 价格", instruction: "每天 08:00 看看 X 的价格,低于 200 告诉我", schedule: "daily 08:00" } } };
+ const p = /PING (\w+)/.exec(user);
+ if (p) return { text: `PONG-${p[1]}` };
+ return { text: "好的" };
+ }
+ // 规则会话:第一条输入里有规则原话和这次是观察还是执行
+ const brief = messages.map((m) => textOf(m.content)).find((t) => t.includes("[规则]")) ?? "";
+ const act = brief.includes("[这次]\n执行");
+ if (/^Report this check with task_report now/.test(user)) return done ? { text: "已报告" } : { tool: { name: "task_report", args: { state: "failed", summary: "没查到" } } };
+ if (brief.includes("ESCALATE")) {
+ if (done === 0) return { tool: { name: "bash", args: { description: "run", command: "echo esc-$((40+2))", sandbox_permissions: "danger-full-access", justification: "测试提权" } } };
+ if (done === 1) return { tool: { name: "task_report", args: { state: "done", summary: outs.includes("esc-42") ? "ran" : "not run" } } };
+ return { text: "已报告" };
+ }
+ if (brief.includes("[事件]")) {
+ const n = /"number":(\d+)/.exec(brief)?.[1] ?? "?";
+ return done ? { text: "已报告" } : { tool: { name: "task_report", args: { state: "done", summary: `issue ${n}`, message: `EVENT-${n}:有新 issue` } } };
+ }
+ // 看价格:先用文件工具、再用命令在自己的文件夹里各写一个文件(观察时都写不了),读工作区里的 price.txt
+ const mode = act ? "act" : "observe";
+ if (done === 0) return { tool: { name: "write", args: { file_path: `probe-write-${mode}.txt`, content: "probe" } } };
+ if (done === 1) return { tool: { name: "bash", args: { description: "check", command: `cat ../../price.txt; (echo probe > probe-${mode}.txt) 2>/dev/null && echo WROTE || echo NOWRITE` } } };
+ if (done === 2) {
+ const bash = textOf(messages.filter((m) => m.role === "tool").at(-1)?.content);
+ const price = Number(/(\d+)/.exec(bash)?.[1] ?? 0);
+ const wrote = bash.includes("WROTE") ? "写文件成功" : "写文件失败";
+ const msg = price < 200 ? `X 降到 ${price} 了` : "";
+ return { tool: { name: "task_report", args: { state: "done", summary: `X 现在 ¥${price};${wrote}`, ...(msg ? { message: msg } : {}), ...(act ? {} : { would: "" }) } } };
+ }
+ return { text: "已报告" };
+ }
+
+ const makeApp = () =>
+ 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,
+ deliveryLimits: { dailyCap: { weixin: 1000 }, coalesceMs: 0 },
+ });
+
+ beforeAll(async () => {
+ llm = await listen(async (req, res) => {
+ const url = req.url?.split("?")[0] ?? "";
+ if (url.endsWith("/models")) return void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ object: "list", data: [{ id: "mock-agent", object: "model" }, { id: "mock-small", object: "model" }] }));
+ const b = await body(req);
+ const tools = (b.tools ?? []).map((t: any) => t.function?.name ?? t.name);
+ const system = (b.messages ?? []).filter((m: any) => m.role === "system" || m.role === "developer").map((m: any) => textOf(m.content)).join("\n");
+ let step: Step;
+ if (b.tools) {
+ step = plan(b.messages ?? [], tools, system);
+ calls.push({ model: b.model, tools, system, users: (b.messages ?? []).filter((m: any) => m.role === "user").map((m: any) => textOf(m.content)), rule: system.includes("# 规则(优先于上面的聊天规则)") });
+ } else if (system.includes(RULE_RESULT_SYSTEM.split("\n")[0])) {
+ // 主模型写那一句
+ const draft = /\[草稿\]\n(.+)/.exec(textOf(b.messages.at(-1).content))?.[1] ?? "";
+ calls.push({ model: b.model, tools: [], system, users: [], rule: false });
+ step = { text: `MAIN:${draft}(主模型写的)` };
+ } else step = { text: "标题" };
+ if (!b.stream) return void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ choices: [{ message: { role: "assistant", content: step.text ?? "" }, finish_reason: "stop" }] }));
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const send = (o: any) => res.write(`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", model: b.model, ...o })}\n\n`);
+ if (step.tool) {
+ send({ choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_" + Math.random().toString(36).slice(2, 8), type: "function", function: { name: step.tool.name, arguments: JSON.stringify(step.tool.args) } }] } }] });
+ send({ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] });
+ } else {
+ send({ choices: [{ index: 0, delta: { role: "assistant", content: step.text } }] });
+ send({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] });
+ }
+ send({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } });
+ res.end("data: [DONE]\n\n");
+ });
+ ilink = await mockIlink();
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-rules-"));
+ app = makeApp();
+ app.store.createBot({ id: "default", name: "小蓝", weixinEnabled: true, settings: { avatar: "blue", utilityModel: "mock-small", 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(/\/+$/, "");
+ }, 60_000);
+
+ afterAll(async () => {
+ await app?.stop();
+ await llm?.close();
+ await ilink?.close();
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ const api = async (p: string, init?: { method?: string; body?: unknown }) =>
+ (await fetch(`${base}/amb/api${p}`, init ? { method: init.method, headers: { "content-type": "application/json" }, body: JSON.stringify(init.body ?? {}) } : undefined)).json() as Promise<any>;
+ const waitFor = async (fn: () => boolean | Promise<boolean>, ms = 60_000) => {
+ for (const end = Date.now() + ms; Date.now() < end; await new Promise((r) => setTimeout(r, 100))) if (await fn()) return;
+ throw new Error("waitFor: timeout");
+ };
+ const sentTo = (text: string) => ilink.state.sent.filter((s) => s.to === OWNER && s.text.startsWith(text));
+ const ws = () => app.agent.host("default").workspace;
+ /** 「到了 08:00」:把下次运行拨到现在,叫醒定时器,等这次跑完 */
+ const tick = async (ruleId: string) => {
+ const before = app.store.ruleRuns(ruleId, { limit: 100 }).length;
+ app.store.updateRule(ruleId, { nextRunAt: Date.now() - 1000 });
+ app.tasks.scheduler.wake();
+ await waitFor(() => {
+ const runs = app.store.ruleRuns(ruleId, { limit: 100 });
+ return runs.length > before && runs[0].state === "ended";
+ }, 90_000);
+ return app.store.ruleRuns(ruleId, { limit: 1 })[0];
+ };
+ const price = (n: number) => fs.writeFileSync(path.join(ws(), "price.txt"), `${n}\n`);
+
+ it("exit demo: 「每天 08:00 看 X 价格」 runs 3 days in observe with a readable log, then switches to act and pushes one line on a hit", async () => {
+ // 微信里说一句,聊天代理建规则(观察),回复确认
+ ilink.push(OWNER, "RULE PRICE");
+ await waitFor(() => sentTo("ACK-RULE").length === 1);
+ const chat = calls.find((c) => !c.rule && c.users.some((u) => u.includes("RULE PRICE")))!;
+ expect(chat.tools).toEqual(expect.arrayContaining(["rule_create", "rule_update", "task_list"]));
+ const [rule] = (await api("/rules?bot=default")).rules;
+ expect(rule).toMatchObject({ title: "看 X 价格", when: "每天 08:00", mode: "observe", state: { key: "observe", label: "观察中" }, instruction: "每天 08:00 看看 X 的价格,低于 200 告诉我", conversationId: CONV, hint: false });
+ // 三天:观察。每次一个新会话,检查用小模型;写不了文件(只读);什么都不发
+ price(259);
+ const d1 = await tick(rule.id);
+ price(199);
+ const d2 = await tick(rule.id);
+ price(262);
+ const d3 = await tick(rule.id);
+ expect([d1, d2, d3].map((r) => [r.mode, r.outcome, r.permission])).toEqual([
+ ["observe", "done", "read-only"],
+ ["observe", "done", "read-only"],
+ ["observe", "done", "read-only"],
+ ]);
+ expect(new Set([d1, d2, d3].map((r) => r.sessionId)).size).toBe(3);
+ expect(d1.report!.summary).toBe("X 现在 ¥259;写文件失败");
+ const folder = path.join(ws(), app.store.getRule(rule.id)!.folder);
+ expect(fs.existsSync(path.join(folder, "probe-observe.txt"))).toBe(false);
+ // 文件工具也写不了(只读沙箱),模型看到的是被拒绝
+ expect(fs.existsSync(path.join(folder, "probe-write-observe.txt"))).toBe(false);
+ const ruleCalls = calls.filter((c) => c.rule);
+ expect(new Set(ruleCalls.map((c) => c.model))).toEqual(new Set(["mock-small"]));
+ // 第二天的输入里有第一天的结果(连续性靠宿主给的最近几次)
+ expect(ruleCalls.find((c) => c.users.some((u) => u.includes("¥199")) || c.users.some((u) => u.includes("[最近几次的结果]\n- ")))).toBeTruthy();
+ // 运行记录读得懂:新的在前;那一句用主模型写
+ const log = (await api(`/rules/${rule.id}/runs`)).runs;
+ expect(log.map((r: any) => [r.mode, r.line])).toEqual([
+ ["observe", "本会保持安静:X 现在 ¥262;写文件失败"],
+ ["observe", "本会发送:“MAIN:X 降到 199 了(主模型写的)”"],
+ ["observe", "本会保持安静:X 现在 ¥259;写文件失败"],
+ ]);
+ expect(log[0]).toMatchObject({ permission: "只读", version: 1 });
+ expect(log[0].steps).toBeGreaterThan(1);
+ const steps = (await api(`/rules/${rule.id}/runs/${log[0].id}/activity`)).steps;
+ expect(steps.length).toBe(log[0].steps);
+ expect(calls.filter((c) => c.tools.length === 0 && c.system.includes(RULE_RESULT_SYSTEM.split("\n")[0])).map((c) => c.model)).toEqual(["mock-agent"]);
+ await app.outbox.idle();
+ expect(ilink.state.sent.filter((s) => /MAIN|199/.test(s.text))).toEqual([]);
+ // 观察了 3 次:提示改为执行(只在界面上)
+ expect((await api(`/rules/${rule.id}`)).rule).toMatchObject({ hint: true, observed: 3 });
+ // 改为执行:命中时推一句(主模型写的),只推一次;执行能写自己的文件夹
+ const put = await api(`/rules/${rule.id}`, { method: "PUT", body: { mode: "act" } });
+ expect(put.rule).toMatchObject({ mode: "act", state: { key: "act", label: "执行中" }, hint: false });
+ price(195);
+ const d4 = await tick(rule.id);
+ expect(d4).toMatchObject({ mode: "act", outcome: "done", permission: "workspace-write" });
+ expect(d4.report!.summary).toBe("X 现在 ¥195;写文件成功");
+ expect(fs.readFileSync(path.join(folder, "probe-write-act.txt"), "utf8")).toBe("probe");
+ await waitFor(() => sentTo("MAIN:X 降到 195 了").length === 1);
+ expect(sentTo("MAIN:X 降到 195 了")[0].text).toBe("MAIN:X 降到 195 了(主模型写的)");
+ await new Promise((r) => setTimeout(r, 1000));
+ await app.outbox.idle();
+ expect(sentTo("MAIN:X 降到 195 了")).toHaveLength(1);
+ expect(app.store.listOutbox({ botId: "default", limit: 100 }).filter((r) => r.id.startsWith(`rule:${rule.id}:`)).map((r) => [r.id, r.status, r.purpose])).toEqual([[`rule:${rule.id}:${d4.id}`, "sent", "rule"]]);
+ expect((await api(`/rules/${rule.id}/runs`)).runs[0]).toMatchObject({ mode: "act", line: "已发送:“MAIN:X 降到 195 了(主模型写的)”", permission: "可写工作区" });
+ // 没命中:不发
+ price(240);
+ await tick(rule.id);
+ await new Promise((r) => setTimeout(r, 500));
+ expect(ilink.state.sent.filter((s) => s.text.includes("240"))).toEqual([]);
+ // 聊天代理下一轮知道发过什么(便条)
+ ilink.push(OWNER, "PING after");
+ await waitFor(() => sentTo("PONG-after").length === 1);
+ const after = calls.findLast((c) => !c.rule && c.users.some((u) => u.includes("PING after")))!;
+ expect(after.users.some((u) => u.includes("[规则「看 X 价格」发给了用户] MAIN:X 降到 195 了"))).toBe(true);
+ expect((await api("/attention")).items).toEqual([]);
+ }, 600_000);
+
+ it("rule sessions get their own tools: observe loses everything that acts (memory writes, present, tasks, rules, media), act keeps memory; both report with task_report", async () => {
+ const observe = calls.find((c) => c.rule && c.users.some((u) => u.includes("[这次]\n观察")))!;
+ const act = calls.find((c) => c.rule && c.users.some((u) => u.includes("[这次]\n执行")))!;
+ for (const t of ["task_report", "bash", "recall"]) expect(observe.tools).toContain(t);
+ for (const t of ["remember", "forget", "present", "ask_user_question", "task_start", "task_message", "task_list", "rule_create", "rule_update", "generate_image", "generate_video"]) expect(observe.tools).not.toContain(t);
+ expect(act.tools).toEqual(expect.arrayContaining(["task_report", "remember"]));
+ expect(act.tools).not.toContain("rule_create");
+ expect(observe.system).toContain("这次是观察:只看、只查,不改任何东西");
+ expect(act.system).toContain("只做规则里写的事");
+ });
+
+ it("an approval asked in observe mode is rejected automatically and recorded as would-need; needs-you stays empty", async () => {
+ const r = app.tasks.createRule({ botId: "default", conversationId: CONV, title: "提权", instruction: "ESCALATE 看看系统", schedule: { kind: "daily", time: "09:00", tz: "UTC" } });
+ const run = await tick(r.rule!.id);
+ expect(run).toMatchObject({ mode: "observe", outcome: "done" });
+ expect(run.report!.summary).toBe("not run");
- expect(run.would).toMatch(/^需要批准:.*echo esc-\$\(\(40\+2\)\)/);
++ expect(run.would).toMatch(/^approval: .*echo esc-\$\(\(40\+2\)\)/);
+ expect(app.store.listApprovals({ ruleId: r.rule!.id })).toEqual([]);
+ expect((await api("/attention")).items).toEqual([]);
- expect((await api(`/rules/${r.rule!.id}/runs`)).runs[0].line).toMatch(/^本会做:需要批准:/);
++ const logged = (await api(`/rules/${r.rule!.id}/runs`)).runs[0];
++ expect(logged.line).toMatch(/^本会做:需要批准:/);
++ expect(logged.would).toMatch(/^需要批准:.*echo esc/);
++ // 界面是英文时(请求头 x-amb-lang):同一条记录按英文给
++ const en = await (await fetch(`${base}/amb/api/rules/${r.rule!.id}/runs`, { headers: { "x-amb-lang": "en" } })).json() as any;
++ expect(en.runs[0]).toMatchObject({ permission: "Read-only" });
++ expect(en.runs[0].line).toMatch(/^Would do: Needs approval: .*echo esc/);
+ await api(`/rules/${r.rule!.id}`, { method: "DELETE" });
+ expect(app.store.getRule(r.rule!.id)).toBeUndefined();
+ }, 180_000);
+
+ it("the rule editor's API: a new check from the UI starts in observe, a reminder acts; a bad schedule is refused; editing the words of an acting rule observes once", async () => {
+ const bad = await fetch(`${base}/amb/api/rules`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ botId: "default", conversationId: CONV, title: "x", instruction: "x", schedule: { kind: "every", minutes: 5 } }) });
+ expect(bad.status).toBe(400);
+ expect(((await bad.json()) as any).error).toBe("间隔至少 15 分钟");
++ const badEn = await fetch(`${base}/amb/api/rules`, { method: "POST", headers: { "content-type": "application/json", "x-amb-lang": "en" }, body: JSON.stringify({ botId: "default", conversationId: CONV, title: "x", instruction: "x", schedule: { kind: "every", minutes: 5 } }) });
++ expect(((await badEn.json()) as any).error).toBe("The interval must be at least 15 minutes");
++ expect((await (await fetch(`${base}/amb/api/rules?bot=default`, { headers: { "x-amb-lang": "en" } })).json() as any).rules[0]).toMatchObject({ when: "Daily 08:00", state: { label: "Acting" } });
+ const c = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title: "看天气", instruction: "每个工作日早上看看会不会下雨", schedule: { kind: "daily", time: "07:30", days: [1, 2, 3, 4, 5] } } })).rule;
+ expect(c).toMatchObject({ mode: "observe", when: "每个工作日 07:30", state: { key: "observe" } });
+ const r = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "remind", title: "喝水", message: "喝水。", schedule: { kind: "every", minutes: 120 } } })).rule;
+ expect(r).toMatchObject({ kind: "remind", mode: "act", message: "喝水。", instruction: "喝水。", when: "每 2 小时", state: { key: "remind" } });
+ await api(`/rules/${c.id}`, { method: "PUT", body: { mode: "act" } });
+ const edited = (await api(`/rules/${c.id}`, { method: "PUT", body: { instruction: "每个工作日早上看看会不会下雨,下雨就提醒我带伞" } })).rule;
+ expect(edited).toMatchObject({ mode: "act", observeLeft: 1, version: 2, state: { key: "observe" } });
+ for (const id of [c.id, r.id]) await api(`/rules/${id}`, { method: "DELETE" });
+ expect((await api("/rules?bot=default")).rules.map((x: any) => x.id)).not.toContain(c.id);
+ });
+
+ it("an event-triggered rule (the extension point for user workloads) runs through the same path when a fake source emits", async () => {
+ const r = app.tasks.createRule({ botId: "default", conversationId: CONV, title: "新 issue", instruction: "仓库有新 issue 时告诉我", trigger: { kind: "event", source: "fake-repo", filter: { action: "opened" } } });
+ app.tasks.updateRule(r.rule!.id, { mode: "act" });
+ expect(app.ruleEvents.emit("fake-repo", { action: "closed", number: 7 })).toEqual([]);
+ expect(app.ruleEvents.emit("fake-repo", { action: "opened", number: 8 })).toEqual([r.rule!.id]);
+ await waitFor(() => app.store.ruleRuns(r.rule!.id, { limit: 1 })[0]?.state === "ended", 90_000);
+ expect(app.store.ruleRuns(r.rule!.id, { limit: 1 })[0]).toMatchObject({ cause: "event", mode: "act", outcome: "done" });
+ await waitFor(() => sentTo("MAIN:EVENT-8").length === 1);
+ }, 180_000);
+});
diff --cc test/rules.unit.test.ts
index 7289fb1,0000000..2b45c8b
mode 100644,000000..100644
--- a/test/rules.unit.test.ts
+++ b/test/rules.unit.test.ts
@@@ -1,796 -1,0 +1,849 @@@
+/**
+ * 规则(3d)的零件:时间表(解析、给人看的话、下一次 / 上一次、夏令时、宽限期、cron)、宿主的定时器、事件的过滤条件、数据目录锁,
+ * 以及 TaskService 对着一个假宿主和一个假时钟:从观察开始、观察只记「本会发送」、3 次好的观察后提示改为执行、执行时经出站队列发一句、
+ * 改了原话先观察 1 次再回到执行、连续失败 3 次自动暂停(执行的推一句,观察的只在「需要你」里)、错过的按宽限期补跑一次或记为跳过、
+ * 等名额超过宽限期跳过、固定提醒不进模型、重启后宽限期内重跑一次、运行记录、事件触发、时间上限、观察时的审批自动拒绝、
+ * 检查用小模型而那一句用主模型写、微信配额预留和续期提醒、/tasks 列出并关掉规则。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { describe as describeSchedule, graceOf, latestRun, localTime, nextRun, normalizeSchedule, parseSchedule, type Schedule } from "../src/tasks/schedule.js";
+import { Scheduler } from "../src/tasks/scheduler.js";
+import { RuleEvents, matchesFilter } from "../src/tasks/rule-events.js";
+import { RULE_DENY, runLine } from "../src/tasks/rules.js";
- import { TaskService, WEIXIN_RULE_NOTE, type TaskHost, type TaskNotification } from "../src/tasks/service.js";
++import { TaskService, type TaskHost, type TaskNotification } from "../src/tasks/service.js";
++import { setLangPref, t as tServer, withLang } from "../src/i18n/index.js";
+import { ApprovalCenter } from "../src/agent/approvals.js";
+import { DEFAULT_SETTINGS } from "../src/agent/settings.js";
+import { RULE_NUDGE, RULE_RERUN, RULE_RESULT_SYSTEM, ruleRules } from "../src/agent/prompts/index.js";
+import { Outbox } from "../src/core/outbox.js";
+import { Delivery } from "../src/core/delivery.js";
+import { Store, type RunRow } from "../src/store/db.js";
+import { DataDirLocked, LOCK_FILE, lockDataDir } from "../src/store/lock.js";
+
+const TZ = "Asia/Shanghai";
+const NY = "America/New_York";
+/** 上海时间 "2026-11-06T08:00" → 时间戳 */
+const at = (s: string) => Date.parse(`${s}${s.length === 16 ? ":00" : ""}+08:00`);
+const MIN = 60_000;
+const H = 3600_000;
+const flush = async (n = 6) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setImmediate(r));
+};
+
+describe("时间表:解析、给人看的话", () => {
+ const now = at("2026-11-02T10:00");
+ const p = (t: string) => parseSchedule(t, TZ, now);
+ it("聊天代理给的一行", () => {
+ expect(p("daily 08:00").schedule).toEqual({ kind: "daily", time: "08:00", tz: TZ });
+ expect(p("weekdays 8:00").schedule).toEqual({ kind: "daily", time: "08:00", days: [1, 2, 3, 4, 5], tz: TZ });
+ expect(p("weekly mon,thu 09:30").schedule).toEqual({ kind: "weekly", time: "09:30", days: [1, 4], tz: TZ });
+ expect(p("weekly 周一、周日 09:30").schedule).toMatchObject({ days: [0, 1] });
+ expect(p("every 30m").schedule).toEqual({ kind: "every", minutes: 30, from: now + MIN, tz: TZ });
+ expect(p("every 2 hours").schedule).toMatchObject({ kind: "every", minutes: 120 });
+ expect(p("once 2026-11-03 15:00").schedule).toEqual({ kind: "once", at: at("2026-11-03T15:00"), tz: TZ });
+ expect(p("cron 0 8 * * 1-5").schedule).toEqual({ kind: "cron", cron: "0 8 * * 1-5", tz: TZ });
+ });
+ it("说不清的给出能照着改的错误", () => {
+ expect(p("every 10m").error).toMatch(/at least 15 minutes/);
+ expect(p("once 2026-11-01 15:00").error).toMatch(/already passed/);
+ expect(p("cron 0 8 * *").error).toMatch(/5 fields/);
+ expect(p("每天早上").error).toMatch(/Use one of: once YYYY-MM-DD HH:MM \| daily HH:MM/);
+ expect(p("daily 25:00").error).toBeDefined();
+ expect(normalizeSchedule({ kind: "weekly", time: "08:00", days: [] }, TZ, now).error).toBe("选一天或几天");
+ });
+ it("给用户看:每天 08:00、每个工作日、每周一、周四、每 30 分钟、日期", () => {
+ const d = (t: string, z = false) => describeSchedule(p(t).schedule!, z);
+ expect(d("daily 08:00")).toBe("每天 08:00");
+ expect(d("weekdays 08:00", true)).toBe("每个工作日 08:00(Asia/Shanghai)");
+ expect(d("weekly sun,thu,mon 09:00")).toBe("每周一、周四、周日 09:00");
+ expect(d("every 30m")).toBe("每 30 分钟");
+ expect(d("every 2h")).toBe("每 2 小时");
+ expect(d("once 2026-11-03 15:00")).toBe("11月3日 15:00");
+ expect(d("cron 0 8 * * 1-5")).toBe("cron 0 8 * * 1-5");
+ });
+});
+
+describe("时间表:下一次、上一次、宽限期", () => {
+ const daily = (time: string, tz = TZ, days?: number[]): Schedule => ({ kind: "daily", time, tz, ...(days ? { days } : {}) });
+ it("每天 08:00:今天还没到就是今天,过了就是明天(不含当时)", () => {
+ expect(nextRun(daily("08:00"), at("2026-11-02T07:59"))).toBe(at("2026-11-02T08:00"));
+ expect(nextRun(daily("08:00"), at("2026-11-02T08:00"))).toBe(at("2026-11-03T08:00"));
+ expect(latestRun(daily("08:00"), at("2026-11-02T07:59"))).toBe(at("2026-11-01T08:00"));
+ expect(latestRun(daily("08:00"), at("2026-11-02T08:00"))).toBe(at("2026-11-02T08:00"));
+ expect(latestRun(daily("08:00"), at("2026-11-02T07:59"), at("2026-11-02T00:00"))).toBeUndefined();
+ });
+ it("工作日:周五晚上之后是周一", () => {
+ // 2026-11-06 是周五
+ expect(nextRun(daily("08:00", TZ, [1, 2, 3, 4, 5]), at("2026-11-06T09:00"))).toBe(at("2026-11-09T08:00"));
+ expect(nextRun({ kind: "weekly", time: "09:00", days: [4], tz: TZ }, at("2026-11-06T09:00"))).toBe(at("2026-11-12T09:00"));
+ });
+ it("夏令时(纽约):跳过的那一小时里的时刻顺延,重复的那一小时取第一次,钟面时间不变", () => {
+ // 3 月 8 日凌晨 2:00 → 3:00:02:30 不存在,顺延到 03:30(EDT)
+ expect(localTime(2026, 3, 8, 150, NY)).toBe(Date.parse("2026-03-08T03:30:00-04:00"));
+ expect(nextRun(daily("02:30", NY), Date.parse("2026-03-07T12:00:00-05:00"))).toBe(Date.parse("2026-03-08T03:30:00-04:00"));
+ expect(nextRun(daily("02:30", NY), Date.parse("2026-03-08T04:00:00-04:00"))).toBe(Date.parse("2026-03-09T02:30:00-04:00"));
+ // 11 月 1 日凌晨 2:00 → 1:00:01:30 有两次,取第一次(EDT),第二天照常
+ expect(nextRun(daily("01:30", NY), Date.parse("2026-10-31T12:00:00-04:00"))).toBe(Date.parse("2026-11-01T01:30:00-04:00"));
+ expect(nextRun(daily("01:30", NY), Date.parse("2026-11-01T01:30:00-04:00"))).toBe(Date.parse("2026-11-02T01:30:00-05:00"));
+ // 早上 8 点在切换前后都是 8 点(中间差 25 小时)
+ const a = nextRun(daily("08:00", NY), Date.parse("2026-10-31T09:00:00-04:00"))!;
+ expect(a).toBe(Date.parse("2026-11-01T08:00:00-05:00"));
+ expect(a - Date.parse("2026-10-31T08:00:00-04:00")).toBe(25 * H);
+ // every 按绝对时间:切换那晚照样每 60 分钟一次
+ const every: Schedule = { kind: "every", minutes: 60, from: Date.parse("2026-11-01T00:00:00-04:00"), tz: NY };
+ expect(nextRun(every, Date.parse("2026-11-01T01:30:00-04:00"))! - Date.parse("2026-11-01T01:30:00-04:00")).toBe(30 * MIN);
+ });
+ it("every:从起点一格一格往后排;上一次是起点之后最近的一格", () => {
+ const s: Schedule = { kind: "every", minutes: 15, from: at("2026-11-02T10:00"), tz: TZ };
+ expect(nextRun(s, at("2026-11-02T09:00"))).toBe(at("2026-11-02T10:00"));
+ expect(nextRun(s, at("2026-11-02T10:00"))).toBe(at("2026-11-02T10:15"));
+ expect(nextRun(s, at("2026-11-02T10:16"))).toBe(at("2026-11-02T10:30"));
+ expect(latestRun(s, at("2026-11-02T11:07"))).toBe(at("2026-11-02T11:00"));
+ expect(latestRun(s, at("2026-11-02T09:59"))).toBeUndefined();
+ });
+ it("cron:工作日 8 点;日和星期都限定时满足一个就行;每 10 分钟", () => {
+ expect(nextRun({ kind: "cron", cron: "0 8 * * 1-5", tz: TZ }, at("2026-11-06T09:00"))).toBe(at("2026-11-09T08:00"));
+ // 每月 1 号或者周一
+ const c: Schedule = { kind: "cron", cron: "30 9 1 * 1", tz: TZ };
+ expect(nextRun(c, at("2026-11-02T10:00"))).toBe(at("2026-11-09T09:30"));
+ expect(nextRun(c, at("2026-11-30T10:00"))).toBe(at("2026-12-01T09:30"));
+ expect(nextRun({ kind: "cron", cron: "*/10 * * * *", tz: TZ }, at("2026-11-02T10:03"))).toBe(at("2026-11-02T10:10"));
+ expect(latestRun({ kind: "cron", cron: "0 8 * * 1-5", tz: TZ }, at("2026-11-08T12:00"))).toBe(at("2026-11-06T08:00"));
+ });
+ it("once:到点之前有,之后没有", () => {
+ const s: Schedule = { kind: "once", at: at("2026-11-03T15:00"), tz: TZ };
+ expect(nextRun(s, at("2026-11-03T14:00"))).toBe(s.at);
+ expect(nextRun(s, s.at)).toBeUndefined();
+ expect(latestRun(s, at("2026-11-03T16:00"))).toBe(s.at);
+ });
+ it("宽限期:间隔的一半和 2 小时取小的", () => {
+ const ref = at("2026-11-02T10:00");
+ expect(graceOf(daily("08:00"), ref)).toBe(2 * H);
+ expect(graceOf({ kind: "every", minutes: 15, from: ref, tz: TZ }, ref)).toBe(7.5 * MIN);
+ expect(graceOf({ kind: "every", minutes: 60, from: ref, tz: TZ }, ref)).toBe(30 * MIN);
+ expect(graceOf({ kind: "cron", cron: "*/10 * * * *", tz: TZ }, ref)).toBe(5 * MIN);
+ expect(graceOf({ kind: "once", at: ref, tz: TZ }, ref)).toBe(2 * H);
+ });
+});
+
+describe("界面:规则的一行(健康时只有状态和下次)", () => {
+ it("第二行:观察中 · 下次 明天 08:00;正在运行;暂停了说连续失败几次;关了、跑完了只有状态;运行记录的时间", async () => {
- (globalThis as any).window ??= { matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }) };
++ (globalThis as any).window ??= { matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), addEventListener() {}, removeEventListener() {} };
+ // @ts-expect-error 界面代码是不经构建的 JS
+ const { ruleSub, fmtRunAt, fmtNext } = await import("../ui/components/rules.js");
++ // @ts-expect-error 同上
++ const ui = await import("../ui/lib/i18n.js");
++ ui.setLangPref("zh-CN");
+ const now = new Date(2026, 10, 2, 7, 30).getTime();
+ const t = (d: number, h: number, m = 0) => new Date(2026, 10, 2 + d, h, m).getTime();
+ const r = (o: any) => ({ failures: 0, nextRunAt: t(1, 8), state: { key: "observe", label: "观察中" }, ...o });
+ expect(ruleSub(r({}), now)).toBe("观察中 · 下次 明天 08:00");
+ expect(ruleSub(r({ state: { key: "act", label: "执行中" }, nextRunAt: t(0, 15) }), now)).toBe("执行中 · 下次 今天 15:00");
+ expect(ruleSub(r({ live: { state: "running" } }), now)).toBe("观察中 · 正在运行");
+ expect(ruleSub(r({ state: { key: "paused", label: "已暂停" }, failures: 3, nextRunAt: 0 }), now)).toBe("已暂停 · 连续失败 3 次");
+ expect(ruleSub(r({ state: { key: "off", label: "已关闭" } }), now)).toBe("已关闭");
+ expect(ruleSub(r({ state: { key: "done", label: "已结束" }, nextRunAt: 0 }), now)).toBe("已结束");
- expect([fmtRunAt(t(0, 8), now), fmtRunAt(t(-1, 8), now), fmtRunAt(t(-2, 8), now), fmtRunAt(t(-6, 8), now)]).toEqual(["今天 08:00", "昨天 08:00", "前天 08:00", "10/27 08:00"]);
++ expect([fmtRunAt(t(0, 8), now), fmtRunAt(t(-1, 8), now), fmtRunAt(t(-6, 8), now)]).toEqual(["今天 08:00", "昨天 08:00", "10/27 08:00"]);
+ // 2026-11-02 是周一
+ expect([fmtNext(t(3, 9), now), fmtNext(t(10, 9), now)]).toEqual(["周四 09:00", "11/12 09:00"]);
++ // 英文:状态文字是服务端按界面语言给的,这里只换了界面自己的那部分
++ ui.setLangPref("en");
++ expect(ruleSub(r({ state: { key: "observe", label: "Observing" } }), now)).toBe("Observing · Next: Tomorrow 08:00");
++ expect(ruleSub(r({ state: { key: "paused", label: "Paused" }, failures: 3, nextRunAt: 0 }), now)).toBe("Paused · failed 3 times in a row");
++ expect([fmtRunAt(t(-1, 8), now), fmtNext(t(3, 9), now)]).toEqual(["Yesterday 08:00", "Thu 09:00"]);
++ ui.setLangPref("zh-CN");
+ });
+});
+
+describe("宿主的定时器", () => {
+ it("开始时先看一遍,按最早的那个设定时器(最长睡 5 分钟);wake 马上再看", () => {
+ let now = 1_000_000;
+ let next = now + 30 * MIN;
+ const fired: number[] = [];
+ const s = new Scheduler({ next: () => next, fire: (t) => fired.push(t), now: () => now });
+ s.start();
+ expect(fired).toEqual([now]);
+ expect(s.wakeAt).toBe(now + 5 * MIN);
+ next = now + 2 * MIN;
+ now += MIN;
+ s.wake();
+ expect(fired).toHaveLength(2);
+ expect(s.wakeAt).toBe(now + MIN);
+ s.stop();
+ s.wake();
+ expect(fired).toHaveLength(2);
+ });
+});
+
+describe("事件的过滤条件", () => {
+ it("每个键都要相等(数组是其中之一,路径用点);没有条件都算", () => {
+ expect(matchesFilter(undefined, { a: 1 })).toBe(true);
+ expect(matchesFilter({ repo: "a/b" }, { repo: "a/b", n: 1 })).toBe(true);
+ expect(matchesFilter({ repo: "a/b" }, { repo: "a/c" })).toBe(false);
+ expect(matchesFilter({ action: ["opened", "reopened"] }, { action: "reopened" })).toBe(true);
+ expect(matchesFilter({ "issue.number": 12 }, { issue: { number: "12" } })).toBe(true);
+ expect(matchesFilter({ "issue.number": 12 }, { issue: {} })).toBe(false);
+ });
+});
+
+describe("数据目录锁", () => {
+ let dir: string;
+ beforeEach(() => (dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-lock-"))));
+ afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
+ it("另一个活着的进程拿着:拿不到;那个进程不在了:接管;放锁只放自己的", () => {
+ const file = path.join(dir, LOCK_FILE);
+ // 父进程(vitest 的)活着
+ fs.writeFileSync(file, JSON.stringify({ pid: process.ppid, host: os.hostname(), at: Date.now(), token: "x" }));
+ expect(() => lockDataDir(dir)).toThrow(DataDirLocked);
+ expect(() => lockDataDir(dir)).toThrow(/正被另一个 anymodel bot 进程使用/);
+ // 不在了(崩溃、kill -9)
+ fs.writeFileSync(file, JSON.stringify({ pid: 2 ** 22 + 12345, host: os.hostname(), at: Date.now(), token: "x" }));
+ const a = lockDataDir(dir);
+ expect(JSON.parse(fs.readFileSync(file, "utf8")).pid).toBe(process.pid);
+ // 同一进程里又开了一个 App(测试里重启):接过来;先开的那个放锁时不动后来的
+ const b = lockDataDir(dir);
+ a.release();
+ expect(fs.existsSync(file)).toBe(true);
+ b.release();
+ expect(fs.existsSync(file)).toBe(false);
+ });
+ it("另一台机器(两个容器挂同一个卷):看心跳,3 分钟没碰就接管", () => {
+ const file = path.join(dir, LOCK_FILE);
+ fs.writeFileSync(file, JSON.stringify({ pid: 1, host: "other-container", at: Date.now(), token: "x" }));
+ expect(() => lockDataDir(dir)).toThrow(/other-container 上的 pid 1/);
+ const old = new Date(Date.now() - 10 * MIN);
+ fs.writeFileSync(file, JSON.stringify({ pid: 1, host: "other-container", at: old.getTime(), token: "x" }));
+ fs.utimesSync(file, old, old);
+ lockDataDir(dir).release();
+ });
+ it("同一台机器、进程号还在但心跳停了(断电重启后进程号被别的程序占了):接管", () => {
+ const file = path.join(dir, LOCK_FILE);
+ const old = new Date(Date.now() - 10 * MIN);
+ // 父进程(vitest 的)活着,但锁文件 10 分钟没碰过
+ fs.writeFileSync(file, JSON.stringify({ pid: process.ppid, host: os.hostname(), at: old.getTime(), token: "x" }));
+ fs.utimesSync(file, old, old);
+ const l = lockDataDir(dir);
+ expect(JSON.parse(fs.readFileSync(file, "utf8")).pid).toBe(process.pid);
+ l.release();
+ });
+});
+
+/** 假的宿主:记下交给会话的输入和停止;安静与否按队列回答 */
+class FakeHost implements TaskHost {
+ available = true;
+ prompts: Array<{ botId: string; sessionId: string; folder: string; model: string; text: string; resume: boolean; id: string }> = [];
+ stops: string[] = [];
+ settingsValue = { ...DEFAULT_SETTINGS };
+ private n = 0;
+ constructor(readonly ws: string) {}
+ workspace() {
+ return this.ws;
+ }
+ settings() {
+ return this.settingsValue;
+ }
+ memoryPrefix() {
+ return "- 用户关心 X 的价格";
+ }
+ async prompt(botId: string, o: { sessionId: string; folder: string; model: string; text: string; resume: boolean }) {
+ const id = `msg-${++this.n}`;
+ this.prompts.push({ botId, ...o, id });
+ return id;
+ }
+ async steer() {
+ return false;
+ }
+ async stop(_botId: string, sessionId: string) {
+ this.stops.push(sessionId);
+ }
+ async quiet() {
+ return { quiet: true };
+ }
+}
+
+describe("规则(假宿主、假时钟)", () => {
+ let store: Store;
+ let host: FakeHost;
+ let outbox: Outbox;
+ let delivery: Delivery;
+ let approvals: ApprovalCenter;
+ let svc: TaskService;
+ let ws: string;
+ let now: number;
+ let writes: Array<{ model: string; system: string; user: string }>;
+ const CONV = "b:weixin:owner";
+ const WEB = "b:web:console";
+
+ const make = (o: { maxBackground?: number; cap?: number } = {}) =>
+ new TaskService({
+ store,
+ host,
+ delivery,
+ approvals,
+ defaultModel: () => "main-model",
+ retryDelaysMs: [5, 5, 5],
+ maxBackground: o.maxBackground ?? 4,
+ now: () => now,
+ timeZone: TZ,
+ ruleRunCapMs: o.cap,
+ complete: async (_botId, model, system, user) => {
+ writes.push({ model, system, user });
+ return "「X 降价了:现在 ¥199(昨天 ¥259)。」";
+ },
+ });
+ beforeEach(() => {
+ now = at("2026-11-02T07:00");
+ writes = [];
+ ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-rules-unit-"));
+ store = new Store(":memory:");
+ store.createBot({ id: "b", name: "小蓝", weixinEnabled: true });
+ store.ensureConversation("b", "weixin", "owner", "owner");
+ store.ensureConversation("b", "web", "console", "console");
+ host = new FakeHost(ws);
+ host.settingsValue = { ...DEFAULT_SETTINGS, utilityModel: "small-model" };
+ outbox = new Outbox(store, { now: () => now });
+ delivery = new Delivery({ store, outbox, now: () => now, timeZone: TZ });
+ approvals = new ApprovalCenter(store, { now: () => now });
+ svc = make();
+ svc.start();
+ });
+ afterEach(() => {
+ svc.stop();
+ store.close();
+ fs.rmSync(ws, { recursive: true, force: true });
+ });
+
+ const ev = (sessionId: string, type: string, data: any = {}): TaskNotification => ({ method: "session.event", params: { sessionId, event: { type, data, time: now } } });
+ const status = (sessionId: string, s: "running" | "idle"): TaskNotification => ({ method: "session.status", params: { sessionId, status: s } });
+ /** 最近一次交给规则会话的输入跑一轮;during 里报告 */
+ const turn = async (during?: (sessionId: string) => void) => {
+ const p = host.prompts.at(-1)!;
+ const sid = p.sessionId;
+ svc.onEvent("b", sid, status(sid, "running"));
+ svc.onEvent("b", sid, ev(sid, "turn/start", { turn: 1 }));
+ svc.onEvent("b", sid, ev(sid, "user/message", { id: p.id, role: "user", content: [{ type: "text", text: p.text }] }));
+ during?.(sid);
+ svc.onEvent("b", sid, ev(sid, "turn/end", { turn: 1, reason: { kind: "completed" } }));
+ svc.onEvent("b", sid, status(sid, "idle"));
+ await flush();
+ };
+ const report = (state: string, message = "", extra: Record<string, unknown> = {}) => (sid: string) => void expect(svc.report({ sessionId: sid, state, summary: "X 现在 ¥199", message, ...extra }).error).toBeUndefined();
+ /** 拨钟,到点的开 run */
+ const go = async (t: number) => {
+ now = t;
+ svc.fireDue(now);
+ await flush();
+ };
+ const create = async (schedule = "daily 08:00", extra: Record<string, unknown> = {}) => {
+ const r = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "看 X 价格", instruction: "每天早上 8 点看看 X 的价格,低于 200 告诉我", schedule, ...extra } });
+ expect(r.error).toBeUndefined();
+ return { text: r.text!, rule: store.listRules({ botId: "b" }).at(-1)! };
+ };
+ const runsOf = (ruleId: string) => store.ruleRuns(ruleId, { limit: 100 }).reverse();
+ const pushes = () => store.listOutbox({ limit: 100 }).filter((r) => r.id.startsWith("rule:"));
+ /** 跑一天:到 08:00 开 run,跑一轮,报告 */
+ const day = async (date: string, during: (sid: string) => void) => {
+ await go(at(`${date}T08:00`));
+ await turn(during);
+ };
+
+ beforeEach(() => store.setAgentSession(CONV, "b", "chat-1"));
+
+ it("rule_create:从观察开始,用户原话原样存,自己的文件夹;回复里有设计里那句话,微信加上 24 小时那句", async () => {
+ const { text, rule } = await create();
+ expect(rule).toMatchObject({ kind: "check", mode: "observe", version: 1, conversationId: CONV, instruction: "每天早上 8 点看看 X 的价格,低于 200 告诉我", anytime: false });
+ expect(rule.id).toMatch(/^rl_[0-9a-f]{12}$/);
+ expect(rule.folder).toBe(`rules/x-${rule.id.slice(3, 9)}`);
+ expect(rule.trigger).toEqual({ kind: "schedule", schedule: { kind: "daily", time: "08:00", tz: TZ } });
+ expect(rule.nextRunAt).toBe(at("2026-11-02T08:00"));
+ expect(text).toContain("「已建好规则:每天 08:00 看 X 价格。先观察几天,只记录不打扰你;在「任务」里可以改成执行。」");
- expect(text).toContain(WEIXIN_RULE_NOTE);
++ expect(text).toContain(tServer("rules.weixinNote"));
+ expect(svc.getRuleView(rule.id)).toMatchObject({ when: "每天 08:00", state: { key: "observe", label: "观察中", dot: "" }, hint: false });
+ // 时间表说不清:照着错误改
+ const bad = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "t", instruction: "i", schedule: "每天" } });
+ expect(bad.error).toMatch(/Use one of/);
+ });
+
+ it("退出演示的单元版:观察 3 天(只记「本会发送」,什么都不推),提示改为执行;改了之后命中时推一句(主模型写的)", async () => {
+ const { rule } = await create();
+ // 第 1 天:到点开一个新会话,第一条输入是规则、原话、这次是观察;检查用小模型
+ await go(at("2026-11-02T08:00"));
+ const p1 = host.prompts.at(-1)!;
+ expect(p1.sessionId).toMatch(new RegExp(`^rule-${rule.id}-[0-9a-f]{12}$`));
+ expect(p1).toMatchObject({ resume: false, model: "small-model", folder: path.join(ws, rule.folder) });
+ expect(p1.text).toContain("[规则]\n看 X 价格(每天 08:00)");
+ expect(p1.text).toContain("[用户的原话]\n每天早上 8 点看看 X 的价格,低于 200 告诉我");
+ expect(p1.text).toContain("[这次]\n观察:只看不动,message 只记下来,不会发给用户。");
+ expect(p1.text).toContain("- 用户关心 X 的价格");
+ // 插件取配置:观察只读、去掉能改变什么的工具、规则段
+ expect(svc.sessionConfig({ sessionId: p1.sessionId })).toEqual({ kind: "rule", mode: "observe", deny: RULE_DENY.observe, denyPrefix: ["mcp__computer-use__"], section: ruleRules("observe"), permission: "read-only" });
+ expect(RULE_DENY.observe).toEqual(expect.arrayContaining(["remember", "forget", "generate_image", "present", "rule_create"]));
+ await turn((sid) => void expect(svc.report({ sessionId: sid, state: "done", summary: "X 现在 ¥259,高于 200", message: "" }).text).toMatch(/hears nothing/));
+ // 第 2 天:上一次的结果带进来(连续性靠它)
+ await go(at("2026-11-03T08:00"));
+ expect(host.prompts.at(-1)!.text).toContain("[最近几次的结果]\n- 11月2日 08:00:没有告诉用户。X 现在 ¥259,高于 200");
+ await turn((sid) => void expect(svc.report({ sessionId: sid, state: "done", summary: "X 现在 ¥199", message: "X 降到 199 了" }).text).toMatch(/observe mode: nothing is sent/));
+ // 第 3 天
+ await day("2026-11-04", report("done", "", { would: "在 X 的页面上点「降价提醒」" }));
+ // 观察什么都不推;只记下来
+ expect(pushes()).toEqual([]);
+ expect(store.listMessages(CONV)).toEqual([]);
+ const log = svc.ruleLog(rule.id);
+ expect(log.map((r) => [r.mode, r.outcome, r.line])).toEqual([
+ ["observe", "done", "本会做:在 X 的页面上点「降价提醒」"],
+ // 那一句用主模型写(检查用的是小模型)
+ ["observe", "done", "本会发送:“X 降价了:现在 ¥199(昨天 ¥259)。”"],
+ ["observe", "done", "本会保持安静:X 现在 ¥259,高于 200"],
+ ]);
+ expect(writes).toHaveLength(1);
+ expect(writes[0]).toMatchObject({ model: "main-model", system: RULE_RESULT_SYSTEM });
+ expect(writes[0].user).toContain("[草稿]\nX 降到 199 了");
+ expect(log[0]).toMatchObject({ version: 1, permission: "只读", cause: "schedule", at: at("2026-11-04T08:00") });
+ // 3 次好的观察:提示改为执行(不推)
+ expect(svc.getRuleView(rule.id)).toMatchObject({ hint: true, observed: 3, state: { key: "observe" } });
+ // 改为执行:下一次带着「执行」,权限是可写工作区,命中时推一句(id 固定)
+ svc.updateRule(rule.id, { mode: "act" });
+ expect(svc.getRuleView(rule.id)).toMatchObject({ hint: false, state: { key: "act", label: "执行中", dot: "ok" } });
+ await go(at("2026-11-05T08:00"));
+ expect(host.prompts.at(-1)!.text).toContain("[这次]\n执行:message 会发给用户。");
+ expect(svc.sessionConfig({ sessionId: host.prompts.at(-1)!.sessionId })).toMatchObject({ mode: "act", permission: "workspace-write", deny: RULE_DENY.act });
+ await turn(report("done", "X 降到 199 了"));
+ const run = runsOf(rule.id).at(-1)!;
+ expect(pushes().map((r) => [r.id, r.purpose, r.subject, r.body.text, r.ref])).toEqual([[`rule:${rule.id}:${run.id}`, "rule", "看 X 价格", "X 降价了:现在 ¥199(昨天 ¥259)。", `rule:${rule.id}`]]);
+ expect(store.listMessages(CONV).at(-1)!.content).toBe("X 降价了:现在 ¥199(昨天 ¥259)。");
+ expect(svc.ruleLog(rule.id)[0]).toMatchObject({ mode: "act", permission: "可写工作区", line: "待发送:“X 降价了:现在 ¥199(昨天 ¥259)。”" });
+ // 没命中:保持安静,不推
+ await day("2026-11-06", report("done"));
+ expect(pushes()).toHaveLength(1);
+ expect(svc.ruleLog(rule.id)[0].line).toBe("保持安静:X 现在 ¥199");
+ });
+
+ it("完全权限的机器人:执行时最多可写工作区;只读的机器人:执行也只读", async () => {
+ const { rule } = await create();
+ svc.updateRule(rule.id, { mode: "act" });
+ host.settingsValue = { ...host.settingsValue, permission: "full" };
+ await go(at("2026-11-02T08:00"));
+ expect(svc.sessionConfig({ sessionId: host.prompts.at(-1)!.sessionId }).permission).toBe("workspace-write");
+ await turn(report("done"));
+ host.settingsValue = { ...host.settingsValue, permission: "readonly" };
+ await go(at("2026-11-03T08:00"));
+ expect(svc.sessionConfig({ sessionId: host.prompts.at(-1)!.sessionId }).permission).toBe("read-only");
+ expect(svc.sessionConfig({ sessionId: "task-x" }).error).toBeDefined();
+ });
+
+ it("改原话:版本加 1,执行中的先观察 1 次再回到执行;只改时间表不动模式;正在跑的照原来的版本跑完", async () => {
+ const { rule } = await create();
+ svc.updateRule(rule.id, { mode: "act" });
+ await go(at("2026-11-02T08:00"));
+ // 跑的时候改了原话
+ svc.updateRule(rule.id, { instruction: "每天早上看看 X 的价格,低于 180 告诉我" });
+ expect(store.getRule(rule.id)).toMatchObject({ version: 2, observeLeft: 1, mode: "act" });
+ expect(svc.getRuleView(rule.id)!.state.key).toBe("observe");
+ await turn(report("done", "X 降到 199 了"));
+ // 那一次是第 1 版、执行的:照样发
+ expect(runsOf(rule.id).at(-1)).toMatchObject({ ruleVersion: 1, mode: "act" });
+ await flush();
+ expect(pushes()).toHaveLength(1);
+ expect(store.getRule(rule.id)!.observeLeft).toBe(1);
+ // 下一次:第 2 版、观察
+ await go(at("2026-11-03T08:00"));
+ expect(host.prompts.at(-1)!.text).toContain("低于 180");
+ expect(host.prompts.at(-1)!.text).toContain("[这次]\n观察");
+ await turn(report("done", "X 降到 170 了"));
+ await flush();
+ expect(pushes()).toHaveLength(1);
+ expect(store.getRule(rule.id)).toMatchObject({ observeLeft: 0, mode: "act" });
+ expect(svc.ruleLog(rule.id)[0]).toMatchObject({ mode: "observe", version: 2 });
+ // 再下一次:回到执行
+ await go(at("2026-11-04T08:00"));
+ expect(host.prompts.at(-1)!.text).toContain("[这次]\n执行");
+ await turn(report("done"));
+ // 只改时间表:模式不变,下一次按新时间
+ svc.updateRule(rule.id, { schedule: parseSchedule("daily 09:30", TZ, now).schedule! });
+ expect(store.getRule(rule.id)).toMatchObject({ mode: "act", observeLeft: 0, version: 2, nextRunAt: at("2026-11-04T09:30") });
+ });
+
+ it("连续失败 3 次自动暂停:执行中的推一句 ⚠️,「需要你」里一行(2 次时就有黄的);成功一次清零;重试重新开并马上跑", async () => {
+ const { rule } = await create();
+ svc.updateRule(rule.id, { mode: "act" });
+ await day("2026-11-02", report("failed", "X 的页面打不开"));
+ expect(store.getRule(rule.id)!.failures).toBe(1);
+ expect(svc.ruleAttention()).toEqual([]);
+ await day("2026-11-03", report("done"));
+ expect(store.getRule(rule.id)!.failures).toBe(0);
+ await day("2026-11-04", report("failed", "X 的页面打不开"));
+ await day("2026-11-05", report("failed", "X 的页面打不开"));
+ expect(svc.ruleAttention().map((a) => [a.kind, a.subject, a.status, a.severity, a.line])).toEqual([["rule", "规则「看 X 价格」", "连续失败 2 次", "warn", "X 的页面打不开"]]);
+ expect(pushes()).toEqual([]);
+ await day("2026-11-06", report("failed", "X 的页面打不开"));
+ expect(store.getRule(rule.id)).toMatchObject({ failures: 3, pausedReason: "failures", nextRunAt: 0 });
+ expect(svc.getRuleView(rule.id)!.state).toEqual({ key: "paused", label: "已暂停", dot: "err" });
+ const last = runsOf(rule.id).at(-1)!;
+ expect(pushes().map((r) => [r.id, r.purpose, r.body.text])).toEqual([[`rule:${rule.id}:paused:${last.id}`, "failure", "⚠️ 规则「看 X 价格」连续失败 3 次,已暂停:X 的页面打不开"]]);
+ expect(svc.ruleAttention()[0]).toMatchObject({ status: "连续失败 3 次,已暂停", severity: "err", actions: ["retry"], ruleId: rule.id });
+ // 暂停了就不再到点开 run
+ const n = host.prompts.length;
+ await go(at("2026-11-07T08:00"));
+ expect(host.prompts).toHaveLength(n);
+ // 重试:重新开、马上跑(人要求的)
+ expect(svc.resumeRule(rule.id)).toEqual({});
+ await flush();
+ expect(host.prompts).toHaveLength(n + 1);
+ expect(runsOf(rule.id).at(-1)).toMatchObject({ cause: "manual", mode: "act" });
+ expect(store.getRule(rule.id)).toMatchObject({ failures: 0, pausedReason: "", nextRunAt: at("2026-11-08T08:00") });
+ expect(svc.ruleAttention()).toEqual([]);
+ });
+
+ it("观察中的规则连续失败 3 次也暂停,但什么都不推,只在「需要你」里", async () => {
+ const { rule } = await create();
+ for (const d of ["2026-11-02", "2026-11-03", "2026-11-04"]) await day(d, report("failed", "打不开"));
+ expect(store.getRule(rule.id)!.pausedReason).toBe("failures");
+ expect(pushes()).toEqual([]);
+ expect(svc.ruleAttention()).toHaveLength(1);
+ });
+
+ it("错过的:宽限期(2 小时)内启动补跑一次(算那个时间的),更早的记一条「跳过:电脑没开」,从不补一串", async () => {
+ const { rule } = await create();
+ svc.stop();
+ // 应用 08:00 没开,09:30 开:补跑一次
+ now = at("2026-11-02T09:30");
+ svc = make();
+ svc.start();
+ await flush();
+ expect(runsOf(rule.id).map((r) => [r.cause, r.queuedAt, r.state])).toEqual([["schedule", at("2026-11-02T08:00"), "running"]]);
+ await turn(report("done"));
+ expect(store.getRule(rule.id)!.nextRunAt).toBe(at("2026-11-03T08:00"));
+ // 关了两天,11:00 开:错过的都太久了,只记一条跳过,不跑
+ svc.stop();
+ now = at("2026-11-05T11:00");
+ svc = make();
+ svc.start();
+ await flush();
- expect(runsOf(rule.id).slice(1).map((r) => [r.outcome, r.error, r.queuedAt])).toEqual([["skipped", "电脑没开", at("2026-11-03T08:00")]]);
++ expect(runsOf(rule.id).slice(1).map((r) => [r.outcome, r.error, r.queuedAt])).toEqual([["skipped", "app_off", at("2026-11-03T08:00")]]);
+ expect(svc.ruleLog(rule.id)[0].line).toBe("跳过:电脑没开");
+ expect(store.getRule(rule.id)!.nextRunAt).toBe(at("2026-11-06T08:00"));
+ // 每 15 分钟的:关了一小时,最近的那格在 7.5 分钟内 → 跳过一条、跑一次
+ const every = (await create("every 15m")).rule;
+ expect(every.nextRunAt).toBe(at("2026-11-05T11:01"));
+ svc.stop();
+ now = at("2026-11-05T12:20");
+ svc = make();
+ svc.start();
+ await flush();
+ expect(runsOf(every.id).map((r) => [r.outcome || r.state, r.queuedAt])).toEqual([
+ ["skipped", at("2026-11-05T11:01")],
+ ["running", at("2026-11-05T12:16")],
+ ]);
+ expect(store.getRule(every.id)!.nextRunAt).toBe(at("2026-11-05T12:31"));
+ });
+
+ it("名额一直被占着:等过了宽限期就跳过(「一直在忙」);上一次还没跑完,这次跳过", async () => {
+ svc.stop();
+ svc = make({ maxBackground: 0 });
+ svc.start();
+ const { rule } = await create();
+ await go(at("2026-11-02T08:00"));
+ expect(runsOf(rule.id).map((r) => r.state)).toEqual(["queued"]);
+ now = at("2026-11-02T10:01");
+ svc.pump();
- expect(runsOf(rule.id).map((r) => [r.outcome, r.error])).toEqual([["skipped", "一直在忙"]]);
++ expect(runsOf(rule.id).map((r) => [r.outcome, r.error])).toEqual([["skipped", "busy"]]);
++ expect(svc.ruleLog(rule.id)[0].line).toBe("跳过:一直在忙");
+ svc.stop();
+ svc = make();
+ svc.start();
+ await go(at("2026-11-03T08:00"));
+ // 跑了一整天还没完(没有时间上限的假设):第二天到点时跳过
+ await go(at("2026-11-04T08:00"));
+ expect(runsOf(rule.id).map((r) => [r.state, r.outcome, r.error]).slice(1)).toEqual([
+ ["running", "", ""],
- ["ended", "skipped", "上次还没跑完"],
++ ["ended", "skipped", "overlap"],
+ ]);
+ });
+
+ it("固定提醒:直接执行,到点只发那句话(不进模型、不占名额、不受免打扰限制),一次性的跑完就结束", async () => {
+ const r = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "开会", instruction: "明天下午 3 点提醒我开会", schedule: "once 2026-11-03 15:00", kind: "remind", message: "该去开会了。" } });
+ expect(r.text).toContain("Created reminder");
+ expect(r.text).toContain("「好,11月3日 15:00 提醒你。」");
+ const rule = store.listRules({ botId: "b" })[0];
+ expect(rule).toMatchObject({ kind: "remind", mode: "act", anytime: true, message: "该去开会了。" });
+ expect(svc.getRuleView(rule.id)!.state).toMatchObject({ key: "remind", label: "提醒" });
+ await go(at("2026-11-03T15:00"));
+ expect(host.prompts).toEqual([]);
+ const [run] = runsOf(rule.id);
+ expect(run).toMatchObject({ state: "ended", outcome: "done", mode: "act" });
+ expect(pushes().map((x) => [x.id, x.purpose, x.body.text, x.body.anytime])).toEqual([[`rule:${rule.id}:${run.id}`, "reminder", "该去开会了。", true]]);
+ expect(svc.ruleLog(rule.id)[0].line).toBe("待发送:“该去开会了。”");
+ expect(store.getRule(rule.id)!.nextRunAt).toBe(0);
+ expect(svc.getRuleView(rule.id)!.state).toMatchObject({ key: "done", label: "已结束" });
+ // 提醒没有观察模式
+ expect(svc.updateRule(rule.id, { mode: "observe" }).error).toBe("提醒没有观察模式");
+ // 没给那句话
+ const bad = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "x", instruction: "x", schedule: "daily 09:00", kind: "remind" } });
+ expect(bad.error).toMatch(/needs message/);
+ });
+
+ it("重启时被打断:宽限期内用新会话重跑一次(前面加一句说明),重跑的再被打断就跳过;超过宽限期的跳过", async () => {
+ const { rule } = await create();
+ await go(at("2026-11-02T08:00"));
+ const first = host.prompts.at(-1)!;
+ svc.stop();
+ now = at("2026-11-02T08:10");
+ svc = make();
+ svc.start();
+ await flush();
+ const runs = runsOf(rule.id);
+ expect(runs.map((r) => [r.cause, r.outcome || r.state])).toEqual([
+ ["schedule", "interrupted"],
+ ["recover", "running"],
+ ]);
+ const again = host.prompts.at(-1)!;
+ expect(again.sessionId).not.toBe(first.sessionId);
+ expect(again.text.startsWith(RULE_RERUN)).toBe(true);
+ expect(again.text).toContain(first.text);
+ // 重跑的又被打断:不再重跑
+ svc.stop();
+ svc = make();
+ svc.start();
+ await flush();
+ expect(runsOf(rule.id).map((r) => [r.cause, r.outcome])).toEqual([
+ ["schedule", "interrupted"],
+ ["recover", "skipped"],
+ ]);
+ expect(svc.ruleLog(rule.id)[0].line).toBe("跳过:应用重启了");
+ // 超过宽限期才重启:跳过
+ await go(at("2026-11-03T08:00"));
+ svc.stop();
+ now = at("2026-11-03T10:30");
+ svc = make();
+ svc.start();
+ await flush();
- expect(runsOf(rule.id).at(-1)).toMatchObject({ cause: "schedule", outcome: "skipped", error: "应用重启了" });
++ expect(runsOf(rule.id).at(-1)).toMatchObject({ cause: "schedule", outcome: "skipped", error: "restart" });
+ });
+
+ it("运行记录:新的在前,一次一行,可以往前翻;展开有报告、版本、权限;runLine 的几种说法", async () => {
+ const { rule } = await create("every 15m");
+ for (let i = 0; i < 4; i++) {
+ await go(store.getRule(rule.id)!.nextRunAt);
+ await turn(report("done"));
+ }
+ const all = svc.ruleLog(rule.id);
+ expect(all).toHaveLength(4);
+ expect(all.map((r) => r.at)).toEqual([...all.map((r) => r.at)].sort((a, b) => b - a));
+ const page = svc.ruleLog(rule.id, { before: all[1].at, limit: 10 });
+ expect(page.map((r) => r.id)).toEqual(all.slice(2).map((r) => r.id));
+ expect(all[0]).toMatchObject({ summary: "X 现在 ¥199", message: "", version: 1, permission: "只读", outcome: "done" });
+ const run = (o: Partial<RunRow>): RunRow => ({ id: "r", botId: "b", taskId: "", ruleId: "x", ruleVersion: 1, mode: "act", sessionId: "", cause: "schedule", state: "ended", outcome: "done", report: undefined, would: "", activity: "", tokensIn: 0, tokensOut: 0, costUsd: 0, error: "", delivery: "", permission: "", queuedAt: 0, startedAt: 0, endedAt: 0, ...o });
- expect(runLine(run({ outcome: "failed", error: "超时" }), "check")).toBe("失败:超时");
++ expect(runLine(run({ outcome: "failed", error: "timeout" }), "check")).toBe("失败:超时");
+ expect(runLine(run({ outcome: "interrupted" }), "check")).toBe("中断:应用重启了");
+ expect(runLine(run({ state: "queued" }), "check")).toBe("排队中");
+ expect(runLine(run({ state: "running" }), "check")).toBe("正在运行");
+ expect(runLine(run({ report: { state: "done", summary: "", message: "hi", at: 0 } }), "check", { status: "sent" } as any)).toBe("已发送:“hi”");
+ expect(runLine(run({ report: { state: "done", summary: "", message: "hi", at: 0 } }), "check", { status: "held", attempts: 0 } as any)).toBe("未送达:“hi”");
+ expect(runLine(run({ report: { state: "done", summary: "", message: "该开会了", at: 0 } }), "remind", { status: "sent" } as any)).toBe("已提醒:“该开会了”");
+ });
+
+ it("事件触发(扩展点):来源和过滤条件对得上的开着的规则各开一个 run,走同一条观察 / 执行的路;对不上、关着的不开", async () => {
+ const events = new RuleEvents(svc);
+ const r = svc.createRule({ botId: "b", conversationId: CONV, title: "仓库新 issue", instruction: "有新 issue 时看看要不要我处理", trigger: { kind: "event", source: "fake", filter: { repo: "me/app" } } });
+ const other = svc.createRule({ botId: "b", conversationId: CONV, title: "别的仓库", instruction: "x", trigger: { kind: "event", source: "fake", filter: { repo: "me/other" } } });
+ expect(r.rule).toMatchObject({ mode: "observe", nextRunAt: 0, trigger: { kind: "event", source: "fake" } });
+ expect(svc.getRuleView(r.rule!.id)).toMatchObject({ when: "事件 fake", state: { key: "observe" } });
+ expect(events.emit("fake", { repo: "me/app", title: "登录页打不开", number: 12 })).toEqual([r.rule!.id]);
+ await flush();
+ const p = host.prompts.at(-1)!;
+ expect(p.sessionId).toMatch(new RegExp(`^rule-${r.rule!.id}-`));
+ expect(p.text).toContain('[事件]\n来源:fake\n{"repo":"me/app","title":"登录页打不开","number":12}');
+ expect(runsOf(r.rule!.id)[0]).toMatchObject({ cause: "event", mode: "observe" });
+ await turn(report("done", "仓库有个新 issue #12:登录页打不开"));
+ expect(svc.ruleLog(r.rule!.id)[0].line).toBe("本会发送:“X 降价了:现在 ¥199(昨天 ¥259)。”");
+ expect(pushes()).toEqual([]);
+ // 对不上、关着的、别的来源
+ expect(events.emit("fake", { repo: "me/nothing" })).toEqual([]);
+ svc.updateRule(other.rule!.id, { mode: "off" });
+ expect(events.emit("fake", { repo: "me/other" })).toEqual([]);
+ expect(events.emit("github", { repo: "me/app" })).toEqual([]);
+ // 执行:命中推一句,id 一样固定
+ svc.updateRule(r.rule!.id, { mode: "act" });
+ expect(events.emit("fake", { repo: "me/app", title: "又一个" })).toEqual([r.rule!.id]);
+ await flush();
+ await turn(report("done", "又一个新 issue"));
+ expect(pushes().map((x) => x.purpose)).toEqual(["rule"]);
+ });
+
+ it("一次运行最长 15 分钟:到了就停掉会话、这次算失败(超时)", async () => {
+ svc.stop();
+ svc = make({ cap: 20 });
+ svc.start();
+ const { rule } = await create();
+ await go(at("2026-11-02T08:00"));
+ const sid = host.prompts.at(-1)!.sessionId;
+ await new Promise((r) => setTimeout(r, 60));
+ await flush();
- expect(runsOf(rule.id)[0]).toMatchObject({ outcome: "failed", error: "超时" });
++ expect(runsOf(rule.id)[0]).toMatchObject({ outcome: "failed", error: "timeout" });
++ expect(svc.ruleLog(rule.id)[0]).toMatchObject({ line: "失败:超时", error: "超时" });
+ expect(host.stops).toContain(sid);
+ expect(store.getRule(rule.id)!.failures).toBe(1);
+ });
+
+ it("没报告:提醒一次(规则的说法),还没有就失败;观察时要批准的自动拒绝、记成「需要批准」", async () => {
+ const { rule } = await create();
+ await go(at("2026-11-02T08:00"));
+ svc.wouldNeedApproval(runsOf(rule.id)[0].id, "curl -X POST https://x.example/alert");
+ await turn();
+ expect(host.prompts.at(-1)!.text).toBe(RULE_NUDGE);
+ await turn();
+ const [run] = runsOf(rule.id);
- expect(run).toMatchObject({ outcome: "failed", error: "没有给出结果", would: "需要批准:curl -X POST https://x.example/alert" });
++ expect(run).toMatchObject({ outcome: "failed", error: "没有给出结果", would: "approval: curl -X POST https://x.example/alert" });
++ expect(svc.ruleLog(rule.id)[0]).toMatchObject({ line: "失败:没有给出结果", would: "需要批准:curl -X POST https://x.example/alert" });
+ // 不能问用户
+ await go(at("2026-11-03T08:00"));
+ expect(svc.report({ sessionId: host.prompts.at(-1)!.sessionId, state: "needs_you", summary: "" }).error).toMatch(/cannot ask the user/);
+ });
+
+ it("执行时的审批:在「需要你」里(规则名),不进聊天回合;1 小时没人管就拒绝、这次失败;ruleOfSession 认得子代理", async () => {
+ const { rule } = await create();
+ svc.updateRule(rule.id, { mode: "act" });
+ await go(at("2026-11-02T08:00"));
+ const sid = host.prompts.at(-1)!.sessionId;
+ const who = svc.ruleOfSession("sub-1", sid)!;
+ expect(who).toMatchObject({ ruleId: rule.id, conversationId: CONV, mode: "act" });
+ const row = approvals.create({ kind: "approval", botId: "b", conversationId: CONV, sessionId: sid, tool: "bash", detail: "npm publish", reason: "", ruleId: rule.id, runId: who.runId, ttlMs: 3600_000 });
+ expect(approvals.pendingChat(CONV)).toEqual([]);
+ expect(approvals.handleReply(CONV, "y", "weixin:owner")).toEqual({ handled: false });
+ now += 3600_001;
+ approvals.sweep();
+ await flush();
+ expect(store.getApproval(row.id)!.status).toBe("expired");
- expect(runsOf(rule.id)[0]).toMatchObject({ outcome: "failed", error: "批准超时" });
++ expect(runsOf(rule.id)[0]).toMatchObject({ outcome: "failed", error: "approval_timeout" });
+ expect(host.stops).toContain(sid);
+ });
+
+ it("微信:执行中的规则(含提醒)每条留 1 条配额,观察中的不留;续期提醒列出窗口关了以后要跑的", async () => {
+ const { rule } = await create();
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(0);
+ svc.updateRule(rule.id, { mode: "act" });
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(1);
+ await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "喝水", instruction: "每天下午三点提醒我喝水", schedule: "daily 15:00", kind: "remind", message: "喝水。" } });
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(2);
+ const peer = { botId: "b", channel: "weixin", peerId: "owner", conversationId: CONV };
+ expect(delivery.upcoming(peer, at("2026-11-02T07:30")).map((u) => [u.label, u.at, u.kind])).toEqual([
+ ["看 X 价格", at("2026-11-02T08:00"), "rule"],
+ ["喝水", at("2026-11-02T15:00"), "reminder"],
+ ]);
+ expect(delivery.upcoming(peer, at("2026-11-02T09:00")).map((u) => u.label)).toEqual(["喝水"]);
+ svc.updateRule(rule.id, { mode: "observe" });
+ expect(delivery.reserved("b", "weixin", "owner")).toBe(1);
+ });
+
+ it("聊天代理:task_list 列出规则;rule_update 改模式、改原话、删掉;/tasks 列出规则,/stop 编号 关掉它", async () => {
+ const { rule } = await create();
+ const list = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "list", args: {} });
+ expect(list.text).toBe(`rule ${rule.id} 「看 X 价格」 每天 08:00 · 观察中`);
+ const up = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_update", args: { rule: "X 价格", mode: "act" } });
+ expect(up.text).toMatch(/^Updated rule 「看 X 价格」: 每天 08:00, 执行中\./);
+ const re = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_update", args: { rule: rule.id, instruction: "低于 150 告诉我" } });
+ expect(re.text).toContain("its next run only observes");
+ expect(svc.listText(CONV)).toBe("规则:\n1. 每天 08:00 看 X 价格 · 观察中\n发 /stop 编号 可停止。");
+ expect(svc.stopByIndex(CONV, 1, "weixin:owner")).toBe("已关闭规则「看 X 价格」。");
+ expect(store.getRule(rule.id)!.mode).toBe("off");
+ expect(svc.listText(CONV)).toBe("没有后台任务。");
+ const del = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_update", args: { rule: "X", delete: true } });
+ expect(del.text).toMatch(/^Deleted rule/);
+ expect(store.getRule(rule.id)).toBeUndefined();
+ expect((await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_update", args: { rule: "X", mode: "act" } })).error).toMatch(/No rule matches/);
+ });
+
+ it("没设小模型:检查和写那一句都用主模型,不再多调一次;网页会话:写进会话历史", async () => {
+ host.settingsValue = { ...DEFAULT_SETTINGS };
+ const r = svc.createRule({ botId: "b", conversationId: WEB, title: "看 X 价格", instruction: "看看 X", schedule: parseSchedule("daily 08:00", TZ, now).schedule });
+ svc.updateRule(r.rule!.id, { mode: "act" });
+ await go(at("2026-11-02T08:00"));
+ expect(host.prompts.at(-1)!.model).toBe("main-model");
+ await turn(report("done", "X 降到 199 了"));
+ await flush();
+ expect(writes).toEqual([]);
+ expect(pushes()).toEqual([]);
+ expect(store.listMessages(WEB).at(-1)!.content).toBe("X 降到 199 了");
+ expect(runsOf(r.rule!.id)[0].delivery).toBe(`rule:${r.rule!.id}:${runsOf(r.rule!.id)[0].id}`);
+ });
+
++ it("英文(界面请求、应用语言是英文时):时间表的话、状态、运行记录、「需要你」、暂停推送、建规则时建议的回复;给模型的第一条输入照旧是中文", async () => {
++ const d = (text: string) => describeSchedule(parseSchedule(text, TZ, now).schedule!, false, "en");
++ expect([d("daily 08:00"), d("weekdays 08:00"), d("weekly sun,thu,mon 09:00"), d("every 30m"), d("every 1h"), d("every 2h"), d("once 2026-11-03 15:00")]).toEqual([
++ "Daily 08:00",
++ "Weekdays 08:00",
++ "Every Mon, Thu, Sun 09:00",
++ "Every 30 min",
++ "Every hour",
++ "Every 2 hours",
++ "Nov 3 15:00",
++ ]);
++ expect(normalizeSchedule({ kind: "every", minutes: 5 }, TZ, now, "en").error).toBe("The interval must be at least 15 minutes");
++ const { rule } = await create();
++ svc.updateRule(rule.id, { mode: "act" });
++ await day("2026-11-02", report("done", "X 降到 199 了"));
++ await day("2026-11-03", report("done"));
++ withLang("en", () => {
++ expect(svc.getRuleView(rule.id)).toMatchObject({ when: "Daily 08:00", state: { key: "act", label: "Acting" } });
++ expect(svc.ruleLog(rule.id).map((r) => [r.line, r.permission])).toEqual([
++ ["Stayed quiet: X 现在 ¥199", "Can write the workspace"],
++ ["Waiting to send: “X 降价了:现在 ¥199(昨天 ¥259)。”", "Can write the workspace"],
++ ]);
++ });
++ // 应用语言是英文:推送的暂停那句、「需要你」、/tasks、建规则时建议的回复都是英文;给模型的第一条输入照旧
++ setLangPref("en");
++ try {
++ for (const date of ["2026-11-04", "2026-11-05", "2026-11-06"]) await day(date, report("failed", "", {}));
++ expect(pushes().find((r) => r.purpose === "failure")!.body.text).toBe("⚠️ Rule “看 X 价格” failed 3 times in a row and is paused: no result");
++ expect(svc.ruleAttention()[0]).toMatchObject({ subject: "Rule “看 X 价格”", status: "Failed 3 times in a row, paused", line: "no result" });
++ expect(svc.listText(CONV)).toBe("Rules:\n1. Daily 08:00 看 X 价格 · Paused\nSend /stop <number> to stop one.");
++ expect(host.prompts.at(-1)!.text).toContain("[规则]\n看 X 价格(每天 08:00)");
++ const made = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "Weather", instruction: "check the rain every weekday", schedule: "weekdays 07:30" } });
++ expect(made.text).toContain("「Rule set: Weather, Weekdays 07:30. It watches quietly for a few days; switch it to act under Tasks.」");
++ expect(made.text).toContain("WeChat lets the bot message you only within 24 hours of your last message.");
++ expect(svc.updateRule(rule.id, { title: " " }).error).toBe("Name can't be empty");
++ } finally {
++ setLangPref("system");
++ }
++ });
++
+ it("模拟 48 小时:三条规则(每天、每 30 分钟、一次性提醒),中间应用关了 3 小时;次数、跳过、推送都对", async () => {
+ const daily = (await create("daily 08:00")).rule;
+ const half = (await create("every 30m")).rule;
+ await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "交房租", instruction: "明天中午提醒我交房租", schedule: "once 2026-11-03 12:00", kind: "remind", message: "该交房租了。" } });
+ svc.updateRule(daily.id, { mode: "act" });
+ const end = at("2026-11-04T07:00");
+ let off = false;
+ for (let t = now; t <= end; t += 5 * MIN) {
+ // 11 月 3 日 01:00–04:00 应用没开
+ const closed = t >= at("2026-11-03T01:00") && t < at("2026-11-03T04:00");
+ if (closed && !off) (svc.stop(), (off = true));
+ if (closed) continue;
+ if (off) {
+ now = t;
+ svc = make();
+ svc.start();
+ off = false;
+ await flush();
+ } else await go(t);
+ // 开了 run 的:这一轮就跑完(每次都没命中,每天的那条命中)
+ while (svc.background().b) {
+ const p = host.prompts.at(-1)!;
+ const isDaily = p.sessionId.startsWith(`rule-${daily.id}`);
+ await turn(report("done", isDaily ? "X 降到 199 了" : ""));
+ }
+ }
+ await flush();
+ const count = (id: string, outcome: string) => runsOf(id).filter((r) => r.outcome === outcome).length;
+ expect([count(daily.id, "done"), count(daily.id, "skipped")]).toEqual([2, 0]);
+ // 每 30 分钟:48 小时减去关着的 3 小时;重新打开时补跑一次、跳过一条
+ expect(count(half.id, "skipped")).toBe(1);
+ expect(count(half.id, "done")).toBeGreaterThanOrEqual(84);
+ expect(count(half.id, "done")).toBeLessThanOrEqual(90);
+ expect(pushes().map((r) => r.purpose).sort()).toEqual(["reminder", "rule", "rule"]);
+ expect(writes).toHaveLength(2);
+ });
+});
diff --cc ui/components/rules.js
index 5cbdaa7,0000000..88487ec
mode 100644,000000..100644
--- a/ui/components/rules.js
+++ b/ui/components/rules.js
@@@ -1,285 -1,0 +1,284 @@@
+// 规则(3d):信息面板「任务」组里一条规则一行——时间表 · 标题,下面一行是状态和下次运行;观察了 3 次的,行里多一句
+// 「已观察 3 次 · 改为执行?」(只在这里,从不推送)。点开是规则的详情:用户的原话、模式(观察 / 执行 / 关)、立即运行、编辑、删除,
+// 和运行记录(一次一行:时间 · 模式 · 本会发送 / 保持安静 / 失败 / 跳过),每行再点开看报告、步骤、版本和权限。
+// 健康时不多说话:状态是"点 + 文字"(绿 = 执行中、提醒,灰 = 观察中、关了,红 = 暂停了)。
+import { useEffect, useState } from "preact/hooks";
+import { html, Icon, Button, Seg, Sheet, Spinner } from "./ui.js";
+import { ActivityLine } from "./activity.js";
+import { api } from "../lib/api.js";
+import { confirmSheet, failed, toast } from "../lib/store.js";
- import { CHANNEL_NAME } from "../lib/access.js";
++import { channelName } from "../lib/access.js";
++import { t, locale } from "../lib/i18n.js";
+
+const pad = (n) => String(n).padStart(2, "0");
+const hm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
- const WEEK = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
- const dayDiff = (t, now = Date.now()) => {
++const dayDiff = (at, now = Date.now()) => {
+ const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
- return Math.round((day(new Date(t)) - day(new Date(now))) / 86_400_000);
++ return Math.round((day(new Date(at)) - day(new Date(now))) / 86_400_000);
+};
++const shortDate = (d) => d.toLocaleDateString(locale(), { month: "numeric", day: "numeric" });
+
- /** 运行记录里的时间:今天 08:00 / 昨天 08:00 / 前天 08:00 / 10/27 08:00 */
- export function fmtRunAt(t, now = Date.now()) {
- const d = new Date(t);
- const n = dayDiff(t, now);
- if (n === 0) return `今天 ${hm(d)}`;
- if (n === -1) return `昨天 ${hm(d)}`;
- if (n === -2) return `前天 ${hm(d)}`;
- return `${d.getMonth() + 1}/${d.getDate()} ${hm(d)}`;
++/** 运行记录里的时间:今天 08:00 / 昨天 08:00 / 10/27 08:00 */
++export function fmtRunAt(at, now = Date.now()) {
++ const d = new Date(at);
++ const n = dayDiff(at, now);
++ if (n === 0) return t("time.today", { time: hm(d) });
++ if (n === -1) return t("time.yesterday", { time: hm(d) });
++ return t("time.dateTime", { date: shortDate(d), time: hm(d) });
+}
+
+/** 下次运行:今天 15:00 / 明天 08:00 / 周一 09:00 / 11/20 09:00 */
- export function fmtNext(t, now = Date.now()) {
- const d = new Date(t);
- const n = dayDiff(t, now);
- if (n <= 0) return `今天 ${hm(d)}`;
- if (n === 1) return `明天 ${hm(d)}`;
- if (n < 7) return `${WEEK[d.getDay()]} ${hm(d)}`;
- return `${d.getMonth() + 1}/${d.getDate()} ${hm(d)}`;
++export function fmtNext(at, now = Date.now()) {
++ const d = new Date(at);
++ const n = dayDiff(at, now);
++ if (n <= 0) return t("time.today", { time: hm(d) });
++ if (n === 1) return t("rules.tomorrow", { time: hm(d) });
++ if (n < 7) return t("rules.weekdayTime", { day: d.toLocaleDateString(locale(), { weekday: "short" }), time: hm(d) });
++ return t("time.dateTime", { date: shortDate(d), time: hm(d) });
+}
+
- const MODE = { observe: "观察", act: "执行" };
-
- /** 行的第二行:观察中 · 下次 明天 08:00;正在运行;已暂停 · 连续失败 3 次 */
++/** 行的第二行:观察中 · 下次 明天 08:00;正在运行;已暂停 · 连续失败 3 次(状态文字由服务端按界面语言给) */
+export function ruleSub(rule, now = Date.now()) {
- if (rule.live) return rule.live.state === "queued" ? `${rule.state.label} · 排队中` : `${rule.state.label} · 正在运行`;
- if (rule.state.key === "paused") return `已暂停 · 连续失败 ${rule.failures} 次`;
++ if (rule.live) return t(rule.live.state === "queued" ? "rules.queued" : "rules.running", { state: rule.state.label });
++ if (rule.state.key === "paused") return t("rules.paused", { count: rule.failures });
+ if (rule.state.key === "off" || rule.state.key === "done") return rule.state.label;
- return rule.nextRunAt ? `${rule.state.label} · 下次 ${fmtNext(rule.nextRunAt, now)}` : rule.state.label;
++ return rule.nextRunAt ? t("rules.sub", { state: rule.state.label, next: fmtNext(rule.nextRunAt, now) }) : rule.state.label;
+}
+
+async function put(rule, body, done) {
+ try {
+ const d = await api(`/rules/${encodeURIComponent(rule.id)}`, { method: "PUT", body });
+ done?.(d.rule);
+ return d.rule;
+ } catch (e) {
+ failed(e);
+ return null;
+ }
+}
+
+/** 信息面板里的一行:点开是详情(和行同一块,像普通的折叠一样展开) */
+export function RuleRow({ rule, onChanged, open, onToggle }) {
+ const [busy, setBusy] = useState(false);
+ const toAct = async (e) => {
+ e.stopPropagation();
+ setBusy(true);
- if (await put(rule, { mode: "act" })) (toast(`「${rule.title}」改为执行`), onChanged?.());
++ if (await put(rule, { mode: "act" })) (toast(t("rules.nowActs", { title: rule.title })), onChanged?.());
+ setBusy(false);
+ };
+ return html`<div class=${`row compact clickable rule-row${open ? " open" : ""}`} role="button" tabindex="0" aria-expanded=${open}
+ onClick=${onToggle} onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), onToggle())}>
+ <span class=${`dot ${rule.state.dot}`} aria-hidden="true"></span>
+ <div class="who">
+ <div class="name">${rule.when} · ${rule.title}</div>
+ <div class="sub">${ruleSub(rule)}</div>
- ${rule.hint && html`<button type="button" class="text rule-hint" disabled=${busy} onClick=${toAct} onKeyDown=${(e) => e.stopPropagation()}>已观察 ${rule.observed} 次 · 改为执行?</button>`}
++ ${rule.hint && html`<button type="button" class="text rule-hint" disabled=${busy} onClick=${toAct} onKeyDown=${(e) => e.stopPropagation()}>${t("rules.hint", { count: rule.observed })}</button>`}
+ </div>
+ </div>
+ ${open && html`<div class="row-edit rule-edit"><${RuleDetail} rule=${rule} onChanged=${onChanged} /></div>`}`;
+}
+
+/** 运行记录的一行:时间 · 模式 · 一句话;点开看报告、步骤、版本和权限(不另起一块) */
+function RunItem({ rule, run }) {
+ const [open, setOpen] = useState(false);
- const mode = rule.kind === "remind" ? "" : MODE[run.mode] || "";
- const meta = [`第 ${run.version} 版`, run.permission, run.cause === "manual" ? "手动运行" : run.cause === "event" ? "事件" : ""].filter(Boolean).join(" · ");
++ const mode = rule.kind === "remind" || !["observe", "act"].includes(run.mode) ? "" : t(`rules.mode.${run.mode}`);
++ const meta = [t("rules.version", { n: run.version }), run.permission, run.cause === "manual" ? t("rules.manual") : run.cause === "event" ? t("rules.event") : ""].filter(Boolean).join(" · ");
+ return html`<li class=${`rule-run${open ? " open" : ""}`}>
+ <button type="button" class="rule-run-head" aria-expanded=${open} onClick=${() => setOpen(!open)}>
+ <span class="at num">${fmtRunAt(run.at)}</span>${mode && html`<span class="m">${mode}</span>`}<span class="l">${run.line}</span>
+ <${Icon} name="chevRight" size=${12} class="chev" />
+ </button>
+ ${open && html`<div class="rule-run-body">
+ ${run.summary && html`<p class="selectable">${run.summary}</p>`}
- ${run.would && html`<p class="selectable"><span class="t-label">本会做</span> ${run.would}</p>`}
++ ${run.would && html`<p class="selectable"><span class="t-label">${t("rules.would")}</span> ${run.would}</p>`}
+ ${meta && html`<span class="hint">${meta}</span>`}
- ${run.steps > 0 && html`<${ActivityLine} label="处理过程" count=${run.steps} load=${() => api(`/rules/${encodeURIComponent(rule.id)}/runs/${encodeURIComponent(run.id)}/activity`).then((x) => x.steps)} />`}
++ ${run.steps > 0 && html`<${ActivityLine} label=${t("rules.steps")} count=${run.steps} load=${() => api(`/rules/${encodeURIComponent(rule.id)}/runs/${encodeURIComponent(run.id)}/activity`).then((x) => x.steps)} />`}
+ </div>`}
+ </li>`;
+}
+
+/** 规则的详情:原话、模式、操作、运行记录。runs 给了就不去取(样例页用) */
+export function RuleDetail({ rule, runs: given, onChanged }) {
+ const [runs, setRuns] = useState(given || null);
+ const [more, setMore] = useState(false);
+ const [busy, setBusy] = useState("");
+ const [editing, setEditing] = useState(false);
+ const load = (before) =>
+ api(`/rules/${encodeURIComponent(rule.id)}/runs${before ? `?before=${before}` : ""}`)
+ .then((d) => (setRuns((v) => (before ? [...(v || []), ...d.runs] : d.runs)), setMore(d.runs.length >= 20)))
+ .catch(() => setRuns((v) => v || []));
+ useEffect(() => {
+ if (given) return;
+ load();
+ if (!rule.live) return;
+ const t = setInterval(() => load(), 3000);
+ return () => clearInterval(t);
+ }, [rule.id, rule.updatedAt, !!rule.live, rule.last?.at]);
+ const act = async (key, fn) => {
+ setBusy(key);
+ try {
+ await fn();
+ onChanged?.();
+ } catch (e) {
+ failed(e);
+ }
+ setBusy("");
+ };
+ const setMode = (mode) => act("mode", () => put(rule, { mode }));
+ const runNow = () => act("run", () => api(`/rules/${encodeURIComponent(rule.id)}/run`, { method: "POST", body: {} }));
+ const del = async () => {
- if (!(await confirmSheet({ title: `删除「${rule.title}」?`, body: "运行记录一起删除。", confirmLabel: "删除", danger: true }))) return;
- act("del", () => api(`/rules/${encodeURIComponent(rule.id)}`, { method: "DELETE" }).then(() => toast("已删除")));
++ if (!(await confirmSheet({ title: t("rules.deleteTitle", { title: rule.title }), body: t("rules.deleteBody"), confirmLabel: t("common.delete"), danger: true }))) return;
++ act("del", () => api(`/rules/${encodeURIComponent(rule.id)}`, { method: "DELETE" }).then(() => toast(t("rules.deleted"))));
+ };
- const modes = rule.kind === "remind" ? [["act", "开"], ["off", "关"]] : [["observe", "观察"], ["act", "执行"], ["off", "关"]];
- const where = CHANNEL_NAME[rule.channel] || rule.channel;
- const line = [rule.nextRunAt && rule.state.key !== "paused" && rule.mode !== "off" ? `下次 ${fmtNext(rule.nextRunAt)}` : "", where && `发到 ${where}`].filter(Boolean).join(" · ");
++ const modes =
++ rule.kind === "remind"
++ ? [["act", t("rules.mode.on")], ["off", t("rules.mode.off")]]
++ : [["observe", t("rules.mode.observe")], ["act", t("rules.mode.act")], ["off", t("rules.mode.off")]];
++ const where = rule.channel ? channelName(rule.channel) : "";
++ const next = rule.nextRunAt && rule.state.key !== "paused" && rule.mode !== "off" ? t("rules.next", { time: fmtNext(rule.nextRunAt) }) : "";
++ const line = [next, where && t("rules.sendsTo", { where })].filter(Boolean).join(" · ");
+ return html`<div class="rule-detail">
- <p class="rule-words selectable">「${rule.kind === "remind" ? rule.message : rule.instruction}」</p>
++ <p class="rule-words selectable">${t("rules.words", { text: rule.kind === "remind" ? rule.message : rule.instruction })}</p>
+ ${line && html`<span class="hint">${line}</span>`}
+ <div class="actions">
- <${Seg} label="模式" options=${modes} value=${rule.mode} disabled=${busy === "mode"} onChange=${setMode} />
++ <${Seg} label=${t("rules.modeLabel")} options=${modes} value=${rule.mode} disabled=${busy === "mode"} onChange=${setMode} />
+ <span class="grow"></span>
- <${Button} size="sm" loading=${busy === "run"} disabled=${!!busy || !!rule.live || rule.mode === "off"} onClick=${runNow}>立即运行<//>
++ <${Button} size="sm" loading=${busy === "run"} disabled=${!!busy || !!rule.live || rule.mode === "off"} onClick=${runNow}>${t("rules.runNow")}<//>
+ </div>
- ${rule.mode === "act" && rule.observeLeft > 0 && html`<span class="hint">改了规则,先观察 ${rule.observeLeft} 次再执行</span>`}
- ${rule.kind === "check" && rule.mode === "observe" && html`<span class="hint">观察时不发消息、不改文件,但拦不住命令联网。</span>`}
++ ${rule.mode === "act" && rule.observeLeft > 0 && html`<span class="hint">${t("rules.observeLeft", { count: rule.observeLeft })}</span>`}
++ ${rule.kind === "check" && rule.mode === "observe" && html`<span class="hint">${t("rules.observeHelp")}</span>`}
+ <div class="actions">
- <button type="button" class="text" onClick=${() => setEditing(true)}>编辑</button>
- <button type="button" class="text danger" disabled=${busy === "del"} onClick=${del}>删除</button>
++ <button type="button" class="text" onClick=${() => setEditing(true)}>${t("common.edit")}</button>
++ <button type="button" class="text danger" disabled=${busy === "del"} onClick=${del}>${t("common.delete")}</button>
+ </div>
- <div class="t-label">运行记录</div>
- ${!runs && html`<span class="hint">加载中…</span>`}
- ${runs && !runs.length && html`<span class="hint">还没有运行过</span>`}
++ <div class="t-label">${t("rules.log")}</div>
++ ${!runs && html`<span class="hint">${t("common.loading")}</span>`}
++ ${runs && !runs.length && html`<span class="hint">${t("rules.noRuns")}</span>`}
+ ${runs && runs.length > 0 && html`<ol class="rule-runs">${runs.map((r) => html`<${RunItem} key=${r.id + r.state} rule=${rule} run=${r} />`)}</ol>`}
- ${more && html`<button type="button" class="text" onClick=${() => load(runs.at(-1).at)}>更早的</button>`}
++ ${more && html`<button type="button" class="text" onClick=${() => load(runs.at(-1).at)}>${t("rules.earlier")}</button>`}
+ ${editing && html`<${RuleEditor} botId=${rule.botId} rule=${rule} onClose=${() => setEditing(false)} onSaved=${() => (setEditing(false), onChanged?.())} />`}
+ </div>`;
+}
+
- const KINDS = [
- ["daily", "每天"],
- ["weekdays", "工作日"],
- ["weekly", "每周"],
- ["every", "每隔"],
- ["once", "一次"],
- ["cron", "cron"],
- ];
++const KINDS = ["daily", "weekdays", "weekly", "every", "once", "cron"];
++const kindOptions = () => KINDS.map((k) => [k, t(`rules.kinds.${k}`)]);
+const DAY_PICKS = [1, 2, 3, 4, 5, 6, 0];
++/** 星期几的短名:2026-11-01 是周日,往后数 */
++const dayName = (d) => new Date(2026, 10, 1 + d).toLocaleDateString(locale(), { weekday: "short" });
+
+/** 规则的时间表 → 编辑器里的字段 */
+function formOf(s) {
+ const base = { kind: "daily", time: "08:00", days: [1], minutes: 60, at: "", cron: "0 8 * * 1-5" };
+ if (!s) return base;
+ if (s.kind === "daily" && (s.days || []).join(",") === "1,2,3,4,5") return { ...base, kind: "weekdays", time: s.time };
+ if (s.kind === "daily") return { ...base, time: s.time };
+ if (s.kind === "weekly") return { ...base, kind: "weekly", time: s.time, days: s.days };
+ if (s.kind === "every") return { ...base, kind: "every", minutes: s.minutes };
+ if (s.kind === "once") {
+ const d = new Date(s.at);
+ return { ...base, kind: "once", at: `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${hm(d)}` };
+ }
+ return { ...base, kind: "cron", cron: s.cron };
+}
+
+/** 编辑器里的字段 → 接口要的时间表 */
+function scheduleOf(f) {
+ if (f.kind === "weekdays") return { kind: "daily", time: f.time, days: [1, 2, 3, 4, 5] };
+ if (f.kind === "daily") return { kind: "daily", time: f.time };
+ if (f.kind === "weekly") return { kind: "weekly", time: f.time, days: f.days };
+ if (f.kind === "every") return { kind: "every", minutes: Number(f.minutes) };
+ if (f.kind === "once") return { kind: "once", at: f.at ? new Date(f.at).getTime() : 0 };
+ return { kind: "cron", cron: f.cron };
+}
+
+/** 发到哪:最近的几个会话;同一渠道只有一个时只写渠道名 */
+function convOptions(convs, current) {
+ const list = convs.slice(0, 5);
+ if (current && !list.some((c) => c.id === current)) {
+ const cur = convs.find((c) => c.id === current);
+ if (cur) list.push(cur);
+ }
+ const n = (ch) => list.filter((c) => c.channel === ch).length;
+ return list.map((c) => {
- const name = CHANNEL_NAME[c.channel] || c.channel;
++ const name = channelName(c.channel);
+ return [c.id, n(c.channel) > 1 ? `${name} · ${(c.title || c.peerId).slice(0, 8)}` : name];
+ });
+}
+
+/**
+ * 新建或编辑一条规则(对话框):名称、要做什么(用户的原话)或提醒的那句话、时间、发到哪个会话。
+ * 新建的检查从观察开始;改了原话的执行中的规则先观察 1 次(服务端处理)。发到微信时说清 24 小时的限制。
+ * 对话框里不放下拉菜单(玻璃对话框会裁掉它):选项都用分段。时间表没改就不发,every 的起点不会被挪动。
+ */
+export function RuleEditor({ botId, rule, onClose, onSaved }) {
+ const [kind, setKind] = useState(rule?.kind || "check");
+ const [title, setTitle] = useState(rule?.title || "");
+ const [words, setWords] = useState(rule ? (rule.kind === "remind" ? rule.message : rule.instruction) : "");
+ const [orig] = useState(() => formOf(rule?.trigger?.kind === "schedule" ? rule.trigger.schedule : undefined));
+ const [f, setF] = useState(orig);
+ const [conv, setConv] = useState(rule?.conversationId || "");
+ const [convs, setConvs] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const event = rule && rule.trigger.kind !== "schedule";
+ useEffect(() => {
+ api(`/conversations?bot=${encodeURIComponent(botId)}`)
+ .then((d) => {
+ setConvs(d.conversations);
+ if (!conv && d.conversations.length) setConv((d.conversations.find((c) => c.channel === "weixin") || d.conversations[0]).id);
+ })
+ .catch(() => setConvs([]));
+ }, [botId]);
+ const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
+ const toggleDay = (d) => setF({ ...f, days: f.days.includes(d) ? f.days.filter((x) => x !== d) : [...f.days, d] });
+ const channel = (convs || []).find((c) => c.id === conv)?.channel || rule?.channel;
+ const save = async () => {
+ setBusy(true);
+ try {
+ const body = {
+ title,
+ ...(kind === "remind" ? { message: words, ...(rule ? {} : { instruction: words }) } : { instruction: words }),
+ ...(event || (rule && JSON.stringify(scheduleOf(f)) === JSON.stringify(scheduleOf(orig))) ? {} : { schedule: scheduleOf(f) }),
+ ...(conv ? { conversationId: conv } : {}),
+ };
+ const d = rule
+ ? await api(`/rules/${encodeURIComponent(rule.id)}`, { method: "PUT", body })
+ : await api("/rules", { method: "POST", body: { ...body, botId, kind } });
- toast(rule ? "已保存" : kind === "remind" ? "已建好提醒" : "已建好规则,先观察");
++ toast(rule ? t("common.saved") : kind === "remind" ? t("rules.createdRemind") : t("rules.createdCheck"));
+ onSaved?.(d.rule);
+ } catch (e) {
+ failed(e);
+ }
+ setBusy(false);
+ };
+ const ok = title.trim() && words.trim() && conv && (event || f.kind !== "weekly" || f.days.length);
- return html`<${Sheet} title=${rule ? "编辑规则" : "新规则"} onClose=${onClose}>
++ const remind = kind === "remind";
++ return html`<${Sheet} title=${rule ? t("rules.editTitle") : t("rules.newTitle")} onClose=${onClose}>
+ <div class="rule-form">
- ${!rule && html`<${Seg} label="类型" options=${[["check", "检查"], ["remind", "提醒"]]} value=${kind} onChange=${setKind} />`}
- <label>名称<input class="field" data-autofocus value=${title} maxlength="40" placeholder=${kind === "remind" ? "开会" : "看 X 价格"} onInput=${(e) => setTitle(e.target.value)} /></label>
- <label>${kind === "remind" ? "提醒的话" : "要做什么"}
- <textarea class="field" rows=${kind === "remind" ? 2 : 3} value=${words} placeholder=${kind === "remind" ? "该去开会了。" : "看看 X 的价格,低于 200 告诉我"} onInput=${(e) => setWords(e.target.value)}></textarea></label>
++ ${!rule && html`<${Seg} label=${t("rules.kind")} options=${[["check", t("rules.kindCheck")], ["remind", t("rules.kindRemind")]]} value=${kind} onChange=${setKind} />`}
++ <label>${t("rules.name")}<input class="field" data-autofocus value=${title} maxlength="40" placeholder=${remind ? t("rules.namePhRemind") : t("rules.namePhCheck")} onInput=${(e) => setTitle(e.target.value)} /></label>
++ <label>${remind ? t("rules.wordsRemind") : t("rules.wordsCheck")}
++ <textarea class="field" rows=${remind ? 2 : 3} value=${words} placeholder=${remind ? t("rules.wordsPhRemind") : t("rules.wordsPhCheck")} onInput=${(e) => setWords(e.target.value)}></textarea></label>
+ ${!event && html`<div class="rule-when">
- <span class="t-label">时间</span>
- <${Seg} label="时间" options=${KINDS} value=${f.kind} onChange=${(v) => setF({ ...f, kind: v })} />
++ <span class="t-label">${t("rules.when")}</span>
++ <${Seg} label=${t("rules.when")} options=${kindOptions()} value=${f.kind} onChange=${(v) => setF({ ...f, kind: v })} />
+ <div class="rule-when-row">
+ ${["daily", "weekdays", "weekly"].includes(f.kind) && html`<input class="field num" type="time" value=${f.time} onInput=${set("time")} />`}
- ${f.kind === "every" && html`<input class="field num" type="number" min="15" step="5" value=${f.minutes} onInput=${set("minutes")} /><span class="hint">分钟</span>`}
++ ${f.kind === "every" && html`<input class="field num" type="number" min="15" step="5" value=${f.minutes} onInput=${set("minutes")} /><span class="hint">${t("rules.minutes")}</span>`}
+ ${f.kind === "once" && html`<input class="field num" type="datetime-local" value=${f.at} onInput=${set("at")} />`}
+ ${f.kind === "cron" && html`<input class="field mono" value=${f.cron} placeholder="0 8 * * 1-5" onInput=${set("cron")} />`}
+ </div>
- ${f.kind === "weekly" && html`<div class="rule-days" role="group" aria-label="星期">
- ${DAY_PICKS.map((d) => html`<button type="button" class=${`chip${f.days.includes(d) ? " on" : ""}`} aria-pressed=${f.days.includes(d)} onClick=${() => toggleDay(d)}>${WEEK[d].slice(1)}</button>`)}
++ ${f.kind === "weekly" && html`<div class="rule-days" role="group" aria-label=${t("rules.days")}>
++ ${DAY_PICKS.map((d) => html`<button type="button" class=${`chip${f.days.includes(d) ? " on" : ""}`} aria-pressed=${f.days.includes(d)} onClick=${() => toggleDay(d)}>${dayName(d)}</button>`)}
+ </div>`}
+ </div>`}
+ <div class="rule-when">
- <span class="t-label">发到</span>
- ${!convs ? html`<${Spinner} />` : convs.length ? html`<${Seg} label="发到" options=${convOptions(convs, conv)} value=${conv} onChange=${setConv} />` : html`<span class="hint">先在微信、飞书或网页里和机器人说句话</span>`}
++ <span class="t-label">${t("rules.to")}</span>
++ ${!convs ? html`<${Spinner} />` : convs.length ? html`<${Seg} label=${t("rules.to")} options=${convOptions(convs, conv)} value=${conv} onChange=${setConv} />` : html`<span class="hint">${t("rules.noConvs")}</span>`}
+ </div>
- ${channel === "weixin" && html`<p class="hint">微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。</p>`}
++ ${channel === "weixin" && html`<p class="hint">${t("rules.weixinNote")}</p>`}
+ </div>
+ <div class="actions">
- <${Button} onClick=${onClose}>取消<//>
- <${Button} variant="primary" loading=${busy} disabled=${!ok} onClick=${save}>${rule ? "保存" : "建好"}<//>
++ <${Button} onClick=${onClose}>${t("common.cancel")}<//>
++ <${Button} variant="primary" loading=${busy} disabled=${!ok} onClick=${save}>${rule ? t("common.save") : t("rules.create")}<//>
+ </div>
+ <//>`;
+}
diff --cc ui/design/gallery.js
index dca854d,5230a1a..93e1f79
--- a/ui/design/gallery.js
+++ b/ui/design/gallery.js
@@@ -372,8 -380,8 +381,8 @@@ function Gallery()
const nav = [
["原则", [["principles", "分层与约定"]]],
["Token", [["color", "颜色"], ["material", "材质"], ["type", "文字"], ["space", "间距与尺寸"], ["elevation", "投影与层级"], ["motion", "动效"]]],
- ["组件", [["states", "状态矩阵"], ["buttons", "按钮"], ["inputs", "输入"], ["menus", "菜单与分段"], ["status", "状态与反馈"], ["lists", "列表行"], ["overlays", "对话框与提示"], ["avatars", "头像"]]],
+ ["组件", [["states", "状态矩阵"], ["icons", "图标"], ["buttons", "按钮"], ["inputs", "输入"], ["menus", "菜单与分段"], ["status", "状态与反馈"], ["lists", "列表行"], ["splitter", "分隔条"], ["overlays", "对话框与提示"], ["avatars", "头像"]]],
- ["页面模式", [["patterns", "对话"], ["needs", "需要你"], ["custom", "定制"]]],
+ ["页面模式", [["patterns", "对话"], ["needs", "需要你"], ["rules", "规则"], ["custom", "定制"]]],
];
return html`<${Compare.Provider} value=${compare}><div class="gal">
<nav class="gal-nav" aria-label="目录">
diff --cc ui/locales/en/botSettings.js
index 0000000,fc7ab8a..ef28f68
mode 000000,100644..100644
--- a/ui/locales/en/botSettings.js
+++ b/ui/locales/en/botSettings.js
@@@ -1,0 -1,119 +1,123 @@@
+ // botSettings · en: bot settings (screens/bot-settings.js)
+ export default {
+ back: "Back to chat",
+ backTitle: "Back to chat (Esc)",
+ title: "Bot settings",
+ identity: "Identity",
+ avatar: "Avatar",
+ avatarHint: "Each character has its own little moves",
+ name: "Name",
+ prompt: "Persona / system prompt",
+ promptHint: "Saved when you leave the field",
+ promptPlaceholder: "e.g. You are a helpful assistant. Keep answers concise and accurate.",
+ model: {
+ head: "Model",
+ default: "Default model",
+ defaultSub: "You can still switch temporarily in a chat",
+ followGlobal: "Use global default",
+ followGlobalWith: "Use global default ({model})",
+ utility: "Background task model",
+ utilitySub: "Memory tidying, context steward, and handoff notes",
+ sameAsChat: "Same as chat model",
+ },
+ budget: {
+ name: "Budget",
+ signedOut: "Sign in to Modelflare to set a separate spending limit for this bot",
+ signIn: "Sign in",
+ off: "Shares this device's key with other bots, with no separate limit",
+ on: "Uses this bot's own key and stops at the limit",
+ usage: "{used} used, {remain} left",
+ exhausted: "{used} used, {remain} left · Used up — the bot has paused model calls",
+ limit: "Limit (USD)",
+ limitSub: "Includes what's already spent. Raising it restores a used-up key automatically.",
+ limitLabel: "Budget limit (USD)",
+ },
+ perm: {
+ head: "Permissions",
+ name: "File access",
+ workspaceSub: "Can only modify this bot's workspace; anything beyond needs your approval",
+ readonlySub: "Can't modify files; commands run in a read-only sandbox",
+ title: "Workspace write (default): can only modify this bot's workspace; anything beyond needs approval. Read-only: can't modify files; commands run in a read-only sandbox. Full access: commands run without a sandbox; only recursive deletes still need confirmation.",
+ workspace: "Workspace write",
+ readonly: "Read-only",
+ full: "Full access",
+ },
+ memory: {
+ head: "Memory",
+ name: "Long-term memory",
+ review: "Tidy up automatically after each turn",
+ reviewLabel: "Auto-tidy memory",
+ team: "Allow writing to team memory",
+ teamSub: "Shared by all bots",
+ teamLabel: "Team memory",
+ },
+ context: {
+ head: "Context",
+ name: "Auto-compact or start a new segment",
+ sub: "Tidies up as the context grows and leaves a handoff note",
+ label: "Context steward",
+ },
+ computer: {
+ head: "Computer use",
+ backend: "Backend",
+ backendLabel: "Computer use backend",
+ cuaNote: "Bundled · macOS / Windows / Linux",
+ codex: "Codex bridge",
+ macOnly: "macOS only",
+ macOnlyUnavailable: "macOS only, unavailable on this device",
+ approval: "Approval",
+ approvalLabel: "Computer use approval",
+ autoSub: "All actions run automatically",
+ askSub: "Ask before clicks, typing, and other UI-changing actions; reading the screen stays automatic",
+ auto: "Run automatically",
+ ask: "Ask before UI changes",
+ },
+ danger: {
+ head: "Danger zone",
+ delete: "Delete bot",
+ deleteSub: "Permanently delete this bot and all its conversations",
+ },
+ delete: {
+ title: "Delete “{name}”?",
+ body: "This permanently deletes the bot and all its conversations. This can't be undone.",
+ confirm: "Delete permanently",
+ },
+ access: {
+ head: "Who can use it",
+ policy: "Only the owner and people you allow",
+ owner: "{channel} owner",
+ reset: "Change",
+ resetOwnerTitle: "Change the {channel} owner?",
+ resetOwnerBody: "The next person to message the bot becomes the {channel} owner, and \"{who}\" will need to be allowed again.",
+ allowed: "Allowed",
+ denied: "Denied",
+ deniedSub: "Denied {when} · they get no reply if they message again",
+ allow: "Allow",
+ remove: "Remove",
+ removeDeniedTitle: "Remove \"{who}\"?",
+ removeDeniedBody: "If they message again after this, they'll show up again under usage requests in the info panel.",
+ revokeTitle: "Stop allowing \"{who}\"?",
+ revokeBody: "If they message again, they'll only get a short notice and will need to be allowed again.",
+ },
+ media: {
+ head: "Images and video",
+ confirm: "Confirm before generating",
+ alwaysSub: "Ask me which model to use before every generation",
+ autoSub: "Generate right away when the default model works and the cost is low; ask first when switching models, above about $0.5, or when the request is unclear",
+ auto: "Ask when needed",
+ always: "Always ask",
+ },
+ proactive: {
+ head: "Proactive messages",
+ quiet: "Do not disturb",
+ quietSub: "Background results wait until it ends",
+ quietFrom: "Do not disturb from",
+ quietTo: "Do not disturb until",
+ nudge: "WeChat renewal reminder",
+ nudgeSub: "When messages are still waiting to be sent, ask you for a reply before the 24-hour window closes",
++ rules: "Rules",
++ rulesSub: "Scheduled checks and reminders",
++ rulesCount: { one: "{count} rule, in the info panel under Tasks", other: "{count} rules, in the info panel under Tasks" },
++ newRule: "New",
+ },
+ };
diff --cc ui/locales/en/index.js
index 0000000,dba0744..223a191
mode 000000,100644..100644
--- a/ui/locales/en/index.js
+++ b/ui/locales/en/index.js
@@@ -1,0 -1,27 +1,28 @@@
+ // en 文案:每个命名空间一个文件,键 = "命名空间.键"(见 ui/lib/i18n.js)。两种语言的键必须一一对应(test/i18n.unit.test.ts 会查)。
+ import common from "./common.js";
+ import app from "./app.js";
+ import time from "./time.js";
+ import settings from "./settings.js";
+ import account from "./account.js";
+ import pwsh from "./pwsh.js";
+ import chat from "./chat.js";
+ import info from "./info.js";
+ import markdown from "./markdown.js";
+ import notify from "./notify.js";
+ import troubleshoot from "./troubleshoot.js";
+ import onboarding from "./onboarding.js";
+ import newBot from "./newBot.js";
+ import botSettings from "./botSettings.js";
+ import sidebar from "./sidebar.js";
+ import avatar from "./avatar.js";
+ import models from "./models.js";
+ import ui from "./ui.js";
+ import guide from "./guide.js";
+ import activity from "./activity.js";
+ import tasks from "./tasks.js";
+ import needs from "./needs.js";
++import rules from "./rules.js";
+ import access from "./access.js";
+ import perms from "./perms.js";
+
-export default { common, app, time, settings, account, pwsh, chat, info, markdown, notify, troubleshoot, onboarding, newBot, botSettings, sidebar, avatar, models, ui, guide, activity, perms, access, tasks, needs };
++export default { common, app, time, settings, account, pwsh, chat, info, markdown, notify, troubleshoot, onboarding, newBot, botSettings, sidebar, avatar, models, ui, guide, activity, perms, access, tasks, needs, rules };
diff --cc ui/locales/en/needs.js
index 0000000,f4cd792..7da731f
mode 000000,100644..100644
--- a/ui/locales/en/needs.js
+++ b/ui/locales/en/needs.js
@@@ -1,0 -1,17 +1,18 @@@
+ // needs · en
+ export default {
+ title: "Needs you",
+ collapse: "Collapse",
+ viewTask: "View task",
++ viewRule: "View rule",
+ openChat: "Open conversation",
+ reply: "Reply…",
+ approveOnce: "Approve once",
+ deny: "Deny",
+ stop: "Stop",
+ seen: "Got it",
+ relogin: "Scan again",
+ answerPlaceholder: "Your answer",
+ send: "Send",
+ none: "Nothing needs you right now",
+ dismiss: "Don't show again",
+ };
diff --cc ui/locales/en/rules.js
index 0000000,0000000..ee1822c
new file mode 100644
--- /dev/null
+++ b/ui/locales/en/rules.js
@@@ -1,0 -1,0 +1,53 @@@
++// rules · en
++export default {
++ tomorrow: "Tomorrow {time}",
++ weekdayTime: "{day} {time}",
++ mode: { observe: "Observe", act: "Act", off: "Off", on: "On" },
++ sub: "{state} · Next: {next}",
++ running: "{state} · running",
++ queued: "{state} · queued",
++ paused: { one: "Paused · failed {count} time in a row", other: "Paused · failed {count} times in a row" },
++ hint: { one: "Observed {count} time · switch to act?", other: "Observed {count} times · switch to act?" },
++ nowActs: "“{title}” now acts",
++ version: "Version {n}",
++ manual: "Run manually",
++ event: "Event",
++ would: "Would do",
++ steps: "Activity",
++ deleteTitle: "Delete “{title}”?",
++ deleteBody: "Its run log is deleted too.",
++ deleted: "Deleted",
++ next: "Next: {time}",
++ sendsTo: "Sends to {where}",
++ words: "“{text}”",
++ modeLabel: "Mode",
++ runNow: "Run now",
++ observeLeft: { one: "Observes {count} more time, then acts", other: "Observes {count} more times, then acts" },
++ observeHelp: "Observing sends nothing and changes no files, but can't block commands that go online.",
++ log: "Run log",
++ noRuns: "No runs yet",
++ earlier: "Earlier",
++ kinds: { daily: "Daily", weekdays: "Weekdays", weekly: "Weekly", every: "Every", once: "Once", cron: "cron" },
++ createdRemind: "Reminder set",
++ createdCheck: "Rule set. It observes first",
++ editTitle: "Edit rule",
++ newTitle: "New rule",
++ kind: "Type",
++ kindCheck: "Check",
++ kindRemind: "Reminder",
++ name: "Name",
++ namePhCheck: "Check X's price",
++ namePhRemind: "Meeting",
++ wordsCheck: "What to do",
++ wordsRemind: "Reminder text",
++ wordsPhCheck: "Check X's price and tell me if it drops below 200",
++ wordsPhRemind: "Time for the meeting.",
++ when: "When",
++ minutes: "minutes",
++ days: "Days",
++ to: "Send to",
++ noConvs: "Message the bot on WeChat, Feishu or the web first",
++ weixinNote: "WeChat lets the bot message you only within 24 hours of your last message. Otherwise it arrives with your next message and shows on the desktop.",
++ create: "Create",
++ gone: "This rule was deleted",
++};
diff --cc ui/locales/zh-CN/botSettings.js
index 0000000,111af7d..b1ce125
mode 000000,100644..100644
--- a/ui/locales/zh-CN/botSettings.js
+++ b/ui/locales/zh-CN/botSettings.js
@@@ -1,0 -1,119 +1,123 @@@
+ // botSettings · zh-CN:机器人设置(screens/bot-settings.js)
+ export default {
+ back: "返回对话",
+ backTitle: "返回对话(Esc)",
+ title: "机器人设置",
+ identity: "身份",
+ avatar: "头像",
+ avatarHint: "每个角色有自己的小动作",
+ name: "名称",
+ prompt: "人设 / 系统提示词",
+ promptHint: "离开输入框时保存",
+ promptPlaceholder: "例如:你是一个乐于助人的中文助手,回答简洁准确。",
+ model: {
+ head: "模型",
+ default: "默认模型",
+ defaultSub: "会话里还可以临时切换",
+ followGlobal: "跟随全局默认",
+ followGlobalWith: "跟随全局默认({model})",
+ utility: "后台小任务模型",
+ utilitySub: "记忆整理、上下文管家与交接便条",
+ sameAsChat: "与对话模型相同",
+ },
+ budget: {
+ name: "预算",
+ signedOut: "登录 Modelflare 账户后,可以给这个机器人单独设花费上限",
+ signIn: "去登录",
+ off: "与其他机器人共用本机的 Key,不单独限额",
+ on: "用这个机器人自己的 Key,花到上限就停",
+ usage: "已用 {used},还剩 {remain}",
+ exhausted: "已用 {used},还剩 {remain} · 已用完,机器人暂停调用模型",
+ limit: "上限(美元)",
+ limitSub: "包括已经花掉的部分;调高后用完的 Key 会自动恢复",
+ limitLabel: "预算上限(美元)",
+ },
+ perm: {
+ head: "权限",
+ name: "文件权限",
+ workspaceSub: "只能改本机器人工作区,越界操作需要你批准",
+ readonlySub: "不能改文件,命令在只读沙箱中运行",
+ title: "工作区可写(默认):只能改本机器人工作区,越界操作需审批;只读:不能改文件,命令在只读沙箱中运行;完全权限:命令不经沙箱,只有递归删除仍需确认",
+ workspace: "工作区可写",
+ readonly: "只读",
+ full: "完全权限",
+ },
+ memory: {
+ head: "记忆",
+ name: "长期记忆",
+ review: "回合结束后自动整理",
+ reviewLabel: "自动整理记忆",
+ team: "允许写入团队记忆",
+ teamSub: "所有机器人共享",
+ teamLabel: "团队记忆",
+ },
+ context: {
+ head: "上下文",
+ name: "自动压缩或开新段",
+ sub: "上下文变长时整理,并留下交接便条",
+ label: "上下文管家",
+ },
+ computer: {
+ head: "电脑操作",
+ backend: "后端",
+ backendLabel: "电脑操作后端",
+ cuaNote: "随附,macOS / Windows / Linux",
+ codex: "Codex 桥",
+ macOnly: "仅 macOS",
+ macOnlyUnavailable: "仅 macOS,本机不可用",
+ approval: "审批",
+ approvalLabel: "电脑操作审批",
+ autoSub: "所有操作自动执行",
+ askSub: "点击、输入等改变界面的操作先问我;读取界面仍自动",
+ auto: "自动执行",
+ ask: "改变界面前先问我",
+ },
+ danger: {
+ head: "危险操作",
+ delete: "删除机器人",
+ deleteSub: "永久删除这个机器人及其全部会话",
+ },
+ delete: {
+ title: "删除「{name}」?",
+ body: "会永久删除这个机器人及其全部会话,无法恢复。",
+ confirm: "永久删除",
+ },
+ access: {
+ head: "谁能使用",
+ policy: "只有主人和你允许的人",
+ owner: "{channel}主人",
+ reset: "更换",
+ resetOwnerTitle: "更换{channel}主人?",
+ resetOwnerBody: "下一个给机器人发消息的人会成为{channel}主人,「{who}」需要重新被允许。",
+ allowed: "允许名单",
+ denied: "拒绝过的人",
+ deniedSub: "{when}拒绝 · 他再发消息不会收到任何回复",
+ allow: "允许",
+ remove: "移除",
+ removeDeniedTitle: "移除「{who}」?",
+ removeDeniedBody: "移除后他再发消息,会重新出现在信息面板的使用请求里。",
+ revokeTitle: "不再允许「{who}」使用?",
+ revokeBody: "他再发消息时只会收到一句提示,需要你重新允许。",
+ },
+ media: {
+ head: "生图 / 生视频",
+ confirm: "生成前确认",
+ alwaysSub: "每次生成前都问我用哪个模型",
+ autoSub: "默认模型能用、花费不高时直接生成;换模型、预计超过 $0.5 或要求不明确时先问我",
+ auto: "需要时再问",
+ always: "每次都问",
+ },
+ proactive: {
+ head: "主动消息",
+ quiet: "免打扰",
+ quietSub: "后台结果留到结束后再发",
+ quietFrom: "免打扰开始",
+ quietTo: "免打扰结束",
+ nudge: "微信续期提醒",
+ nudgeSub: "还有消息要发时,24 小时到期前请你回一句",
++ rules: "规则",
++ rulesSub: "到点检查或提醒",
++ rulesCount: { other: "{count} 条,在信息面板的「任务」里" },
++ newRule: "新建",
+ },
+ };
diff --cc ui/locales/zh-CN/index.js
index 0000000,b7cb44c..f5fc6da
mode 000000,100644..100644
--- a/ui/locales/zh-CN/index.js
+++ b/ui/locales/zh-CN/index.js
@@@ -1,0 -1,27 +1,28 @@@
+ // zh-CN 文案:每个命名空间一个文件,键 = "命名空间.键"(见 ui/lib/i18n.js)。两种语言的键必须一一对应(test/i18n.unit.test.ts 会查)。
+ import common from "./common.js";
+ import app from "./app.js";
+ import time from "./time.js";
+ import settings from "./settings.js";
+ import account from "./account.js";
+ import pwsh from "./pwsh.js";
+ import chat from "./chat.js";
+ import info from "./info.js";
+ import markdown from "./markdown.js";
+ import notify from "./notify.js";
+ import troubleshoot from "./troubleshoot.js";
+ import onboarding from "./onboarding.js";
+ import newBot from "./newBot.js";
+ import botSettings from "./botSettings.js";
+ import sidebar from "./sidebar.js";
+ import avatar from "./avatar.js";
+ import models from "./models.js";
+ import ui from "./ui.js";
+ import guide from "./guide.js";
+ import activity from "./activity.js";
+ import tasks from "./tasks.js";
+ import needs from "./needs.js";
++import rules from "./rules.js";
+ import access from "./access.js";
+ import perms from "./perms.js";
+
-export default { common, app, time, settings, account, pwsh, chat, info, markdown, notify, troubleshoot, onboarding, newBot, botSettings, sidebar, avatar, models, ui, guide, activity, perms, access, tasks, needs };
++export default { common, app, time, settings, account, pwsh, chat, info, markdown, notify, troubleshoot, onboarding, newBot, botSettings, sidebar, avatar, models, ui, guide, activity, perms, access, tasks, needs, rules };
diff --cc ui/locales/zh-CN/needs.js
index 0000000,557c422..1016417
mode 000000,100644..100644
--- a/ui/locales/zh-CN/needs.js
+++ b/ui/locales/zh-CN/needs.js
@@@ -1,0 -1,17 +1,18 @@@
+ // needs · zh-CN(screens/needs-you.js:「需要你」)
+ export default {
+ title: "需要你",
+ collapse: "收起",
+ viewTask: "查看任务",
++ viewRule: "查看规则",
+ openChat: "打开对话",
+ reply: "回复…",
+ approveOnce: "批准一次",
+ deny: "拒绝",
+ stop: "停止",
+ seen: "知道了",
+ relogin: "重新扫码",
+ answerPlaceholder: "你的回答",
+ send: "发送",
+ none: "没有需要你处理的事",
+ dismiss: "不再提示",
+ };
diff --cc ui/locales/zh-CN/rules.js
index 0000000,0000000..2e37880
new file mode 100644
--- /dev/null
+++ b/ui/locales/zh-CN/rules.js
@@@ -1,0 -1,0 +1,53 @@@
++// rules · zh-CN(components/rules.js:信息面板里规则的行、详情、运行记录,新建 / 编辑规则的对话框)
++export default {
++ tomorrow: "明天 {time}",
++ weekdayTime: "{day} {time}",
++ mode: { observe: "观察", act: "执行", off: "关", on: "开" },
++ sub: "{state} · 下次 {next}",
++ running: "{state} · 正在运行",
++ queued: "{state} · 排队中",
++ paused: { other: "已暂停 · 连续失败 {count} 次" },
++ hint: { other: "已观察 {count} 次 · 改为执行?" },
++ nowActs: "「{title}」改为执行",
++ version: "第 {n} 版",
++ manual: "手动运行",
++ event: "事件",
++ would: "本会做",
++ steps: "处理过程",
++ deleteTitle: "删除「{title}」?",
++ deleteBody: "运行记录一起删除。",
++ deleted: "已删除",
++ next: "下次 {time}",
++ sendsTo: "发到 {where}",
++ words: "「{text}」",
++ modeLabel: "模式",
++ runNow: "立即运行",
++ observeLeft: { other: "改了规则,先观察 {count} 次再执行" },
++ observeHelp: "观察时不发消息、不改文件,但拦不住命令联网。",
++ log: "运行记录",
++ noRuns: "还没有运行过",
++ earlier: "更早的",
++ kinds: { daily: "每天", weekdays: "工作日", weekly: "每周", every: "每隔", once: "一次", cron: "cron" },
++ createdRemind: "已建好提醒",
++ createdCheck: "已建好规则,先观察",
++ editTitle: "编辑规则",
++ newTitle: "新规则",
++ kind: "类型",
++ kindCheck: "检查",
++ kindRemind: "提醒",
++ name: "名称",
++ namePhCheck: "看 X 价格",
++ namePhRemind: "开会",
++ wordsCheck: "要做什么",
++ wordsRemind: "提醒的话",
++ wordsPhCheck: "看看 X 的价格,低于 200 告诉我",
++ wordsPhRemind: "该去开会了。",
++ when: "时间",
++ minutes: "分钟",
++ days: "星期",
++ to: "发到",
++ noConvs: "先在微信、飞书或网页里和机器人说句话",
++ weixinNote: "微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。",
++ create: "建好",
++ gone: "规则已经删了",
++};
diff --cc ui/screens/bot-settings.js
index 88be7a7,8f418de..55e82cc
--- a/ui/screens/bot-settings.js
+++ b/ui/screens/bot-settings.js
@@@ -6,10 -6,10 +6,11 @@@ import { ModelPicker, shortModel } fro
import { api } from "../lib/api.js";
import { confirmSheet, failed, saved } from "../lib/store.js";
import { usd } from "../lib/links.js";
- import { PERMS, FULL_WARNING, confirmPermission } from "../lib/perms.js";
- import { CHANNEL_NAME, SOURCE_LABEL } from "../lib/access.js";
+ import { perms, fullWarning, confirmPermission } from "../lib/perms.js";
+ import { channelName, sourceLabel } from "../lib/access.js";
import { fmtAgo } from "../lib/format.js";
+ import { t } from "../lib/i18n.js";
+import { RuleEditor } from "../components/rules.js";
/** 免打扰的起止:整点 */
const HOURS = Array.from({ length: 24 }, (_, h) => {
@@@ -284,38 -279,34 +285,38 @@@ export function BotSettingsScreen({ bot
<//>
</div>
- <div class="list-head">主动消息</div>
+ <div class="list-head">${t("botSettings.proactive.head")}</div>
<div class="list">
- <${Row} id="quiet" name="免打扰" sub="后台结果留到结束后再发">
- ${s.quietHours.enabled && html`<${MenuButton} label="免打扰开始" value=${s.quietHours.from} width=${120} options=${HOURS}
+ <${Row} id="quiet" name=${t("botSettings.proactive.quiet")} sub=${t("botSettings.proactive.quietSub")}>
+ ${s.quietHours.enabled && html`<${MenuButton} label=${t("botSettings.proactive.quietFrom")} 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}
+ <${MenuButton} label=${t("botSettings.proactive.quietTo")} 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 } })} />
+ <${Switch} label=${t("botSettings.proactive.quiet")} 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 })} />
+ ${bot.weixinEnabled && html`<${Row} id="nudge" name=${t("botSettings.proactive.nudge")} sub=${t("botSettings.proactive.nudgeSub")}>
+ <${Switch} label=${t("botSettings.proactive.nudge")} value=${s.nudge} onChange=${(v) => put({ nudge: v })} />
<//>`}
- <${Row} id="rules" name="规则" sub=${rules && rules.length ? `${rules.length} 条,在信息面板的「任务」里` : "到点检查或提醒"}>
- <button type="button" class="btn" onClick=${() => setNewRule(true)}>新建</button>
++ <${Row} id="rules" name=${t("botSettings.proactive.rules")} sub=${rules && rules.length ? t("botSettings.proactive.rulesCount", { count: rules.length }) : t("botSettings.proactive.rulesSub")}>
++ <button type="button" class="btn" onClick=${() => setNewRule(true)}>${t("botSettings.proactive.newRule")}</button>
+ <//>
</div>
+ ${newRule && html`<${RuleEditor} botId=${bot.id} onClose=${() => setNewRule(false)} onSaved=${() => (setNewRule(false), loadRules())} />`}
- <div class="list-head">电脑操作</div>
+ <div class="list-head">${t("botSettings.computer.head")}</div>
<div class="list">
- <${Row} id="computer" name="电脑操作" sub=${cu ? cu.reason : ""} title=${cu && cu.notice}>
+ <${Row} id="computer" name=${t("botSettings.computer.head")} sub=${cu ? cu.reason : ""} title=${cu && cu.notice}>
<span class=${`dot ${cu && cu.available ? "ok" : "err"}`}></span>
- <${Switch} label="电脑操作" value=${s.computerUse.enabled} onChange=${(v) => put({ computerUse: { enabled: v } })} />
+ <${Switch} label=${t("botSettings.computer.head")} value=${s.computerUse.enabled} onChange=${(v) => put({ computerUse: { enabled: v } })} />
<//>
- <${Row} id="computer-backend" name="后端" off=${!s.computerUse.enabled}>
- <${MenuButton} label="电脑操作后端" value=${s.computerUse.backend} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { backend: v } })}
- options=${[["cua", "Cua Driver", "随附,macOS / Windows / Linux"], ...(codex ? [["codex", "Codex 桥", codex.available ? "仅 macOS" : "仅 macOS,本机不可用"]] : [])]} />
+ <${Row} id="computer-backend" name=${t("botSettings.computer.backend")} off=${!s.computerUse.enabled}>
+ <${MenuButton} label=${t("botSettings.computer.backendLabel")} value=${s.computerUse.backend} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { backend: v } })}
+ options=${[["cua", "Cua Driver", t("botSettings.computer.cuaNote")], ...(codex ? [["codex", t("botSettings.computer.codex"), codex.available ? t("botSettings.computer.macOnly") : t("botSettings.computer.macOnlyUnavailable")]] : [])]} />
<//>
- <${Row} id="computer-approval" name="审批" sub=${s.computerUse.approval === "auto" ? "所有操作自动执行" : "点击、输入等改变界面的操作先问我;读取界面仍自动"} off=${!s.computerUse.enabled}>
- <${Seg} label="电脑操作审批" value=${s.computerUse.approval} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { approval: v } })}
- options=${[["auto", "自动执行"], ["ask-input", "改变界面前先问我"]]} />
+ <${Row} id="computer-approval" name=${t("botSettings.computer.approval")} sub=${s.computerUse.approval === "auto" ? t("botSettings.computer.autoSub") : t("botSettings.computer.askSub")} off=${!s.computerUse.enabled}>
+ <${Seg} label=${t("botSettings.computer.approvalLabel")} value=${s.computerUse.approval} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { approval: v } })}
+ options=${[["auto", t("botSettings.computer.auto")], ["ask-input", t("botSettings.computer.ask")]]} />
<//>
</div>
diff --cc ui/screens/info-panel.js
index b4dbe3e,80ade74..baf5d0e
--- a/ui/screens/info-panel.js
+++ b/ui/screens/info-panel.js
@@@ -5,10 -5,11 +5,12 @@@ import { ActivityLine, currentStep, use
import { PromptCard } from "./chat.js";
import { api } from "../lib/api.js";
import { confirmSheet, failed, saved, toast } from "../lib/store.js";
- import { fmtAgo, fmtDur, fmtTime } from "../lib/format.js";
- import { CHANNEL_NAME } from "../lib/access.js";
+ import { markDone } from "../lib/guide.js";
+ import { fmtAgo, fmtClock, fmtDur, fmtTime } from "../lib/format.js";
+ import { channelName as accessChannel } from "../lib/access.js";
import { TaskRow } from "../components/tasks.js";
+ import { t } from "../lib/i18n.js";
+import { RuleRow } from "../components/rules.js";
export function usePoll(fn, ms, deps = []) {
const [data, setData] = useState(null);
@@@ -220,20 -224,22 +225,26 @@@ export function InfoPanel({ bot, leavin
// 后台任务:只列还没结束的(进行中、等你的);一个都没有时不显示这一组
const [taskData, , reloadTasks] = usePoll(() => api(`/tasks?bot=${encodeURIComponent(bot.id)}&limit=20`), 4000, [bot.id]);
const tasks = (taskData?.tasks || []).filter((t) => t.stage.group !== "ended");
+ // 规则(3d):和任务在同一组;跑完了的一次性规则只留一天
+ const [ruleData, , reloadRules] = usePoll(() => api(`/rules?bot=${encodeURIComponent(bot.id)}`), 6000, [bot.id]);
+ const rules = (ruleData?.rules || []).filter((r) => r.state.key !== "done" || Date.now() - (r.last?.at || r.updatedAt) < 86_400_000);
+ const [openRule, setOpenRule] = useState("");
const [viewing, setViewing] = useState(null);
const pending = (appr && appr.approvals) || [];
- return html`<aside class="panel" aria-label="信息面板">
+ // 上手清单:微信扫码绑定了,或飞书连上了,就算接好了渠道
+ useEffect(() => {
+ const ch = detail && detail.channels;
+ if (ch && (ch.weixin.account || ch.feishu.state === "connected")) markDone("weixin");
+ }, [detail]);
+ // leaving:关上后还在播滑出的那一小会儿(main.js 的 usePresence),不再接收操作
+ return html`<aside class=${`panel${leaving ? " leaving" : ""}`} aria-label=${t("info.aria")} inert=${leaving || undefined}>
<div class="panel-head">
<span class="title">${bot.name}</span>
- <button type="button" class="icon-btn" title="机器人设置" aria-label="机器人设置" onClick=${onOpenBotSettings}><${Icon} name="gear" /></button>
- <button type="button" class="icon-btn" title="关闭(⌘⇧I)" aria-label="关闭信息面板" onClick=${onClose}><${Icon} name="close" /></button>
+ <button type="button" class="icon-btn" title=${t("info.botSettings")} aria-label=${t("info.botSettings")} onClick=${onOpenBotSettings}><${Icon} name="gear" size="md" /></button>
+ <button type="button" class="icon-btn panel-close" title=${t("info.closeTitle")} aria-label=${t("info.closeAria")} onClick=${onClose}><${Icon} name="close" size="md" /></button>
</div>
<div class="panel-body">
- <div class="list-head">渠道</div>
+ <div class="list-head">${t("info.channels")}</div>
<div class="list">
${detail && detail.bot
? html`<${FeishuRow} bot=${detail.bot} st=${detail.channels.feishu} owner=${access ? access.owners.feishu : undefined} reload=${reloadDetail} /><${WeixinRow} bot=${detail.bot} st=${detail.channels.weixin} reload=${reloadDetail} />`
@@@ -242,19 -248,18 +253,19 @@@
<${AccessRequests} botId=${bot.id} data=${access} reload=${reloadAccess} />
- <div class="list-head">待审批${pending.length > 0 && html`<span class="badge count warn">${pending.length}</span>`}</div>
+ <div class="list-head">${t("info.approvals")}${pending.length > 0 && html`<span class="badge count warn">${pending.length}</span>`}</div>
${pending.length
? html`<div class="stack">${pending.map((a) => html`<div key=${a.id} class="stack approval" style="--gap: var(--space-1)">
- <span class="hint">${CHANNEL_NAME[a.conversationId.split(":")[1]] || ""} · ${fmtAgo(a.createdAt)} · 截止 ${fmtTime(a.expiresAt).slice(-8, -3)}</span>
+ <span class="hint">${channelName(a.conversationId.split(":")[1]) || ""} · ${fmtAgo(a.createdAt)} · ${t("info.due", { time: fmtClock(a.expiresAt) })}</span>
<${PromptCard} requestId=${a.id} fallback="" />
</div>`)}
- <button type="button" class="text" style="justify-self:start" onClick=${reloadAppr}>刷新</button></div>`
- : html`<div class="list"><div class="row"><span class="hint">没有待处理的审批</span></div></div>`}
+ <button type="button" class="text" style="justify-self:start" onClick=${reloadAppr}>${t("common.refresh")}</button></div>`
+ : html`<div class="list"><div class="row"><span class="hint">${t("info.noApprovals")}</span></div></div>`}
- ${(tasks.length > 0 || rules.length > 0) && html`<div class="list-head">任务</div>
- ${tasks.length > 0 && html`<div class="list-head">${t("info.tasks")}</div>
++ ${(tasks.length > 0 || rules.length > 0) && html`<div class="list-head">${t("info.tasks")}</div>
<div class="list">${tasks.slice(0, 8).map((t) => html`<${TaskRow} key=${t.id} task=${t} onChanged=${reloadTasks}
- onOpen=${() => (t.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === t.conversationId) || null))} />`)}</div>`}
+ onOpen=${() => (t.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === t.conversationId) || null))} />`)}
+ ${rules.map((r) => html`<${RuleRow} key=${r.id} rule=${r} open=${openRule === r.id} onToggle=${() => setOpenRule(openRule === r.id ? "" : r.id)} onChanged=${reloadRules} />`)}</div>`}
<${MemorySection} botId=${bot.id} />
diff --cc ui/screens/needs-you.js
index 571517c,e80468f..1483cd4
--- a/ui/screens/needs-you.js
+++ b/ui/screens/needs-you.js
@@@ -58,43 -57,32 +59,43 @@@ export function NeedItem({ item, multiB
return html`<div class=${`need${open ? " open" : ""}`}>
<span class=${`dot ${item.severity === "err" ? "err" : "warn"}`} aria-hidden="true"></span>
${canOpen
- ? html`<button type="button" class="need-head" aria-expanded=${expands ? open : undefined} title=${expands ? (open ? "收起" : item.ruleId ? "查看规则" : "查看任务") : "打开对话"} onClick=${head}>${headIn}</button>`
- ? html`<button type="button" class="need-head" aria-expanded=${item.taskId ? open : undefined} title=${item.taskId ? (open ? t("needs.collapse") : t("needs.viewTask")) : t("needs.openChat")} onClick=${head}>${headIn}</button>`
++ ? html`<button type="button" class="need-head" aria-expanded=${expands ? open : undefined} title=${expands ? (open ? t("needs.collapse") : item.ruleId ? t("needs.viewRule") : t("needs.viewTask")) : t("needs.openChat")} onClick=${head}>${headIn}</button>`
: html`<div class="need-head">${headIn}</div>`}
${item.line && html`<div class=${`need-line selectable${item.kind === "approval" ? " mono" : ""}`}>${item.line}</div>`}
<div class="need-actions">
${opts && opts.map((o, i) => html`<${Button} loading=${busy === `o${i}`} disabled=${!!busy} onClick=${() => act("answer", { text: String(i + 1) }, `o${i}`)}>${o.label}<//>`)}
- ${item.kind === "question" && !writing && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => setWriting(true)}>回复…</button>`}
- ${item.kind === "approval" && html`<${Button} variant="primary" loading=${busy === "approve"} disabled=${!!busy} onClick=${() => act("approve")}>批准一次<//>
- <${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 === "rule" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>重试<//>`}
- ${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)}>重新扫码<//>`}
+ ${item.kind === "question" && !writing && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => setWriting(true)}>${t("needs.reply")}</button>`}
+ ${item.kind === "approval" && html`<${Button} variant="primary" loading=${busy === "approve"} disabled=${!!busy} onClick=${() => act("approve")}>${t("needs.approveOnce")}<//>
+ <${Button} loading=${busy === "deny"} disabled=${!!busy} onClick=${() => act("deny")}>${t("needs.deny")}<//>`}
+ ${item.kind === "failed" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>
+ <button type="button" class="text danger" disabled=${!!busy} onClick=${() => act("stop")}>${t("needs.stop")}</button>`}
++ ${item.kind === "rule" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`}
+ ${item.kind === "delivery" && item.actions.includes("retry") && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`}
+ ${item.kind === "delivery" && item.actions.includes("dismiss") && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.dismiss")}</button>`}
+ ${item.kind === "login" && html`<${Button} onClick=${() => onRelogin?.(item.botId)}>${t("needs.relogin")}<//>`}
</div>
${writing && html`<div class="need-reply">
- <input ref=${input} class="field" placeholder="你的回答" value=${text} disabled=${busy === "text"}
+ <input ref=${input} class="field" placeholder=${t("needs.answerPlaceholder")} value=${text} disabled=${busy === "text"}
onInput=${(e) => setText(e.target.value)} onKeyDown=${(e) => {
if (e.key === "Enter" && !e.isComposing) send();
if (e.key === "Escape") (e.stopPropagation(), setWriting(false));
}} />
- <${Button} variant="primary" loading=${busy === "text"} disabled=${!text.trim()} onClick=${send}>发送<//>
+ <${Button} variant="primary" loading=${busy === "text"} disabled=${!text.trim()} onClick=${send}>${t("needs.send")}<//>
</div>`}
${open && item.taskId && html`<div class="need-detail"><${TaskDetail} task=${{ id: item.taskId, title: item.subject, stage: { group: "needs" } }} /></div>`}
+ ${open && item.ruleId && html`<div class="need-detail"><${RuleOpen} id=${item.ruleId} /></div>`}
</div>`;
}
+/** 「需要你」里展开的规则:取到最新的规则再画详情(运行记录、模式、重试) */
+function RuleOpen({ id }) {
+ const [rule, setRule] = useState(null);
+ const load = useCallback(() => api(`/rules/${encodeURIComponent(id)}`).then((d) => setRule(d.rule)).catch(() => setRule(false)), [id]);
+ useEffect(() => void load(), [load]);
- if (rule === false) return html`<span class="hint">规则已经删了</span>`;
++ if (rule === false) return html`<span class="hint">${t("rules.gone")}</span>`;
+ return rule ? html`<${RuleDetail} rule=${rule} onChanged=${load} />` : html`<${Skeleton} w="60%" />`;
+}
+
/** 主区的「需要你」:每 3 秒看一次;处理掉的那件立刻消失(onChanged 让侧栏的件数也跟上) */
export function NeedsYouScreen({ multiBot, onChanged, onOpenChat, onRelogin }) {
const [items, setItems] = useState(null);