Skip to content

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

Phase 3d: rules and observe mode

Marlaeeb4f093286a
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.md
index f8725f3..227649f 100644
--- a/docs/design/background-tasks-and-proactive.md
+++ b/docs/design/background-tasks-and-proactive.md
@@ -1,6 +1,6 @@
# Background tasks and proactive rules (Phase 3 design)
-Status: **3a (task core) is built**: `src/tasks/`, `dsh-runtime/plugins/amb-tasks.mjs`, tests in `test/tasks.*.test.ts`. 3b–3f are still design. Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.
+Status: **3a–3d are built**: tasks, questions and needs-you, delivery, and rules with observe mode (`src/tasks/`, `src/core/delivery.ts`, `dsh-runtime/plugins/amb-tasks.mjs`; tests in `test/tasks.*`, `test/delivery.*`, `test/rules.*`). 3e–3f are still design. Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.
Feasibility evidence is in [Appendix A](#appendix-a-feasibility-answers-with-evidence). The spike that produced it is `scripts/spikes/p3-tasks/`.
## Summary
@@ -250,6 +250,8 @@ The host therefore stores everything it owes a session, and recovers like this:
The time zone is the system's IANA zone, stored on the rule when it is created. The schedule is shown back in words for confirmation, for example 「每个工作日 08:00(Asia/Shanghai)」.
+**Triggers (as built in 3d).** A rule's trigger is a tagged union: `{kind: "schedule", schedule}` (the host timer below) or `{kind: "event", source, filter?}`. Event rules are started through `RuleEvents.emit(source, event)` (`src/tasks/rule-events.ts`) and run through the same observe/act path. This is only the extension point for user-configured event sources ("workloads", such as a GitHub repo) that come later; no event source, workload config or UI is built yet.
+
**Mechanics.**
- `rules.next_run_at` holds the next time, and a single timer is set for the earliest one.
diff --git a/dsh-runtime/plugins/amb-permission.mjs b/dsh-runtime/plugins/amb-permission.mjs
index a5d2bae..3f2a7af 100644
--- a/dsh-runtime/plugins/amb-permission.mjs
+++ b/dsh-runtime/plugins/amb-permission.mjs
@@ -4,14 +4,23 @@
// bot's preset in the web UI (DSH_PERMISSION_MODE) would only affect new conversations. Before any
// tool runs we re-apply the configured preset to the calling session, so a switch to read-only
// takes effect in existing chats too.
+//
+// Rule sessions (3d) and their subagents get their own preset from the host (observe: read-only; act: at most
+// workspace-write, even on a full-permission bot); amb-tasks puts it in a shared per-session map.
export const name = 'amb-permission'
export const inject = ['permissionPresets']
+/** Shared with amb-tasks: sessionId → preset for rule sessions. */
+const PRESETS = Symbol.for('amb.session.presets')
+
export function apply(ctx) {
- const want = process.env.DSH_PERMISSION_MODE || 'workspace-write'
+ const fallback = process.env.DSH_PERMISSION_MODE || 'workspace-write'
+ const presets = (globalThis[PRESETS] ??= new Map())
ctx.on('tools/pre-execute', (exec, next) => {
const session = exec?.agent?.session
if (session) {
+ // a rule session whose config never arrived is not in the map: it is refused by amb-tasks anyway
+ const want = presets.get(String(session.id ?? exec?.agent?.id ?? '')) ?? (/^rule-/.test(String(session.id ?? '')) ? 'read-only' : fallback)
try {
if (ctx.permissionPresets.current(session) !== want) ctx.permissionPresets.set(session, want)
} catch (e) {
diff --git a/dsh-runtime/plugins/amb-tasks.mjs b/dsh-runtime/plugins/amb-tasks.mjs
index b54e2c7..894df99 100644
--- a/dsh-runtime/plugins/amb-tasks.mjs
+++ b/dsh-runtime/plugins/amb-tasks.mjs
@@ -9,7 +9,14 @@
// - registers task_report, which reports the task's state to the host (needs_you carries one question for the
// user; the host asks it and hands the answer back as the session's next input),
// - refuses every tool call once the host has stopped the task.
-// Chat sessions get task_start / task_message / task_list; subagents get none of the task tools.
+// Chat sessions get task_start / task_message / task_list and rule_create / rule_update; subagents get none of them.
+//
+// Rule sessions (`rule-<rule>-<run>`, one fresh session per run of a standing rule, 3d) are decorated from the host's
+// answer to /dsh/task-config (the host owns the mode): the denied tools (observe denies everything that acts), the rule
+// section, a rule variant of task_report (done with or without a message, failed, progress; no needs_you) and the
+// session's sandbox (observe: read-only; act: at most workspace-write), which amb-permission applies before every tool
+// call through a shared per-session map. Subagents of a rule session inherit its config. If the host cannot be
+// reached the session fails closed: read-only and every tool refused.
//
// Settling: when a task session goes idle the host asks `task-quiet` over the control channel (amb-control hands
// the ops it does not know to this plugin). A session that still owns running background jobs or subagents is not
@@ -23,9 +30,11 @@ export const inject = ['tools']
/** Shared with amb-control: control-channel ops this plugin answers. */
export const HANDLERS = Symbol.for('amb.control.handlers')
-export const CHAT_TOOLS = ['task_start', 'task_message', 'task_list']
+export const CHAT_TOOLS = ['task_start', 'task_message', 'task_list', 'rule_create', 'rule_update']
/** Tools a task session never gets (filtered to registered names before tools.restrict). */
-export const TASK_DENY = ['present', 'ask_user_question', 'rule_create', ...CHAT_TOOLS]
+export const TASK_DENY = ['present', 'ask_user_question', ...CHAT_TOOLS]
+/** Shared with amb-permission: sessionId → DSH permission preset for rule sessions (and their subagents). */
+export const PRESETS = Symbol.for('amb.session.presets')
export const SECTION = 'amb:task'
/** After the bot's section (amb:bot, 20000): the task rules win over the chat rules. */
export const ORDER = 20_100
@@ -35,6 +44,9 @@ const WATCH_MS = 1_000
const live = (status) => status === 'running' || status === 'stopping'
export const isTask = (id) => /^task-/.test(String(id ?? ''))
+export const isRule = (id) => /^rule-/.test(String(id ?? ''))
+/** Rule session when the host cannot be reached: read-only, every tool refused (fail closed). */
+const RULE_FALLBACK = { mode: 'observe', deny: [], denyPrefix: [], section: '', permission: 'read-only', offline: true }
function bridge() {
const url = process.env.AMB_BRIDGE_URL
@@ -65,6 +77,9 @@ export function apply(ctx) {
const stopped = new Set()
/** task sessions being watched until they are quiet: id → { since, timer } */
const watching = new Map()
+ /** rule sessions and their subagents: id → the host's config for the run */
+ const ruleConfigs = new Map()
+ const presets = (globalThis[PRESETS] ??= new Map())
const agents = () => ctx.get('agents')
const jobs = () => ctx.get('jobs')
@@ -103,11 +118,37 @@ export function apply(ctx) {
}))
ctx.tools.register(defineTool({
name: 'task_list',
- description: 'List this chat\'s background tasks with their state and latest result.',
+ description: 'List this chat\'s background tasks and rules with their state and latest result.',
parameters: {},
output: TEXT_OUT,
execute: tool('list'),
}))
+ ctx.tools.register(defineTool({
+ name: 'rule_create',
+ description: 'Set up a standing rule the user asks for: a recurring check (kind check; it tells the user only when it matters, and starts in observe mode, only recording what it would say) or a fixed reminder (kind remind: sends message at the time). Confirm in one sentence.',
+ parameters: {
+ title: { type: 'string', required: true, description: 'Short, e.g. 看 X 价格.' },
+ instruction: { type: 'string', required: true, description: 'The user\'s words, verbatim.' },
+ schedule: { type: 'string', required: true, description: 'Local time: 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' },
+ kind: { type: 'string', enum: ['check', 'remind'] },
+ message: { type: 'string', description: 'remind: the line to send.' },
+ },
+ output: TEXT_OUT,
+ execute: tool('rule_create'),
+ }))
+ ctx.tools.register(defineTool({
+ name: 'rule_update',
+ description: 'Change a rule of this chat when the user asks: mode act (results are sent), observe (only records) or off; new instruction or schedule; or delete.',
+ parameters: {
+ rule: { type: 'string', required: true, description: 'Rule id or part of its title.' },
+ mode: { type: 'string', enum: ['observe', 'act', 'off'] },
+ instruction: { type: 'string' },
+ schedule: { type: 'string' },
+ delete: { type: 'boolean' },
+ },
+ output: TEXT_OUT,
+ execute: tool('rule_update'),
+ }))
}
const known = (names) => {
@@ -136,14 +177,66 @@ export function apply(ctx) {
execute: (args, exec) => host('/dsh/task-report', { sessionId: sessionOf(exec), ...args }, exec.signal),
})
+ const ruleReportTool = (mode) => defineTool({
+ name: 'task_report',
+ description: `Report this check to the app. done: finished; message is the one line for the user (at most 300 characters, in their language) only when they should hear about it${mode === 'observe' ? ' (observe mode: it is only recorded)' : ''}; leave it out to stay quiet. failed: you could not check, with the reason. progress is recorded, never sent. Then end your turn.`,
+ parameters: {
+ state: { type: 'string', required: true, enum: ['progress', 'done', 'failed'] },
+ summary: { type: 'string', required: true, description: 'What you checked and found, for the record.' },
+ message: { type: 'string', description: 'For done: the one line for the user, or nothing.' },
+ ...(mode === 'observe' ? { would: { type: 'string', description: 'What you would have done if you could act.' } } : {}),
+ },
+ output: TEXT_OUT,
+ execute: (args, exec) => host('/dsh/task-report', { sessionId: sessionOf(exec), ...args }, exec.signal),
+ })
+
+ /** The host's config for a rule run (mode, denied tools, section, sandbox); fail closed when it cannot be reached. */
+ async function ruleConfig(id) {
+ if (!call) return RULE_FALLBACK
+ try {
+ const r = await call('/dsh/task-config', { botId, sessionId: id }, AbortSignal.timeout(10_000))
+ if (r?.error || r?.kind !== 'rule') throw new Error(String(r?.error ?? 'not a rule session'))
+ return { mode: r.mode === 'act' ? 'act' : 'observe', deny: r.deny ?? [], denyPrefix: r.denyPrefix ?? [], section: String(r.section ?? ''), permission: r.permission === 'workspace-write' ? 'workspace-write' : 'read-only' }
+ } catch (e) {
+ ctx.logger?.warn?.(`amb-tasks: no config for rule session ${id}: ${e?.message ?? e}`)
+ return RULE_FALLBACK
+ }
+ }
+
+ /** Deny the rule's tools (exact names; computer use by prefix) and pin its sandbox; the same for its subagents. */
+ function applyRule(agent, id, cfg, root) {
+ ruleConfigs.set(id, { ...cfg, root })
+ presets.set(id, cfg.permission)
+ // the guard first: if anything below fails, the session is still refused what it must not do
+ agent.ctx.tools.guard?.((exec) => {
+ if (cfg.offline) return 'The app cannot be reached, so this check cannot run. End your turn.'
+ if (stopped.has(root)) return 'This check was stopped. End your turn.'
+ const name = String(exec?.name ?? exec?.tool?.name ?? '')
+ if (cfg.denyPrefix.some((p) => name.startsWith(p)) || cfg.deny.includes(name)) return 'This tool is not available while running a rule.'
+ return undefined
+ })
+ const deny = known([...new Set([...TASK_DENY, ...cfg.deny])])
+ if (deny.length) agent.ctx.tools.restrict({ deny })
+ }
+
// ---------- decorate task sessions (created over the SDK, or resumed after a restart) ----------
const decorated = new WeakSet()
- ctx.on('agent/created', ({ agent }) => {
+ ctx.on('agent/created', async ({ agent }) => {
if (!agent || decorated.has(agent)) return
decorated.add(agent)
const id = String(agent.id ?? '')
+ const parent = agent.session?.header?.parentSession
try {
- if (isTask(id)) {
+ if (isRule(id)) {
+ const cfg = await ruleConfig(id)
+ applyRule(agent, id, cfg, id)
+ if (cfg.section) agent.ctx.systemPrompt?.section({ name: SECTION, order: ORDER, interpolate: false, text: () => cfg.section })
+ if (call && !cfg.offline) agent.ctx.tools.register(ruleReportTool(cfg.mode))
+ } else if (parent && ruleConfigs.has(String(parent))) {
+ // a subagent of a rule session (or of its subagent): same sandbox and denied tools
+ const cfg = ruleConfigs.get(String(parent))
+ applyRule(agent, id, cfg, cfg.root)
+ } else if (isTask(id)) {
const deny = known(TASK_DENY)
if (deny.length) agent.ctx.tools.restrict({ deny })
if (rules) agent.ctx.systemPrompt?.section({ name: SECTION, order: ORDER, interpolate: false, text: () => rules })
@@ -246,7 +339,12 @@ export function apply(ctx) {
}
try {
- ctx.on('agent/disposed', ({ agent }) => unwatch(String(agent?.id ?? '')))
+ ctx.on('agent/disposed', ({ agent }) => {
+ const id = String(agent?.id ?? '')
+ unwatch(id)
+ ruleConfigs.delete(id)
+ presets.delete(id)
+ })
ctx.on('dispose', () => {
for (const id of [...watching.keys()]) unwatch(id)
delete handlers['task-quiet']
diff --git a/electron/main.ts b/electron/main.ts
index 8710d8a..1d87abd 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -8,7 +8,7 @@
* - 设置页里的开机自启、缩放、打开数据目录经 core.desktop 回调到这里(同进程,无需 preload/IPC)
* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。
*/
-import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, net, shell, dialog, safeStorage } from "electron";
+import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, net, powerMonitor, shell, dialog, safeStorage } from "electron";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
@@ -208,6 +208,9 @@ async function boot(): Promise<void> {
};
await core.start();
if (!core.web) throw new Error("管理界面未启动");
+ // 规则的定时器:电脑醒来、解锁时马上重新看一遍(睡着时错过的按宽限期补跑一次或记为跳过)
+ 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 --git a/src/agent/approvals.ts b/src/agent/approvals.ts
index 5d2d2b3..1aa4956 100644
--- a/src/agent/approvals.ts
+++ b/src/agent/approvals.ts
@@ -140,6 +140,8 @@ export class ApprovalCenter {
reason: string;
payload?: string;
taskId?: string;
+ /** 规则(3d)执行时的审批:只在「需要你」里,不进聊天回合 */
+ ruleId?: string;
runId?: string;
blocking?: boolean;
ttlMs?: number;
@@ -160,12 +162,13 @@ export class ApprovalCenter {
createdAt: now,
expiresAt: ttl === 0 ? 0 : now + ttl,
taskId: input.taskId ?? "",
+ ruleId: input.ruleId ?? "",
runId: input.runId ?? "",
blocking: input.blocking !== false,
});
- log.info(`${row.kind} ${row.code} created`, { bot: row.botId, tool: row.tool, ...(row.taskId ? { task: row.taskId } : {}) });
- // 聊天回合的提示进这一轮的回复;任务的由任务服务推(不混进同一会话里正在进行的聊天回复)
- const sink = row.taskId ? undefined : this.sinks.get(row.conversationId);
+ log.info(`${row.kind} ${row.code} created`, { bot: row.botId, tool: row.tool, ...(row.taskId ? { task: row.taskId } : {}), ...(row.ruleId ? { rule: row.ruleId } : {}) });
+ // 聊天回合的提示进这一轮的回复;任务的由任务服务推(不混进同一会话里正在进行的聊天回复);规则的只在「需要你」里
+ const sink = row.taskId || row.ruleId ? undefined : this.sinks.get(row.conversationId);
if (sink) void sink(row).catch((e) => log.warn("prompt sink failed", { message: (e as Error).message }));
this.emit({ type: "created", row });
return row;
@@ -243,7 +246,7 @@ export class ApprovalCenter {
/** 这个会话里聊天回合在等的(不含后台任务的):中止、/reset 只作废这些 */
pendingChat(conversationId: string): ApprovalRow[] {
- return this.pending(conversationId).filter((r) => !r.taskId);
+ return this.pending(conversationId).filter((r) => !r.taskId && !r.ruleId);
}
/** 这个任务还在等的提问和审批 */
@@ -268,7 +271,7 @@ export class ApprovalCenter {
const t = text.trim();
if (!t || t.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 --git a/src/agent/bridge.ts b/src/agent/bridge.ts
index e876c5f..71ad5be 100644
--- a/src/agent/bridge.ts
+++ b/src/agent/bridge.ts
@@ -25,8 +25,8 @@ export interface BridgeHandlers {
control?: { poll(body: any, signal: AbortSignal): Promise<unknown>; result(body: any): void };
/** 服务端压缩:长会话的 /v1/responses 换上上游压缩过的历史(见 server-compaction.ts) */
compaction?: ServerCompaction;
- /** amb-tasks 插件:task_report(report)、收尾结束(settled)、聊天代理的任务工具(tool) */
- tasks?(route: "report" | "settled" | "tool", body: any): Promise<unknown>;
+ /** amb-tasks 插件:task_report(report)、收尾结束(settled)、聊天代理的任务工具(tool)、规则会话的配置(config) */
+ tasks?(route: "report" | "settled" | "tool" | "config", body: any): Promise<unknown>;
}
/** 模型代理的一次请求(故障排查的"测试代理"用它判断模型调用这一步) */
@@ -51,7 +51,7 @@ export const BOT_HEADER = "x-amb-bot";
* - /v1/*:模型代理(Chat Completions、Responses、Anthropic Messages),把令牌换成真实网关密钥(子进程环境里没有任何真实密钥)
* - /dsh/ask|wait|cancel:amb-bridge 插件的审批/提问长轮询
* - /dsh/control/poll|result:amb-control 插件取宿主的指令(中止、插话、换模型)并回报
- * - /dsh/task-report|task-settled|task-tool:amb-tasks 插件(后台任务的报告、收尾结束、聊天代理的任务工具)
+ * - /dsh/task-report|task-settled|task-tool|task-config:amb-tasks 插件(后台任务的报告、收尾结束、聊天代理的任务工具、规则会话的配置)
*/
export class AgentBridge {
readonly token = crypto.randomBytes(24).toString("base64url");
@@ -277,6 +277,7 @@ export class AgentBridge {
else if (url === "/dsh/task-report" && this.h.tasks) out = await this.h.tasks("report", body);
else if (url === "/dsh/task-settled" && this.h.tasks) out = await this.h.tasks("settled", body);
else if (url === "/dsh/task-tool" && this.h.tasks) out = await this.h.tasks("tool", body);
+ else if (url === "/dsh/task-config" && this.h.tasks) out = await this.h.tasks("config", body);
else return void res.writeHead(404).end();
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(out));
}
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 1d62c9d..e4543a4 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -1572,12 +1572,12 @@ exec "$REAL" "$@"
return this.taskRoot({ method: "session.event", params: { sessionId } } as SdkNotification);
}
- /** 通知属于哪个任务会话(task-* 本身,或它的子代理);不属于任务就是 undefined */
+ /** 通知属于哪个任务会话(task-* 本身、规则的 rule-*,或它们的子代理);不属于任务就是 undefined */
private taskRoot(n: SdkNotification): string | undefined {
const sub = n.method === "subagent.started" || n.method === "subagent.finished";
const sid = String((sub ? n.params?.parentSessionId : n.params?.sessionId) ?? "");
if (!sid) return undefined;
- if (sid.startsWith("task-")) return sid;
+ if (sid.startsWith("task-") || sid.startsWith("rule-")) return sid;
if (!this.taskSessions.size) return undefined;
const c = this.harness?.client;
if (typeof c?.isDescendantOf !== "function") return undefined;
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index 4773636..0eda731 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -12,6 +12,7 @@ import type { MediaModel, MediaPlan, MediaService } from "./media.js";
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 {
HANDOFF_SYSTEM,
@@ -28,6 +29,9 @@ import {
const log = logger("agent");
+/** 规则观察时的审批:不建审批行,直接按拒绝回给插件(id 以它开头) */
+const AUTO_REJECT = "auto-reject:";
+
export interface AgentManagerOptions {
store: Store;
dataDir: string;
@@ -191,6 +195,7 @@ export class AgentManager {
if (route === "report") return t.report(b);
if (route === "settled") return t.settled(b);
if (route === "tool") return t.chatTool(b);
+ if (route === "config") return t.sessionConfig(b);
return { error: "unknown route" };
},
});
@@ -622,7 +627,7 @@ export class AgentManager {
private async mediaOp(b: any): Promise<{ text?: string; error?: string }> {
const botId = String(b?.botId ?? "");
// 后台任务里还不能生成(确认要问用户,3b 才有任务的提问)
- if (String(b?.sessionId ?? "").startsWith("task-")) return { error: "生成图片和视频暂时只能在聊天里用,后台任务里不行;需要的话在结果里告诉用户。" };
+ if (/^(task|rule)-/.test(String(b?.sessionId ?? ""))) return { error: "生成图片和视频暂时只能在聊天里用,后台任务里不行;需要的话在结果里告诉用户。" };
if (!this.hosts.has(botId) || !this.activeConvs.get(botId)?.size) return { error: "unknown bot" };
const media = this.o.media;
if (!media) return { error: "生成图片和视频需要连接 Modelflare" };
@@ -906,12 +911,19 @@ export class AgentManager {
return this.tasks?.taskOfSession(sessionId, this.hosts.get(botId)?.taskRootOf(sessionId));
}
+ /** 规则会话或它的子代理属于哪条规则、哪次运行 */
+ private ruleOf(botId: string, sessionId: string) {
+ return this.tasks?.ruleOfSession(sessionId, this.hosts.get(botId)?.taskRootOf(sessionId));
+ }
+
private resolveConversation(botId: string, sessionId: string): string {
const c = this.o.store.conversationForSession(sessionId);
if (c) return c;
// 后台任务会话(和它的子代理):落到请求它的会话
const task = this.taskOf(botId, sessionId);
if (task) return task.conversationId;
+ const rule = this.ruleOf(botId, sessionId);
+ if (rule) return rule.conversationId;
const active = [...(this.activeConvs.get(botId) ?? [])];
return active.length === 1 ? active[0] : "";
}
@@ -923,8 +935,10 @@ export class AgentManager {
const conversationId = this.resolveConversation(botId, sessionId);
// 后台任务里来的:记下是哪个任务、哪个 run,由任务服务推给用户;没人在旁边看,等 12 小时
const t = this.o.store.conversationForSession(sessionId) ? undefined : this.taskOf(botId, sessionId);
- const task = t ? { taskId: t.taskId, runId: t.runId, ttlMs: TASK_APPROVAL_TTL_MS } : {};
- if (b?.kind === "question") {
+ // 规则(3d):观察时一律自动拒绝,记成「需要批准:…」;执行时进「需要你」,等 1 小时
+ const rule = t || this.o.store.conversationForSession(sessionId) ? undefined : this.ruleOf(botId, sessionId);
+ const task = t ? { taskId: t.taskId, runId: t.runId, ttlMs: TASK_APPROVAL_TTL_MS } : rule ? { ruleId: rule.ruleId, runId: rule.runId, ttlMs: RULE_APPROVAL_TTL_MS } : {};
+ if (b?.kind === "question" && !rule) {
const qs = (Array.isArray(b.questions) ? b.questions : []) as QuestionItem[];
const row = this.approvals.create({ kind: "question", botId, conversationId, sessionId, tool: "ask_user_question", detail: qs.map((q) => q.question).join(" / "), reason: "", payload: JSON.stringify(qs), ...task });
return { id: row.id };
@@ -936,6 +950,11 @@ export class AgentManager {
await new Promise((r) => setTimeout(r, 50));
call = host.calls.get(callId);
}
+ // 观察时(规则会话里也没人能回答提问):不建审批,直接拒绝,记成「需要批准:…」
+ if (rule && (rule.mode === "observe" || b?.kind === "question")) {
+ this.tasks!.wouldNeedApproval(rule.runId, call ? callDetail(call.name, call.args) : String(b?.toolName ?? b?.reason ?? ""));
+ return { id: `${AUTO_REJECT}${crypto.randomUUID()}` };
+ }
const tool = String(b?.toolName ?? call?.name ?? "tool");
const row = this.approvals.create({
kind: "approval",
@@ -952,6 +971,7 @@ export class AgentManager {
private async wait(b: any): Promise<Record<string, unknown>> {
const id = String(b?.id ?? "");
+ if (id.startsWith(AUTO_REJECT)) return { done: true, outcome: "rejected", answer: null };
const row = await this.approvals.wait(id, Math.min(Number(b?.timeoutMs) || 20_000, 25_000));
if (!row) return { done: true, outcome: "rejected", answer: null };
if (row.status === "pending") return { done: false };
diff --git a/src/agent/prompts/index.ts b/src/agent/prompts/index.ts
index 6967b8e..13ce56a 100644
--- a/src/agent/prompts/index.ts
+++ b/src/agent/prompts/index.ts
@@ -1,8 +1,9 @@
/**
- * 交给代理模型的提示词都在这个目录:系统提示词(system.ts)、每段第一条消息(segment.ts)、技能说明(skills.ts)、后台任务(tasks.ts)。
+ * 交给代理模型的提示词都在这个目录:系统提示词(system.ts)、每段第一条消息(segment.ts)、技能说明(skills.ts)、后台任务(tasks.ts)、规则(rules.ts)。
* 工具说明在 dsh-runtime/plugins/*.mjs 里,和工具定义放在一起。
*/
export * from "./system.js";
export * from "./segment.js";
export * from "./skills.js";
export * from "./tasks.js";
+export * from "./rules.js";
diff --git a/src/agent/prompts/rules.ts b/src/agent/prompts/rules.ts
new file mode 100644
index 0000000..148a8bf
--- /dev/null
+++ b/src/agent/prompts/rules.ts
@@ -0,0 +1,68 @@
+/**
+ * 规则(3d)的提示词:规则会话的系统提示词段(amb-tasks 插件经 /dsh/task-config 取,加在机器人段之后)、每次运行的第一条输入、
+ * 没有报告时的提醒、重启后重跑的说明,以及用主模型写那一句结果的提示词。改这里的文字要过 test/prompts.unit.test.ts。
+ *
+ * 每次运行是一个新会话:连续性来自宿主给的最近 3 次结果和(执行时)规则的文件夹。观察时只看不动,message 只记成「本会发送」;
+ * 执行时 message 会发给用户。检查用机器人的小模型跑,真要发的那一句由主模型来写(产品负责人的决定 5)。
+ */
+
+export type RuleRunMode = "observe" | "act";
+
+/** 规则会话的系统提示词段(观察 / 执行) */
+export function ruleRules(mode: RuleRunMode): string {
+ const lines = [
+ "# 规则(优先于上面的聊天规则)",
+ "你在按用户写的一条规则做一次例行检查,用户不在旁边。规则原话和最近几次的结果在第一条消息里;当前目录是这条规则的文件夹。",
+ mode === "observe"
+ ? "- 这次是观察:只看、只查,不改任何东西(不写文件、不发消息、不调用会改动东西的接口)。本来要做的事写进 would。"
+ : "- 只做规则里写的事。做会改变外部的事之前和之后,各在 .task/journal.md 里追加一行。",
+ `- 查完调用 task_report:值得告诉用户就 state 为 done,message 是给用户的一句话(不超过 300 字${mode === "observe" ? ",这次只记下来" : ",会发给用户"});不值得说就 done 不带 message。查不了报 failed 和原因。然后结束这一轮。`,
+ "- 不调用 task_report,这次就算失败。",
+ ];
+ return lines.join("\n");
+}
+
+export interface RuleBriefInput {
+ title: string;
+ /** 时间表的话(每天 08:00);事件触发的是事件源 */
+ when: string;
+ /** 用户的原话 */
+ instruction: string;
+ mode: RuleRunMode;
+ /** 最近几次的结果(旧→新):时间和一句话 */
+ recent: Array<{ at: string; line: string }>;
+ /** 事件触发:来源和内容(JSON) */
+ event?: { source: string; payload: string };
+ /** 冻结的记忆快照;undefined = 关着记忆 */
+ memory?: string;
+}
+
+const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+
+/** 每次运行的第一条输入:规则、用户原话、最近几次的结果、这次是观察还是执行 */
+export function ruleBrief(o: RuleBriefInput): string {
+ const parts = [`[规则]\n${o.title}(${o.when})`, `[用户的原话]\n${o.instruction.trim()}`];
+ if (o.recent.length) parts.push(`[最近几次的结果]\n${o.recent.map((r) => `- ${r.at}:${clip(r.line.replace(/\s+/g, " ").trim(), 300)}`).join("\n")}`);
+ if (o.event) parts.push(`[事件]\n来源:${o.event.source}\n${clip(o.event.payload, 2000)}`);
+ if (o.memory !== undefined) parts.push(`[长期记忆快照]\n${o.memory.trim() || "(目前为空)"}`);
+ parts.push(o.mode === "observe" ? "[这次]\n观察:只看不动,message 只记下来,不会发给用户。" : "[这次]\n执行:message 会发给用户。");
+ return parts.join("\n\n");
+}
+
+/** 一轮结束了却没有 task_report:提醒一次 */
+export const RULE_NUDGE = "Report this check with task_report now: state done with a one-line message if the user should hear about it, done without a message to stay quiet, or failed with the reason if you could not check.";
+
+/** 上一次运行被应用重启打断了,这次重跑(新会话):重复外部动作之前先看日志 */
+export const RULE_RERUN =
+ "[说明]\n上一次运行被应用重启打断了,这是重跑。重复会改变外部的事之前,先看这个文件夹里的 .task/journal.md 和外部系统。";
+
+/** 用主模型写那一句结果(检查用的是小模型):系统提示词 */
+export const RULE_RESULT_SYSTEM = [
+ "你替用户的个人助手写一条主动发给用户的消息。下面是用户写的一条规则、这次检查的记录和草稿。",
+ "只输出这一句话:用用户的语言,先说结果(数字、变化、要做什么),不超过 120 字;不说过程,不提规则和检查本身,不加表情符号。",
+].join("\n");
+
+/** 用主模型写那一句结果:用户消息 */
+export function ruleResultInput(o: { instruction: string; summary: string; draft: string }): string {
+ return `[规则]\n${o.instruction.trim()}\n\n[这次检查的记录]\n${clip(o.summary.trim(), 2000) || "(没有)"}\n\n[草稿]\n${o.draft.trim()}`;
+}
diff --git a/src/app.ts b/src/app.ts
index c4b72b3..1e1567a 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -44,6 +44,8 @@ import { MediaService, pickDefault } from "./agent/media.js";
import { COMPACT_ENDPOINT, serverCompactionEnabled, type CompactEndpoint } from "./agent/server-compaction.js";
import type { BotSettings } from "./agent/settings.js";
import { TaskService } from "./tasks/service.js";
+import { RuleEvents } from "./tasks/rule-events.js";
+import { lockDataDir, type DataDirLock } from "./store/lock.js";
import { Attention, approvalItems, deliveryItem, type AttentionItem } from "./tasks/attention.js";
const log = logger("app");
@@ -129,8 +131,10 @@ export class App {
readonly delivery: Delivery;
/** 谁能和机器人对话:主人 + 允许名单 + 使用请求 */
readonly access: AccessControl;
- /** 后台任务:自己的会话和文件夹,结果经出站队列回到请求它的会话 */
+ /** 后台任务:自己的会话和文件夹,结果经出站队列回到请求它的会话;规则(3d)也由它跑(定时器是 tasks.scheduler) */
readonly tasks: TaskService;
+ /** 事件触发的规则的入口:以后用户配置的 workload(事件源)在这里把事件交进来(见 tasks/rule-events.ts) */
+ readonly ruleEvents: RuleEvents;
/** "需要你":所有机器人里在等人的事(侧栏、托盘角标、系统通知) */
readonly attention: Attention;
web: WebServer | undefined;
@@ -145,6 +149,8 @@ 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 = {}) {
// 日志文件:<dataDir>/logs/app.log(打包后的桌面版看不到 stdout,故障排查全靠它)
@@ -234,11 +240,20 @@ export class App {
defaultModel: () => this.config.llm.defaultModel,
route: (botId, model) => this.routeModel(botId, model),
maxBackground: config.agent.maxBackground,
+ // 规则:检查用小模型,真要发的那一句用主模型写(决定 5)
+ complete: (botId, model, system, user) =>
+ this.models.streamChat(
+ { model: this.routeModel(botId, model), messages: [{ role: "system", content: system }, { role: "user", content: user }], signal: AbortSignal.timeout(120_000) },
+ () => {},
+ ),
+ timeZone: opts.timeZone,
});
this.agent.tasks = this.tasks;
- // "需要你"的四份:在等的提问和审批、任务(失败、预算)、没送到的结果(出站队列)、渠道(微信登录过期)
+ this.ruleEvents = new RuleEvents(this.tasks);
+ // "需要你"的五份:在等的提问和审批、任务(失败、预算)、规则(连续失败、暂停了)、没送到的结果(出站队列)、渠道(微信登录过期)
this.attention.addSource(() => approvalItems(this.store, this.agent.approvals.pendingAll()));
this.attention.addSource(() => this.tasks.attention());
+ this.attention.addSource(() => this.tasks.ruleAttention());
this.attention.addSource(() => this.delivery.attentionItems().map((d) => deliveryItem(d, this.store.getBot(d.botId)?.name ?? d.botId)));
this.attention.addSource(() => this.loginAttention());
this.agent.approvals.listen(() => this.attention.kick());
@@ -474,6 +489,8 @@ export class App {
}
async start(): Promise<void> {
+ // 同一个数据目录只能有一个宿主(两个调度器会把规则跑两遍、两个渠道连接抢同一个微信):桌面版另有单实例锁
+ this.lock ??= lockDataDir(this.config.dataDir);
if (this.magpie) {
try {
await this.magpie.start();
@@ -565,6 +582,8 @@ export class App {
await this.agent.stop();
await this.magpie?.stop();
this.store.close();
+ this.lock?.release();
+ this.lock = undefined;
}
get username(): string {
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index 3892ae4..41c940d 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -111,8 +111,8 @@ const HELP = [
"/new — 开始新的一段对话:旧对话归档并生成交接便条,长期记忆保留",
"/status — 查看当前模型、代理状态和正在处理的消息走到了哪一步",
"/stop — 中止正在处理的消息(只停这个会话,机器人的其它会话照常进行)",
- "/tasks — 列出这个会话的后台任务",
- "/stop <编号> — 停止 /tasks 里的一个后台任务",
+ "/tasks — 列出这个会话的后台任务和规则",
+ "/stop <编号> — 停止 /tasks 里的一个后台任务或规则",
"/help — 显示本帮助",
].join("\n");
diff --git a/src/store/db.ts b/src/store/db.ts
index 0d15641..45b8dc9 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -3,6 +3,7 @@ import path from "node:path";
import { randomUUID } from "node:crypto";
import { DatabaseSync } from "node:sqlite";
import { normalizeSettings, type BotSettings } from "../agent/settings.js";
+import type { Schedule } from "../tasks/schedule.js";
/**
* SQLite 存储(node:sqlite,无原生模块,Electron 下也无需 rebuild)。
@@ -89,6 +90,8 @@ export interface ApprovalRow {
decidedAt: number;
/** 后台任务的(任务会话或它的子代理里来的,或任务报的 needs_you 提问);聊天里的是空 */
taskId: string;
+ /** 规则(3d)执行时的审批:属于哪条规则(runId 是那次运行);只在「需要你」里,不推、不进聊天回合 */
+ ruleId: string;
runId: string;
/** true:有一次 DSH 调用在等它(审批、聊天里的提问);false:任务的提问,回答作为任务的新输入 */
blocking: boolean;
@@ -205,6 +208,8 @@ export interface TaskReport {
state: ReportState;
summary: string;
message?: string;
+ /** 3d 规则:观察时本会做的事(执行时做了的事) */
+ would?: string;
files?: string[];
/** 3b:要问用户的一个问题 */
question?: { question: string; options?: string[]; multiSelect?: boolean };
@@ -241,7 +246,7 @@ export interface TaskRow {
}
export type RunState = "queued" | "running" | "settling" | "ended";
export type RunOutcome = "" | "done" | "needs_you" | "failed" | "budget" | "stopped" | "interrupted" | "skipped";
-export type RunCause = "launch" | "answer" | "followup" | "retry" | "continue" | "recover" | "schedule" | "manual";
+export type RunCause = "launch" | "answer" | "followup" | "retry" | "continue" | "recover" | "schedule" | "manual" | "event";
/** 一段工作(一次启动、回答、追加、重试、恢复):占着名额直到结束 */
export interface RunRow {
id: string;
@@ -264,6 +269,9 @@ export interface RunRow {
error: string;
/** 结果交给出站队列 / 写进会话时的确定 id(交过就不再交) */
delivery: string;
+ /** 规则的 run 当时的沙箱:read-only / workspace-write(任务的是空的,权限记在任务上) */
+ permission: string;
+ /** 排队时间;规则的 run 是它该跑的时间(错过、等名额都从这里算宽限) */
queuedAt: number;
startedAt: number;
endedAt: number;
@@ -284,6 +292,45 @@ export interface RunInputRow {
createdAt: number;
}
+/**
+ * 规则(设计文档第 1、4、5、9 节,3d):用户写的一条长期指令 + 什么时候跑 + 模式。check 每次开一个新会话判断要不要说话,
+ * remind 到点只发一句固定的话(不进模型)。
+ * 触发是带标签的联合:schedule(宿主的定时器)或 event(事件源:以后由用户配置的 workload 接进来,见 TaskService.emitRuleEvent)。
+ */
+export type RuleKind = "check" | "remind";
+export type RuleMode = "off" | "observe" | "act";
+export type RuleTrigger = { kind: "schedule"; schedule: Schedule } | { kind: "event"; source: string; filter?: Record<string, unknown> };
+export interface RuleRow {
+ id: string;
+ botId: string;
+ /** 结果发到哪个会话(建规则的那个) */
+ conversationId: string;
+ title: string;
+ /** 用户的原话 */
+ instruction: string;
+ /** remind:到点发的那句话 */
+ message: string;
+ kind: RuleKind;
+ trigger: RuleTrigger;
+ mode: RuleMode;
+ /** 改了规则原话后先观察几次再执行(产品负责人:观察 1 次) */
+ observeLeft: number;
+ /** 相对工作区:rules/<slug>-<id6> */
+ folder: string;
+ /** 原话每改一次加 1;每个 run 记下它跑的是哪一版 */
+ version: number;
+ /** 下次该跑的时间;0 = 没有(事件触发、关着、暂停了、一次性的已经跑过) */
+ nextRunAt: number;
+ /** 连续失败几次(成功一次清零;3 次自动暂停) */
+ failures: number;
+ /** 暂停的原因:failures;空 = 没暂停 */
+ pausedReason: string;
+ /** 不受免打扰和每天上限限制(固定提醒:时间是用户定的) */
+ anytime: boolean;
+ createdAt: number;
+ updatedAt: number;
+}
+
type Row = Record<string, unknown>;
/** JSON 列 → 对象;坏的、空的都当没有 */
@@ -333,10 +380,27 @@ const RUN_COLS: Record<string, string> = {
costUsd: "cost_usd",
error: "error",
delivery: "delivery",
+ permission: "permission",
startedAt: "started_at",
endedAt: "ended_at",
};
const INPUT_COLS: Record<string, string> = { runId: "run_id", messageId: "message_id", deliveredAt: "delivered_at", takenAt: "taken_at" };
+const RULE_COLS: Record<string, string> = {
+ conversationId: "conversation_id",
+ title: "title",
+ instruction: "instruction",
+ message: "message",
+ kind: "kind",
+ trigger: "trigger_spec",
+ mode: "mode",
+ observeLeft: "observe_left",
+ version: "version",
+ nextRunAt: "next_run_at",
+ failures: "failures",
+ pausedReason: "paused_reason",
+ anytime: "anytime",
+ updatedAt: "updated_at",
+};
const SCHEMA = `
CREATE TABLE IF NOT EXISTS bots (
@@ -417,6 +481,16 @@ CREATE TABLE IF NOT EXISTS run_inputs (
message_id TEXT NOT NULL DEFAULT '', delivered_at INTEGER NOT NULL DEFAULT 0, taken_at INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS run_inputs_open ON run_inputs(task_id, taken_at);
+CREATE TABLE IF NOT EXISTS rules (
+ id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
+ title TEXT NOT NULL, instruction TEXT NOT NULL, message TEXT NOT NULL DEFAULT '',
+ kind TEXT NOT NULL DEFAULT 'check', trigger_spec TEXT NOT NULL, mode TEXT NOT NULL DEFAULT 'observe',
+ observe_left INTEGER NOT NULL DEFAULT 0, folder TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1,
+ next_run_at INTEGER NOT NULL DEFAULT 0, failures INTEGER NOT NULL DEFAULT 0, paused_reason TEXT NOT NULL DEFAULT '',
+ anytime INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
+CREATE INDEX IF NOT EXISTS rules_due ON rules(mode, next_run_at);
+CREATE INDEX IF NOT EXISTS runs_rule ON runs(rule_id, queued_at);
+CREATE INDEX IF NOT EXISTS run_inputs_run ON run_inputs(run_id, taken_at);
`;
/** 旧库补列(CREATE TABLE IF NOT EXISTS 不会改已有表)。 */
@@ -438,6 +512,9 @@ const COLUMNS: Array<[string, string, string]> = [
["approvals", "task_id", "TEXT NOT NULL DEFAULT ''"],
["approvals", "run_id", "TEXT NOT NULL DEFAULT ''"],
["approvals", "blocking", "INTEGER NOT NULL DEFAULT 1"],
+ // 规则(3d)执行时的审批
+ ["approvals", "rule_id", "TEXT NOT NULL DEFAULT ''"],
+ ["runs", "permission", "TEXT NOT NULL DEFAULT ''"],
];
export class Store {
@@ -582,8 +659,10 @@ export class Store {
this.db.prepare("DELETE FROM access WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM outbox WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM run_inputs WHERE task_id IN (SELECT id FROM tasks WHERE bot_id = ?)").run(id);
+ this.db.prepare("DELETE FROM run_inputs WHERE rule_id IN (SELECT id FROM rules WHERE bot_id = ?)").run(id);
this.db.prepare("DELETE FROM runs WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM tasks WHERE bot_id = ?").run(id);
+ this.db.prepare("DELETE FROM rules WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM bots WHERE id = ?").run(id);
}
@@ -814,17 +893,18 @@ export class Store {
expiresAt: Number(r.expires_at),
decidedAt: Number(r.decided_at),
taskId: String(r.task_id ?? ""),
+ ruleId: String(r.rule_id ?? ""),
runId: String(r.run_id ?? ""),
blocking: Number(r.blocking ?? 1) !== 0,
};
}
- insertApproval(a: Omit<ApprovalRow, "status" | "result" | "decidedBy" | "decidedAt" | "taskId" | "runId" | "blocking"> & Partial<Pick<ApprovalRow, "taskId" | "runId" | "blocking">>): ApprovalRow {
+ insertApproval(a: Omit<ApprovalRow, "status" | "result" | "decidedBy" | "decidedAt" | "taskId" | "ruleId" | "runId" | "blocking"> & Partial<Pick<ApprovalRow, "taskId" | "ruleId" | "runId" | "blocking">>): ApprovalRow {
this.db
.prepare(
- `INSERT INTO approvals(id, code, kind, bot_id, conversation_id, session_id, tool, detail, reason, payload, status, created_at, expires_at, task_id, run_id, blocking)
- VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?)`,
+ `INSERT INTO approvals(id, code, kind, bot_id, conversation_id, session_id, tool, detail, reason, payload, status, created_at, expires_at, task_id, rule_id, run_id, blocking)
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?)`,
)
- .run(a.id, a.code, a.kind, a.botId, a.conversationId, a.sessionId, a.tool, a.detail, a.reason, a.payload, a.createdAt, a.expiresAt, a.taskId ?? "", a.runId ?? "", a.blocking === false ? 0 : 1);
+ .run(a.id, a.code, a.kind, a.botId, a.conversationId, a.sessionId, a.tool, a.detail, a.reason, a.payload, a.createdAt, a.expiresAt, a.taskId ?? "", a.ruleId ?? "", a.runId ?? "", a.blocking === false ? 0 : 1);
return this.getApproval(a.id)!;
}
getApproval(id: string): ApprovalRow | undefined {
@@ -835,13 +915,14 @@ export class Store {
const r = this.db.prepare("SELECT * FROM approvals WHERE code = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(code) as Row | undefined;
return r ? this.toApproval(r) : undefined;
}
- listApprovals(opts: { status?: ApprovalStatus; botId?: string; conversationId?: string; taskId?: string; runId?: string; limit?: number } = {}): ApprovalRow[] {
+ listApprovals(opts: { status?: ApprovalStatus; botId?: string; conversationId?: string; taskId?: string; ruleId?: string; runId?: string; limit?: number } = {}): ApprovalRow[] {
const where: string[] = [];
const args: Array<string | number> = [];
if (opts.status) (where.push("status = ?"), args.push(opts.status));
if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
if (opts.conversationId) (where.push("conversation_id = ?"), args.push(opts.conversationId));
if (opts.taskId) (where.push("task_id = ?"), args.push(opts.taskId));
+ if (opts.ruleId) (where.push("rule_id = ?"), args.push(opts.ruleId));
if (opts.runId) (where.push("run_id = ?"), args.push(opts.runId));
const sql = `SELECT * FROM approvals ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY created_at DESC LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 100))}`;
return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toApproval(r));
@@ -1167,39 +1248,60 @@ export class Store {
costUsd: Number(r.cost_usd),
error: String(r.error),
delivery: String(r.delivery),
+ permission: String(r.permission ?? ""),
queuedAt: Number(r.queued_at),
startedAt: Number(r.started_at),
endedAt: Number(r.ended_at),
};
}
- insertRun(r: Pick<RunRow, "id" | "botId" | "taskId" | "sessionId" | "cause" | "queuedAt">): RunRow {
+ insertRun(r: Pick<RunRow, "id" | "botId" | "taskId" | "sessionId" | "cause" | "queuedAt"> & Partial<Pick<RunRow, "ruleId" | "ruleVersion" | "mode">>): RunRow {
this.db
- .prepare("INSERT INTO runs(id, bot_id, task_id, session_id, cause, state, queued_at) VALUES(?, ?, ?, ?, ?, 'queued', ?)")
- .run(r.id, r.botId, r.taskId, r.sessionId, r.cause, r.queuedAt);
+ .prepare("INSERT INTO runs(id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, queued_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?)")
+ .run(r.id, r.botId, r.taskId, r.ruleId ?? "", r.ruleVersion ?? 0, r.mode ?? "act", r.sessionId, r.cause, r.queuedAt);
+ return this.getRun(r.id)!;
+ }
+ /** 规则的一条运行记录,直接以结束的状态写进去(跳过:电脑没开、一直在忙、上次还没跑完) */
+ insertEndedRun(r: Pick<RunRow, "id" | "botId" | "ruleId" | "ruleVersion" | "mode" | "cause" | "outcome" | "error" | "queuedAt" | "endedAt">): RunRow {
+ this.db
+ .prepare("INSERT INTO runs(id, bot_id, rule_id, rule_version, mode, session_id, cause, state, outcome, error, queued_at, ended_at) VALUES(?, ?, ?, ?, ?, '', ?, 'ended', ?, ?, ?, ?)")
+ .run(r.id, r.botId, r.ruleId, r.ruleVersion, r.mode, r.cause, r.outcome, r.error, r.queuedAt, r.endedAt);
return this.getRun(r.id)!;
}
getRun(id: string): RunRow | undefined {
const r = this.db.prepare("SELECT * FROM runs WHERE id = ?").get(id) as Row | undefined;
return r ? this.toRun(r) : undefined;
}
- updateRun(id: string, patch: Partial<Pick<RunRow, "sessionId" | "state" | "outcome" | "report" | "would" | "activity" | "tokensIn" | "tokensOut" | "costUsd" | "error" | "delivery" | "startedAt" | "endedAt">>): void {
+ updateRun(id: string, patch: Partial<Pick<RunRow, "sessionId" | "state" | "outcome" | "report" | "would" | "activity" | "tokensIn" | "tokensOut" | "costUsd" | "error" | "delivery" | "permission" | "startedAt" | "endedAt">>): void {
updateRow(this.db, "runs", RUN_COLS, id, patch);
}
- /** 一个任务的 runs(旧→新);不含活动记录(大) */
- listRuns(opts: { taskId?: string; botId?: string; states?: RunState[]; limit?: number } = {}): RunRow[] {
+ /** 一个任务(或规则)的 runs(旧→新);不含活动记录(大) */
+ listRuns(opts: { taskId?: string; ruleId?: string; botId?: string; states?: RunState[]; limit?: number } = {}): RunRow[] {
const where: string[] = [];
const args: Array<string | number> = [];
if (opts.taskId) (where.push("task_id = ?"), args.push(opts.taskId));
+ if (opts.ruleId) (where.push("rule_id = ?"), args.push(opts.ruleId));
if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
if (opts.states?.length) (where.push(`state IN (${opts.states.map(() => "?").join(", ")})`), args.push(...opts.states));
- const sql = `SELECT id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, outcome, report, would, '' AS activity, tokens_in, tokens_out, cost_usd, error, delivery, queued_at, started_at, ended_at
+ const sql = `SELECT id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, outcome, report, would, '' AS activity, tokens_in, tokens_out, cost_usd, error, delivery, permission, queued_at, started_at, ended_at
FROM runs ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY queued_at, rowid LIMIT ${Math.max(1, Math.min(1000, opts.limit ?? 500))}`;
return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toRun(r));
}
+ /** 规则的运行记录(新→旧):before 之前的(按排队时间,翻页用) */
+ ruleRuns(ruleId: string, opts: { before?: number; limit?: number; mode?: string; outcome?: RunOutcome; version?: number } = {}): RunRow[] {
+ const where = ["rule_id = ?"];
+ const args: Array<string | number> = [ruleId];
+ if (opts.before) (where.push("queued_at < ?"), args.push(opts.before));
+ if (opts.mode) (where.push("mode = ?"), args.push(opts.mode));
+ if (opts.outcome) (where.push("outcome = ?"), args.push(opts.outcome));
+ if (opts.version) (where.push("rule_version = ?"), args.push(opts.version));
+ const sql = `SELECT id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, outcome, report, would, '' AS activity, tokens_in, tokens_out, cost_usd, error, delivery, permission, queued_at, started_at, ended_at
+ FROM runs WHERE ${where.join(" AND ")} ORDER BY queued_at DESC, rowid DESC LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 20))}`;
+ return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toRun(r));
+ }
/** 任务最近的一个 run(不含活动记录) */
latestRun(taskId: string): RunRow | undefined {
const r = this.db
- .prepare("SELECT id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, outcome, report, would, '' AS activity, tokens_in, tokens_out, cost_usd, error, delivery, queued_at, started_at, ended_at FROM runs WHERE task_id = ? ORDER BY queued_at DESC, rowid DESC LIMIT 1")
+ .prepare("SELECT id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, outcome, report, would, '' AS activity, tokens_in, tokens_out, cost_usd, error, delivery, permission, queued_at, started_at, ended_at FROM runs WHERE task_id = ? ORDER BY queued_at DESC, rowid DESC LIMIT 1")
.get(taskId) as Row | undefined;
return r ? this.toRun(r) : undefined;
}
@@ -1219,10 +1321,10 @@ export class Store {
createdAt: Number(r.created_at),
};
}
- insertInput(i: Pick<RunInputRow, "id" | "taskId" | "runId" | "kind" | "text" | "fromPerson" | "createdAt"> & Partial<Pick<RunInputRow, "messageId" | "deliveredAt">>): RunInputRow {
+ insertInput(i: Pick<RunInputRow, "id" | "taskId" | "runId" | "kind" | "text" | "fromPerson" | "createdAt"> & Partial<Pick<RunInputRow, "ruleId" | "messageId" | "deliveredAt">>): RunInputRow {
this.db
- .prepare("INSERT INTO run_inputs(id, task_id, run_id, kind, text, from_person, message_id, delivered_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)")
- .run(i.id, i.taskId, i.runId, i.kind, i.text, i.fromPerson ? 1 : 0, i.messageId ?? "", i.deliveredAt ?? 0, i.createdAt);
+ .prepare("INSERT INTO run_inputs(id, task_id, rule_id, run_id, kind, text, from_person, message_id, delivered_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
+ .run(i.id, i.taskId, i.ruleId ?? "", i.runId, i.kind, i.text, i.fromPerson ? 1 : 0, i.messageId ?? "", i.deliveredAt ?? 0, i.createdAt);
return this.toInput(this.db.prepare("SELECT * FROM run_inputs WHERE id = ?").get(i.id) as Row);
}
updateInput(id: string, patch: Partial<Pick<RunInputRow, "runId" | "messageId" | "deliveredAt" | "takenAt">>): void {
@@ -1239,6 +1341,83 @@ export class Store {
takeInputs(taskId: string, messageId: string, at = Date.now()): number {
return Number(this.db.prepare("UPDATE run_inputs SET taken_at = ? WHERE task_id = ? AND message_id = ? AND taken_at = 0").run(at, taskId, messageId).changes);
}
+ /** 规则的一个 run 里会话还没收下的输入(旧→新):每个 run 一个新会话,输入跟着 run 走 */
+ openRunInputs(runId: string): RunInputRow[] {
+ return (this.db.prepare("SELECT * FROM run_inputs WHERE run_id = ? AND task_id = '' AND taken_at = 0 ORDER BY created_at, rowid").all(runId) as Row[]).map((r) => this.toInput(r));
+ }
+ /** 规则的 run:会话里出现了这条用户消息 */
+ takeRunInputs(runId: string, messageId: string, at = Date.now()): number {
+ return Number(this.db.prepare("UPDATE run_inputs SET taken_at = ? WHERE run_id = ? AND task_id = '' AND message_id = ? AND taken_at = 0").run(at, runId, messageId).changes);
+ }
+ /** 规则的 run 的第一条输入(重跑时照原样再交一次) */
+ runInputs(runId: string): RunInputRow[] {
+ return (this.db.prepare("SELECT * FROM run_inputs WHERE run_id = ? ORDER BY created_at, rowid").all(runId) as Row[]).map((r) => this.toInput(r));
+ }
+
+ // ---------- rules(3d) ----------
+ private toRule(r: Row): RuleRow {
+ const trigger = parseJson<RuleTrigger>(r.trigger_spec) ?? { kind: "event", source: "" };
+ return {
+ id: String(r.id),
+ botId: String(r.bot_id),
+ conversationId: String(r.conversation_id),
+ title: String(r.title),
+ instruction: String(r.instruction),
+ message: String(r.message),
+ kind: String(r.kind) === "remind" ? "remind" : "check",
+ trigger,
+ mode: (["off", "observe", "act"].includes(String(r.mode)) ? String(r.mode) : "off") as RuleMode,
+ observeLeft: Number(r.observe_left),
+ folder: String(r.folder),
+ version: Number(r.version),
+ nextRunAt: Number(r.next_run_at),
+ failures: Number(r.failures),
+ pausedReason: String(r.paused_reason),
+ anytime: Number(r.anytime) === 1,
+ createdAt: Number(r.created_at),
+ updatedAt: Number(r.updated_at),
+ };
+ }
+ insertRule(r: Omit<RuleRow, "version" | "failures" | "pausedReason" | "observeLeft"> & Partial<Pick<RuleRow, "version" | "observeLeft">>): RuleRow {
+ this.db
+ .prepare(
+ `INSERT INTO rules(id, bot_id, conversation_id, title, instruction, message, kind, trigger_spec, mode, observe_left, folder, version, next_run_at, anytime, created_at, updated_at)
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(r.id, r.botId, r.conversationId, r.title, r.instruction, r.message, r.kind, JSON.stringify(r.trigger), r.mode, r.observeLeft ?? 0, r.folder, r.version ?? 1, r.nextRunAt, r.anytime ? 1 : 0, r.createdAt, r.updatedAt);
+ return this.getRule(r.id)!;
+ }
+ getRule(id: string): RuleRow | undefined {
+ const r = this.db.prepare("SELECT * FROM rules WHERE id = ?").get(id) as Row | undefined;
+ return r ? this.toRule(r) : undefined;
+ }
+ updateRule(id: string, patch: Partial<Omit<RuleRow, "id" | "botId" | "folder" | "createdAt">>): void {
+ updateRow(this.db, "rules", RULE_COLS, id, patch);
+ }
+ listRules(opts: { botId?: string; conversationId?: string; limit?: number } = {}): RuleRow[] {
+ const where: string[] = [];
+ const args: Array<string | number> = [];
+ if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
+ if (opts.conversationId) (where.push("conversation_id = ?"), args.push(opts.conversationId));
+ const sql = `SELECT * FROM rules ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY created_at LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 200))}`;
+ return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toRule(r));
+ }
+ /** 到点了的规则(开着、没暂停、按时间表):next_run_at 在 now 及之前 */
+ dueRules(now: number): RuleRow[] {
+ return (this.db.prepare("SELECT * FROM rules WHERE mode != 'off' AND paused_reason = '' AND next_run_at > 0 AND next_run_at <= ? ORDER BY next_run_at").all(now) as Row[]).map((r) => this.toRule(r));
+ }
+ /** 最早的下次运行时间(定时器只设这一个);没有就是 0 */
+ nextRuleDue(): number {
+ const r = this.db.prepare("SELECT MIN(next_run_at) AS t FROM rules WHERE mode != 'off' AND paused_reason = '' AND next_run_at > 0").get() as Row | undefined;
+ return Number(r?.t ?? 0) || 0;
+ }
+ /** 删掉规则和它的运行记录 */
+ deleteRule(id: string): void {
+ this.db.prepare("DELETE FROM run_inputs WHERE rule_id = ?").run(id);
+ this.db.prepare("DELETE FROM runs WHERE rule_id = ?").run(id);
+ this.db.prepare("DELETE FROM rules WHERE id = ?").run(id);
+ }
+
/** 任务的会话建过(交出去过输入):之后要 resume */
taskPrompted(taskId: string): boolean {
return !!this.db.prepare("SELECT 1 FROM run_inputs WHERE task_id = ? AND delivered_at > 0 LIMIT 1").get(taskId);
diff --git a/src/store/lock.ts b/src/store/lock.ts
new file mode 100644
index 0000000..f813408
--- /dev/null
+++ b/src/store/lock.ts
@@ -0,0 +1,127 @@
+/**
+ * 数据目录锁(设计文档第 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";
+
+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)。`);
+ 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 --git a/src/tasks/attention.ts b/src/tasks/attention.ts
index 3dd499a..16c66a0 100644
--- a/src/tasks/attention.ts
+++ b/src/tasks/attention.ts
@@ -14,13 +14,13 @@ import { logger } from "../log.js";
const log = logger("attention");
-/** question / approval:在等你回答、批准;failed:任务失败了;delivery:结果没送到;login:渠道登录过期了 */
-export type AttentionKind = "question" | "approval" | "failed" | "delivery" | "login";
+/** question / approval:在等你回答、批准;failed:任务失败了;rule:规则连续失败(暂停了);delivery:结果没送到;login:渠道登录过期了 */
+export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login";
/** answer、approve、deny、retry(任务再试 / 消息再发)、stop、dismiss(不再提示)、relogin(去重新扫码)、open(打开对话) */
export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open";
export interface AttentionItem {
- /** 稳定 id:approval:<id>、task:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道> */
+ /** 稳定 id:approval:<id>、task:<id>、rule:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道> */
id: string;
kind: AttentionKind;
botId: string;
@@ -37,6 +37,8 @@ export interface AttentionItem {
conversationId?: string;
channel?: string;
taskId?: string;
+ /** 规则(3d):连续失败的、执行时的审批 */
+ ruleId?: string;
approvalId?: string;
code?: string;
questions?: QuestionItem[];
@@ -45,7 +47,7 @@ export interface AttentionItem {
export type AttentionSource = () => AttentionItem[];
/** 排序:提问和审批在前(等着的事),再是失败、没送到,最后是系统的(登录);同一类旧的在前 */
-const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, delivery: 2, login: 3 };
+const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3 };
const NOTIFIED = "attention:notified";
@@ -173,6 +175,7 @@ const CHANNEL: Record<string, string> = { weixin: "微信", feishu: "飞书", we
export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[] {
return rows.map((r) => {
const task = r.taskId ? store.getTask(r.taskId) : undefined;
+ const rule = r.ruleId ? store.getRule(r.ruleId) : undefined;
const channel = store.getConversation(r.conversationId)?.channel ?? r.conversationId.split(":")[1] ?? "";
const qs = questionsOf(r);
const line = r.kind === "approval" ? r.detail || r.reason || r.tool : qs.map((q) => q.question).join(" / ") || r.detail;
@@ -181,7 +184,7 @@ export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[
kind: r.kind,
botId: r.botId,
botName: store.getBot(r.botId)?.name ?? r.botId,
- subject: task?.title ?? CHANNEL[channel] ?? "对话",
+ subject: task?.title ?? (rule ? `规则「${rule.title}」` : (CHANNEL[channel] ?? "对话")),
status: r.kind === "approval" ? "等你批准" : "等你回答",
line: line.length > 300 ? line.slice(0, 299) + "…" : line,
since: r.createdAt,
@@ -190,6 +193,7 @@ export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[
conversationId: r.conversationId,
channel,
...(r.taskId ? { taskId: r.taskId } : {}),
+ ...(r.ruleId ? { ruleId: r.ruleId } : {}),
approvalId: r.id,
code: r.code,
...(r.kind === "question" ? { questions: qs } : {}),
diff --git a/src/tasks/rule-events.ts b/src/tasks/rule-events.ts
new file mode 100644
index 0000000..ee2fe8b
--- /dev/null
+++ b/src/tasks/rule-events.ts
@@ -0,0 +1,40 @@
+/**
+ * 事件触发的规则的接入点(3d 只做这个扩展点):规则的触发是带标签的联合,schedule 走宿主的定时器,
+ * event 由事件源把事件交到这里(RuleEvents.emit),开着的、来源相同、过滤条件对得上的规则各开一个 run,
+ * 和定时的 run 走同一条路(观察 / 执行、名额、送达、自动暂停)。
+ *
+ * 以后用户自己配置的 workload(比如盯一个 GitHub 仓库)就接在这里:workload 负责拿到事件(轮询、webhook),
+ * 调 emit(source, event);这里不内置任何事件源,也没有界面。source 是 workload 的名字(如 "github:owner/repo"),
+ * filter 是规则里存的一组键值,事件里对应的值相等(filter 的值是数组时,等于其中一个)才算对得上。
+ */
+
+/** 一个事件:任意 JSON;id 可选(同一个事件交两次时,以后可以按它去重) */
+export type RuleEvent = Record<string, unknown>;
+
+/** 事件对不对得上规则的过滤条件:每个键都要相等(数组 = 其中之一);键可以是 a.b 这样的路径;没有条件就都算 */
+export function matchesFilter(filter: Record<string, unknown> | undefined, event: RuleEvent): boolean {
+ if (!filter) return true;
+ for (const [key, want] of Object.entries(filter)) {
+ const got = key.split(".").reduce<unknown>((v, k) => (v && typeof v === "object" ? (v as Record<string, unknown>)[k] : undefined), event);
+ const ok = Array.isArray(want) ? want.some((w) => same(w, got)) : same(want, got);
+ if (!ok) return false;
+ }
+ return true;
+}
+
+const same = (a: unknown, b: unknown) => a === b || (a != null && b != null && typeof a !== "object" && typeof b !== "object" && String(a) === String(b));
+
+/** 任务服务里开 run 的那一个方法(一个写入者:规则、run、输入都由任务服务写) */
+export interface RuleEventSink {
+ emitRuleEvent(source: string, event: RuleEvent): string[];
+}
+
+/** 宿主进程里的事件入口:workload 拿到事件就调 emit;返回开了 run 的规则 id */
+export class RuleEvents {
+ constructor(private sink: RuleEventSink) {}
+
+ emit(source: string, event: RuleEvent): string[] {
+ if (!source.trim() || !event || typeof event !== "object") return [];
+ return this.sink.emitRuleEvent(source.trim(), event);
+ }
+}
diff --git a/src/tasks/rules.ts b/src/tasks/rules.ts
new file mode 100644
index 0000000..32dd8c3
--- /dev/null
+++ b/src/tasks/rules.ts
@@ -0,0 +1,168 @@
+/**
+ * 规则(3d)的纯函数部分:状态、给人看的一行、每种模式的权限和去掉的工具。写库的是任务服务(service.ts,唯一的写入者)。
+ *
+ * 状态(第一条符合的为准):暂停了(连续失败 3 次)→ 已暂停;关了 → 已关闭;一次性的跑过了 → 已结束;提醒 → 提醒;
+ * 观察中(含改了原话后先观察的那一次)→ 观察中;其余 → 执行中。状态是"点 + 文字":红 = 暂停,绿 = 执行中、提醒,灰 = 观察、关闭、结束。
+ */
+import type { OutboxRow, RuleMode, RuleRow, RunRow } from "../store/db.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 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}`;
+}
+
+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 "待发送";
+}
+
+/**
+ * 运行记录的一行(设计第 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 "正在运行";
+ 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 || "电脑没开"}`;
+ case "failed":
+ return `失败:${clip(oneLine(r?.message || run.error || "没有给出结果"), 120)}`;
+ case "interrupted":
+ return "中断:应用重启了";
+ case "stopped":
+ return "已停止";
+ case "budget":
+ return "预算用完";
+ 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 || "");
+ if (run.mode === "observe") {
+ if (msg) return `本会发送:“${clip(msg, 120)}”`;
+ if (would) return `本会做:${clip(would, 120)}`;
+ return note ? `本会保持安静:${clip(note, 60)}` : "本会保持安静";
+ }
+ if (msg) return `${sentWord(carrier)}:“${clip(msg, 120)}”`;
+ return note ? `保持安静:${clip(note, 60)}` : "保持安静";
+}
+
+/** 运行记录里的一项(界面展开看报告、步骤、版本和权限) */
+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 --git a/src/tasks/schedule.ts b/src/tasks/schedule.ts
new file mode 100644
index 0000000..bae4676
--- /dev/null
+++ b/src/tasks/schedule.ts
@@ -0,0 +1,335 @@
+/**
+ * 规则的时间表(设计文档第 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。
+ */
+import { localParts, minuteOf } from "../core/quiet.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 } {
+ 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: "这个时间已经过了" };
+ 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 这样" };
+ 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") 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 天" };
+ 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 段:分 时 日 月 星期" };
+ return { schedule: { kind: "cron", cron, tz: zone } };
+ }
+ default:
+ return { error: "不认识的时间表" };
+ }
+}
+
+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);
+ }
+ 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);
+ }
+ 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);
+ 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);
+ return r.error ? { error: `That time (${tail}, ${tz}) has already passed.` } : r;
+ }
+ if (kind === "cron") {
+ const r = normalizeSchedule({ kind: "cron", cron: tail }, tz, now);
+ 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 "每天";
+ const key = days.join(",");
+ if (key === "1,2,3,4,5") return "每个工作日";
+ if (key === "0,6") return "每个周末";
+ // 周一在前、周日在最后
+ return "每" + [...days].sort((a, b) => ((a + 6) % 7) - ((b + 6) % 7)).map((d) => WEEK[d]).join("、");
+}
+
+/** 给用户看的时间表:每天 08:00、每个工作日 08:00、每周一、周四 09:00、每 30 分钟、11月2日 15:00;withZone 时带上时区 */
+export function describe(s: Schedule, withZone = false): 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;
+}
diff --git a/src/tasks/scheduler.ts b/src/tasks/scheduler.ts
new file mode 100644
index 0000000..a948d9a
--- /dev/null
+++ b/src/tasks/scheduler.ts
@@ -0,0 +1,76 @@
+/**
+ * 宿主的定时器(设计文档第 4 节:调度归宿主):rules.next_run_at 里最早的那个设一个定时器,到点让任务服务开 run。
+ * DSH 的 dsh-schedule 在 sdk 配置下加载不了,而且只在代理进程活着时才跑;宿主常驻托盘。
+ *
+ * - 一次最多睡 maxSleepMs(默认 5 分钟)就醒来看一眼:电脑睡眠、改了系统时间之后不会错过太久(Node 的定时器按单调时钟走)。
+ * - wake():规则改了、电脑醒了(Electron powerMonitor 的 resume)、时钟变了,马上重新看一遍。
+ * - 错过的怎么办(宽限期内补跑一次、更早的记为跳过)由任务服务的 fireDue 决定,这里只管时间。
+ */
+import { logger } from "../log.js";
+
+const log = logger("scheduler");
+
+export const MAX_SLEEP_MS = 5 * 60_000;
+
+export interface SchedulerOptions {
+ /** 最早的下次运行时间;0 = 没有 */
+ next(): number;
+ /** 到点了:开该开的 run(错过太久的记为跳过),把它们的 next_run_at 往后挪 */
+ fire(now: number): void;
+ now?: () => number;
+ maxSleepMs?: number;
+}
+
+export class Scheduler {
+ private timer: NodeJS.Timeout | undefined;
+ private running = false;
+ /** 下一次醒来的时间(测试和状态页看) */
+ wakeAt = 0;
+
+ constructor(private o: SchedulerOptions) {}
+
+ private now(): number {
+ return (this.o.now ?? Date.now)();
+ }
+
+ /** 开始:先看一遍(应用没开时错过的,按宽限期补跑或跳过),再设定时器 */
+ start(): void {
+ if (this.running) return;
+ this.running = true;
+ this.tick();
+ }
+
+ stop(): void {
+ this.running = false;
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ this.wakeAt = 0;
+ }
+
+ /** 规则改了、电脑醒了、时钟变了:马上重新看一遍 */
+ wake(): void {
+ if (this.running) this.tick();
+ }
+
+ private tick(): void {
+ if (!this.running) return;
+ try {
+ this.o.fire(this.now());
+ } catch (e) {
+ log.warn("firing due rules failed", { message: (e as Error).message.slice(0, 300) });
+ }
+ this.arm();
+ }
+
+ private arm(): void {
+ clearTimeout(this.timer);
+ if (!this.running) return;
+ const now = this.now();
+ const next = this.o.next();
+ const max = this.o.maxSleepMs ?? MAX_SLEEP_MS;
+ const ms = next > 0 ? Math.min(max, Math.max(200, next - now)) : max;
+ this.wakeAt = now + ms;
+ this.timer = setTimeout(() => this.tick(), ms);
+ this.timer.unref?.();
+ }
+}
diff --git a/src/tasks/service.ts b/src/tasks/service.ts
index ce34d47..9870862 100644
--- a/src/tasks/service.ts
+++ b/src/tasks/service.ts
@@ -15,7 +15,11 @@
* - 提问(3b):代理报 needs_you 带一个问题,这一轮结束时变成审批中心里一条不阻塞、不过期的提问,推给请求它的会话
* (一个会话同时只推一个);回答成为任务的新输入,任务在人的名额里接着做。任务会话里的审批也推过去(阻塞、12 小时)。
*
- * 3c–3f 的缝:规则(rule_id)、花费(cost_usd、budget)。
+ * - 规则(3d):一条规则每次运行开一个新会话(rule-<规则>-<run>,工作目录是 rules/<slug>-<id6>/),和任务的 run 走同一套
+ * 排队、名额、收尾、提醒、重试;不同的是结束之后(见「规则」一节):观察只记「本会发送」,执行时那一句经出站队列发出去,
+ * 连续失败 3 次自动暂停。定时器在 scheduler.ts,错过的按宽限期补跑一次或记为跳过。
+ *
+ * 3e–3f 的缝:花费(cost_usd、budget)。
*/
import crypto from "node:crypto";
import fs from "node:fs";
@@ -25,13 +29,35 @@ import { ActivityLog, type ActivityStep } from "../agent/activity.js";
import { ResumeFailed, deliverables } from "../agent/host.js";
import { answerLine, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";
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 { 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,
+ ruleState,
+ rulePermission,
+ runLine,
+ runMode,
+ whenOf,
+ type RuleRunView,
+ type RuleView,
+} from "./rules.js";
const log = logger("tasks");
@@ -92,8 +118,14 @@ export interface TaskServiceOptions {
maxBackground?: number;
now?: () => number;
retryDelaysMs?: number[];
- /** 任务有变化(阶段、进展) */
+ /** 任务有变化(阶段、进展);规则有变化时是规则 id */
onChange?: (taskId: string) => void;
+ /** 规则:用主模型写那一句结果(检查用的是小模型);没有就用检查时的草稿 */
+ complete?: (botId: string, model: string, system: string, user: string) => Promise<string>;
+ /** 新规则的时区(默认本机的) */
+ timeZone?: string;
+ /** 规则一次运行最长多久(测试注入) */
+ ruleRunCapMs?: number;
}
/** 界面、/tasks 和 task_list 看到的任务 */
@@ -117,10 +149,17 @@ export interface TaskView {
live?: { runId: string; since: number; steps: number; current?: ActivityStep };
}
-/** 一个在跑(或收尾中)的 run 的内存状态 */
+/** 一个在跑(或收尾中)的 run 的内存状态(任务的,或规则的:ruleId 不空、taskId 是空的) */
interface Live {
runId: string;
taskId: string;
+ ruleId: string;
+ /** 规则:这次是观察还是执行;会话的工作目录和模型(每次一个新会话,不 resume) */
+ mode: "observe" | "act";
+ folder: string;
+ model: string;
+ /** 规则:一次运行的时间上限 */
+ capTimer?: NodeJS.Timeout;
botId: string;
sessionId: string;
activity: ActivityLog;
@@ -144,11 +183,23 @@ interface Live {
seen: Set<string>;
tokensIn: number;
tokensOut: number;
+ /** 规则观察时要批准的事(自动拒绝了,记成「需要批准:…」) */
+ would?: string[];
}
const hex = (n: number) => crypto.randomBytes(n).toString("hex");
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 {
@@ -188,12 +239,23 @@ export class TaskService {
private dropped = new Set<string>();
private unlisten: (() => void) | undefined;
+ /** 宿主的定时器:规则到点开 run(scheduler.ts) */
+ readonly scheduler: Scheduler;
+
constructor(private o: TaskServiceOptions) {
// 进行中的任务:给微信留 1 条配额(聊天回复不会把它挤掉),续期提醒里也算"之后还要发的"
o.delivery?.addReserver((p) => this.working(p.conversationId).length);
// 推给用户、还没回答的提问(审批):再留 1 条(设计第 6 节:任务、待答问题各占 1 条,一共最多 3 条)
o.delivery?.addReserver((p) => (o.approvals?.pending(p.conversationId).some((r) => r.taskId) ? 1 : 0));
o.delivery?.addUpcoming((p) => this.working(p.conversationId).map((t) => ({ label: t.title, kind: "task" as const })));
+ // 执行中的规则(含提醒):每条留 1 条配额;窗口关闭之后还要跑的,续期提醒里列出来(观察中的规则什么都不发,不算)
+ o.delivery?.addReserver((p) => this.pushingRules(p.conversationId).length);
+ o.delivery?.addUpcoming((p, after) =>
+ this.pushingRules(p.conversationId)
+ .filter((r) => r.nextRunAt >= after)
+ .map((r) => ({ label: r.title, at: r.nextRunAt, kind: r.kind === "remind" ? ("reminder" as const) : ("rule" as const) })),
+ );
+ this.scheduler = new Scheduler({ next: () => this.store.nextRuleDue(), fire: (now) => this.fireDue(now), now: () => this.now() });
}
private get store(): Store {
@@ -225,16 +287,21 @@ export class TaskService {
}
}
for (const conv of new Set((this.o.approvals?.pendingAll() ?? []).filter((r) => r.taskId).map((r) => r.conversationId))) this.pushNext(conv);
+ this.redeliverRules();
this.pump();
+ // 定时器最后开:应用没开时错过的规则,宽限期内的补跑一次,更早的记为跳过
+ this.scheduler.start();
}
/** 应用退出:不再开始新的 run;跑着的留在库里(下次启动时恢复),步骤先存下 */
stop(): void {
this.closing = true;
+ this.scheduler.stop();
this.unlisten?.();
this.unlisten = undefined;
for (const l of this.live.values()) {
clearTimeout(l.timer);
+ clearTimeout(l.capTimer);
try {
this.store.updateRun(l.runId, { activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });
} catch {
@@ -268,6 +335,10 @@ export class TaskService {
const steps: ActivityStep[] = l ? l.activity.steps : parseSteps(this.store.getRun(run.id)?.activity);
if (l) this.forget(l);
this.store.updateRun(run.id, { state: "ended", outcome: "interrupted", endedAt: this.now(), error: why, ...(l ? { activity: JSON.stringify(steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut } : {}) });
+ if (run.ruleId) {
+ this.recoverRule(run);
+ continue;
+ }
const task = run.taskId ? this.store.getTask(run.taskId) : undefined;
// 这一轮在等的批准随它没了(DSH 那次调用不在了):恢复后代理需要的话再问
for (const a of run.taskId ? (this.o.approvals?.pendingForTask(run.taskId) ?? []) : []) if (a.blocking) this.o.approvals!.cancel(a.id, "interrupted");
@@ -434,7 +505,7 @@ export class TaskService {
/** 有空名额就开始排队的 run(人的唤醒在前,见 slots.ts) */
pump(): void {
if (!this.started || this.closing) return;
- const queued = this.store.listRuns({ states: ["queued"] }).filter((r) => r.taskId && !this.dropped.has(r.botId));
+ const queued = this.store.listRuns({ states: ["queued"] }).filter((r) => (r.taskId || (r.ruleId && !this.skipStale(r))) && !this.dropped.has(r.botId));
if (!queued.length) return;
// 等批准的 run 让出名额(DSH 那次调用照样等着,批了就接着做)
const blocked = new Set((this.o.approvals?.pendingAll() ?? []).filter((a) => a.taskId && a.blocking && a.kind === "approval").map((a) => a.taskId));
@@ -451,6 +522,7 @@ export class TaskService {
private async startRun(runId: string): Promise<void> {
const run = this.store.getRun(runId);
if (!run || run.state !== "queued") return;
+ if (run.ruleId) return this.startRuleRun(run);
const task = this.store.getTask(run.taskId);
const now = this.now();
if (!task || task.endReason === "stopped") {
@@ -461,6 +533,10 @@ export class TaskService {
const l: Live = {
runId,
taskId: task.id,
+ ruleId: "",
+ mode: "act",
+ folder: "",
+ model: "",
botId: task.botId,
sessionId: task.sessionId,
activity: new ActivityLog(undefined, task.model),
@@ -487,21 +563,22 @@ export class TaskService {
*/
private async deliver_(l: Live, inputs: RunInputRow[]): Promise<void> {
if (!inputs.length || this.live.get(l.runId) !== l) return;
- const task = this.store.getTask(l.taskId);
- if (!task) return;
+ // 规则的 run:每次一个新会话,工作目录和模型在开始时定好
+ const task = l.ruleId ? undefined : this.store.getTask(l.taskId);
+ if (!task && !l.ruleId) return;
l.starting = true;
l.settling = false;
if (inputs.some((i) => i.fromPerson)) this.reopen(l);
const text = inputs.map((i) => i.text).join("\n\n");
- const folder = path.join(this.o.host.workspace(task.botId), task.folder);
- const model = this.modelOf(task);
+ const folder = task ? path.join(this.o.host.workspace(task.botId), task.folder) : l.folder;
+ const model = task ? this.modelOf(task) : l.model;
try {
let id: string;
try {
fs.mkdirSync(folder, { recursive: true });
- id = await this.o.host.prompt(task.botId, { sessionId: l.sessionId, folder, model, text, resume: this.store.taskPrompted(task.id) });
+ id = await this.o.host.prompt(l.botId, { sessionId: l.sessionId, folder, model, text, resume: task ? this.store.taskPrompted(task.id) : false });
} catch (e) {
- if (!(e instanceof ResumeFailed)) throw e;
+ if (!(e instanceof ResumeFailed) || !task) throw e;
// 会话记录恢复不了:换一个新会话,从宿主记下的任务重新交代
const n = this.store.listRuns({ taskId: task.id }).length + 1;
const sessionId = `task-${task.id}-${n}`;
@@ -516,8 +593,8 @@ export class TaskService {
id = await this.o.host.prompt(task.botId, { sessionId, folder, model, text: `${again}\n\n${text}`, resume: false });
}
if (this.live.get(l.runId) !== l) {
- // 交出去的时候任务被停了:输入已经到了会话里,再停一次(插件拒绝它之后的工具调用)
- if (this.store.getTask(l.taskId)?.endReason === "stopped") await this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);
+ // 交出去的时候任务被停了(规则被删了、超时了):输入已经到了会话里,再停一次(插件拒绝它之后的工具调用)
+ if (l.ruleId || this.store.getTask(l.taskId)?.endReason === "stopped") await this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);
return;
}
const at = this.now();
@@ -534,7 +611,7 @@ export class TaskService {
const delay = this.delays[l.retries++];
l.timer = setTimeout(() => {
l.timer = undefined;
- void this.deliver_(l, this.store.openInputs(l.taskId).filter((i) => !i.deliveredAt || i.runId === l.runId));
+ void this.deliver_(l, this.inputsOf(l).filter((i) => !i.deliveredAt || i.runId === l.runId));
}, delay);
l.timer.unref?.();
return;
@@ -568,6 +645,17 @@ export class TaskService {
return this.store.insertInput({ id: `i_${hex(6)}`, taskId, runId: "", kind, text, fromPerson, createdAt: this.now() });
}
+ /** 会话还没收下的输入:任务的按任务,规则的按这次 run(每次一个新会话) */
+ private inputsOf(l: Live): RunInputRow[] {
+ return l.ruleId ? this.store.openRunInputs(l.runId) : this.store.openInputs(l.taskId);
+ }
+
+ /** 给这个 run 的会话加一条(自动的)输入 */
+ private inputFor(l: Live, kind: InputKind, text: string): RunInputRow {
+ if (!l.ruleId) return this.addInput(l.taskId, kind, text, false);
+ return this.store.insertInput({ id: `i_${hex(6)}`, taskId: "", ruleId: l.ruleId, runId: l.runId, kind, text, fromPerson: false, createdAt: this.now() });
+ }
+
// ---------- 会话事件(宿主转来的 SDK 通知) ----------
/** root:任务会话 id(子代理的通知也归到它) */
@@ -602,12 +690,13 @@ export class TaskService {
if (type === "user/message" && data.id) {
const id = String(data.id);
l.seen.add(id);
- if (this.store.takeInputs(l.taskId, id, this.now())) this.changed(l.taskId);
+ const took = l.ruleId ? this.store.takeRunInputs(l.runId, id, this.now()) : this.store.takeInputs(l.taskId, id, this.now());
+ if (took) this.changed(l.taskId || l.ruleId);
} else if (type === "turn/start") l.turnError = undefined;
else if (type === "turn/end") {
if (data?.reason?.kind === "error") l.turnError = String(data.reason.error?.message ?? "unknown error");
this.store.updateRun(l.runId, { activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });
- this.changed(l.taskId);
+ this.changed(l.taskId || l.ruleId);
} else if (type === "assistant/message" && data.usage) {
l.tokensIn += Number(data.usage.inputTokens) || 0;
l.tokensOut += Number(data.usage.outputTokens) || 0;
@@ -620,7 +709,7 @@ export class TaskService {
*/
private async checkSettle(l: Live): Promise<void> {
if (l.busy || l.starting || l.checking || l.timer || this.closing || this.live.get(l.runId) !== l) return;
- const open = this.store.openInputs(l.taskId);
+ const open = this.inputsOf(l);
if (open.some((i) => i.deliveredAt && i.runId === l.runId)) return;
const waiting = open.filter((i) => !i.deliveredAt);
if (waiting.length) return void this.deliver_(l, waiting);
@@ -637,16 +726,16 @@ export class TaskService {
if (q.quiet) return this.finish(l);
l.settling = true;
this.store.updateRun(l.runId, { state: "settling" });
- this.changed(l.taskId);
+ this.changed(l.taskId || l.ruleId);
}
/** 插件:收尾中的会话安静下来了(后台命令、子代理都结束了,或者收尾超时被停掉了) */
settled(b: any): { ok: true } {
const l = this.bySession.get(String(b?.sessionId ?? ""));
if (!l || l.busy || l.starting || l.checking) return { ok: true };
- if (this.store.openInputs(l.taskId).some((i) => i.deliveredAt && i.runId === l.runId)) return { ok: true };
+ if (this.inputsOf(l).some((i) => i.deliveredAt && i.runId === l.runId)) return { ok: true };
const killed = Array.isArray(b?.killedJobs) ? b.killedJobs.map(String) : [];
- if (killed.length) log.info("task settling timed out; background jobs were stopped", { task: l.taskId, jobs: killed });
+ if (killed.length) log.info("task settling timed out; background jobs were stopped", { task: l.taskId || l.ruleId, jobs: killed });
this.finish(l);
return { ok: true };
}
@@ -661,26 +750,27 @@ export class TaskService {
const error = l.turnError;
l.turnError = undefined;
const delay = this.delays[l.retries++];
- log.warn("task turn failed; continuing after a pause", { task: l.taskId, inMs: delay, message: error.slice(0, 200) });
+ log.warn("task turn failed; continuing after a pause", { task: l.taskId || l.ruleId, inMs: delay, message: error.slice(0, 200) });
l.timer = setTimeout(() => {
l.timer = undefined;
- void this.deliver_(l, [this.addInput(l.taskId, "note", retryNote(error), false)]);
+ void this.deliver_(l, [this.inputFor(l, "note", retryNote(error))]);
}, delay);
l.timer.unref?.();
return;
}
if (!l.nudged) {
l.nudged = true;
- void this.deliver_(l, [this.addInput(l.taskId, "nudge", NUDGE, false)]);
+ void this.deliver_(l, [this.inputFor(l, "nudge", l.ruleId ? RULE_NUDGE : NUDGE)]);
return;
}
- if (l.turnError) log.warn("task failed after retries", { task: l.taskId, message: l.turnError.slice(0, 300) });
+ if (l.turnError) log.warn("task failed after retries", { task: l.taskId || l.ruleId, message: l.turnError.slice(0, 300) });
this.end(l, "failed", undefined, l.turnError ? "模型一直出错" : "没有给出结果");
}
/** 结束 run:存下步骤、结果;done / failed 发回会话;空出名额 */
private end(l: Live, outcome: RunOutcome, report?: TaskReport, error = ""): void {
if (this.live.get(l.runId) !== l) return;
+ if (l.ruleId) return this.endRule(l, outcome, report, error);
this.forget(l);
const now = this.now();
this.store.updateRun(l.runId, { state: "ended", outcome, report, error, endedAt: now, activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });
@@ -696,7 +786,9 @@ export class TaskService {
private forget(l: Live): void {
clearTimeout(l.timer);
+ clearTimeout(l.capTimer);
l.timer = undefined;
+ l.capTimer = undefined;
this.live.delete(l.runId);
if (this.bySession.get(l.sessionId) === l) this.bySession.delete(l.sessionId);
}
@@ -778,6 +870,7 @@ export class TaskService {
report(b: any): { text?: string; error?: string } {
const l = this.bySession.get(String(b?.sessionId ?? ""));
if (!l) return { error: "This background task is not running any more (it was stopped or has ended). Stop working on it." };
+ if (l.ruleId) return this.ruleReport(l, b);
const state = String(b?.state ?? "");
if (state !== "progress" && state !== "done" && state !== "failed" && state !== "needs_you") return { error: "state must be progress, needs_you, done or failed" };
const question = state === "needs_you" ? questionOf(b) : undefined;
@@ -826,9 +919,19 @@ export class TaskService {
}
case "list": {
const list = this.list({ conversationId: conv.id, limit: 10 });
- if (!list.length) return { text: "This conversation has no background tasks." };
- return { text: list.map((t) => `${t.id} 「${t.title}」 ${t.stage.label}${t.latest ? ` — ${t.latest}` : ""}`).join("\n") };
+ const rules = this.listRules({ conversationId: conv.id });
+ if (!list.length && !rules.length) return { text: "This conversation has no background tasks or rules." };
+ return {
+ text: [
+ ...list.map((t) => `${t.id} 「${t.title}」 ${t.stage.label}${t.latest ? ` — ${t.latest}` : ""}`),
+ ...rules.map((r) => `rule ${r.id} 「${r.title}」 ${r.when} · ${r.state.label}${r.last ? ` — ${r.last.line}` : ""}`),
+ ].join("\n"),
+ };
}
+ case "rule_create":
+ return this.ruleCreateTool(conv, a);
+ case "rule_update":
+ return this.ruleUpdateTool(conv, a);
default:
return { error: "unknown task tool" };
}
@@ -870,6 +973,7 @@ export class TaskService {
/** 审批中心有新的、或有了决定:任务的提问有了回答就交给任务;更新阶段;同一会话的下一个提问可以推了 */
private onApproval(e: ApprovalEvent): void {
const row = e.row;
+ if (row.ruleId) return this.onRuleApproval(e);
if (!row.taskId) return;
const task = this.store.getTask(row.taskId);
if (!task) return;
@@ -1037,16 +1141,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)}` : ""}`);
+ // 规则接着编号(/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 ["后台任务:", ...lines, ...(working >= 0 ? ["发 /stop 编号 可停止。"] : [])].join("\n");
+ return [...(list.length ? ["后台任务:", ...lines] : []), ...(rules.length ? ["规则:", ...ruleLines] : []), ...(working >= 0 || rules.length ? ["发 /stop 编号 可停止。"] : [])].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}」。`;
+ }
if (!t) return `没有第 ${n} 个后台任务,发 /tasks 查看。`;
if (t.stage.group !== "working") return `「${t.title}」${t.stage.label}。`;
void this.stopTask(t.id, by);
@@ -1065,6 +1183,689 @@ export class TaskService {
/* 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: "名称不能为空" };
+ next.title = t;
+ }
+ let reworded = false;
+ if (patch.instruction !== undefined) {
+ const t = patch.instruction.trim().slice(0, 2000);
+ if (!t) return { error: "规则不能为空" };
+ 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 !== 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: "没有这个会话" };
+ next.conversationId = c.id;
+ }
+ let trigger = rule.trigger;
+ if (patch.schedule) {
+ if (rule.trigger.kind !== "schedule") return { error: "这条规则由事件触发,没有时间表" };
+ 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: "提醒没有观察模式" };
+ 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: "正在运行" };
+ 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, "电脑没开");
+ continue;
+ }
+ if (last > due) this.skipRun(rule, due, "电脑没开");
+ 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, "上次还没跑完");
+ 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),
+ 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)!;
+ }
+
+ /** 记一条跳过(电脑没开、一直在忙、上次还没跑完) */
+ 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 });
+ 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, "超时");
+ 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");
+ 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}`);
+ }
+ }
+
+ /** 那一句用主模型写(检查用的小模型只给草稿);执行时发出去。主模型不可用就用草稿 */
+ 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.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, "批准超时");
+ }
+
+ // ---------- 规则:聊天代理的工具 ----------
+
+ /** 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}` };
+ 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}`,
+ };
+ }
+
+ /** 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,
+ version: r.ruleVersion,
+ permission: r.permission === "read-only" ? "只读" : r.permission === "workspace-write" ? "可写工作区" : "",
+ 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),
+ 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 --git a/src/tasks/slots.ts b/src/tasks/slots.ts
index c182cee..355d8b1 100644
--- a/src/tasks/slots.ts
+++ b/src/tasks/slots.ts
@@ -14,7 +14,7 @@ const ORDER: Record<Priority, number> = { person: 0, launch: 1, recover: 2, rule
export function priorityOf(cause: RunCause): Priority {
if (cause === "launch") return "launch";
if (cause === "recover") return "recover";
- if (cause === "schedule") return "rule";
+ if (cause === "schedule" || cause === "event") return "rule";
return "person";
}
diff --git a/src/web/server.ts b/src/web/server.ts
index ee70647..af73bca 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -21,7 +21,8 @@ import { normalizeSettings } from "../agent/settings.js";
import { scopeLabel } from "../agent/memory.js";
import { pwshProbe, type PwshMode } 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";
const log = logger("web");
const require = createRequire(import.meta.url);
@@ -452,6 +453,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
? app.agent.approvals.answer(item.approvalId!, { answers: b.answers.map((a: any) => ({ id: String(a.id), selected: (a.selected ?? []).map(String), ...(a.custom ? { custom: String(a.custom) } : {}) })) }, "web")
: app.agent.approvals.answerText(item.approvalId!, String(b.text ?? ""), "web");
} else if (item.kind === "delivery" && (action === "retry" || action === "dismiss")) ok = app.delivery.act(item.id, action);
+ else if (item.kind === "rule" && action === "retry") ok = !app.tasks.resumeRule(item.ruleId!).error;
else if (action === "retry") ok = !(await app.tasks.retry(item.taskId!)).error;
else if (action === "stop") ok = await app.tasks.stopTask(item.taskId!, "web");
if (!ok) throw new HttpError(409, "没能完成,可能已经处理过了");
@@ -489,6 +491,69 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
}
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 ?? "时间表不对");
+ 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 ?? "没能建好");
+ 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 (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, "模式只能是关、观察或执行");
+ 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 ?? "没能保存");
+ 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, "没有这次运行");
+ return send(res, 200, { steps: app.tasks.activity(run.id) });
+ }
+ throw new HttpError(404, "not found");
+ }
// —— Windows:代理用的 PowerShell(对话空状态、设置 → 常规、故障排查)——
if (seg[0] === "pwsh") {
const view = () => ({ ...pwshProbe.snapshot(), dismissed: cfg.ui.pwshHintDismissed });
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index c4b37c7..22dd9e7 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -437,10 +437,11 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
const userTexts = (c: { body: any }) => (c.body.messages ?? []).filter((m: any) => m.role === "user").map((m: any) => textOf(m.content)) as string[];
const DEFAULT_PERSONA = "你是一个乐于助人的中文助手,回答简洁准确。";
/**
- * 系统提示词加工具定义的字符数上限(DSH 自己的部分 + 我们的人设、机器人段和工具;基线 34,052 = 提示词 3,692 + 工具 30,360,其中后台任务的 task_start、task_message、task_list 约 1,460;上限高约 5%)。
+ * 系统提示词加工具定义的字符数上限(DSH 自己的部分 + 我们的人设、机器人段和工具;基线 34,052 = 提示词 3,692 + 工具 30,360,其中后台任务的 task_start、task_message、task_list 约 1,460;
+ * 3b、3c 之后 34,289;3d 加上规则的 rule_create、rule_update 后 35,649 = 提示词 3,692 + 工具 31,957(多了 1,360);上限高约 5%)。
* 缩短了就调低;要调高,在提交说明里写清原因。电脑操作的 MCP 工具随平台变化,不计入。
*/
- const SURFACE_BUDGET = 35_800;
+ const SURFACE_BUDGET = 37_400;
it("the system prompt has our persona and the bot's section, not DSH's coding persona; the segment's first message has channel and memory", async () => {
await chat("/reset");
diff --git a/test/prompts.unit.test.ts b/test/prompts.unit.test.ts
index a3c4ac9..87788c6 100644
--- a/test/prompts.unit.test.ts
+++ b/test/prompts.unit.test.ts
@@ -6,7 +6,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import {
BOT_SECTION,
BOT_SECTION_ORDER,
@@ -25,7 +25,14 @@ import {
recoveryNote,
segmentInput,
taskBrief,
+ RULE_NUDGE,
+ RULE_RERUN,
+ RULE_RESULT_SYSTEM,
+ ruleBrief,
+ ruleResultInput,
+ ruleRules,
} from "../src/agent/prompts/index.js";
+import { RULE_DENY, RULE_DENY_PREFIX } from "../src/tasks/rules.js";
import { AgentHost, locateDshRuntime } from "../src/agent/host.js";
import { normalizeSettings } from "../src/agent/settings.js";
import { findAppRoot } from "../src/magpie/supervisor.js";
@@ -64,6 +71,43 @@ async function loadPlugins(): Promise<{ chat: ToolDef[]; task: { tools: ToolDef[
}
}
+/**
+ * 规则会话建出来:amb-tasks 经 bridge 问宿主要配置(/dsh/task-config),这里用宿主会给的那份回答它(answer 为 undefined 时模拟宿主不可达),
+ * 拿到限定的工具、规则段、规则版的 task_report、权限;再建一个它的子代理,看它跟不跟着
+ */
+async function loadRule(mode: "observe" | "act", answer: "ok" | "down" = "ok") {
+ const env = { ...process.env };
+ const fetchMock = vi.fn(async (url: string, init: any) => {
+ if (answer === "down") throw new Error("ECONNREFUSED");
+ const b = JSON.parse(init.body);
+ expect(url).toBe("http://127.0.0.1:9/dsh/task-config");
+ const cfg = { kind: "rule", mode, deny: RULE_DENY[mode], denyPrefix: RULE_DENY_PREFIX, section: ruleRules(mode), permission: mode === "observe" ? "read-only" : "workspace-write" };
+ return new Response(JSON.stringify(b.sessionId.startsWith("rule-") ? cfg : { error: "no" }), { status: 200, headers: { "content-type": "application/json" } });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ try {
+ Object.assign(process.env, { AMB_BRIDGE_URL: "http://127.0.0.1:9", AMB_BRIDGE_TOKEN: "t", AMB_MEMORY: "1" });
+ const tools: any[] = [];
+ const created: Array<(e: any) => unknown> = [];
+ const ctx = { tools: { register: (t: any) => tools.push(t), get: (n: string) => tools.find((t) => t.name === n) ?? (["present", "ask_user_question"].includes(n) ? {} : undefined) }, inject: () => {}, on: (ev: string, fn: any) => ev === "agent/created" && created.push(fn), get: () => undefined };
+ for (const f of ["amb-memory.mjs", "amb-media.mjs", "amb-tasks.mjs"]) (await import(path.join(runtime!, "plugins", f))).apply(ctx);
+ const make = (id: string, parentSession?: string) => {
+ const out = { tools: [] as ToolDef[], sections: [] as any[], deny: [] as string[][], guards: [] as Array<(e: any) => string | undefined> };
+ const agent = { id, session: { header: parentSession ? { parentSession } : {} }, ctx: { tools: { restrict: (f: any) => out.deny.push(f.deny), register: (t: any) => out.tools.push(def(t)), guard: (g: any) => out.guards.push(g) }, systemPrompt: { section: (x: any) => out.sections.push(x) } } };
+ return { agent, out };
+ };
+ const rule = make("rule-rl_1-abc");
+ for (const fn of created) await fn({ agent: rule.agent });
+ const sub = make("sub-1", "rule-rl_1-abc");
+ for (const fn of created) await fn({ agent: sub.agent });
+ const presets = (globalThis as any)[Symbol.for("amb.session.presets")] as Map<string, string>;
+ return { rule: rule.out, sub: sub.out, presets: new Map(presets), calls: fetchMock.mock.calls.length };
+ } finally {
+ process.env = env;
+ vi.unstubAllGlobals();
+ }
+}
+
/** 提示词的各段,按名字 */
async function parts(): Promise<Record<string, string>> {
const tools = runtime ? await ourTools() : [];
@@ -89,6 +133,15 @@ async function parts(): Promise<Record<string, string>> {
"task recovery": recoveryNote(["sleep 600"]),
"task nudge": NUDGE,
"tool task_report": runtime ? JSON.stringify((await loadPlugins()).task.tools.find((t) => t.name === "task_report") ?? "") : "",
+ "tool rule_create": tool("rule_create"),
+ "tool rule_update": tool("rule_update"),
+ "rule observe": ruleRules("observe"),
+ "rule act": ruleRules("act"),
+ "rule brief": ruleBrief({ title: "看 X 价格", when: "每天 08:00", instruction: "每天早上 8 点看看 X 的价格,低于 200 告诉我", mode: "observe", recent: [{ at: "11月1日 08:00", line: "没有告诉用户。X 现在 ¥259" }], memory: "" }),
+ "rule nudge": RULE_NUDGE,
+ "rule rerun": RULE_RERUN,
+ "rule result": RULE_RESULT_SYSTEM + "\n\n" + ruleResultInput({ instruction: "低于 200 告诉我", summary: "X 现在 ¥199", draft: "X 降到 199 了" }),
+ "tool rule report observe": runtime ? JSON.stringify((await loadRule("observe")).rule.tools.find((t) => t.name === "task_report") ?? "") : "",
};
out["*"] = Object.values(out).join("\n\n");
return out;
@@ -136,6 +189,17 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [
["任务的第一条输入:用户原话在前,说明在后", "task brief", ["[用户的原话]\n帮我调研三家云的 GPU 价格", "[对话助手的说明]\n比较 A100 包月价", "tasks/gpu-abc123"]],
["恢复说明:被停的后台命令;重复外部动作之前先查日志和外部系统", "task recovery", ["The app restarted", "sleep 600", "Before repeating any outside action", ".task/journal.md", "task_report"]],
["没报告时提醒一次:done 带一句话、failed 带原因", "task nudge", ["task_report", "done", "failed"]],
+ // —— 规则(3d):检查从观察开始,只在值得说时说一句;观察只看不动;执行最多可写工作区 ——
+ ["rule_create:用户原话原样;检查从观察开始只记录;提醒到点发那句;确认一句", "tool rule_create", ["verbatim", "starts in observe mode", "only recording what it would say", "kind remind", "Confirm in one sentence", "every 30m", "weekly mon,thu"]],
+ ["rule_update:用户要求时改模式(执行才发)、原话、时间表或删掉", "tool rule_update", ["when the user asks", "mode act (results are sent)", "observe (only records)", "off", "delete"]],
+ ["规则段(观察):优先于聊天规则;只看不动,本来要做的写进 would;值得说才说一句,只记下来;不报告就算失败", "rule observe",
+ ["优先于上面的聊天规则", "只看、只查,不改任何东西", "would", "task_report", "值得告诉用户", "不值得说就 done 不带 message", "这次只记下来", "不超过 300 字", "就算失败"], ["needs_you", ".task/journal.md"]],
+ ["规则段(执行):只做规则里写的事,外部动作前后记日志;那一句会发给用户", "rule act", ["只做规则里写的事", ".task/journal.md", "会发给用户", "不值得说就 done 不带 message"], ["would"]],
+ ["规则的第一条输入:规则、用户原话、最近几次的结果、这次是观察", "rule brief", ["[规则]\n看 X 价格(每天 08:00)", "[用户的原话]\n每天早上 8 点看看 X 的价格,低于 200 告诉我", "[最近几次的结果]\n- 11月1日 08:00:没有告诉用户。X 现在 ¥259", "[这次]\n观察:只看不动,message 只记下来,不会发给用户。"]],
+ ["规则没报告时提醒一次:值得说带一句,不值得说不带,查不了报失败", "rule nudge", ["task_report", "done with a one-line message", "done without a message to stay quiet", "failed with the reason"]],
+ ["重跑:先看日志和外部系统再重复外部动作", "rule rerun", ["重跑", ".task/journal.md", "外部系统"]],
+ ["主模型写那一句:只输出一句,先说结果,不说过程、不提规则", "rule result", ["只输出这一句话", "先说结果", "不超过 120 字", "不说过程", "不提规则和检查本身", "[草稿]\nX 降到 199 了"]],
+ ["规则版 task_report:值得说才带 message,不带就保持安静;观察时只记下来;没有 needs_you", "tool rule report observe", ["only when they should hear about it", "leave it out to stay quiet", "observe mode: it is only recorded", "would", "failed"], ["needs_you"]],
];
describe.skipIf(!runtime)("提示词约定", () => {
@@ -146,16 +210,18 @@ describe.skipIf(!runtime)("提示词约定", () => {
for (const words of gone) expect(text.toLowerCase()).not.toContain(words.toLowerCase());
});
- it("聊天规则、人设和任务规则都短", () => {
+ it("聊天规则、人设、任务规则和规则段都短", () => {
expect(CHAT_RULES.length).toBeLessThan(440);
expect(agentPersona({ computerUse: true }).length).toBeLessThan(180);
expect(TASK_RULES.length).toBeLessThan(400);
+ expect(ruleRules("observe").length).toBeLessThan(300);
+ expect(ruleRules("act").length).toBeLessThan(300);
});
it("任务会话:只去掉注册了的聊天专用工具,规则段在机器人段之后(优先),有 task_report;子代理拿不到任务工具", async () => {
const { task } = await loadPlugins();
- // 只有 present 和三个任务工具是"注册了的":ask_user_question、rule_create 在这个假环境里没有,不能交给 restrict(它会抛错)
- expect(task.deny).toEqual([["present", "task_start", "task_message", "task_list"]]);
+ // 只有 present 和聊天的任务、规则工具是"注册了的":ask_user_question 在这个假环境里没有,不能交给 restrict(它会抛错)
+ expect(task.deny).toEqual([["present", "task_start", "task_message", "task_list", "rule_create", "rule_update"]]);
expect(task.sections).toHaveLength(1);
expect(task.sections[0]).toMatchObject({ name: TASK_SECTION, order: TASK_SECTION_ORDER, interpolate: false });
expect(TASK_SECTION_ORDER).toBeGreaterThan(BOT_SECTION_ORDER);
@@ -163,12 +229,49 @@ describe.skipIf(!runtime)("提示词约定", () => {
expect(task.tools.map((t) => t.name)).toEqual(["task_report"]);
});
+ it("规则会话:插件按宿主给的配置去掉工具、加规则段、注册规则版的 task_report、定权限;子代理跟着;宿主不可达就只读、一律拒绝", async () => {
+ const o = await loadRule("observe");
+ expect(o.calls).toBe(1);
+ // 只交注册了的:present、ask_user_question、聊天的任务和规则工具、生图、记忆的 remember / forget(recall 留着)
+ expect(o.rule.deny).toHaveLength(1);
+ expect(new Set(o.rule.deny[0])).toEqual(new Set(["present", "ask_user_question", "task_start", "task_message", "task_list", "rule_create", "rule_update", "generate_image", "generate_video", "media_models", "media_docs", "remember", "forget"]));
+ expect(o.rule.sections).toHaveLength(1);
+ expect(o.rule.sections[0]).toMatchObject({ name: TASK_SECTION, order: TASK_SECTION_ORDER, interpolate: false });
+ expect(o.rule.sections[0].text()).toBe(ruleRules("observe"));
+ expect(o.rule.tools.map((t) => t.name)).toEqual(["task_report"]);
+ const props = (t: ToolDef) => JSON.stringify(t.parameters);
+ expect(props(o.rule.tools[0])).toContain('"enum":["progress","done","failed"]');
+ expect(props(o.rule.tools[0])).toContain('"would"');
+ // 电脑操作按前缀拒绝(MCP 工具名列不全)
+ const guard = (g: Array<(e: any) => string | undefined>, name: string) => g.map((f) => f({ name })).find(Boolean);
+ expect(guard(o.rule.guards, "mcp__computer-use__click")).toMatch(/not available while running a rule/);
+ expect(guard(o.rule.guards, "bash")).toBeUndefined();
+ expect(o.presets.get("rule-rl_1-abc")).toBe("read-only");
+ // 子代理:同样的权限和去掉的工具,没有规则段和 task_report
+ expect(o.presets.get("sub-1")).toBe("read-only");
+ expect(new Set(o.sub.deny[0])).toEqual(new Set(o.rule.deny[0]));
+ expect(o.sub.sections).toEqual([]);
+ expect(guard(o.sub.guards, "mcp__computer-use__type")).toBeDefined();
+ // 执行:记忆可以写,权限是可写工作区
+ const a = await loadRule("act");
+ expect(a.rule.deny[0]).not.toContain("remember");
+ expect(a.rule.sections[0].text()).toBe(ruleRules("act"));
+ expect(props(a.rule.tools[0])).not.toContain('"would"');
+ expect(a.presets.get("rule-rl_1-abc")).toBe("workspace-write");
+ // 宿主不可达:只读,什么工具都拒绝,也没有 task_report(这次会失败)
+ const d = await loadRule("act", "down");
+ expect(d.presets.get("rule-rl_1-abc")).toBe("read-only");
+ expect(d.rule.tools).toEqual([]);
+ expect(guard(d.rule.guards, "bash")).toMatch(/cannot be reached/);
+ });
+
/**
- * 我们交给模型的部分:人设 + 机器人段(典型人设、开着记忆)+ 我们的工具定义(记忆、生图、后台任务)。
- * 基线 8,514(提示词 907 + 工具 7,607,其中 task_start、task_message、task_list 1,370),上限高约 5%。
+ * 我们交给模型的部分:人设 + 机器人段(典型人设、开着记忆)+ 我们的工具定义(记忆、生图、后台任务、规则)。
+ * 3a 基线 8,514(提示词 907 + 工具 7,607,其中 task_start、task_message、task_list 1,370);3b、3c 之后 8,751(工具 7,844)。
+ * 3d 加上 rule_create(819)、rule_update(467)和 task_list 多一句「and rules」后 10,049(工具 9,142)。上限高约 5%。
* 缩短了就调低;要调高,在提交说明里写清原因。
*/
- const BUDGET = 8_950;
+ const BUDGET = 10_550;
it("我们的提示词加工具定义不超过字符数上限", async () => {
const prompt = agentPersona({ computerUse: true }).length + botPrompt({ name: "小蓝", persona: PERSONA, memory: true }).length;
const tools = JSON.stringify(await ourTools()).length;
@@ -185,6 +288,19 @@ describe.skipIf(!runtime)("提示词约定", () => {
const extra = TASK_RULES.length + JSON.stringify(task.tools).length;
expect(extra, `${TASK_RULES.length} characters of rules and ${JSON.stringify(task.tools).length} of task_report`).toBeLessThanOrEqual(TASK_BUDGET);
});
+
+ /**
+ * 规则会话(观察,比执行长)在聊天会话之外多出来的:规则段 + 规则版的 task_report(去掉的工具不算)。上限高约 5%。
+ * 3d 基线 1,058(观察:规则段 285 + task_report 773)。
+ */
+ const RULE_BUDGET = 1_110;
+ it("规则会话多出来的提示词和工具不超过字符数上限", async () => {
+ for (const mode of ["observe", "act"] as const) {
+ const { rule } = await loadRule(mode);
+ const extra = ruleRules(mode).length + JSON.stringify(rule.tools).length;
+ expect(extra, `${mode}: ${ruleRules(mode).length} characters of rules and ${JSON.stringify(rule.tools).length} of task_report`).toBeLessThanOrEqual(RULE_BUDGET);
+ }
+ });
});
describe("渠道说明与第一条消息", () => {
diff --git a/test/rules.integration.test.ts b/test/rules.integration.test.ts
new file mode 100644
index 0000000..671b25a
--- /dev/null
+++ b/test/rules.integration.test.ts
@@ -0,0 +1,279 @@
+/**
+ * 规则(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(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(/^本会做:需要批准:/);
+ 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 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 --git a/test/rules.unit.test.ts b/test/rules.unit.test.ts
new file mode 100644
index 0000000..7289fb1
--- /dev/null
+++ b/test/rules.unit.test.ts
@@ -0,0 +1,796 @@
+/**
+ * 规则(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 { 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() {} }) };
+ // @ts-expect-error 界面代码是不经构建的 JS
+ const { ruleSub, fmtRunAt, fmtNext } = await import("../ui/components/rules.js");
+ 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"]);
+ // 2026-11-02 是周一
+ expect([fmtNext(t(3, 9), now), fmtNext(t(10, 9), now)]).toEqual(["周四 09:00", "11/12 09:00"]);
+ });
+});
+
+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(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(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", "一直在忙"]]);
+ 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", "上次还没跑完"],
+ ]);
+ });
+
+ 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: "应用重启了" });
+ });
+
+ 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: "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(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" });
+ // 不能问用户
+ 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(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("模拟 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 --git a/ui/components/rules.js b/ui/components/rules.js
new file mode 100644
index 0000000..5cbdaa7
--- /dev/null
+++ b/ui/components/rules.js
@@ -0,0 +1,285 @@
+// 规则(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";
+
+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 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);
+};
+
+/** 运行记录里的时间:今天 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)}`;
+}
+
+/** 下次运行:今天 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)}`;
+}
+
+const MODE = { observe: "观察", act: "执行" };
+
+/** 行的第二行:观察中 · 下次 明天 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.state.key === "off" || rule.state.key === "done") return rule.state.label;
+ return rule.nextRunAt ? `${rule.state.label} · 下次 ${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?.());
+ 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>`}
+ </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(" · ");
+ 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>`}
+ ${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)} />`}
+ </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("已删除")));
+ };
+ 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(" · ");
+ return html`<div class="rule-detail">
+ <p class="rule-words selectable">「${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} />
+ <span class="grow"></span>
+ <${Button} size="sm" loading=${busy === "run"} disabled=${!!busy || !!rule.live || rule.mode === "off"} onClick=${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>`}
+ <div class="actions">
+ <button type="button" class="text" onClick=${() => setEditing(true)}>编辑</button>
+ <button type="button" class="text danger" disabled=${busy === "del"} onClick=${del}>删除</button>
+ </div>
+ <div class="t-label">运行记录</div>
+ ${!runs && html`<span class="hint">加载中…</span>`}
+ ${runs && !runs.length && html`<span class="hint">还没有运行过</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>`}
+ ${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 DAY_PICKS = [1, 2, 3, 4, 5, 6, 0];
+
+/** 规则的时间表 → 编辑器里的字段 */
+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;
+ 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" ? "已建好提醒" : "已建好规则,先观察");
+ 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}>
+ <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>
+ ${!event && html`<div class="rule-when">
+ <span class="t-label">时间</span>
+ <${Seg} label="时间" options=${KINDS} 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 === "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>`)}
+ </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>`}
+ </div>
+ ${channel === "weixin" && html`<p class="hint">微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。</p>`}
+ </div>
+ <div class="actions">
+ <${Button} onClick=${onClose}>取消<//>
+ <${Button} variant="primary" loading=${busy} disabled=${!ok} onClick=${save}>${rule ? "保存" : "建好"}<//>
+ </div>
+ <//>`;
+}
diff --git a/ui/css/settings.css b/ui/css/settings.css
index 17c8806..c9ed757 100644
--- a/ui/css/settings.css
+++ b/ui/css/settings.css
@@ -81,7 +81,7 @@ button.need-head:hover, button.need-head:hover .need-who b { color: var(--fg); }
.need-actions:empty { display: none; }
.need-reply { display: flex; align-items: center; gap: var(--ctl-gap); }
.need-reply .field { flex: 1; --field-h: var(--ctl-md); }
-.need-detail .task-detail { margin-top: var(--space-1); }
+.need-detail .task-detail, .need-detail .rule-detail { margin-top: var(--space-1); }
/* 故障排查(screens/troubleshoot.js):状态和检测结果是普通的行;stderr 尾部是组里展开的一块(不再套底);
日志是自己的一块 --well(和代码块同一种面),不描边 */
diff --git a/ui/css/shell.css b/ui/css/shell.css
index 88b4feb..ddd19a7 100644
--- a/ui/css/shell.css
+++ b/ui/css/shell.css
@@ -216,6 +216,41 @@ button.thread:active { background: var(--side-press); }
.transcript-turn { display: grid; gap: var(--space-1); }
.transcript .work-line { font-size: var(--fs-sm); }
+/* 规则(components/rules.js):「任务」组里一条规则一行(时间表 · 标题、状态和下次),观察够了的行里多一句改为执行;
+ 点开是同一块里的详情(原话、模式、操作、运行记录),运行记录一次一行、不画分隔线,点开一行看报告和步骤,也不另起一块 */
+.rule-row .dot { flex: none; }
+.rule-hint { display: block; margin-top: var(--space-0-5); font-size: var(--fs-xs); text-align: left; }
+.rule-detail { display: grid; gap: var(--space-2); min-width: 0; }
+.rule-detail > .actions { display: flex; align-items: center; gap: var(--ctl-gap); flex-wrap: wrap; }
+.rule-detail > .actions .grow { flex: 1; }
+.rule-detail > .t-label { margin-top: var(--space-1); }
+.rule-words { font-size: var(--fs-sm); color: var(--fg); line-height: var(--lh-snug); overflow-wrap: anywhere; }
+.rule-runs { display: grid; list-style: none; margin: 0; padding: 0; }
+.rule-run-head {
+ display: flex; align-items: baseline; gap: var(--space-2); width: 100%; min-width: 0; padding: var(--space-1) 0;
+ text-align: left; font-size: var(--fs-xs); color: var(--fg-2); border-radius: var(--r-sm); transition: color var(--t-fast);
+}
+.rule-run-head:hover { color: var(--fg); }
+.rule-run-head :is(.at, .m) { flex: none; color: var(--muted); }
+.rule-run-head .l { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rule-run.open .rule-run-head .l { white-space: normal; overflow-wrap: anywhere; }
+.rule-run-head .chev { flex: none; align-self: center; color: var(--muted); transition: transform var(--t-fast); }
+.rule-run.open .rule-run-head .chev { transform: rotate(90deg); }
+.rule-run-body { display: grid; gap: var(--space-1-5); padding: 0 0 var(--space-2); font-size: var(--fs-xs); color: var(--fg-2); line-height: var(--lh-normal); }
+.rule-run-body p { overflow-wrap: anywhere; }
+.rule-run-body .activity, .rule-run-body .work-line { margin-bottom: 0; }
+/* 详情本身就是一块 --well(面板里的展开区、「需要你」的列表):步骤列表不再铺一层底,只是折叠打开 */
+.rule-detail .act-list { background: none; padding: 0; margin-bottom: 0; }
+/* 新建 / 编辑规则的对话框:表单直接排在对话框里 */
+.rule-form { display: grid; gap: var(--space-3); }
+.rule-form label { display: grid; gap: var(--space-1-5); font-size: var(--fs-xs); color: var(--fg-2); font-weight: var(--fw-medium); }
+.rule-when { display: grid; gap: var(--space-1-5); justify-items: start; }
+.rule-when-row { display: flex; align-items: center; gap: var(--ctl-gap); flex-wrap: wrap; }
+.rule-when-row .field { width: auto; --field-h: var(--ctl-md); }
+.rule-days { display: flex; gap: var(--space-1); flex-wrap: wrap; }
+.rule-days .chip { height: var(--ctl-sm); padding: 0 var(--space-2-5); }
+.rule-days .chip.on { background: var(--pill-press); color: var(--fg); font-weight: var(--fw-medium); }
+
.panel-scrim { display: none; }
/* narrow window: the panel floats over the chat as a glass drawer over a scrim */
@media (max-width: 1180px) {
diff --git a/ui/design/gallery.js b/ui/design/gallery.js
index bdf2870..dca854d 100644
--- a/ui/design/gallery.js
+++ b/ui/design/gallery.js
@@ -5,6 +5,7 @@ import { html, Icon, Button, IconButton, Seg, Switch, MenuButton, Menu, Badge, N
import { BotAvatar, AvatarPicker, AppMark, BOT_CHARS, CHAR_KEYS, MAIN_CHAR } from "../components/avatar.js";
import { TEMPLATES } from "../screens/new-bot.js";
import { NeedItem, NeedsRow } from "../screens/needs-you.js";
+import { RuleRow, RuleDetail } from "../components/rules.js";
import { Markdown } from "../components/markdown.js";
import { useStore, toast, saved, failed, confirmSheet } from "../lib/store.js";
import { themeMode, setThemeMode } from "../lib/theme.js";
@@ -372,7 +373,7 @@ function Gallery() {
["原则", [["principles", "分层与约定"]]],
["Token", [["color", "颜色"], ["material", "材质"], ["type", "文字"], ["space", "间距与尺寸"], ["elevation", "投影与层级"], ["motion", "动效"]]],
["组件", [["states", "状态矩阵"], ["buttons", "按钮"], ["inputs", "输入"], ["menus", "菜单与分段"], ["status", "状态与反馈"], ["lists", "列表行"], ["overlays", "对话框与提示"], ["avatars", "头像"]]],
- ["页面模式", [["patterns", "对话"], ["needs", "需要你"], ["custom", "定制"]]],
+ ["页面模式", [["patterns", "对话"], ["needs", "需要你"], ["rules", "规则"], ["custom", "定制"]]],
];
return html`<${Compare.Provider} value=${compare}><div class="gal">
<nav class="gal-nav" aria-label="目录">
@@ -577,6 +578,19 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场
<//>
<//>
+ <${Section} id="rules" title="规则" lead="信息面板「任务」组里一条规则一行:时间表 · 标题,状态和下次运行。观察了 3 次的,行里多一句改为执行(只在这里,从不推送)。点开是同一块里的详情和运行记录,记录一次一行、不画分隔线,再点开一行看报告。">
+ <${Demo} title="行" note="RuleRow:观察中(提示改为执行)/ 执行中 / 暂停 / 提醒">
+ ${() => html`<div class="panel-body" style="width: 340px; flex: none; padding: var(--space-2); border-radius: var(--r-pane); background: var(--grain), var(--glass-panel)">
+ <div class="list">${RULES.map((r) => html`<${RuleRow} rule=${r} open=${false} onToggle=${() => {}} />`)}</div>
+ </div>`}
+ <//>
+ <${Demo} title="详情与运行记录" note="RuleDetail:原话、模式、立即运行、运行记录(本会发送 / 保持安静 / 失败 / 跳过)">
+ ${() => html`<div class="panel-body" style="width: 340px; flex: none; padding: var(--space-2); border-radius: var(--r-pane); background: var(--grain), var(--glass-panel)">
+ <div class="list"><div class="row-edit rule-edit"><${RuleDetail} rule=${RULES[0]} runs=${RULE_RUNS} /></div></div>
+ </div>`}
+ <//>
+ <//>
+
<${Section} id="custom" title="定制" lead="不改组件源码:在上下文里覆盖组件变量;需要一块不同主题的区域时,加 data-theme。">
<${Demo} title="覆盖组件变量" code=${`.notice .btn { --btn-h: var(--ctl-sm); --btn-px: var(--space-2-5); } /* 上下文覆盖 */
<button class="btn" style="--btn-bg: var(--green-soft); --btn-fg: var(--green)">…</button>
@@ -604,9 +618,31 @@ const NEEDS = [
{ id: "a", kind: "approval", botName: "小蓝", subject: "清理旧构建", status: "等你批准", line: "rm -rf build/", since: Date.now() - 5 * 60_000, severity: "warn" },
{ id: "d", kind: "delivery", botName: "小蓝", subject: "1 条结果未送达微信", status: "在微信里发条消息就能收到", line: "季度报告做好了,在 tasks 文件夹里。", since: Date.now() - 20 * 60_000, severity: "warn", actions: [] },
{ id: "f", kind: "failed", botName: "红魔", subject: "季度报告", status: "失败", line: "X 云的价格页要登录,我进不去", since: Date.now() - 40 * 60_000, severity: "err" },
+ { id: "r", kind: "rule", botName: "红魔", subject: "规则「每日 issue 巡检」", status: "连续失败 3 次,已暂停", line: "GitHub 返回 401:令牌可能过期了", since: Date.now() - 90 * 60_000, severity: "err", actions: ["retry"] },
{ id: "l", kind: "login", botName: "绿草", subject: "微信登录已过期", status: "", line: "", since: Date.now() - 3 * 3600_000, severity: "err" },
];
+/** 规则的样例(单人:自己的机器人小蓝):每天 8 点看 X 价格(观察了 3 次)、每周的 issue 周报、暂停了的巡检、一次性的提醒 */
+const at = (days, h, m = 0) => {
+ const d = new Date();
+ d.setDate(d.getDate() + days);
+ d.setHours(h, m, 0, 0);
+ return d.getTime();
+};
+const rule = (o) => ({ botId: "b", kind: "check", mode: "observe", observeLeft: 0, failures: 0, hint: false, observed: 0, channel: "weixin", message: "", trigger: { kind: "schedule" }, version: 1, ...o });
+const RULES = [
+ rule({ id: "g1", title: "看 X 价格", when: "每天 08:00", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", state: { key: "observe", label: "观察中", dot: "" }, nextRunAt: at(1, 8), hint: true, observed: 3 }),
+ rule({ id: "g2", title: "issue 周报", when: "每周一 09:00", instruction: "每周一早上把仓库上周的 issue 汇总成三句话发给我", mode: "act", state: { key: "act", label: "执行中", dot: "ok" }, nextRunAt: at(3, 9) }),
+ rule({ id: "g3", title: "每日 issue 巡检", when: "每天 08:30", instruction: "每天看看有没有新的 issue 需要我回复", mode: "act", state: { key: "paused", label: "已暂停", dot: "err" }, failures: 3, nextRunAt: 0 }),
+ rule({ id: "g4", title: "交房租", when: "11月3日 12:00", kind: "remind", mode: "act", message: "该交房租了。", state: { key: "remind", label: "提醒", dot: "ok" }, nextRunAt: at(2, 12) }),
+];
+const RULE_RUNS = [
+ { id: "x1", at: at(0, 8), mode: "observe", line: "本会发送:“X 降价了,现在 ¥199(昨天 ¥259)”", summary: "X 现在 ¥199,比昨天低 ¥60,低于 200。", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule" },
+ { id: "x2", at: at(-1, 8), mode: "observe", line: "本会保持安静:X 现在 ¥259", summary: "X 现在 ¥259,高于 200。", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule" },
+ { id: "x3", at: at(-2, 8), mode: "observe", line: "失败:页面打不开", summary: "", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule" },
+ { id: "x4", at: at(-5, 8), mode: "observe", line: "跳过:电脑没开", summary: "", would: "", version: 1, permission: "", steps: 0, cause: "schedule" },
+];
+
// 等 @import 进来的样式表都加载完再复制伪类规则
if (document.readyState === "complete") mirrorPseudoStates();
else addEventListener("load", mirrorPseudoStates, { once: true });
diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.js
index 10ff102..88be7a7 100644
--- a/ui/screens/bot-settings.js
+++ b/ui/screens/bot-settings.js
@@ -9,6 +9,7 @@ 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 { fmtAgo } from "../lib/format.js";
+import { RuleEditor } from "../components/rules.js";
/** 免打扰的起止:整点 */
const HOURS = Array.from({ length: 24 }, (_, h) => {
@@ -155,10 +156,15 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod
const [prompt, setPrompt] = useState(bot.systemPrompt || "");
const promptRef = useRef(null);
const [hi, setHi] = useState(null);
+ // 规则(3d):在这里新建;列表、详情和运行记录在信息面板的「任务」组里
+ const [rules, setRules] = useState(null);
+ const [newRule, setNewRule] = useState(false);
+ const loadRules = () => api(`/rules?bot=${encodeURIComponent(bot.id)}`).then((x) => setRules(x.rules)).catch(() => setRules([]));
useEffect(() => {
setName(bot.name);
setPrompt(bot.systemPrompt || "");
api(`/bots/${bot.id}/settings`).then(setD).catch(failed);
+ loadRules();
}, [bot.id]);
useEffect(() => autoGrow(promptRef.current, 320), [prompt, d]);
useEffect(() => {
@@ -291,7 +297,11 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod
${bot.weixinEnabled && html`<${Row} id="nudge" name="微信续期提醒" sub="还有消息要发时,24 小时到期前请你回一句">
<${Switch} label="微信续期提醒" 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>
+ <//>
</div>
+ ${newRule && html`<${RuleEditor} botId=${bot.id} onClose=${() => setNewRule(false)} onSaved=${() => (setNewRule(false), loadRules())} />`}
<div class="list-head">电脑操作</div>
<div class="list">
diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.js
index 6dc668b..b4dbe3e 100644
--- a/ui/screens/info-panel.js
+++ b/ui/screens/info-panel.js
@@ -8,6 +8,7 @@ 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 { TaskRow } from "../components/tasks.js";
+import { RuleRow } from "../components/rules.js";
export function usePoll(fn, ms, deps = []) {
const [data, setData] = useState(null);
@@ -219,6 +220,10 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {
// 后台任务:只列还没结束的(进行中、等你的);一个都没有时不显示这一组
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="信息面板">
@@ -246,9 +251,10 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {
<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>`}
- ${tasks.length > 0 && html`<div class="list-head">任务</div>
+ ${(tasks.length > 0 || rules.length > 0) && html`<div class="list-head">任务</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 --git a/ui/screens/needs-you.js b/ui/screens/needs-you.js
index f885d53..571517c 100644
--- a/ui/screens/needs-you.js
+++ b/ui/screens/needs-you.js
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { html, Icon, Button, Skeleton } from "../components/ui.js";
import { TaskDetail } from "../components/tasks.js";
+import { RuleDetail } from "../components/rules.js";
import { api } from "../lib/api.js";
import { failed } from "../lib/store.js";
import { fmtAgo } from "../lib/format.js";
@@ -46,17 +47,18 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin }) {
setBusy("");
};
const send = () => text.trim() && act("answer", { text: text.trim() }, "text");
- // 详情一下就能看到:任务的展开处理过程;网页对话里的去对话
- const canOpen = !!item.taskId || item.channel === "web";
- const head = () => (item.taskId ? setOpen((v) => !v) : onOpenChat?.(item.botId));
+ // 详情一下就能看到:任务的展开处理过程,规则的展开运行记录;网页对话里的去对话
+ const expands = !!item.taskId || !!item.ruleId;
+ const canOpen = expands || item.channel === "web";
+ const head = () => (expands ? setOpen((v) => !v) : onOpenChat?.(item.botId));
const [lead, ...rest] = [multiBot && item.botName, item.subject, item.status].filter(Boolean);
const headIn = html`<span class="need-who"><b>${lead}</b>${rest.map((x) => ` · ${x}`).join("")}</span>
<span class="need-when num">${fmtAgo(item.since)}</span>
- ${item.taskId && html`<${Icon} name="chevRight" size=${12} class="chev" />`}`;
+ ${expands && html`<${Icon} name="chevRight" size=${12} class="chev" />`}`;
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=${item.taskId ? open : undefined} title=${item.taskId ? (open ? "收起" : "查看任务") : "打开对话"} onClick=${head}>${headIn}</button>`
+ ? html`<button type="button" class="need-head" aria-expanded=${expands ? open : undefined} title=${expands ? (open ? "收起" : item.ruleId ? "查看规则" : "查看任务") : "打开对话"} 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">
@@ -66,6 +68,7 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin }) {
<${Button} loading=${busy === "deny"} disabled=${!!busy} onClick=${() => act("deny")}>拒绝<//>`}
${item.kind === "failed" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>重试<//>
<button type="button" class="text danger" disabled=${!!busy} onClick=${() => act("stop")}>停止</button>`}
+ ${item.kind === "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)}>重新扫码<//>`}
@@ -79,9 +82,19 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin }) {
<${Button} variant="primary" loading=${busy === "text"} disabled=${!text.trim()} onClick=${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>`;
+ 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);