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.

Act by default; ask only when it is really needed

Marla0b148308f060
diff --git a/README.md b/README.md
index dcf4a6b..a0b5a0e 100644
--- a/README.md
+++ b/README.md
@@ -197,17 +197,17 @@ npm start # 本地管理界面:http://127.0.0.1:3600/
- **后台任务。** 要跑一阵子的事(调研、做报告、整理文件),或者你说一句「后台做」,机器人会开一个后台任务,你可以接着聊别的。做完把结果发回原来的对话。
- **接着问。** 在微信里引用结果、在飞书里回复那条消息,就是继续问这个任务。
-- **规则。** 「每天早上 8 点看看 X 的价格,低于 200 告诉我」会建成一条规则。新规则先观察:只记下本会说什么,不发消息、不改文件;看过几次觉得靠谱,再改成执行。固定的提醒直接执行。
+- **规则。** 「每天早上 8 点看看 X 的价格,低于 200 告诉我」会建成一条规则,到点就去查,有值得说的才告诉你。想先看看它会怎么做,就说「先观察」:只记下本会说什么,不发消息、不改文件,看过几次再改成执行。
- **「需要你」。** 所有机器人在等你回答、批准或重试的事都在侧栏这一行里;没事时这一行不出现。信息面板的「任务」组列着这个机器人的任务和规则,每一步都看得到。
- **不吵你。** 只推结果、要你决定的事和失败,进展不推。默认 22:00 到 08:00 免打扰;主动消息每天有上限(微信 3 条、飞书 5 条),多了合成一条。
- **有预算。** 每个任务、每条规则都有预算(任务默认 1 美元,规则每次 0.1 美元、每月 3 美元),快用完时停下问你,可以在任务详情和规则编辑器里改。
- **随时暂停。** 机器人设置 › 主动消息里一个开关暂停后台工作,聊天照常。
-- **用完会清理。** 任务和运行记录留 30 天;任务文件夹 30 天没动过会删除,删之前在「需要你」里告诉你,可以保留。运行记录能导出成 Markdown。
+- **用完会清理。** 任务和运行记录留 30 天;任务文件夹 30 天没动过会自动删除,不来问你,任务详情里写着哪天删,想留就点保留。运行记录能导出成 Markdown。
## 🖥️ 操作你的电脑,生成图片和视频
- **电脑操作**由内置的 [Cua Driver](https://github.com/trycua/cua) 提供。默认自动执行;把某个机器人切到「改变界面前先问我」,每一次点击和输入都要等你点头。读取屏幕内容永远不需要审批。macOS 上的电脑操作是 Beta 功能。
-- **图片和视频生成**用默认模型、花费不高时直接生成;要换模型、预计花费较高或要求不明确时先问你,让你看到模型和提示词,也可以当场换模型。想每次都确认,在机器人设置里打开即可。
+- **图片和视频生成**直接生成,要求没说清的按最合理的理解来;预计花费超过 0.5 美元时才先问你,让你看到模型和提示词,也可以当场换模型。想每次都确认,在机器人设置里打开即可。
<p align="center">
<img src="docs/assets/features/computer-use.gif" alt="机器人打开记事本、输入一段备忘并保存,每次点击和输入前都有审批卡片" width="100%">
diff --git a/README_en.md b/README_en.md
index bf17017..2d4e075 100644
--- a/README_en.md
+++ b/README_en.md
@@ -197,17 +197,17 @@ A bot is more than a chat window: it has a persona, a default model, its own wor
- **Background tasks.** For work that takes a while (research, a report, sorting files), or when you say "do it in the background", the bot starts a background task and you keep chatting. The result comes back to the conversation that asked for it.
- **Follow-ups.** Quote the result in WeChat, or reply to it in Feishu, to keep talking to that task.
-- **Rules.** "Every morning at 8, check X's price and tell me if it drops below 200" becomes a rule. A new rule observes first: it records what it would have said, and sends nothing and changes no files. Once it looks right, switch it to act. Fixed reminders act straight away.
+- **Rules.** "Every morning at 8, check X's price and tell me if it drops below 200" becomes a rule that checks on schedule and tells you only when something matters. To see how it behaves first, say "observe first": it records what it would have said, and sends nothing and changes no files. Once it looks right, switch it to act.
- **Needs you.** Everything any bot is waiting on you for, an answer, an approval or a retry, sits in one sidebar row that is only there when something needs you. The info panel's Tasks group lists the bot's tasks and rules, with every step visible.
- **Quiet by default.** Only results, decisions and failures are pushed, never progress. Quiet hours are 22:00 to 08:00, and unprompted messages are capped per day (3 on WeChat, 5 on Feishu), with the rest merged into one.
- **Budgets.** Every task and rule has a budget (1 US dollar per task; 0.10 per rule run and 3 a month), and work stops and asks when it runs out. Change them in the task details and the rule editor.
- **Pause anytime.** One switch in bot settings › Proactive messages pauses background work; chat carries on.
-- **Cleans up after itself.** Tasks and run logs are kept for 30 days. A task folder unused for 30 days is deleted, and you are told first in Needs you, with the option to keep it. Run logs export as Markdown.
+- **Cleans up after itself.** Tasks and run logs are kept for 30 days. A task folder unused for 30 days is deleted without asking; the task details show the date, and Keep holds on to it. Run logs export as Markdown.
## 🖥️ Operates your computer, and makes images and video
- **Computer use** is powered by the bundled [Cua Driver](https://github.com/trycua/cua). By default, actions run automatically. Switch a bot to *ask before changing the screen* and every click and keystroke waits for you. Reading the screen never needs approval. On macOS, computer use is a Beta feature.
-- **Image and video generation** runs right away with the default model at a normal cost. It asks first when switching models, when the estimated cost is high or when the request is unclear, so you see the model and prompt and can swap the model on the spot. To be asked every time, turn it on in the bot's settings.
+- **Image and video generation** runs right away, taking the most reasonable reading of a loose request. It asks first only when the estimated cost is above 0.50 US dollars, so you see the model and prompt and can swap the model on the spot. To be asked every time, turn it on in the bot's settings.
<p align="center">
<img src="docs/assets/features/computer-use.gif" alt="A bot opens Notepad, types a short note and saves it, while an approval card asks before each click and keystroke" width="100%">
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.md
index 4f8362b..de0489a 100644
--- a/docs/design/background-tasks-and-proactive.md
+++ b/docs/design/background-tasks-and-proactive.md
@@ -1,6 +1,8 @@
# Background tasks and proactive rules (Phase 3 design)
-Status: **3a–3f are built**, plus questions that don't block (a task asks right away and keeps working while a question with a default waits, see [Questions](#questions-ask-early-keep-working)): tasks, questions and needs-you, delivery, rules with observe mode, cost controls, and the tasks view with retention, cleanup and Markdown export (`src/tasks/`, `src/core/delivery.ts`, `dsh-runtime/plugins/amb-tasks.mjs`, `ui/components/tasks.js`; tests in `test/tasks.*`, `test/delivery.*`, `test/rules.*`, `test/cost.*`, `test/retention.*`, `test/tasks-view.*`). Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.
+Status: **3a–3f are built**, plus questions that don't block (a task asks right away and keeps working while a question with a default waits, see [Questions](#questions-ask-early-keep-working)): tasks, questions and needs-you, delivery, rules with an opt-in observe mode, cost controls, and the tasks view with retention, cleanup and Markdown export (`src/tasks/`, `src/core/delivery.ts`, `dsh-runtime/plugins/amb-tasks.mjs`, `ui/components/tasks.js`; tests in `test/tasks.*`, `test/delivery.*`, `test/rules.*`, `test/cost.*`, `test/retention.*`, `test/tasks-view.*`). Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.
+
+> **2026-11-01, the PO changed the defaults: act, and ask only when it is really needed.** "We need to be automatic, not an infinite prompt for users." Since then: a rule the user asks for acts right away, because the user's words are its mandate just as an explicit task request is; observe is opt-in (「先观察」 in chat, or Observe in the rule editor), and editing a rule's words no longer sends it back to observe. Agents decide for themselves and say what they chose; they ask only when a wrong guess would cause harm, cost money or waste most of the work, when they need something only the user has, or when the step cannot be undone, and never about language, format, scope or style. Image and video generation asks only above the cost threshold. Idle task folders are cleaned up without a needs-you row or a notification. The sections below are updated; the new decisions are in [15](#15-decisions-product-owner-2026-11-01-act-and-ask-only-when-really-needed), and the ones they replace are marked in [14](#14-decisions-product-owner-2026-10-31).
Feasibility evidence is in [Appendix A](#appendix-a-feasibility-answers-with-evidence). The spike that produced it is `scripts/spikes/p3-tasks/`.
## Summary
@@ -8,7 +10,7 @@ Feasibility evidence is in [Appendix A](#appendix-a-feasibility-answers-with-evi
The product owner (PO) confirmed that background work and proactive behaviour are what make AnyModelBot different. This doc covers three features:
1. **Background tasks.** "Build me X" or "research Y and report back" runs in its own DSH session and folder while the user keeps chatting.
-2. **Proactive rules.** These are reminders, watchers and scheduled checks that the user writes in words. A new rule starts in **observe** mode: it records what it would have said or done and does not act.
+2. **Proactive rules.** These are reminders, watchers and scheduled checks that the user writes in words. A new rule **acts** right away and speaks only when something matters. The user can ask for **observe** mode first: it records what it would have said or done and does not act.
3. **A "needs you" view.** It lists everything across all bots that waits for a person. When everything is healthy it takes no space.
Key decisions:
@@ -17,7 +19,7 @@ Key decisions:
- **The host is the source of truth.** It owns the tasks, the schedule, delivery and the budget. DSH runs the sessions. One in-child plugin, `amb-tasks.mjs`, decorates the task sessions: it restricts their tools, adds a prompt section and a `task_report` tool, and reports when a session has settled.
- **Scheduling stays in the host.** `@deepseek-ai/dsh-schedule` can't be activated under our `sdk` profile. Even if it could, it would fire into chat sessions that nobody is watching.
- **The human lane never waits.** Chat turns never take a task slot. Tasks run in separate DSH sessions in the same process; the spike measured a 63 ms chat reply while two 4-second task turns ran. When a person answers a task's question, the task wakes on a reserved slot.
-- **A task asks as soon as it needs to know, and keeps working when it can.** A question with a reasonable default doesn't stop the task: it goes on with the work that doesn't depend on the answer and, if nobody answered by the time it finishes, uses the default, says so in its result and withdraws the question. Only a question nobody but the user can decide (paying, deleting, choosing an account) makes the task wait. See [Questions](#questions-ask-early-keep-working).
+- **A task decides for itself and asks only when it must.** It picks the most reasonable option and says what it chose in its result; it never asks about language, format, scope or style. It asks only when a wrong guess would cause harm, cost money or waste most of the work, when it needs something only the user has (a login, a file, a password), or when the step cannot be undone (paying, deleting the user's data, messaging other people). A question where a wrong guess would only waste work carries a default and doesn't stop the task (rare); the others make it wait. See [Questions](#questions-ask-early-keep-working).
- **We push only three things:** a result the user can use, a decision the user must make, and a failure. WeChat may hold even these: iLink allows sends only within 24 h of the user's last message, and at most 10 sends per inbound message. See [WeChat](#wechat-the-hard-constraint).
- **Depends on P1** (the host→child control channel with per-session `steer`, `cancel` and model). Without per-session cancel, stopping one task means killing the bot's DSH process, which also ends the chat and every other task.
@@ -26,7 +28,7 @@ Key decisions:
**Goals**
- Long work happens off the chat lane. Its result comes back to the conversation that asked for it, and it survives an app restart without repeating side effects.
-- Proactive help that the user can trust before it acts. It starts in observe mode, stays inside a strict attention budget, and every run can be audited.
+- Proactive help that the user can trust. It acts on the user's own words, stays inside a strict attention budget and a permission cap, and every run can be audited. Observe mode is there for a user who wants to watch first.
- Transparency that costs no attention. The user can always look, and we push only what needs them.
**Non-goals (Phase 3)**
@@ -37,8 +39,8 @@ Key decisions:
**Principles**, from dsh-superagent `000-philosophy.md`, adapted:
- **Take as little attention as possible and give as much value as possible.** Every message, notification, setting and panel element must earn its place.
-- **Act only when asked, or when a written rule allows it.** A rule that judges whether to speak or act starts in observe mode.
-- **Speak only when a person must act or can use a result.** Ask one concrete question at a time. Report honestly: a draft is not "done", and a failure is a failure.
+- **Act only when asked, or when a written rule allows it.** A rule the user wrote is that permission; observe mode is opt-in (since 2026-11-01).
+- **Speak only when a person must act or can use a result.** Decide what you can and say what you chose; ask only when it is really needed, one concrete question at a time. Report honestly: a draft is not "done", and a failure is a failure.
- **Use few concepts and few settings.** Use a default when one value suits almost everyone. Write behaviour the user describes in words as prompt text, not as a setting.
- **Healthy takes no space.**
@@ -59,7 +61,7 @@ flowchart LR
| Concept | What it is | Rules it keeps | Why it exists |
| --- | --- | --- | --- |
| **Task** | A unit of authorized background work. It has its own DSH session (`task-<id>`) and folder (`tasks/<slug>-<id6>/`). | It is created only by a person's request, either through the chat agent's `task_start` or the "new task" button. It holds its origin conversation, a snapshot of the permission preset, the model and the budget. It ends only when it is **done**, when a **person stops** it, or when it fails and is archived. A follow-up from a person can resume a done task. It defines its own stage instead of following the DSH session (see [stage table](#2-states-and-transitions)). | Owns the work, the result and the questions. |
-| **Rule** | A standing instruction in the user's own words, plus a schedule and a mode: `off`, `observe` or `act`. | It is created in `observe` mode, except for a fixed reminder (see [observe](#5-observe-mode)). It never acts beyond its mode or its permission cap. It records its `version`, and each run records which version it ran. Three failed runs in a row, or its monthly budget, pause it. | Proactive work with a mandate the user wrote. |
+| **Rule** | A standing instruction in the user's own words, plus a schedule and a mode: `off`, `observe` or `act`. | It is created in `act` mode, or in `observe` when the user asks to watch first; a fixed reminder always acts (see [observe](#5-observe-mode)). It never acts beyond its mode or its permission cap. It records its `version`, and each run records which version it ran. Three failed runs in a row, or its monthly budget, pause it. | Proactive work with a mandate the user wrote. |
| **Run** | One stretch of work in a session: a task's launch, an answer, a retry or a recovery, or one firing of a rule. | It goes `queued`, `running`, `settling`, then `ended` with an outcome. It holds a slot while running or settling. It stores its activity steps and its cost. A rule gets a fresh session for each run. | The unit of audit, cost and recovery (superagent's Assignment). |
| **Report** | The structured state a Run reports through `task_report`. Its state is `progress`, `needs_you`, `done` or `failed`, with a `message` (user-facing, at most 300 characters), a `question` (one question with options and an optional `default`, one of the options), `summary` (internal) and `files`. A `needs_you` with a default is asked but doesn't end the run. | The latest Report is "what the task last said". A `progress` Report is internal and never pushed. In observe mode, `message` is recorded as "would have said". | We classify needs-you from structured fields, never from free text. |
| **Attention** | One thing that waits for a person. Some are stored: a question, or an approval (the existing `approvals` table, extended). Others are derived from state: a failed task, a rule that keeps failing, an undelivered message, an expired channel login, a stuck turn, a budget that ran out. | It is shown once, in "needs you". It is pushed only when the [push rules](#what-is-pushed-and-only-that) allow. It goes away by itself when its cause is gone. | It answers "does anything need me now?" |
@@ -105,7 +107,7 @@ A person's input after rows 3–6 (an answer, a follow-up, "retry" or "continue"
| `interrupted` | The app or DSH restarted mid-run; a `recover` run follows if the task should continue |
| `skipped` | Rule only: the app wasn't running, or the slots were busy past the grace period |
-**Rule.** The mode is `off`, `observe` or `act`. The rule is visible in "needs you" only when it is paused because of failures or budget, or when it has failed two runs in a row.
+**Rule.** The mode is `off`, `observe` or `act`. The rule is visible in "needs you" only when it is paused because of failures or budget, when it has failed two runs in a row, or when the user put it in observe and it has observed enough to ask whether to act.
```mermaid
stateDiagram-v2
@@ -269,7 +271,8 @@ The time zone is the system's IANA zone, stored on the rule when it is created.
- The user writes 「每天早上 8 点看看 X 的价格,低于 200 告诉我」.
- The chat agent calls `rule_create({ title, instruction, schedule })`. The instruction is the user's words, verbatim, and the agent supplies the structured schedule. The UI form does the same with the utility model.
-- The host creates the rule in `observe` and replies once: 「已建好规则:每天 08:00 看 X 价格。先观察几天,只记录不打扰你;在「任务」里可以改成执行。」
+- The host creates the rule in `act` and replies once: 「已建好规则:每天 08:00 看 X 价格,有值得说的就告诉你。」 On WeChat it adds the 24 h note.
+- When the user says 「先观察」, the agent passes `mode: "observe"` and the reply is 「已建好规则:每天 08:00 看 X 价格,先观察几天,只记录不打扰你。」 The rule editor has the same choice (执行 by default, 观察).
## 5. Observe mode
@@ -282,9 +285,10 @@ The time zone is the system's IANA zone, stored on the rule when it is created.
| Messages to anyone | **never** | through the outbox and attention budget |
| Recorded | "本会发送:…" / "本会保持安静" / "本会做:…" plus cost and steps | what it said and did |
-- **Every new rule starts in observe.** The one exception is a **fixed reminder**, such as 「明天下午 3 点提醒我开会」. The user dictated both the text and the time, so there is nothing to judge. It runs in act and delivers the text without a model turn. (Open question Q6.)
-- **Switching modes.** After 3 good observed runs on the current version (outcome done; failed and skipped runs don't count), "needs you" asks: 「规则「看 X 价格」已观察 3 次,需要你来决定是否执行」, with the latest run's line (「本会发送:“…”」) under it and [改为执行] [继续观察]. It is the least urgent kind: last in the list, never pushed, no desktop notification, though it counts toward the badge. 继续观察 stops asking for this version (kept across restarts); editing the instruction makes a new version, which asks again after 3 more good runs. The row goes away when the rule switches to act or off, pauses, or is deleted. The user can also switch in the rule detail or by telling the bot. Act can go back to observe at any time.
-- **Editing the instruction** puts the rule back in observe; this needs PO confirmation (Q7). Editing only the schedule keeps the mode.
+- **Observe is opt-in (since 2026-11-01).** A new rule acts: the user's words are its mandate, just as an explicit task request is. Observe is for a user who wants to watch first, by saying 「先观察」 or picking 观察 in the rule editor; the permission cap, budgets and failure pausing are the same either way. Until 2026-11-01 every new check started in observe.
+- **A fixed reminder always acts**, such as 「明天下午 3 点提醒我开会」. The user dictated both the text and the time, so there is nothing to judge. It delivers the text without a model turn and has no observe mode. (Q6.)
+- **Switching modes.** For a rule the user put in observe: after 3 good observed runs on the current version (outcome done; failed and skipped runs don't count), "needs you" asks: 「规则「看 X 价格」已观察 3 次,需要你来决定是否执行」, with the latest run's line (「本会发送:“…”」) under it and [改为执行] [继续观察]. It is the least urgent kind: last in the list, never pushed, no desktop notification, though it counts toward the badge. 继续观察 stops asking for this version (kept across restarts); editing the instruction makes a new version, which asks again after 3 more good runs. The row goes away when the rule switches to act or off, pauses, or is deleted. The user can also switch in the rule detail or by telling the bot. Act can go back to observe at any time.
+- **Editing the instruction** makes a new version and keeps the mode: an acting rule keeps acting. (From 2026-10-31 to 2026-11-01 an acting rule observed once after an edit, `observe_left`; the column stays in the schema, unused.) Editing only the schedule keeps the mode.
- **Tasks a person asked for are never in observe.** An explicit request is its own mandate, as in superagent, where explicit requests work in every accept mode.
- **What observe guarantees:** no message to anyone through AnyModelBot, and no file changes, because the sandbox is read-only. It does not block network calls from shell tools. The prompt forbids outside actions, and the Report lists what the rule would do. We say exactly this in the UI help text.
@@ -308,7 +312,7 @@ Nothing below is ever pushed. It lives in the tasks view, the bot's info panel a
| Push | When | Never |
| --- | --- | --- |
| **A result the user can use** | A task's `done` Report; a rule hit in act mode | Progress, "still working", partial drafts, retries, recovery after restart |
-| **A decision the user must make** | A task question (as soon as the task asks, with or without a default) or an approval, one at a time per conversation | A question the agent could decide itself; repeating an unchanged question |
+| **A decision the user must make** | A task question (as soon as the task asks, with or without a default) or an approval, one at a time per conversation | A question the agent could decide itself (language, format, scope, style); repeating an unchanged question |
| **A failure that needs them** | A task failed after automatic retries, or a rule paused after 3 failures | A one-off network error; a failure the agent can work around |
The acknowledgement of a new task is the chat reply itself, so it costs no extra message. Observe mode pushes nothing.
@@ -321,15 +325,15 @@ Every pushed message is one line, with an optional second line only for a blocke
| --- | --- | --- | --- |
| Ack (part of the chat reply) | 好,后台开始调研三家云的 GPU 价格,好了告诉你,你可以继续聊别的。 | same text | same text, plus a task chip 「后台任务 · GPU 价格调研 · 进行中 ›」 |
| Result | GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800,报告已发给你。引用这条消息可以继续问。 | same line; buttons [详情] [继续改] | message in the conversation; the chip turns 已完成; OS notification only if the window isn't focused |
-| Question | ❓「GPU 价格调研」想问你:报告用中文还是英文?<br>1. 中文<br>2. 英文<br>(回复编号,或引用这条消息回答) | question card with option buttons, as for `ask_user_question` today | the same card in the conversation and in "needs you" |
-| Question with a default (the task keeps working) | ❓「GPU 价格调研」想问你:报告用中文还是英文?<br>1. 中文<br>2. 英文<br>不回复就按中文做<br>(回复编号,或引用这条消息回答) | the same card, with 不回复就按中文做 under the question | the card and the needs-you row carry 不回复就按中文做; the task row and chip read 进行中,有个问题等你回答 |
-| Result after going with the default | 报告写好了,按中文做的,要英文的话引用这条说一声。引用这条消息可以继续问。 | same line | message in the conversation |
+| Question | ❓「GPU 价格调研」想问你:要登录 X 云的控制台才看得到包月价,账号用哪个?<br>(回复,或引用这条消息回答) | question card with option buttons, as for `ask_user_question` today | the same card in the conversation and in "needs you" |
+| Question with a default (rare: the task keeps working) | ❓「GPU 价格调研」想问你:比较包月价还是按小时价?<br>1. 包月价<br>2. 按小时价<br>不回复就按包月价做<br>(回复编号,或引用这条消息回答) | the same card, with 不回复就按包月价做 under the question | the card and the needs-you row carry 不回复就按包月价做; the task row and chip read 进行中,有个问题等你回答 |
+| Result after going with the default | 报告写好了,按包月价比较的,要按小时价的话引用这条说一声。引用这条消息可以继续问。 | same line | message in the conversation |
| Approval | 需批准(任务「清理旧构建」):`rm -rf build/` — 回复 y 4821 / n 4821 | the existing approval card, titled with the task | "needs you" row with [批准一次] [拒绝] |
| Failure | ⚠️「GPU 价格调研」没做完:X 云的价格页要登录,我进不去。发我一个能打开的链接,或者回复「停止」。 | same, with buttons [重试] [停止] | "needs you" row |
| Rule hit | X 降价了:现在 ¥199(昨天 ¥259)。 | same | message, with the rule named in small text |
| Digest (2 or more due within 2 min, or over the daily cap) | 2 条提醒:<br>· X 降价到 ¥199<br>· 仓库 Y 的 issue #12 有新回复 | one card with a line per item | one message |
| Held, then delivered when the WeChat window reopens | 你不在时:GPU 价格调研好了(A100 最便宜是 X 云,约 ¥7,800)。 (sent just before the reply to the user's next message) | n/a | n/a |
-| Desktop notification | title 「小蓝 需要你」, body 「GPU 价格调研:报告用中文还是英文?」 | | |
+| Desktop notification | title 「小蓝 需要你」, body 「GPU 价格调研:要登录 X 云的控制台才看得到包月价,账号用哪个?」 | | |
### Communication rules and attention budget per channel
@@ -347,14 +351,16 @@ These rules apply to every pushed message. Replies within a user's active chat t
As built (decided by the product owner after 3f). A question can wait for hours (quiet hours, the WeChat window), so a task asks as soon as it knows it needs to, and stops only when it must.
+**When to ask at all (PO, 2026-11-01).** Asking is the exception. The agent decides and says what it chose in its result. It asks only when a wrong guess would cause harm, cost money or waste most of the work; when it needs something only the user has (a login, a file, a password); or when the step cannot be undone (paying, deleting the user's data, messaging other people). Language, format, scope and style are never asked: it uses the conversation's language and the most reasonable option. So a question with a default is rare: it is for a guess that would only waste work.
+
- **Two kinds.** `task_report` `needs_you` takes an optional `default` (one of `options` when options are given; a number is read as that option).
- - **With a default** (「报告用中文还是英文?」, default 中文): the host asks right away and the turn goes on. The tool result tells the agent to keep working on what doesn't depend on the answer. An answer reaches the running task at its next step, the same way as a follow-up (steered, or delivered as its next input while it settles). If the agent finishes first, it goes with the default, says so in its result (「按中文做了,要英文的话引用这条说一声」) and reports `done`; the host then withdraws the question everywhere: the ApprovalCenter row is cancelled (`decided_by = default`), so needs-you drops it, and a push that is still pending, scheduled or held is withdrawn. A push that was already sent can't be taken back: quoting it (WeChat) or tapping its card button (Feishu) later reaches the task as a late answer and resumes it; a bare number is ordinary chat.
- - **Must decide** (no safe default: paying, deleting, choosing an account, anything irreversible): unchanged, the agent ends its turn and the Run ends `needs_you` once the session is quiet.
+ - **With a default** (「比较包月价还是按小时价?」, default 包月价; a wrong guess would redo most of the report): the host asks right away and the turn goes on. The tool result tells the agent to keep working on what doesn't depend on the answer. An answer reaches the running task at its next step, the same way as a follow-up (steered, or delivered as its next input while it settles). If the agent finishes first, it goes with the default, says so in its result (「按包月价比较的,要按小时价的话引用这条说一声」) and reports `done`; the host then withdraws the question everywhere: the ApprovalCenter row is cancelled (`decided_by = default`), so needs-you drops it, and a push that is still pending, scheduled or held is withdrawn. A push that was already sent can't be taken back: quoting it (WeChat) or tapping its card button (Feishu) later reaches the task as a late answer and resumes it; a bare number is ordinary chat.
+ - **Must decide** (no safe default: harm or money, something only the user has, anything irreversible such as paying, deleting the user's data or messaging other people): unchanged, the agent does the work that doesn't depend on the answer, then ends its turn and the Run ends `needs_you` once the session is quiet.
- **Ask immediately.** Both kinds are created and pushed when `task_report` is called, not when the Run ends or settles. An answer that arrives while the Run still settles (background jobs) or while the host is checking whether it is quiet is delivered to the session as its next input; the Run doesn't end until the session took it.
- **What else ends a question.** A Run that ends `done` or `failed` withdraws the task's open questions (a failed task asks again on retry); a stopped or archived task withdraws them as before. Asking the same question again replaces the open one. A `budget` or `interrupted` Run leaves them open.
-- **Stage.** A question with a default doesn't block: the task stays in the working group as `working/asking` (进行中,有个问题等你回答). The task detail shows the question, with 不回复就按中文做 under it; the needs-you row shows the question, its options and the same line; so do the pushed WeChat text and the Feishu card.
+- **Stage.** A question with a default doesn't block: the task stays in the working group as `working/asking` (进行中,有个问题等你回答). The task detail shows the question, with 不回复就按包月价做 under it; the needs-you row shows the question, its options and the same line; so do the pushed WeChat text and the Feishu card.
- **Unchanged.** One open pushed question per conversation (a question with a default that was pushed holds the slot until it is answered or withdrawn); quiet hours, daily caps and the WeChat window apply as before; approvals and the budget question still block; rules have no `needs_you`.
-- **Prompt.** The task rules say: decide yourself when you can; with a reasonable default, ask as early as possible with `default` and keep doing only what doesn't depend on the answer; when only the user can decide, do the independent work first, then ask and end the turn.
+- **Prompt.** The task rules say: decide yourself and say what you chose; never ask about language, format, scope or style; ask only in the three cases above. When a wrong guess would only waste work, ask as early as possible with `default` and keep doing only what doesn't depend on the answer; otherwise do the independent work first, then ask and end the turn. The chat rules say the same, with `ask_user_question` for choices.
### WeChat: the hard constraint
@@ -403,16 +409,18 @@ Expanding a row shows the Report (summary, message, would-do), the steps, the ru
| Setting | Default |
| --- | --- |
-| New rule mode | observe (except fixed reminders) |
+| New rule mode | act; observe only when the user asks for it (since 2026-11-01; before, every new check started in observe) |
| Background slots | 2 per bot, 4 overall |
| Quiet hours | 22:00–08:00 |
| Unsolicited cap | WeChat 3 per day, Feishu 5 per day, per bot per conversation; overflow becomes a digest |
-| Questions | one open pushed question per conversation; no reminders for unanswered questions |
+| Questions | only when really needed (harm or money, something only the user has, irreversible); never about language, format, scope or style; one open pushed question per conversation; no reminders for unanswered questions |
| Progress | never pushed |
| Budgets | task $1.00, rule run $0.10, rule $3.00 per month (Q3) |
| Automatic pause | a rule after 3 failures in a row; background work when the bot's Modelflare budget falls below 20 % |
| Manual pause | one switch per bot (bot settings › 主动消息, the info panel's 「后台工作已暂停」 line, or asking the bot): no new task runs, scheduled rules are logged as skipped and not caught up, pushes wait; chat and running turns carry on |
-| Observe → act hint | after 3 observed runs, shown in place, never pushed |
+| Observe → act hint | for a rule the user put in observe: after 3 observed runs, shown in place, never pushed |
+| Image and video generation | generates right away; asks only above the $0.5 cost threshold (or when the bot is set to always ask) |
+| Idle task folders | deleted after 30 idle days without asking or notifying; the date and 保留 are in the task detail |
| Desktop notifications | needs-you only, window unfocused, once per item |
### Mock-ups
@@ -444,9 +452,9 @@ These use `ui/design/README.md`:
需要你
┌─────────────────────────────────────────────────────────────┐
│ ● 小蓝 · GPU 价格调研 · 等你回答 2 分钟前 │
-│ 报告用中文还是英文? │
-│ 不回复就按中文做 │ only for a question with a default
-│ [中文] [英文] [回复…] │
+│ 比较包月价还是按小时价? │
+│ 不回复就按包月价做 │ only for a question with a default
+│ [包月价] [按小时价] [回复…] │
│─────────────────────────────────────────────────────────────│
│ ● 小蓝 · 清理旧构建 · 等你批准 5 分钟前 │
│ rm -rf build/ │
@@ -470,7 +478,7 @@ These use `ui/design/README.md`:
└─────────────────────────────────────────────────────────────┘
```
-Order: questions and approvals first (time-sensitive), then failures, then deliveries, then the system (logins, stuck turns, budget), and last a rule that has observed enough and asks whether to act. When the list is empty, there is no sidebar row and no badge. Opening the view directly shows a quiet 「没有需要你处理的事」.
+Order: questions and approvals first (time-sensitive), then failures, then deliveries, then the system (logins, stuck turns, budget), and last a rule the user put in observe that has observed enough and asks whether to act. When the list is empty, there is no sidebar row and no badge. Opening the view directly shows a quiet 「没有需要你处理的事」.
**Tasks view** (main pane; all bots, with a bot filter). Sections appear only when non-empty.
@@ -484,7 +492,7 @@ Order: questions and approvals first (time-sensitive), then failures, then deliv
└─────────────────────────────────────────────────────────────┘
规则
┌─────────────────────────────────────────────────────────────┐
-│ ○ 每天 08:00 · 看 X 价格 观察中 · 下次 明天 08:00 › │ grey
+│ ○ 每天 08:00 · 看 X 价格 观察中,明天 08:00 再运行 › │ grey: the user chose observe
│ ● 每周一 09:00 · issue 周报 执行中 · 上次 周一 · 说了 1 句 › │
└─────────────────────────────────────────────────────────────┘
已完成 · 最近 7 天
@@ -523,7 +531,7 @@ GPU 价格调研 [停止]
- The panel is already the place for "this bot" (channels, approvals, memory, conversations), bot settings' rules row already points there (「N 条,在信息面板的「任务」里」), and the cross-bot question "does anything need me?" is the needs-you page. A main-pane page would add a permanent sidebar control that shows nothing when healthy.
- Order: working and needs-you tasks (`GET /tasks?bot=&group=working,needs`), then rules, then one quiet row 「已结束 3」 that folds the ended tasks of the last 30 days (`group=ended`). The group is absent when the bot has no task or rule.
- A row opens in place, as rules already do (one `--well`, no lines between the detail's rows): 来自 (channel, time and the user's words; it opens that conversation), 最新进展, 预算 (约 $0.08 / $1.00 with 改), 文件夹 (path, size, 打开 on the desktop), 清理 (only when a date is set, with 保留), then each run as a folded 处理过程, and 停止 / 导出 / 删除. The chat chip and needs-you show the same detail. The command palette has 「任务和规则」.
-- Rule detail is as in 3d, plus 导出 next to 编辑 and 删除. The rule editor has 每次 / 每月 budgets for checks.
+- Rule detail is as in 3d, plus 导出 next to 编辑 and 删除. The rule editor has 每次 / 每月 budgets for checks and, for a new check, the mode: 执行 (default) or 观察.
## 7. Permissions
@@ -593,7 +601,7 @@ CREATE TABLE IF NOT EXISTS rules (
title TEXT NOT NULL, instruction TEXT NOT NULL, -- the user's words, verbatim
kind TEXT NOT NULL DEFAULT 'check', -- check | remind (fixed text, no model turn)
schedule TEXT NOT NULL, -- JSON {kind, at|time|days|minutes|cron, tz}
- mode TEXT NOT NULL DEFAULT 'observe', -- off | observe | act
+ mode TEXT NOT NULL DEFAULT 'observe', -- off | observe | act; the host always writes it (act unless the user asked to observe, since 2026-11-01)
act_permission TEXT NOT NULL DEFAULT 'workspace', -- workspace | bot
folder TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1,
run_budget_usd REAL NOT NULL DEFAULT 0.1, month_budget_usd REAL NOT NULL DEFAULT 3,
@@ -680,7 +688,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);
| `task_start` | chat | `{title, brief, budget_usd?}` → `{task, accepted}` or a refusal |
| `task_message` | chat | `{task, text}`: steer a working task or resume a done one |
| `task_list` | chat | Open tasks and rules with their stage and latest line, read from the host without waking any task |
-| `rule_create` | chat | `{title, instruction, schedule, kind}` → a rule in observe mode, or in act mode for a fixed reminder |
+| `rule_create` | chat | `{title, instruction, schedule, kind, mode}` → a rule in act mode; in observe mode only when the user asked to watch first (`mode: "observe"`; a fixed reminder always acts). `POST /rules` takes the same optional `mode` from the rule editor |
| `task_report` | task and rule | `{state: progress\|needs_you\|done\|failed, summary, message?, question?, options?, default?, files?, would?}`; `question` may also be `{question, options?, multiSelect?, default?}`. With `default`, `needs_you` is asked and the run goes on |
**Bridge** (child → host; the existing loopback with a per-launch token):
@@ -718,7 +726,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);
| Two hosts open the same data dir | On desktop, Electron's `requestSingleInstanceLock()` already prevents it. The headless CLI and Docker build need a data-dir lock before the Scheduler starts (a small addition in 3d) |
| Prompt injection from a web page during a task or rule | Permission caps (observe is read-only; act is capped at workspace), approvals go to needs-you, and denied acting tools. We can't fully prevent network side effects from shell tools, and the UI says so |
| The DSH child's memory grows with sessions the SDK can't close (one per rule run) | About 0.25–0.45 MB per finished session (measured). After more than 100 task and rule sessions the child is replaced as soon as it is fully idle: no chat turn, run, pending approval, compaction or background job. Nothing is interrupted or recovered |
-| Disk growth (task folders, DSH session JSONL) | Retention (decision 9, as built in 3f): a task with no run in flight and nothing new for 30 days is archived (hidden, no follow-ups, open questions withdrawn); run logs are pruned after 30 days, keeping each task's latest run and the current month's rule runs. A folder with files gets a needs-you row (「2 个任务文件夹 11月4日 删除」, 保留 / 知道了, never pushed) at 27 idle days and is deleted at 30 days, no sooner than 3 days after the row appeared, together with the task's DSH session directories (`dsh/<bot>/sessions/*/task-<id>[-N]`; the SDK has no delete, so the host removes them, and retries later if the session is still open in the child). Any use of the task, or 保留, restarts the 30 days. Folder and session sizes are in the task detail; deleting a task removes its folder. State is in `tasks.cleanup_at` and `kv`, so it survives restarts and long times off |
+| Disk growth (task folders, DSH session JSONL) | Retention (decision 9, as built in 3f): a task with no run in flight and nothing new for 30 days is archived (hidden, no follow-ups, open questions withdrawn); run logs are pruned after 30 days, keeping each task's latest run and the current month's rule runs. A folder with files gets a deletion date at 27 idle days and is deleted at 30 days, no sooner than 3 days after the date was set, together with the task's DSH session directories (`dsh/<bot>/sessions/*/task-<id>[-N]`; the SDK has no delete, so the host removes them, and retries later if the session is still open in the child). Any use of the task, or 保留, restarts the 30 days. Since 2026-11-01 the user is not asked: no needs-you row (it used to read 「2 个任务文件夹 11月4日 删除」 with 保留 / 知道了) and no desktop notification; the date and 保留 are in the task detail. Folder and session sizes are in the task detail; deleting a task removes its folder. State is in `tasks.cleanup_at`, so it survives restarts and long times off |
## 12. Testing strategy
@@ -742,7 +750,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);
- **Channels:** a fake iLink server for the WeChat window and quota (hold, then piggyback); Feishu card actions for answer, retry and stop.
- **UI:** design-gallery cases for the tasks view, needs-you and the chip, in both themes; a test that a healthy state renders no needs-you row and no badge.
- **Time:** a fake-clock run of 3 rules over 48 simulated hours, checking run counts, skips, caps and digests.
-- **Dogfooding:** the team runs real rules in observe mode for a week before act ships, and reviews each run log against the [push rules](#what-is-pushed-and-only-that).
+- **Dogfooding:** the team runs real rules for a week and reviews each run log against the [push rules](#what-is-pushed-and-only-that). (Planned in observe mode before act shipped; since 2026-11-01 rules act by default.)
## 13. Phased build plan
@@ -757,21 +765,21 @@ Estimates are in developer-days and include tests.
| **3e Cost controls** | Per-run cost estimate; task, run and rule-month budgets; budget pause and continue; reserve for the bot's Modelflare key; time caps | A task stops at $1 with 「再给 $1 继续?」; continuing works | 3 | 3a, 3d |
| **3f Tasks view and polish** | Full tasks view and detail; rule detail; retention and cleanup; Markdown export of run logs; docs and help text | Matches the mock-ups; healthy shows nothing | 4 | 3b–3e |
-**Total: about 32 developer-days.** 3a and 3b are the minimum to show the differentiator. 3d is the riskiest product-wise; observe mode is what makes it safe to ship.
+**Total: about 32 developer-days.** 3a and 3b are the minimum to show the differentiator. 3d is the riskiest product-wise; observe mode was meant to make it safe to ship. On 2026-11-01 the PO chose acting by default with observe as an opt-in; the permission cap, budgets and failure pausing are what keep it safe.
## 14. Decisions (product owner, 2026-10-31)
-The product owner accepted the recommendations below; item 8 is their own refinement.
+The product owner accepted the recommendations below; item 8 is their own refinement. Items 6, 7 and 9 were changed on 2026-11-01 (see [15](#15-decisions-product-owner-2026-11-01-act-and-ask-only-when-really-needed)).
1. **Who decides "background":** both. The chat agent starts a task for long work and says so in one line (「这个要跑一会儿,我放到后台做,好了告诉你」). The user can also say 「后台做」, or 「前台做」 to keep it in chat.
2. **Concurrency:** 2 background runs per bot, 4 overall. Chat never waits behind them.
3. **Budgets:** task $1.00, rule run $0.10, rule $3.00 per month. At the limit we pause and ask (shown in "needs you"); we never stop silently.
4. **Quiet hours:** 22:00–08:00 in the user's time zone, on by default, per user. A rule can override them.
5. **Models for rules:** checks run on the cheaper utility model; the main model only writes the actual result.
-6. **Fixed reminders** skip observe mode.
-7. **Observe → act:** after 3 good observed runs we suggest switching to act. Editing a rule's instruction sends it back to observe for one run.
+6. **Fixed reminders** skip observe mode. (Since 2026-11-01 every rule acts by default; a reminder still has no observe mode.)
+7. **Observe → act:** after 3 good observed runs we suggest switching to act. Editing a rule's instruction sends it back to observe for one run. (Superseded 2026-11-01: observe is opt-in, the suggestion stays for rules the user put in observe, and an edit keeps the mode.)
8. **WeChat 24 h window:** the "reply ok" nudge described in [WeChat: the hard constraint](#wechat-the-hard-constraint). Held messages show in "needs you" and go out with the user's next message, and desktop notifications are the reliable channel for time-sensitive rules.
-9. **Retention:** tasks and run logs are kept 30 days. Task folders are kept until the task is deleted and cleaned up after 30 idle days; the user is told first.
+9. **Retention:** tasks and run logs are kept 30 days. Task folders are kept until the task is deleted and cleaned up after 30 idle days; the user is told first. (Since 2026-11-01 the user is not told: the date and 保留 are in the task detail, and deletion still waits at least 3 days after the date is set.)
10. **Feishu groups:** only the owner and allowed people (P2's allowlist) may start tasks and rules.
11. **`/tasks`** chat command: yes, to list and stop tasks and rules.
12. **Permission cap:** act-mode rules are capped at `workspace-write`, even on full-permission bots.
@@ -791,6 +799,17 @@ The product owner accepted the recommendations below; item 8 is their own refine
11. **Chat commands:** should WeChat and Feishu get a `/tasks` command (one message listing open tasks and rules), or is the desktop enough?
12. **Permission cap:** should act-mode rules be capped at `workspace-write` even on full-permission bots, as proposed?
+## 15. Decisions (product owner, 2026-11-01): act, and ask only when really needed
+
+"We don't need infinite permission from agents. Stop being super reservative and keep asking human in the loop. We need to be automatic, not an infinite prompt for users. Only ask users when REALLY needed."
+
+1. **Rules act right away.** A rule the user asks for (chat `rule_create`, or the rule editor) is created in act mode; the user's words are its mandate, as for a task. Observe is opt-in: 「先观察」 in chat, or 观察 in the rule editor. Editing a rule's words keeps its mode (`observe_left` is gone). The observe → act suggestion stays, only for rules the user put in observe. The permission cap, budgets and failure pausing are unchanged.
+2. **Agents decide instead of asking.** In chat and in tasks the agent decides and says what it chose. It asks only when a wrong guess would cause harm, cost money or waste most of the work; when it needs something only the user has (a login, a file, a password); or when the step cannot be undone (paying, deleting the user's data, messaging other people). Language, format, scope and style are never asked. A question with a default is rare.
+3. **Media asks less.** The default asks only when the estimated cost is above $0.5 (a video whose cost cannot be estimated counts as above). A non-default model the agent or the user picked, or an ambiguous request, is not asked about; the agent takes the most reasonable reading. 每次都问 stays as an opt-in.
+4. **Cleanup doesn't ask.** Idle task folders are cleaned up after 30 days without a needs-you row or a desktop notification. The task detail shows the date with 保留, and a folder is never deleted sooner than 3 days after the date was set.
+
+What still asks, because only the user can decide: recursive deletes (`amb-delete-gate`); writes outside the workspace in the workspace tier, including approvals in act-mode rules; a task or rule at its budget; anything that needs something only the user has; strangers asking to use the bot; and the failure rows (failed task, rule paused after failures, expired login, undelivered result).
+
## Appendix A. Feasibility answers with evidence
**Spike.** `node scripts/spikes/p3-tasks/driver.mjs [base|schedule|schedule2|preset]`. It starts the pinned DSH (`dsh-runtime`, `@deepseek-ai/dsh` 0.2.1-rc.4) the way `src/agent/host.ts` does:
diff --git a/docs/development.md b/docs/development.md
index 0f42815..be7af47 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -94,7 +94,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令
- 登录后还能在 设置 → Modelflare 查看按天、按模型的用量,Modelflare 发来的通知,以及复制邀请链接。
- 机器人预算(需要登录):机器人设置 → 预算,开启后这个机器人用自己的 Key(内置网关里单独的 provider),最多花设定的美元数;关闭后回到共用的 Key。
- 生图 / 生视频:代理模式下机器人有 `media_models`(可用模型、默认模型、参数范围、参考价)、`media_docs`(从 docs.modelflare.dev 实时读该模型的请求格式)、`generate_image`、`generate_video` 四个工具,并自带一份 media 技能说明。各模型的参数格式不同,机器人按文档写请求体,工作区里的参考图写成 `workspace:路径` 即可;Key 始终只在本程序里,由本程序带着该机器人用的 Key 调 Modelflare,结果存进机器人工作区的 `media/`,再交付到聊天。
-- 生成前确认:用默认模型、预计花费不超过 $0.5 时直接生成,不打扰你。只在这几种情况先在聊天里问你这次用哪个模型(附提示词、参数、参考价和为什么问):机器人要换用不是默认的模型(你点名的除外,代理传 `confirm: false`)、预计花费超过 $0.5(按参考价、张数、视频时长和分辨率估算;视频估不出来也问)、要求不明确(代理传 `confirm: true`)。可以确认、换成别的模型或取消;微信回复编号或模型名,飞书 / 网页点选。10 分钟内没回答就不生成。想每次都确认:机器人设置 → 生图 / 生视频 → 生成前确认 →「每次都问」。
+- 生成前确认:直接生成,不打扰你。机器人选了不是默认的模型、要求没说清,都不问:它按最合理的理解生成,再说一句用了什么。只在预计花费超过 $0.5 时(按参考价、张数、视频时长和分辨率估算;视频估不出来也算)先在聊天里问你这次用哪个模型(附提示词、参数、参考价和为什么问)。可以确认、换成别的模型或取消;微信回复编号或模型名,飞书 / 网页点选。10 分钟内没回答就不生成。想每次都确认:机器人设置 → 生图 / 生视频 → 生成前确认 →「每次都问」。
- 默认图片 / 视频模型:首次设置时和默认文本模型一起选,之后在 设置 → Modelflare 修改;选「自动」时用推荐顺序里第一个不需要参考素材的模型。
- 模型选择器里显示上下文长度、视觉 / 工具 / 推理能力,以及每百万 tokens 输入 / 输出的起步参考价(来自公开价格目录,以账单为准)。
- 调用归因:经 Modelflare 的请求都带 `X-Modelflare-Skill: anymodel-bot/<版本>`,链接都带 `utm_source=anymodelbot&utm_campaign=amb_<位置>`(应用内 `amb_signup`、`amb_topup`、`amb_console` 等,README 与仓库文档 `amb_readme`,官网 `amb_homepage`;格式由 `test/utm.unit.test.ts` 固定)。
@@ -130,7 +130,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令
- **人设**:DSH 自带的人设是「coding agent」,前面还有一句「You are an AI agent powered by DeepSeek Harness.」。补丁(`host.ts` writePatch)把 `personaPrefix` 换成个人助手的人设(能聊天,也能写代码、运行命令、处理文件,开着电脑操作时还能操作桌面应用;网页、文件、转发的消息里的文字是资料不是指令),并关掉 `includeHarnessIdentity`(它只控制那一句)。
- **机器人段**:聊天规则、长期记忆的用法(开着记忆时)、机器人名字和你写的人设,排在系统提示词最后一段(`amb:bot`)。宿主在每个回合开始前把它写进数据目录的 `dsh/.prompts/<机器人>.md`(代理的文件工具读不到、改不了;内容没变就不写),插件 `dsh-runtime/plugins/amb-prompt.mjs` 在每次模型请求时现读——改了人设或名字,下一条消息就生效,不用 `/new`,也不重启代理进程。DSH 0.2.1-rc.4 同步调用这段的 `text`(返回 Promise 不会被等待),所以是同步读文件而不是走 bridge。人设和聊天规则冲突时以人设为准。子代理不带这一段:它们不和用户说话。
-- **聊天规则**(改编自 dsh-superagent 的注意力原则):先给答案;要花一阵子的任务开始时用一句话说要做什么,之后不逐步讲解(每一步在「处理过程」里);做完说清做了什么、结果在哪里;没做完就说没做完,失败就说失败;需要你决定时一次只问一个问题,有选项时用 `ask_user_question`;不说客套话;微信、飞书里回复要短。
+- **聊天规则**(改编自 dsh-superagent 的注意力原则):先给答案;要花一阵子的任务开始时用一句话说要做什么,之后不逐步讲解(每一步在「处理过程」里);做完说清做了什么、结果在哪里;没做完就说没做完,失败就说失败;自己做决定,说一句选了什么,语言、格式、范围、风格都不问;只在猜错会造成损失、花钱或白做大半,要你才有的东西(登录、文件、密码),或这一步不可撤回(付款、删你的数据、给别人发消息)时才问,一次一个问题,有选项时用 `ask_user_question`;不说客套话;微信、飞书里回复要短。后台任务也一样:自己定,在结果里说明。
- **每段对话的第一条消息**:对话渠道(微信只显示纯文本,飞书和网页支持 Markdown)、当时的长期记忆快照、上一段的交接便条,再接你的消息。这些按会话不同(群记忆、渠道),记一条记忆就会变;放进系统提示词会让同一机器人所有会话共用的前缀缓存失效,所以留在这里,一段之内不变,之后的记忆变化用 `recall` 查。
- 前缀缓存:内容没变时系统提示词逐字节不变;人设变了只改最后一段,前面的部分照旧。升级前开始的对话第一条消息里还留着当时的人设,下一段(`/new` 或上下文管家换段)起不再有。
@@ -167,11 +167,11 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令
要跑一阵子的事在后台做,不占聊天(设计见 `docs/design/background-tasks-and-proactive.md`,代码在 `src/tasks/`):
- **后台任务**:聊天代理用 `task_start` 开一个任务(自己的 DSH 会话 `task-<id>` 和工作区里的文件夹 `tasks/<名字>-<id6>/`),一句话说清在后台做什么;做完把结果发回原会话(微信引用、飞书回复那条消息可以接着问)。中途要问你的,一个会话一次只推一个问题。应用重启后接着做,已经做过的外部动作先查再做。`/tasks` 列出任务和规则,`/stop 编号` 停一个。
-- **规则**:`rule_create` 或 机器人设置 › 主动消息 › 规则 建好。检查从观察开始(只读,不发消息,只记「本会发送」),好好观察 3 次后在「需要你」里问要不要改为执行;固定提醒直接执行。每次运行一个新会话,运行记录可以导出成 Markdown。
+- **规则**:`rule_create` 或 机器人设置 › 主动消息 › 规则 建好,直接执行:你的原话就是授权,到点去查,有值得说的才发一句;改了原话也照样执行。观察要自己选(跟机器人说「先观察」,或在规则编辑器里选观察):只读,不发消息,只记「本会发送」,好好观察 3 次后在「需要你」里问要不要改为执行。每次运行一个新会话,运行记录可以导出成 Markdown。
- **看得到、不打扰**:信息面板的「任务」组列着这个机器人的任务和规则(结束了的收在「已结束」里),点开看来自哪、最新进展、预算、文件夹和每次运行的处理过程;所有在等你的事在侧栏的「需要你」里。只推结果、要你决定的事和失败;免打扰(默认 22:00–08:00)、每天上限(微信 3 条、飞书 5 条)、合并成摘要都在 机器人设置 › 主动消息。
- **预算**:任务默认 $1,规则每次 $0.10、每月 $3(估算,按 Modelflare 的参考价)。用完时停下问你;任务详情里能改任务的预算,规则编辑器里能改规则的。机器人的预算 Key 剩不到 20% 时停后台工作,留给聊天。
- **暂停**:机器人设置 › 主动消息 › 暂停后台工作(或跟机器人说),任务和规则先停、主动消息排着,聊天照常。
-- **保留与清理**:任务和运行记录留 30 天,30 天没动过的任务归档。任务文件夹 30 天没动过就删除,连同 DSH 里它的会话记录(`dsh/<机器人>/sessions/` 下;SDK 没有删会话的接口,由应用直接删,会话还开在代理进程里的等进程换过再删);删之前在「需要你」里说一次,可以保留。任务详情里能看到文件夹多大,也能直接删掉任务(连同文件夹)。
+- **保留与清理**:任务和运行记录留 30 天,30 天没动过的任务归档。任务文件夹 30 天没动过就删除,连同 DSH 里它的会话记录(`dsh/<机器人>/sessions/` 下;SDK 没有删会话的接口,由应用直接删,会话还开在代理进程里的等进程换过再删);不问你、不发通知:第 27 天定下删除的日期,任务详情里写着,可以保留(至少 3 天后才删)。任务详情里能看到文件夹多大,也能直接删掉任务(连同文件夹)。
## 电脑操作(Computer Use)
diff --git a/docs/development_en.md b/docs/development_en.md
index 7edfac8..cdd5a37 100644
--- a/docs/development_en.md
+++ b/docs/development_en.md
@@ -94,7 +94,7 @@ Inside the container the console listens on 0.0.0.0, so token access is enforced
- When signed in, Settings → Modelflare also shows usage per day and per model, notifications from Modelflare, and your invite link.
- Bot budgets (requires sign-in): Bot settings → Budget. When enabled, the bot uses its own key (a separate provider in the gateway) capped at the dollar amount you set; when disabled it goes back to the shared key.
- Image / video generation: in agent mode, bots get four tools — `media_models` (available models, defaults, parameter ranges, reference prices), `media_docs` (reads the model's request format live from docs.modelflare.dev), `generate_image` and `generate_video` — plus a bundled media skill. Parameter formats differ per model, so the bot writes the request body from the docs; reference images in the workspace are written as `workspace:path`. The key never leaves the app: the app calls Modelflare with the bot's key, saves results in the bot workspace's `media/`, and delivers them to the chat.
-- Confirmation before generation: with the default model and an estimated cost of at most $0.5, the image or video is generated right away. The chat asks which model to use (with prompt, parameters, reference price and the reason for asking) only when the bot wants a model other than the default (unless you named it; the agent passes `confirm: false`), when the estimated cost is above $0.5 (from the reference price, number of images, video length and resolution; a video whose cost cannot be estimated is asked too), or when the request is ambiguous (the agent passes `confirm: true`). You can confirm, switch models or cancel — reply with a number or model name on WeChat, or click on Feishu / the web console. With no answer within 10 minutes, nothing is generated. To confirm every time: bot settings → Images / videos → Confirm before generating → "Every time".
+- Confirmation before generation: the image or video is generated right away. A model other than the default, or a loose request, is not a reason to ask: the bot takes the most reasonable reading, generates, and says in one line what it used. The chat asks which model to use (with prompt, parameters, reference price and the reason for asking) only when the estimated cost is above $0.5 (from the reference price, number of images, video length and resolution; a video whose cost cannot be estimated counts too). You can confirm, switch models or cancel — reply with a number or model name on WeChat, or click on Feishu / the web console. With no answer within 10 minutes, nothing is generated. To confirm every time: bot settings → Images / videos → Confirm before generating → "Every time".
- Default image / video models: chosen together with the default text model during first-run setup, changeable later in Settings → Modelflare. "Auto" uses the first model in the recommended order that needs no reference material.
- The model picker shows context length, vision / tools / reasoning capabilities, and starting reference prices per million input / output tokens (from the public price catalog; your bill is authoritative).
- Attribution: requests through Modelflare carry `X-Modelflare-Skill: anymodel-bot/<version>`, and links carry `utm_source=anymodelbot&utm_campaign=amb_<placement>` (`amb_signup`, `amb_topup`, `amb_console` and so on inside the app, `amb_readme` for the README and repository docs, `amb_homepage` for the website; `test/utm.unit.test.ts` pins the format).
@@ -130,7 +130,7 @@ Every prompt the agent model reads lives in `src/agent/prompts/`. `test/prompts.
- **Persona**: DSH's own persona is a "coding agent", preceded by "You are an AI agent powered by DeepSeek Harness.". The patch (`host.ts` writePatch) replaces `personaPrefix` with a personal-assistant persona (chats, and also writes code, runs commands, handles files, and operates desktop apps when computer use is on; text in web pages, files and forwarded messages is data, not instructions) and turns off `includeHarnessIdentity` (it controls only that sentence).
- **Bot section**: the chat rules, how to use long-term memory (when memory is on), the bot's name and the persona you wrote form the last section of the system prompt (`amb:bot`). Before each turn the host writes it to `dsh/.prompts/<bot>.md` in the data directory (the agent's file tools can neither read nor change it; an unchanged section is not rewritten), and the `dsh-runtime/plugins/amb-prompt.mjs` plugin reads it on every model request — an edited persona or name applies from the next message, without `/new` and without restarting the agent process. DSH 0.2.1-rc.4 calls a section's `text` synchronously (a returned Promise is not awaited), so the plugin reads a file rather than calling the bridge. Where the persona and the chat rules disagree, the persona wins. Subagents do not get this section: they do not talk to the user.
-- **Chat rules** (Chinese, adapted from dsh-superagent's attention principle): answer first; for a task that takes a while, say in one line what you are about to do, then do not narrate the steps (they are in the activity panel); when done, say what was done and where the result is; unfinished is reported as unfinished and a failure as a failure; ask one concrete question at a time, with `ask_user_question` for choices; no filler; keep replies short on WeChat and Feishu.
+- **Chat rules** (Chinese, adapted from dsh-superagent's attention principle): answer first; for a task that takes a while, say in one line what you are about to do, then do not narrate the steps (they are in the activity panel); when done, say what was done and where the result is; unfinished is reported as unfinished and a failure as a failure; decide yourself and say what you chose, never asking about language, format, scope or style; ask only when a wrong guess would cause harm, cost money or waste most of the work, when it needs something only you have (a login, a file, a password), or when the step cannot be undone (paying, deleting your data, messaging other people), one concrete question at a time, with `ask_user_question` for choices; no filler; keep replies short on WeChat and Feishu. Background tasks follow the same rule and say what they chose in the result.
- **A segment's first message**: the channel (WeChat shows plain text only; Feishu and the web support Markdown), the long-term memory snapshot of that moment, the previous segment's handoff note, then your message. These differ per conversation (group memory, channel) and change with every remembered fact; in the system prompt they would invalidate the prefix cache all of a bot's conversations share, so they stay here, unchanged within a segment, and later memory changes are read with `recall`.
- Prefix cache: an unchanged section keeps the system prompt byte-identical; an edited persona changes only the last section. Conversations started before the upgrade still carry the old persona in their first message until the next segment (`/new` or a steward switch).
@@ -167,11 +167,11 @@ Final replies, delivered files, approval prompts and notices are written to an o
Work that takes a while runs in the background and never holds up chat (design: `docs/design/background-tasks-and-proactive.md`; code: `src/tasks/`):
- **Background tasks**: the chat agent starts one with `task_start` (its own DSH session `task-<id>` and a folder `tasks/<name>-<id6>/` in the workspace) and says in one line what it will do; the result comes back to the conversation that asked (quote it in WeChat or reply to it in Feishu to follow up). A task that needs you asks one question at a time per conversation. After an app restart it carries on and checks before repeating outside actions. `/tasks` lists tasks and rules, `/stop <number>` stops one.
-- **Rules**: made with `rule_create` or in bot settings › Proactive messages › Rules. A check starts in observe mode (read-only, sends nothing, records "would send"), and after 3 observed runs it suggests switching to act; fixed reminders act straight away. Each run gets a fresh session, and the run log exports as Markdown.
+- **Rules**: made with `rule_create` or in bot settings › Proactive messages › Rules, and they act right away: your own words are the mandate, so each run checks and sends a line only when something matters, and editing the words keeps it acting. Observe mode is opt-in (tell the bot "observe first", or pick Observe in the rule editor): read-only, sends nothing, records "would send", and after 3 observed runs Needs you asks whether to switch it to act. Each run gets a fresh session, and the run log exports as Markdown.
- **Visible, not noisy**: the info panel's Tasks group lists the bot's tasks and rules (ended tasks fold into one "ended" row); open one to see where it came from, the latest progress, the budget, the folder and each run's steps. Everything waiting on you is in the sidebar's Needs you. Only results, decisions and failures are pushed; quiet hours (22:00–08:00 by default), daily caps (3 on WeChat, 5 on Feishu) and digests are in bot settings › Proactive messages.
- **Budgets**: $1 per task, $0.10 per rule run and $3 per rule per month by default (estimated from Modelflare's reference prices). At the limit the work stops and asks; change a task's budget in its details and a rule's in the rule editor. When the bot's budget key is below 20 %, background work stops so chat keeps the rest.
- **Pause**: bot settings › Proactive messages › Pause background work (or ask the bot) holds tasks, rules and pushed messages; chat carries on.
-- **Retention**: tasks and run logs are kept for 30 days; a task unused for 30 days is archived. A task folder unused for 30 days is deleted along with the task's DSH session files (under `dsh/<bot>/sessions/`; the SDK has no call to delete a session, so the app removes the files itself, and a session still open in the agent process is removed after the process is replaced). You are told once in Needs you first and can keep it. The task details show the folder's size and can delete the task with its folder.
+- **Retention**: tasks and run logs are kept for 30 days; a task unused for 30 days is archived. A task folder unused for 30 days is deleted along with the task's DSH session files (under `dsh/<bot>/sessions/`; the SDK has no call to delete a session, so the app removes the files itself, and a session still open in the agent process is removed after the process is replaced). You are not asked and get no notification: at 27 idle days the deletion date is set and shown in the task details, where Keep holds on to the folder (it is never deleted sooner than 3 days after the date is set). The task details show the folder's size and can delete the task with its folder.
## Computer use
diff --git a/dsh-runtime/plugins/amb-media.mjs b/dsh-runtime/plugins/amb-media.mjs
index 7e4a947..8f9bdd8 100644
--- a/dsh-runtime/plugins/amb-media.mjs
+++ b/dsh-runtime/plugins/amb-media.mjs
@@ -2,10 +2,10 @@
//
// Registers media_models, media_docs, generate_image and generate_video. The agent never holds a
// Modelflare key: each call goes to the host over the loopback bridge (AMB_BRIDGE_URL / AMB_BRIDGE_TOKEN),
-// which asks the user to confirm the model when needed (not the default model, a high estimated cost, an
-// ambiguous request, or a bot set to always ask), calls Modelflare with this bot's key and saves the result
-// under media/ in the workspace. The agent then delivers the file with the present tool. Every model has
-// its own request format, so the agent reads the model's live docs with media_docs and passes the body.
+// which asks the user to confirm the model only for a high estimated cost or a bot set to always ask, calls
+// Modelflare with this bot's key and saves the result under media/ in the workspace. The agent then delivers
+// the file with the present tool. Every model has its own request format, so the agent reads the model's live
+// docs with media_docs and passes the body.
import { defineTool } from '@deepseek-ai/dsh-tools'
export const name = 'amb-media'
@@ -35,11 +35,6 @@ export function apply(ctx) {
return { text: String(r.text ?? '') }
}
- const CONFIRM = {
- type: 'boolean',
- description: 'true: ask the user before generating, because the request is ambiguous. false: the user named this model, so a model other than the default needs no question. Omit otherwise. A high estimated cost is always asked.',
- }
-
const BODY = {
type: 'object',
additionalProperties: true,
@@ -68,11 +63,10 @@ export function apply(ctx) {
ctx.tools.register(defineTool({
name: 'generate_image',
- description: 'Generate or edit an image with an image model on Modelflare. With the default model and a normal cost it generates right away; otherwise the user is asked to confirm the model first and may pick another one or cancel. The image is saved in the workspace under media/; deliver it with the present tool when the user should receive it. Write the prompt in detail (subject, style, composition, text in the image).',
+ description: 'Generate or edit an image with an image model on Modelflare. It generates right away; only a high estimated cost (or a bot set to always ask) makes the app ask the user to confirm the model first, who may pick another one or cancel. The image is saved in the workspace under media/; deliver it with the present tool when the user should receive it. Write the prompt in detail (subject, style, composition, text in the image).',
parameters: {
prompt: { type: 'string', required: true, description: 'What the image should show, in detail. Shown to the user when asked; keep it in sync with the prompt inside body.' },
model: { type: 'string', description: 'Image model id. Omit to use the default model.' },
- confirm: CONFIRM,
body: BODY,
endpoint: { type: 'string', enum: ['generations', 'edits'], description: 'For OpenAI Images models only: "edits" when the docs say reference images go to /v1/images/edits. Default generations.' },
size: { type: 'string', description: 'Optional size such as 1024x1024 for a plain request without body, Images API models only.' },
@@ -83,11 +77,10 @@ export function apply(ctx) {
ctx.tools.register(defineTool({
name: 'generate_video',
- description: 'Generate a short video with a video model on Modelflare. With the default model and a normal cost it generates right away; otherwise the user is asked to confirm the model first and may pick another one or cancel. It can take several minutes. The video is saved in the workspace under media/; deliver it with the present tool. Only use it when the user asks for a video: video generation costs much more than images.',
+ description: 'Generate a short video with a video model on Modelflare. It generates right away; only a high estimated cost (or a bot set to always ask) makes the app ask the user to confirm the model first, who may pick another one or cancel. It can take several minutes. The video is saved in the workspace under media/; deliver it with the present tool. Only use it when the user asks for a video: video generation costs much more than images.',
parameters: {
prompt: { type: 'string', required: true, description: 'What the video should show, in detail. Shown to the user when asked; keep it in sync with the prompt inside body.' },
model: { type: 'string', description: 'Video model id. Omit to use the default model.' },
- confirm: CONFIRM,
body: BODY,
seconds: { type: 'number', description: 'Optional length in seconds for a plain request without body.' },
size: { type: 'string', description: 'Optional size such as 1280x720 for a plain request without body.' },
diff --git a/dsh-runtime/plugins/amb-tasks.mjs b/dsh-runtime/plugins/amb-tasks.mjs
index db04b05..21656ad 100644
--- a/dsh-runtime/plugins/amb-tasks.mjs
+++ b/dsh-runtime/plugins/amb-tasks.mjs
@@ -7,8 +7,9 @@
// tools.restrict throws on unknown ones),
// - adds the task rules (AMB_TASK_RULES, written by the host) as the last system-prompt section,
// - registers task_report, which reports the task's state to the host (needs_you carries one question for the
-// user; the host asks it right away and hands the answer back as an input: with a default the task keeps working
-// and the answer reaches its next step, without one the task ends its turn and waits),
+// user, only when the task cannot decide itself; the host asks it right away and hands the answer back as an
+// input: with a default the task keeps working and the answer reaches its next step, without one the task ends
+// its turn and waits),
// - refuses every tool call once the host has stopped the task.
// Chat sessions get task_start / task_message / task_list, rule_create / rule_update and background_pause (pause or
// resume all of the bot's background work); subagents get none of them.
@@ -129,12 +130,13 @@ export function apply(ctx) {
}))
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.',
+ description: 'Set up a standing rule the user asks for: a recurring check (kind check; it acts right away and tells the user only when it matters) 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'] },
+ mode: { type: 'string', enum: ['act', 'observe'], description: 'observe only when the user wants to watch first (先观察): it only records what it would say.' },
message: { type: 'string', description: 'remind: the line to send.' },
},
output: TEXT_OUT,
@@ -177,7 +179,7 @@ export function apply(ctx) {
const reportTool = () => defineTool({
name: 'task_report',
- description: 'Report this background task\'s state to the app. done: finished. failed: you cannot finish it. For both, message is the one line the user receives (at most 300 characters, in their language): the result and where it is; files are files to send them. needs_you: the app asks the user question now. With default, keep working on what does not depend on the answer; if you finish first, use default and say so in message. Without default (only the user can decide), their answer is your next message. progress is recorded, never sent. After done, failed or needs_you without default, end your turn.',
+ description: 'Report this background task\'s state to the app. done: finished. failed: you cannot finish it. For both, message is the one line the user receives (at most 300 characters, in their language): the result, where it is and what you chose; files are files to send them. needs_you only if a wrong guess could cause harm, cost money or waste most of the work, you need something only the user has, or the step cannot be undone; decide everything else yourself. The app asks the user question now. With default (rare), keep working on what does not depend on the answer; if you finish first, use default and say so in message. Without default, their answer is your next message. progress is recorded, never sent. After done, failed or needs_you without default, end your turn.',
parameters: {
state: { type: 'string', required: true, enum: ['progress', 'needs_you', 'done', 'failed'] },
summary: { type: 'string', required: true, description: 'What you did and found, for the record (not sent to the user).' },
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index 5a2e059..a71ac0b 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -89,18 +89,17 @@ const CANCELS = [tl("zh-CN", "media.cancel"), tl("en", "media.cancel")];
/** 预计花费超过它(美元)就先问用户 */
export const MEDIA_ASK_USD = 0.5;
-/** 为什么要先问:机器人设成每次都问 / 代理说要问 / 花费 / 模型不是默认的 */
-export type MediaAskReason = "always" | "agent" | "cost" | "model";
+/** 为什么要先问:机器人设成每次都问 / 花费超过上限 */
+export type MediaAskReason = "always" | "cost";
/**
- * 生成前要不要先问用户;不用问时为空。confirm 是代理传的:true = 要求不明确,要问;false = 用户点名了这个模型。
- * 花费超过上限(视频算不出花费也算)和"每次都问"不看 confirm。
+ * 生成前要不要先问用户;不用问时为空。默认(需要时再问)只在预计花费超过上限时问,视频算不出花费也算(可能很贵)。
+ * 代理或用户选了不是默认的模型、要求不够明确,都不问:代理按最合理的理解直接生成(产品负责人 2026-11-01)。
+ * "每次都问"是用户自己打开的。
*/
-export function mediaAsk(plan: Pick<MediaPlan, "kind" | "model" | "default" | "estimate">, confirm: unknown, setting: MediaConfirm): MediaAskReason | undefined {
+export function mediaAsk(plan: Pick<MediaPlan, "kind" | "estimate">, setting: MediaConfirm): MediaAskReason | undefined {
if (setting === "always") return "always";
- if (confirm === true || confirm === "true") return "agent";
if (plan.estimate !== undefined ? plan.estimate > MEDIA_ASK_USD : plan.kind === "video") return "cost";
- if (plan.model.id !== plan.default.id && confirm !== false && confirm !== "false") return "model";
return undefined;
}
@@ -636,7 +635,7 @@ export class AgentManager {
/**
* 生图 / 生视频:只在该机器人有回合进行中时受理(工具调用只会发生在回合里)。
- * models / docs 直接回答;image / video 用默认模型、花费不高时直接生成,需要时(mediaAsk)先问用户用哪个模型。
+ * models / docs 直接回答;image / video 直接生成,预计花费超过上限或设成每次都问时(mediaAsk)先问用户用哪个模型。
*/
private async mediaOp(b: any): Promise<{ text?: string; error?: string }> {
const botId = String(b?.botId ?? "");
@@ -656,7 +655,7 @@ export class AgentManager {
const tool = plan.kind === "image" ? "generate_image" : "generate_video";
let model = plan.model;
const grant = conv ? this.mediaGrants.get(conv) : undefined;
- const why = mediaAsk(plan, args.confirm, this.settings(botId).media.confirm);
+ const why = mediaAsk(plan, this.settings(botId).media.confirm);
if (grant?.kind === plan.kind && grant.model === model.id && Date.now() - grant.at < (this.o.approvalTtlMs ?? APPROVAL_TTL_MS)) {
this.mediaGrants.delete(conv);
} else if (why) {
@@ -703,15 +702,13 @@ export class AgentManager {
private async confirmMedia(botId: string, conv: string, sessionId: string, plan: MediaPlan, tool: string, why: MediaAskReason): Promise<{ model?: MediaModel; cancel?: boolean; reply?: string }> {
const image = plan.kind === "image";
const opt = (m: MediaModel, tag = "") => ({ label: m.id, description: [tag, m.price].filter(Boolean).join(" · ") || undefined });
- // 为什么问:花费高、不是默认模型时说一句(每次都问、代理要问的不用解释)
+ // 为什么问:花费高时说一句(每次都问是用户自己设的,不用解释)
const reason =
why === "cost"
? plan.estimate !== undefined
? t("media.reasonCost", { amount: Math.round(plan.estimate * 100) / 100, limit: MEDIA_ASK_USD })
: t("media.reasonCostUnknown")
- : why === "model"
- ? t("media.reasonModel", { model: plan.default.id })
- : "";
+ : "";
const q: QuestionItem = {
id: "model",
header: t(image ? "media.confirmHeaderImage" : "media.confirmHeaderVideo"),
diff --git a/src/agent/media.ts b/src/agent/media.ts
index 5aaddfb..fb64154 100644
--- a/src/agent/media.ts
+++ b/src/agent/media.ts
@@ -1,8 +1,8 @@
/**
* 生图 / 生视频:代理的 media_models / media_docs / generate_image / generate_video 工具经内部 bridge 调到这里,
* 由宿主带着该机器人用的 Key 直连 Modelflare(代理子进程拿不到任何密钥),结果存进机器人工作区的 media/,
- * 再由代理用 present 交付到聊天。生成前要不要先问用户由 AgentManager 决定(manager.ts mediaAsk):模型不是默认的、
- * 预计花费超过上限、要求不明确或机器人设成每次都问时才问。
+ * 再由代理用 present 交付到聊天。生成前要不要先问用户由 AgentManager 决定(manager.ts mediaAsk):只在预计花费超过上限
+ * 或机器人设成每次都问时问。
* - 模型取自 GET /v1/models?scope=authorized&kind=image|video(这把 Key 真正能用的);参数范围、是否必须带参考素材、
* 参考价、推荐顺序取自公开价格目录 /api/pricing。
* - 每个模型的请求格式都不一样,以 docs.modelflare.dev 上该模型的文档为准:代理先用 media_docs 读文档,按文档写
@@ -356,7 +356,7 @@ export class MediaService {
const lines = list.map((m) => `- ${m.id}${m === def ? "(默认)" : ""}${[m.price, optionsNote(m)].filter(Boolean).map((s) => ` — ${s}`).join("")}`);
blocks.push(`可用的${name}模型(按推荐顺序):\n${lines.join("\n")}`);
}
- blocks.push("用默认模型、花费不高时直接生成;模型不是默认的(用户点名的除外)、预计花费较高或机器人设成每次都问时,程序会先问用户。要用参考图、比例、分辨率、时长等参数时,先用 media_docs 读该模型的文档,按文档写 body。");
+ blocks.push("调用后直接生成;只在预计花费较高或机器人设成每次都问时,程序会先问用户。要用参考图、比例、分辨率、时长等参数时,先用 media_docs 读该模型的文档,按文档写 body。");
return blocks.join("\n\n");
}
diff --git a/src/agent/prompts/skills.ts b/src/agent/prompts/skills.ts
index 9a6cef5..1d27f50 100644
--- a/src/agent/prompts/skills.ts
+++ b/src/agent/prompts/skills.ts
@@ -27,7 +27,7 @@ Tools are named \`mcp__computer-use__<tool>\`. Actions run automatically; no app
/**
* 生图 / 生视频的技能说明:不含 Key、不让代理自己调接口,参数格式以 Modelflare 文档为准。
- * 什么时候先问用户由宿主决定(manager.ts mediaAsk):这里只说清规则,让代理知道何时传 confirm。
+ * 什么时候先问用户由宿主决定(manager.ts mediaAsk:花费高或设成每次都问);代理自己不问,按最合理的理解直接生成。
*/
export const MEDIA_SKILL = `---
name: media
@@ -39,12 +39,8 @@ description: Generate or edit images and generate videos with Modelflare image a
You have no Modelflare key and must not call the API yourself (no curl, no scripts): the tools call it with this bot's key. Every generation costs the user money.
## When the user is asked first
-With the default model and a normal cost the app generates right away. It asks the user to confirm the model first only when:
-- the model is not the default one, unless you pass \`confirm: false\` because the user named that model;
-- the estimated cost is high (an expensive model, a long or high-resolution video, many images);
-- this bot is set to always ask;
-- you pass \`confirm: true\` because the request is ambiguous.
-A clear request the default model can do needs no question: generate it. If the subject, style or purpose is unclear, ask one question with \`ask_user_question\` first, or pass \`confirm: true\`.
+The app generates right away. It asks the user to confirm the model first only when the estimated cost is high (above $0.5: an expensive model, a long or high-resolution video, many images) or this bot is set to always ask.
+Do not ask about the subject, style, purpose or model yourself: if they are not spelled out, make the most reasonable interpretation, generate it, and say in one line what you chose.
## Steps
1. \`media_models\` (kind \`image\` or \`video\`) lists the models this bot may use, the default one, their parameter ranges and reference prices. Use the default unless the user named a model or the request needs something the default cannot do (a reference image, a ratio or length it does not support).
diff --git a/src/agent/prompts/system.ts b/src/agent/prompts/system.ts
index e74e311..bb88a3e 100644
--- a/src/agent/prompts/system.ts
+++ b/src/agent/prompts/system.ts
@@ -23,7 +23,10 @@ export function agentPersona(o: { computerUse?: boolean } = {}): string {
].join("\n");
}
-/** 聊天规则:先答后说、不逐步讲解、一次只问一个问题、如实报告、不说空话、IM 里回复要短、做完说清做了什么和在哪 */
+/**
+ * 聊天规则:先答后说、不逐步讲解、自己做决定(只在猜错有代价、要用户才有的东西、不可撤回时问,一次一个问题)、如实报告、
+ * 不说空话、IM 里回复要短、做完说清做了什么和在哪
+ */
export const CHAT_RULES = [
"# 聊天规则",
"用户的注意力有限,每条消息都要值得读。",
@@ -31,7 +34,7 @@ export const CHAT_RULES = [
"- 要花一阵子的任务(多步操作、生成文件或视频),开始时用一句话说你要做什么,只说一次。之后不要逐步讲解,每一步都会显示在界面的「处理过程」里。",
"- 最后一条回复是用户一定会看到的那条:做完时在里面说清做了什么、结果在哪里(文件用 present 发给用户,或写明工作区里的路径)。",
"- 如实报告:没做完就说没做完、还差什么;失败就说失败和原因。没验证过的结果不要说成已完成。",
- "- 需要用户决定时,一次只问一个具体问题,有几个选项时用 ask_user_question。能自己判断的事不要问,已经让你做的事不要再确认。",
+ "- 自己做决定,说一句选了什么;语言、格式、范围、风格都不问,已经让你做的事不要再确认。只在猜错会造成损失、花钱或白做大半,要用户才有的东西(登录、文件、密码),或这一步不可撤回(付款、删除用户的数据、给别人发消息)时才问,一次一个具体问题,有选项时用 ask_user_question。",
"- 不说客套话和空话,不复述问题,结尾不追问还需要什么。",
"- 在微信、飞书里回复要短,通常几句话;长内容写成文件交付,聊天里只给结论。微信只显示纯文本,不要用表格和标题。",
].join("\n");
diff --git a/src/agent/prompts/tasks.ts b/src/agent/prompts/tasks.ts
index fd5dd19..d2a24ae 100644
--- a/src/agent/prompts/tasks.ts
+++ b/src/agent/prompts/tasks.ts
@@ -3,8 +3,10 @@
* 重启后的恢复说明、没有报告时的提醒。改这里的文字要过 test/prompts.unit.test.ts(必须有、不能有的句子和长度上限)。
*
* 沟通规则改编自 dsh-superagent(MIT,DeepSeek)的 worker 提示词:只在做完、需要决定或做不下去时说话,一句话,不汇报进展。
- * 需要决定时(3b):先自己选合理的默认;要问就一次一个问题。有合理默认的尽早问、带上 default,接着做不依赖回答的部分,
- * 没等到回答就按默认做完、在结果里说明;非用户定不可的(付款、删除、选账号),先做完不依赖它的部分再问,结束这一轮等回答。
+ * 需要决定时:自己定,在结果里说明选了什么;语言、格式、范围、风格从不问(产品负责人 2026-11-01:自动做,不要一直问)。
+ * 只在猜错会造成损失、花钱或白做大半,要用户才有的东西(登录、文件、密码),或这一步不可撤回时问,一次一个问题。
+ * 猜错只会白做的尽早问、带上 default(3b 之后的不阻塞提问),接着做不依赖回答的部分,没等到回答就按默认做完;
+ * 其余的先做完不依赖它的部分再问,结束这一轮等回答。
*/
/** 任务会话的系统提示词段:名字与位置(排在机器人段 amb:bot 之后,同时冲突时以它为准) */
@@ -15,9 +17,9 @@ export const TASK_SECTION_ORDER = 20_100;
export const TASK_RULES = [
"# 后台任务(优先于上面的聊天规则)",
"你在后台独立完成一个任务,用户不在旁边。任务和用户的原话在第一条消息里;当前目录是这个任务的文件夹,产出的文件放在这里。",
- "- 能自己定的就选一个合理的做法,在结果里说明。要问用户就用 task_report 报 needs_you 和一个问题(有选项就给):",
- " 有合理默认的尽早问、给 default,接着只做不依赖回答的部分,做完还没回答就按默认;",
- " 非用户定不可的(付款、删除、选账号),先做完不依赖它的部分再问,然后结束这一轮。",
+ "- 自己做决定,在结果里说明选了什么。语言、格式、范围、风格都不问:用对话的语言,选最合理的做法。",
+ "- 只在这些时候用 task_report 报 needs_you 问一个问题:猜错会造成损失、花钱或白做大半;要用户才有的东西(登录、文件、密码);这一步不可撤回(付款、删除用户的数据、给别人发消息)。",
+ " 猜错只会白做的,尽早问、给 default,接着只做不依赖回答的部分,做完还没回答就按默认;其余的先做完不依赖回答的部分再问,然后结束这一轮。",
"- 做会改变外部的事(发送、发帖、付款、删除、调用会改动东西的接口)之前和之后,各在 .task/journal.md 里追加一行。",
"- 做完或做不下去时调用 task_report:state 为 done 或 failed,message 是给用户的一句话(不超过 300 字:结果是什么、在哪里),files 列出要发给用户的文件。然后结束这一轮。",
"- 中途不用汇报;想记下进展可以报 progress,不会发给用户。",
diff --git a/src/agent/settings.ts b/src/agent/settings.ts
index faf6e2d..dc77f9a 100644
--- a/src/agent/settings.ts
+++ b/src/agent/settings.ts
@@ -3,7 +3,7 @@ import { DEFAULT_QUIET, minuteOf, type QuietHours } from "../core/quiet.js";
export type PermissionPreset = "readonly" | "workspace" | "full";
export type CuBackend = "cua" | "codex";
export type CuApproval = "auto" | "ask-input";
-/** auto = 只在需要时问(模型不是默认的、预计花费超过上限、要求不明确);always = 每次生成前都问 */
+/** auto = 只在预计花费超过上限时问(视频算不出花费也问);always = 每次生成前都问 */
export type MediaConfirm = "auto" | "always";
/** 内置头像角色(ui/components/avatar.js 的 BOT_CHARS);blue 是主角 */
export const BOT_AVATARS = ["blue", "yellow", "green", "red", "purple", "orange"] as const;
@@ -100,7 +100,7 @@ export function normalizeSettings(raw: unknown): BotSettings {
// 旧值(always / readonly-free)一律迁移为自动执行
approval: cu.approval === "ask-input" ? "ask-input" : "auto",
},
- // 以前每次都问;升级后默认只在需要时问
+ // 以前每次都问;升级后默认只在花费高时问
media: { confirm: md.confirm === "always" ? "always" : "auto" },
utilityModel: typeof r.utilityModel === "string" ? r.utilityModel.trim().slice(0, 200) : "",
avatar: (BOT_AVATARS as readonly string[]).includes(r.avatar) ? r.avatar : "",
diff --git a/src/i18n/messages/media.ts b/src/i18n/messages/media.ts
index ab465d2..39fc43c 100644
--- a/src/i18n/messages/media.ts
+++ b/src/i18n/messages/media.ts
@@ -22,7 +22,6 @@ export const zh = {
confirmDetail: "{summary}{reason}\n也可以直接回复其他模型名。",
reasonCost: "预计花费约 ${amount},超过 ${limit}",
reasonCostUnknown: "这次的花费估算不出来",
- reasonModel: "不是默认模型(默认是 {model})",
tagDefault: "默认",
tagBotPick: "机器人选的",
cancel: "取消",
@@ -46,7 +45,6 @@ export const en: Catalog<typeof zh> = {
confirmDetail: "{summary}{reason}\nYou can also reply with another model name.",
reasonCost: "Estimated cost about ${amount}, above ${limit}",
reasonCostUnknown: "The cost of this run can't be estimated",
- reasonModel: "Not the default model (the default is {model})",
tagDefault: "default",
tagBotPick: "picked by the bot",
cancel: "Cancel",
diff --git a/src/i18n/messages/rules.ts b/src/i18n/messages/rules.ts
index da9b326..44d0de5 100644
--- a/src/i18n/messages/rules.ts
+++ b/src/i18n/messages/rules.ts
@@ -71,8 +71,9 @@ export const zh = {
headMonth: "规则「{title}」本月预算用完了",
// 推送:连续失败暂停了(执行中的规则)
pausedPush: "⚠️ 规则「{title}」连续失败 {count} 次,已暂停:{why}",
- // 建规则时建议给用户的那句(经聊天代理转述)
- createdReply: "已建好规则:{when} {title}。先观察几天,只记录不打扰你;在「任务」里可以改成执行。",
+ // 建规则时建议给用户的那句(经聊天代理转述):新规则直接执行;用户说了先观察的才观察
+ createdReply: "已建好规则:{when} {title},有值得说的就告诉你。",
+ createdObserveReply: "已建好规则:{when} {title},先观察几天,只记录不打扰你。",
remindReply: "好,{when} 提醒你。",
weixinNote: "微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。",
// /tasks、/stop 编号(行的写法、提示语用 tasks.* 的)
@@ -165,7 +166,8 @@ export const en: Catalog<typeof zh> = {
headFailingPaused: { one: "Rule “{title}” failed {count} time in a row and is paused", other: "Rule “{title}” failed {count} times in a row and is paused" },
headMonth: "Rule “{title}” used up this month's budget",
pausedPush: "⚠️ Rule “{title}” failed {count} times in a row and is paused: {why}",
- createdReply: "Rule set: {title}, {when}. It watches quietly for a few days; switch it to act under Tasks.",
+ createdReply: "Rule set: {title}, {when}. I'll tell you when something matters.",
+ createdObserveReply: "Rule set: {title}, {when}. It watches quietly for a few days and sends nothing.",
remindReply: "OK, reminder set for {when}.",
weixinNote: "WeChat lets the bot message you only within 24 hours of your last message. Otherwise it arrives with your next message and shows on the desktop.",
listHead: "Rules:",
diff --git a/src/i18n/messages/tasks.ts b/src/i18n/messages/tasks.ts
index 5c98be8..4c8141d 100644
--- a/src/i18n/messages/tasks.ts
+++ b/src/i18n/messages/tasks.ts
@@ -59,10 +59,8 @@ export const zh = {
reserveStep: "预算留给聊天",
reserveSubject: "后台工作已停",
reserveLine: "机器人预算只剩约 {remain}(共 {limit}),留给聊天",
- // 保留与清理(3f):归档了的任务、「需要你」里清理文件夹那一行
+ // 保留与清理(3f):归档了的任务
archivedNoFollowup: "「{title}」已归档,不能再追加;需要的话开个新任务。",
- cleanupSubject: { other: "{count} 个任务文件夹 {date} 删除" },
- cleanupLine: { other: "{titles} 30 天没动过了" },
// 导出成 Markdown(3f,tasks/export.ts)
exportedAt: "导出于 {time}",
exportLog: "运行记录",
@@ -149,8 +147,6 @@ export const en: Catalog<typeof zh> = {
reserveSubject: "Background work stopped",
reserveLine: "The bot's budget is down to about {remain} of {limit}; the rest is kept for chat",
archivedNoFollowup: "\"{title}\" is archived and can't take follow-ups; start a new task if you need one.",
- cleanupSubject: { one: "{count} task folder will be deleted {date}", other: "{count} task folders will be deleted {date}" },
- cleanupLine: { one: "{titles} hasn't been used in 30 days", other: "{titles} haven't been used in 30 days" },
exportedAt: "Exported {time}",
exportLog: "Run log",
exportNoRuns: "No runs yet.",
diff --git a/src/store/db.ts b/src/store/db.ts
index 5dc9940..803950b 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -320,8 +320,6 @@ export interface RuleRow {
kind: RuleKind;
trigger: RuleTrigger;
mode: RuleMode;
- /** 改了规则原话后先观察几次再执行(产品负责人:观察 1 次) */
- observeLeft: number;
/** 相对工作区:rules/<slug>-<id6> */
folder: string;
/** 原话每改一次加 1;每个 run 记下它跑的是哪一版 */
@@ -405,7 +403,6 @@ const RULE_COLS: Record<string, string> = {
kind: "kind",
trigger: "trigger_spec",
mode: "mode",
- observeLeft: "observe_left",
version: "version",
nextRunAt: "next_run_at",
failures: "failures",
@@ -499,6 +496,7 @@ 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(改了原话后先观察几次)2026-11-01 起不再用,列留着
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);
@@ -1396,7 +1394,6 @@ export class Store {
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),
@@ -1410,14 +1407,14 @@ export class Store {
};
}
insertRule(
- r: Omit<RuleRow, "version" | "failures" | "pausedReason" | "observeLeft" | "runBudgetUsd" | "monthBudgetUsd"> & Partial<Pick<RuleRow, "version" | "observeLeft" | "runBudgetUsd" | "monthBudgetUsd">>,
+ r: Omit<RuleRow, "version" | "failures" | "pausedReason" | "runBudgetUsd" | "monthBudgetUsd"> & Partial<Pick<RuleRow, "version" | "runBudgetUsd" | "monthBudgetUsd">>,
): 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, run_budget_usd, month_budget_usd)
- VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT INTO rules(id, bot_id, conversation_id, title, instruction, message, kind, trigger_spec, mode, folder, version, next_run_at, anytime, created_at, updated_at, run_budget_usd, month_budget_usd)
+ 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, r.runBudgetUsd ?? 0.1, r.monthBudgetUsd ?? 3);
+ .run(r.id, r.botId, r.conversationId, r.title, r.instruction, r.message, r.kind, JSON.stringify(r.trigger), r.mode, r.folder, r.version ?? 1, r.nextRunAt, r.anytime ? 1 : 0, r.createdAt, r.updatedAt, r.runBudgetUsd ?? 0.1, r.monthBudgetUsd ?? 3);
return this.getRule(r.id)!;
}
/** 规则从 since 起(按该跑的时间)花了多少:本月的花费 */
diff --git a/src/tasks/attention.ts b/src/tasks/attention.ts
index 342313f..be7e1ac 100644
--- a/src/tasks/attention.ts
+++ b/src/tasks/attention.ts
@@ -19,18 +19,19 @@ const log = logger("attention");
/**
* question / approval:在等你回答、批准(任务预算用完时的「再给 $1 继续?」也是 question);failed:任务失败了;
* rule:规则连续失败或本月预算用完(暂停了);delivery:结果没送到;login:渠道登录过期了;budget:机器人的预算留给聊天,后台工作停着;
- * cleanup:任务文件夹 30 天没动过,过几天清理(3f);suggest:观察中的规则这一版好好观察了 3 次,问要不要改为执行(最不急:不推送、不发系统通知)
+ * suggest:用户选了观察的规则这一版好好观察了 3 次,问要不要改为执行(最不急:不推送、不发系统通知)。
+ * 任务文件夹 30 天没动过的清理不在这里(2026-11-01 起不问):清理的日期和「保留」在任务详情里。
*/
-export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login" | "budget" | "cleanup" | "suggest";
+export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login" | "budget" | "suggest";
/**
* answer、approve、deny、retry(任务再试 / 消息再发)、stop、dismiss(不再提示)、relogin(去重新扫码)、
- * open(打开对话;budget 是打开机器人设置的预算)、continue(加预算接着做:任务 $1,规则每月 $3)、keep(保留要清理的任务文件夹)、
+ * open(打开对话;budget 是打开机器人设置的预算)、continue(加预算接着做:任务 $1,规则每月 $3)、
* act(规则改为执行;suggest 的 dismiss 是继续观察)
*/
-export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open" | "continue" | "keep" | "act";
+export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open" | "continue" | "act";
export interface AttentionItem {
- /** 稳定 id:approval:<id>、task:<id>、rule:<id>、suggest:<规则>、delivery:<会话>:held|failed、login:<bot>:<渠道>、reserve:<bot>(预算留给聊天)、cleanup:<bot> */
+ /** 稳定 id:approval:<id>、task:<id>、rule:<id>、suggest:<规则>、delivery:<会话>:held|failed、login:<bot>:<渠道>、reserve:<bot>(预算留给聊天) */
id: string;
kind: AttentionKind;
botId: string;
@@ -66,7 +67,7 @@ export interface AttentionItem {
export type AttentionSource = () => AttentionItem[];
/** 排序:提问和审批在前(等着的事),再是失败、没送到,再是系统的(登录、预算),问要不要改为执行的最后;同一类旧的在前 */
-const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3, budget: 3, cleanup: 3, suggest: 4 };
+const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3, budget: 3, suggest: 4 };
/** 不发系统通知的:只是建议,等用户自己来看 */
const QUIET = new Set<AttentionKind>(["suggest"]);
diff --git a/src/tasks/retention.ts b/src/tasks/retention.ts
index ca33828..1e11ada 100644
--- a/src/tasks/retention.ts
+++ b/src/tasks/retention.ts
@@ -3,9 +3,9 @@
*
* - 任务和运行记录留 30 天:30 天没动过的任务归档(不再列出、不能再追加,等着的提问作废),运行记录只留 30 天
* (每个任务最近的那个 run 留着:阶段看它)。
- * - 任务文件夹留到任务删掉为止;30 天没动过就清理,清理前先告诉用户一次(「需要你」里一行,可以保留),至少 3 天之后才删,
- * 连同 DSH 里这个任务的会话记录。文件夹是空的就不打扰,直接归档。
- * - 状态都在库里(tasks.cleanup_at、kv),重启不影响;时间都从任务服务的时钟取(测试用假时钟)。
+ * - 任务文件夹留到任务删掉为止;30 天没动过就清理,连同 DSH 里这个任务的会话记录。不问用户、不发通知(产品负责人
+ * 2026-11-01):第 27 天定下清理的日期,任务详情里写着,可以保留;定下之后至少 3 天才删。文件夹是空的直接归档。
+ * - 状态都在库里(tasks.cleanup_at),重启不影响;时间都从任务服务的时钟取(测试用假时钟)。
*/
import fs from "node:fs";
import path from "node:path";
@@ -13,7 +13,7 @@ import path from "node:path";
export const DAY_MS = 86_400_000;
/** 任务、运行记录、没动过的文件夹留多久 */
export const KEEP_MS = 30 * DAY_MS;
-/** 删文件夹之前提前多久告诉用户(之后至少等这么久) */
+/** 定下清理日期之后至少等多久才删(任务详情里看得到日期,可以保留) */
export const WARN_MS = 3 * DAY_MS;
/** 多久看一次 */
export const SWEEP_MS = 3600_000;
diff --git a/src/tasks/rules.ts b/src/tasks/rules.ts
index 83b0d7c..540cc46 100644
--- a/src/tasks/rules.ts
+++ b/src/tasks/rules.ts
@@ -2,7 +2,7 @@
* 规则(3d)的纯函数部分:状态、给人看的一行、每种模式的权限和去掉的工具。写库的是任务服务(service.ts,唯一的写入者)。
*
* 状态(第一条符合的为准):暂停了(连续失败 3 次、本月预算用完)→ 已暂停;关了 → 已关闭;一次性的跑过了 → 已结束;提醒 → 提醒;
- * 观察中(含改了原话后先观察的那一次)→ 观察中;其余 → 执行中。状态是"点 + 文字":红 = 连续失败暂停,黄 = 本月预算用完暂停,
+ * 观察中 → 观察中;其余 → 执行中。新的检查直接执行(用户的原话就是授权,和让做的任务一样);观察要用户自己选。状态是"点 + 文字":红 = 连续失败暂停,黄 = 本月预算用完暂停,
* 绿 = 执行中、提醒,灰 = 观察、关闭、结束。
* 给人看的文字跟着语言(src/i18n 的 rules.*);跳过、失败的原因存成代码(RUN_ERROR),显示时再翻。
*/
@@ -14,10 +14,8 @@ import { describe } from "./schedule.js";
export const RULE_FAILS_TO_PAUSE = 3;
/** 连续失败几次出现在「需要你」里 */
export const RULE_FAILS_TO_SHOW = 2;
-/** 这一版好好观察了几次(做完了的;失败、跳过的不算)之后,「需要你」里问要不要改为执行 */
+/** 用户选了观察的规则:这一版好好观察了几次(做完了的;失败、跳过的不算)之后,「需要你」里问要不要改为执行 */
export const RULE_SUGGEST_AFTER = 3;
-/** 改了原话之后先观察几次(产品负责人:1 次) */
-export const RULE_OBSERVE_AFTER_EDIT = 1;
/** 每个机器人最多几条规则 */
export const MAX_RULES = 30;
/** 一次运行最长多久(不算等批准的时间) */
@@ -37,10 +35,10 @@ export const RULE_DENY: Readonly<Record<"observe" | "act", string[]>> = {
/** 按前缀拒绝的工具(MCP 的电脑操作,名字随平台变化,没法列全) */
export const RULE_DENY_PREFIX = ["mcp__computer-use__"];
-/** 这次运行用的模式:改了原话后先观察 observeLeft 次 */
-export function runMode(rule: Pick<RuleRow, "mode" | "observeLeft" | "kind">): "observe" | "act" {
+/** 这次运行用的模式:提醒总是执行;检查照规则的模式(改了原话也不再先观察,产品负责人 2026-11-01) */
+export function runMode(rule: Pick<RuleRow, "mode" | "kind">): "observe" | "act" {
if (rule.kind === "remind") return "act";
- return rule.mode === "act" && rule.observeLeft <= 0 ? "act" : "observe";
+ return rule.mode === "act" ? "act" : "observe";
}
/** DSH 的沙箱:观察只读;执行是机器人的预设和可写工作区里取小的(完全权限的机器人也一样,决定 12) */
@@ -79,8 +77,6 @@ export interface RuleView {
/** 时间表的话:每天 08:00;事件触发的是来源 */
when: string;
mode: RuleMode;
- /** 改了原话后还要先观察几次 */
- observeLeft: number;
state: RuleState;
nextRunAt: number;
/** 最近一次:时间、结果、一行 */
diff --git a/src/tasks/service.ts b/src/tasks/service.ts
index f205485..ec3a39b 100644
--- a/src/tasks/service.ts
+++ b/src/tasks/service.ts
@@ -72,7 +72,6 @@ import {
RULE_DENY_PREFIX,
RULE_FAILS_TO_PAUSE,
RULE_FAILS_TO_SHOW,
- RULE_OBSERVE_AFTER_EDIT,
RULE_RUN_CAP_MS,
RULE_SUGGEST_AFTER,
RUN_ERROR,
@@ -88,7 +87,7 @@ import {
type RuleRunView,
type RuleView,
} from "./rules.js";
-import { lang, t as tr } from "../i18n/index.js";
+import { t as tr } from "../i18n/index.js";
import { KEEP_MS, SWEEP_MS, WARN_MS, dirBytes, hasFiles, taskFolder } from "./retention.js";
import { ruleMarkdown, taskMarkdown, type ExportedTaskRun } from "./export.js";
@@ -278,8 +277,6 @@ export function slugOf(title: string): string {
const NOTES = "task-notes:";
/** 还没删掉的会话记录("<机器人>:<任务>",会话开在代理进程里时删不了,下次清理再删) */
const TRASH = "tasks:session-trash";
-/** 「需要你」里清理文件夹那一行点过「知道了」:到哪个清理时间为止不再显示(每个机器人一个) */
-const CLEANUP_SEEN = "tasks:cleanup-seen:";
/** 「需要你」里问要不要改为执行的那一行点过「继续观察」:哪一版不再问(每条规则一个;删规则时一起删) */
const SUGGEST_SEEN = "rules:suggest-seen:";
@@ -1713,7 +1710,6 @@ export class TaskService {
actions: ["open"],
});
}
- out.push(...this.cleanupAttention());
return out;
}
@@ -1864,7 +1860,8 @@ export class TaskService {
* 保留与清理(启动时一次,之后每小时一次;决定 9):每个没在跑的任务看它多久没动了(最近的输入、结果、改预算、保留):
* - 不到 27 天:什么都不做(之前定了清理的取消:用户又用了它);
* - 文件夹是空的:到 30 天归档(没什么会丢的,不打扰);
- * - 有文件、还没告诉过:定在 3 天后(且不早于第 30 天)清理,「需要你」里一行(cleanupAttention);
+ * - 有文件、还没定:定在 3 天后(且不早于第 30 天)清理。不问用户、不发通知(产品负责人 2026-11-01):任务详情里写着
+ * 哪天清理,可以保留;
* - 到了定的时间、也满 30 天了:删文件夹,归档(连同 DSH 里的会话记录)。
* 运行记录只留 30 天(本月的规则运行留着:本月花费从它们汇总)。之前删不掉的会话记录(还开在代理进程里)再删一次。
*/
@@ -1902,7 +1899,7 @@ export class TaskService {
if (!task.cleanupAt) {
const at = Math.max(now + WARN_MS, last + KEEP_MS);
this.store.updateTask(task.id, { cleanupAt: at });
- log.info("task folder unused for a while; telling the user before cleaning it up", { task: task.id, at: new Date(at).toISOString() });
+ log.info("task folder unused for a while; cleanup date set", { task: task.id, at: new Date(at).toISOString() });
this.changed(task.id);
return;
}
@@ -1969,56 +1966,6 @@ export class TaskService {
return this.get(task.id);
}
- /** 「需要你」里的保留:这个机器人定了清理的文件夹都保留 */
- keepCleanup(botId: string): boolean {
- const tasks = this.store.listTasks({ botId, limit: 500 }).filter((t) => t.cleanupAt > 0);
- for (const t of tasks) this.keepFolder(t.id);
- return tasks.length > 0;
- }
-
- /** 「需要你」里的知道了:这一行不再显示(到时照样清理);之后又有文件夹要清理时再出现 */
- dismissCleanup(botId: string): boolean {
- const at = Math.max(0, ...this.store.listTasks({ botId, limit: 500 }).map((t) => t.cleanupAt));
- if (!at) return false;
- this.store.setKV(CLEANUP_SEEN + botId, String(at));
- this.changed(botId);
- return true;
- }
-
- /**
- * 「需要你」里清理文件夹那一份:一个机器人一行,「2 个任务文件夹 11月4日 删除」,第二行是哪几个任务。不推送:
- * 只在应用里(和一次系统通知)。可以保留(再算 30 天)或知道了。
- */
- private cleanupAttention(): AttentionItem[] {
- const out: AttentionItem[] = [];
- const byBot = new Map<string, TaskRow[]>();
- for (const t of this.store.listTasks({ limit: 500 })) if (t.cleanupAt > 0) byBot.set(t.botId, [...(byBot.get(t.botId) ?? []), t]);
- const l = lang();
- for (const [botId, tasks] of byBot) {
- const seen = Number(this.store.getKV(CLEANUP_SEEN + botId) || 0);
- if (tasks.every((t) => t.cleanupAt <= seen)) continue;
- const first = Math.min(...tasks.map((t) => t.cleanupAt));
- const date = new Intl.DateTimeFormat(l === "en" ? "en-US" : "zh-CN", { month: l === "en" ? "short" : "long", day: "numeric", timeZone: this.timeZone }).format(first);
- const names = tasks.slice(0, 3).map((t) => t.title);
- const titles = new Intl.ListFormat(l === "en" ? "en" : "zh-CN", { type: "conjunction" }).format(names) + (tasks.length > 3 ? "…" : "");
- const subject = tr("tasks.cleanupSubject", { count: tasks.length, date });
- out.push({
- id: `cleanup:${botId}`,
- kind: "cleanup",
- botId,
- botName: this.store.getBot(botId)?.name ?? botId,
- subject,
- status: "",
- head: subject,
- line: tr("tasks.cleanupLine", { titles, count: tasks.length }),
- since: first - WARN_MS,
- severity: "warn",
- actions: ["keep", "dismiss"],
- });
- }
- return out;
- }
-
/** 删掉任务(任务详情里的删除):在跑的先停下,等着的提问、审批作废,没发出去的结果不发了,文件夹和 DSH 里的会话记录、运行记录一起删 */
async deleteTask(taskId: string, by: string): Promise<boolean> {
const task = this.store.getTask(taskId);
@@ -2134,8 +2081,9 @@ export class TaskService {
}
/**
- * 新规则(聊天代理的 rule_create、界面):检查从观察开始;固定提醒没什么要判断的,直接执行(决定 6),
- * 不受免打扰限制(时间是用户定的)。时间表或事件触发二选一。
+ * 新规则(聊天代理的 rule_create、界面):直接执行,用户的原话就是授权,和让做的任务一样(产品负责人 2026-11-01);
+ * 用户说了先观察(mode observe)的检查才观察。固定提醒没什么要判断的,总是执行(决定 6),不受免打扰限制(时间是用户定的)。
+ * 时间表或事件触发二选一。
*/
createRule(o: {
botId: string;
@@ -2143,6 +2091,8 @@ export class TaskService {
title: string;
instruction: string;
kind?: RuleKind;
+ /** 检查的模式:默认执行;observe = 用户要先观察 */
+ mode?: "observe" | "act";
message?: string;
schedule?: Schedule;
trigger?: RuleTrigger;
@@ -2173,7 +2123,7 @@ export class TaskService {
}
const now = this.now();
const id = `rl_${hex(6)}`;
- const mode: RuleMode = kind === "remind" ? "act" : "observe";
+ const mode: RuleMode = kind === "check" && o.mode === "observe" ? "observe" : "act";
const rule = this.store.insertRule({
id,
botId: o.botId,
@@ -2191,14 +2141,14 @@ export class TaskService {
createdAt: now,
updatedAt: now,
});
- log.info("rule created", { bot: o.botId, rule: id, kind, trigger: trigger.kind, conversationId: conv.id });
+ log.info("rule created", { bot: o.botId, rule: id, kind, mode, trigger: trigger.kind, conversationId: conv.id });
this.ruleChanged(id);
return { rule };
}
/**
- * 改规则(界面、rule_update)。改原话:版本加 1;执行中的检查先观察 1 次再回到执行(决定 7)。只改时间表:模式不变。
- * 改模式:重新开的清掉连续失败和暂停。正在跑的那次照它开始时的版本跑完。
+ * 改规则(界面、rule_update)。改原话:版本加 1,模式不变(执行中的照样执行,不再先观察:产品负责人 2026-11-01)。
+ * 只改时间表:模式不变。改模式:重新开的清掉连续失败和暂停。正在跑的那次照它开始时的版本跑完。
*/
updateRule(
id: string,
@@ -2245,12 +2195,8 @@ export class TaskService {
if (patch.mode !== undefined && patch.mode !== rule.mode) {
if (rule.kind === "remind" && patch.mode === "observe") return { error: tr("rules.remindNoObserve") };
mode = next.mode = patch.mode;
- next.observeLeft = 0;
- }
- if (reworded) {
- next.version = rule.version + 1;
- if (rule.kind === "check" && mode === "act") next.observeLeft = RULE_OBSERVE_AFTER_EDIT;
}
+ if (reworded) next.version = rule.version + 1;
// 重新开(关着、暂停了 → 开着):连续失败清零
const reopened = patch.mode !== undefined && mode !== "off" && (rule.mode === "off" || !!rule.pausedReason || patch.mode !== rule.mode);
if (reopened) (next.failures = 0), (next.pausedReason = "");
@@ -2269,7 +2215,7 @@ export class TaskService {
if (!rule) return { error: "rule not found" };
if (rule.pausedReason === "budget" && this.monthSpent(rule) >= rule.monthBudgetUsd) return { error: tr("rules.monthUsed", { spent: usdText(this.monthSpent(rule)) }) };
if (rule.pausedReason || rule.failures) {
- const mode = rule.mode === "off" ? (rule.kind === "remind" ? "act" : "observe") : rule.mode;
+ const mode = rule.mode === "off" ? "act" : 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);
@@ -2540,7 +2486,7 @@ export class TaskService {
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:存下步骤、报告、本会做的事;之后按结果更新规则(连续失败、先观察的次数)、送出那一句 */
+ /** 结束规则的 run:存下步骤、报告、本会做的事;之后按结果更新规则(连续失败)、送出那一句 */
private endRule(l: Live, outcome: RunOutcome, report?: TaskReport, error = ""): void {
this.forget(l);
const now = this.now();
@@ -2556,16 +2502,13 @@ export class TaskService {
}
/**
- * 一次运行之后:成功清零连续失败,改了原话后先观察的那一次跑完了就回到执行;有要说的那一句(观察时是「本会发送」)用主模型写,
- * 执行时发出去。失败加 1(超出单次预算也算),连续 3 次自动暂停:执行中的规则推一句 ⚠️,观察中的只在「需要你」里。
+ * 一次运行之后:成功清零连续失败;有要说的那一句(观察时是「本会发送」)用主模型写,执行时发出去。
+ * 失败加 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);
+ this.store.updateRule(rule.id, { failures: 0 });
if (report?.message) void this.ruleResult(rule, runId, mode, report);
} else if (outcome === "failed" || (outcome === "budget" && error === RUN_ERROR.runBudget)) {
const failures = rule.failures + 1;
@@ -2754,20 +2697,21 @@ export class TaskService {
// ---------- 规则:聊天代理的工具 ----------
- /** rule_create:用户原话、一行时间表、检查还是提醒 */
+ /** rule_create:用户原话、一行时间表、检查还是提醒;检查默认执行,用户说先观察时 mode 是 observe */
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 });
+ const mode = a.mode === "observe" ? "observe" : "act";
+ const r = this.createRule({ botId: conv.botId, conversationId: conv.id, title: String(a.title ?? ""), instruction: String(a.instruction ?? ""), kind, mode, message: String(a.message ?? ""), schedule: s.schedule });
if (!r.rule) return { error: r.error };
// 建议给用户的那几句按应用的语言(模型照着说,聊天的语言不同时它会自己换);其余是给模型的指示
const when = whenOf(r.rule);
+ const title = r.rule.title;
const wx = conv.channel === "weixin" ? ` This chat is WeChat, so also say: 「${tr("rules.weixinNote")}」` : "";
if (kind === "remind") return { text: `Created reminder ${r.rule.id}: ${when} the user gets 「${r.rule.message}」. Confirm in one sentence, e.g. 「${tr("rules.remindReply", { when })}」${wx}` };
- return {
- text: `Created rule ${r.rule.id} 「${r.rule.title}」 (${when}) in observe mode: it only records what it would say until the user switches it to act. Tell the user in one sentence: 「${tr("rules.createdReply", { when, title: r.rule.title })}」${wx}`,
- };
+ if (r.rule.mode === "observe") return { text: `Created rule ${r.rule.id} 「${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: 「${tr("rules.createdObserveReply", { when, title })}」${wx}` };
+ return { text: `Created rule ${r.rule.id} 「${title}」 (${when}): each run checks and messages the user only when something matters. Tell the user in one sentence: 「${tr("rules.createdReply", { when, title })}」${wx}` };
}
/** rule_update:改模式(执行 / 观察 / 关)、原话、时间表,或删掉 */
@@ -2795,8 +2739,7 @@ export class TaskService {
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.` };
+ return { text: `Updated rule 「${v.title}」: ${v.when}, ${v.state.label}. Tell the user in one short sentence.` };
}
// ---------- 规则:查看 ----------
@@ -2821,7 +2764,6 @@ export class TaskService {
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)) } } : {}),
@@ -2926,7 +2868,7 @@ export class TaskService {
}
/**
- * 观察中、没暂停的检查,这一版好好观察了 3 次(做完了的;失败、跳过的不算):「需要你」里问要不要改为执行,第二行是最近那次
+ * 用户选了观察、没暂停的检查,这一版好好观察了 3 次(做完了的;失败、跳过的不算):「需要你」里问要不要改为执行,第二行是最近那次
* 运行记录里的那一行。只在应用里:不推送、不发系统通知。改为执行、关掉、暂停、删掉就消失;继续观察了的这一版不再问
* (改了原话版本加 1,新的一版再好好观察 3 次再问)。
*/
diff --git a/src/web/server.ts b/src/web/server.ts
index baf34d1..0d03ef3 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -485,8 +485,6 @@ 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);
- // 清理任务文件夹(3f):保留(再算 30 天)、知道了(到时照样清理)
- else if (item.kind === "cleanup") ok = action === "keep" ? app.tasks.keepCleanup(item.botId) : app.tasks.dismissCleanup(item.botId);
// 观察够了的规则:改为执行(和规则详情里切模式一样)、继续观察(这一版不再问)
else if (item.kind === "suggest") ok = action === "act" ? !app.tasks.updateRule(item.ruleId!, { mode: "act" }).error : app.tasks.keepObserving(item.ruleId!);
else if (item.kind === "rule" && action === "retry") ok = !app.tasks.resumeRule(item.ruleId!).error;
@@ -585,12 +583,15 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
}
if (seg.length === 1 && m === "POST") {
const b = await readJson(req);
+ // 检查默认执行;mode observe = 用户在编辑器里选了先观察
+ if (b.mode !== undefined && !["observe", "act"].includes(b.mode)) throw new HttpError(400, t("rules.badMode"));
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",
+ ...(b.mode === "observe" ? { mode: "observe" as const } : {}),
message: String(b.message ?? ""),
schedule: scheduleOf(b.schedule, app.delivery.timeZone),
...(b.runBudgetUsd !== undefined ? { runBudgetUsd: Number(b.runBudgetUsd) } : {}),
diff --git a/test/account.test.ts b/test/account.test.ts
index 57fc9b7..4edb384 100644
--- a/test/account.test.ts
+++ b/test/account.test.ts
@@ -558,25 +558,20 @@ describe("amb-media 插件与 bridge", () => {
}
});
- it("什么时候先问:每次都问 > 代理说要问 > 花费超过上限(视频算不出也算)> 不是默认模型(用户点名的除外)", () => {
- const M1 = { id: "m1" } as MediaModel;
- const M2 = { id: "m2" } as MediaModel;
- const plan = (o: { model?: MediaModel; estimate?: number; kind?: "image" | "video" } = {}) => ({ kind: o.kind ?? ("image" as const), model: o.model ?? M1, default: M1, estimate: o.estimate });
- expect(mediaAsk(plan({ estimate: 0.04 }), undefined, "auto")).toBeUndefined();
- expect(mediaAsk(plan({ estimate: 0.04 }), undefined, "always")).toBe("always");
- expect(mediaAsk(plan({ estimate: 0.04 }), true, "auto")).toBe("agent");
- expect(mediaAsk(plan({ estimate: 0.04 }), "true", "auto")).toBe("agent");
- expect(mediaAsk(plan({ estimate: MEDIA_ASK_USD }), undefined, "auto")).toBeUndefined();
- expect(mediaAsk(plan({ estimate: MEDIA_ASK_USD + 0.01 }), false, "auto")).toBe("cost");
- // 图片算不出花费不问(便宜),视频算不出就问
- expect(mediaAsk(plan({}), undefined, "auto")).toBeUndefined();
- expect(mediaAsk(plan({ kind: "video" }), undefined, "auto")).toBe("cost");
- expect(mediaAsk(plan({ kind: "video", estimate: 0.3 }), undefined, "auto")).toBeUndefined();
- expect(mediaAsk(plan({ model: M2, estimate: 0.04 }), undefined, "auto")).toBe("model");
- expect(mediaAsk(plan({ model: M2, estimate: 0.04 }), false, "auto")).toBeUndefined();
- });
-
- it("默认模型、花费不高直接生成;换模型、花费高、代理要问、设成每次都问时先问;换模型后按新文档重写的那一次免确认", async () => {
+ /** 少问(产品负责人 2026-11-01):默认只在预计花费超过上限时问;换了模型、要求不明确都不问(代理按最合理的理解直接生成) */
+ it("什么时候先问:每次都问;或者预计花费超过上限(视频算不出也算)。不是默认模型、要求不明确都不问", () => {
+ const plan = (o: { estimate?: number; kind?: "image" | "video" } = {}) => ({ kind: o.kind ?? ("image" as const), estimate: o.estimate });
+ expect(mediaAsk(plan({ estimate: 0.04 }), "auto")).toBeUndefined();
+ expect(mediaAsk(plan({ estimate: 0.04 }), "always")).toBe("always");
+ expect(mediaAsk(plan({ estimate: MEDIA_ASK_USD }), "auto")).toBeUndefined();
+ expect(mediaAsk(plan({ estimate: MEDIA_ASK_USD + 0.01 }), "auto")).toBe("cost");
+ // 图片算不出花费不问(便宜),视频算不出就问(可能很贵)
+ expect(mediaAsk(plan({}), "auto")).toBeUndefined();
+ expect(mediaAsk(plan({ kind: "video" }), "auto")).toBe("cost");
+ expect(mediaAsk(plan({ kind: "video", estimate: 0.3 }), "auto")).toBeUndefined();
+ });
+
+ it("直接生成(换了模型、代理还传着旧的 confirm 也不问);花费高、设成每次都问时先问;换模型后按新文档重写的那一次免确认", async () => {
const store = new Store(":memory:");
store.createBot({ id: "b1", name: "b1" });
const M1 = { id: "m1", kind: "image", price: "$0.03/张" };
@@ -621,38 +616,41 @@ describe("amb-media 插件与 bridge", () => {
try {
// 默认模型、花费不高:不问,直接生成
expect(await call({ prompt: "猫" })).toEqual({ text: "done m1" });
+ // 代理(或用户)选了别的模型:不问
+ expect(await call({ prompt: "猫", model: "m2" })).toEqual({ text: "done m2" });
+ // 旧提示词里的 confirm: true(要求不明确)不再算数:不问
+ expect(await call({ prompt: "猫", confirm: true })).toEqual({ text: "done m1" });
expect(mgr.approvals.pending("c1", "question")).toEqual([]);
- // 用户点名了别的模型(confirm: false):也不问
- expect(await call({ prompt: "猫", model: "m2", confirm: false })).toEqual({ text: "done m2" });
- // 代理自己换了模型:问,并说明默认是哪个
- let [r, q] = await Promise.all([call({ prompt: "猫", model: "m2" }), answer({ selected: ["m2"] })]);
+ // 花费超过上限:问,附上预计花费
+ let [r, q] = await Promise.all([call({ prompt: "猫", body: { n: 30 } }), answer({ selected: ["取消"] })]);
+ expect(q.question).toBe("这次用 m1 生成图片吗?");
+ expect(q.detail).toContain(`预计花费约 $0.9,超过 $${MEDIA_ASK_USD}`);
+ expect(q.options[0]).toEqual({ label: "m1", description: "默认 · $0.03/张" });
+ expect(r.text).toMatch(/取消/);
+
+ // 机器人选的模型花费高:问的是它,标着「机器人选的」
+ [r, q] = await Promise.all([call({ prompt: "猫", model: "m2", body: { n: 30 } }), answer({ selected: ["m2"] })]);
expect(q.question).toBe("这次用 m2 生成图片吗?");
- expect(q.detail).toContain("不是默认模型(默认是 m1)");
expect(q.options.map((o: any) => o.label)).toEqual(["m2", "m2", "取消"]);
+ expect(q.options[0].description).toBe("机器人选的");
expect(r).toEqual({ text: "done m2" });
- // 花费超过上限:就算 confirm: false 也问;附上预计花费
- [r, q] = await Promise.all([call({ prompt: "猫", body: { n: 30 }, confirm: false }), answer({ selected: ["取消"] })]);
- expect(q.detail).toContain(`预计花费约 $0.9,超过 $${MEDIA_ASK_USD}`);
- expect(r.text).toMatch(/取消/);
-
- // 要求不明确(confirm: true):问;请求体按 m1 的文档写的,换成 m2 时先让代理按 m2 的文档重写,重写后的那一次不再确认
- [r, q] = await Promise.all([call({ prompt: "猫", body: { a: 1 }, confirm: true }), answer({ custom: "用 M2" })]);
- expect(q.options[0]).toEqual({ label: "m1", description: "默认 · $0.03/张" });
+ // 请求体按 m1 的文档写的,用户换成 m2:先让代理按 m2 的文档重写,重写后的那一次不再确认
+ [r] = await Promise.all([call({ prompt: "猫", body: { n: 30 } }), answer({ custom: "用 M2" })]);
expect(r.text).toMatch(/media_docs 查 m2/);
- expect(await call({ prompt: "猫", model: "m2", body: { b: 1 } })).toEqual({ text: "done m2" });
+ expect(await call({ prompt: "猫", model: "m2", body: { n: 30, b: 1 } })).toEqual({ text: "done m2" });
- [r] = await Promise.all([call({ prompt: "猫", confirm: true }), answer({ custom: "好的" })]);
+ [r] = await Promise.all([call({ prompt: "猫", body: { n: 30 } }), answer({ custom: "好的" })]);
expect(r).toEqual({ text: "done m1" });
- [r] = await Promise.all([call({ prompt: "猫", confirm: true }), answer({ custom: "换成竖屏的" })]);
+ [r] = await Promise.all([call({ prompt: "猫", body: { n: 30 } }), answer({ custom: "换成竖屏的" })]);
expect(r.text).toMatch(/「换成竖屏的」/);
// 机器人设成每次都问
store.updateBot("b1", { settings: normalizeSettings({ media: { confirm: "always" } }) });
[r] = await Promise.all([call({ prompt: "猫" }), answer({ selected: ["m1"] })]);
expect(r).toEqual({ text: "done m1" });
- expect(ran).toEqual(["m1", "m2", "m2", "m2", "m1", "m1"]);
+ expect(ran).toEqual(["m1", "m2", "m1", "m2", "m2", "m1", "m1"]);
} finally {
await mgr.bridge.stop();
store.close();
diff --git a/test/cost.unit.test.ts b/test/cost.unit.test.ts
index f906f1b..8bac30d 100644
--- a/test/cost.unit.test.ts
+++ b/test/cost.unit.test.ts
@@ -180,8 +180,9 @@ describe("预算(假宿主、假时钟)", () => {
svc.fireDue(now);
await flush();
};
- const createRule = async () => {
- const r = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "看 X 价格", instruction: "每天早上看看 X 的价格,低于 200 告诉我", schedule: "daily 08:00" } });
+ /** 新规则直接执行;extra 里 mode: "observe" = 用户说了先观察 */
+ const createRule = async (extra: Record<string, unknown> = {}) => {
+ const r = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "看 X 价格", instruction: "每天早上看看 X 的价格,低于 200 告诉我", schedule: "daily 08:00", ...extra } });
expect(r.error).toBeUndefined();
return store.listRules({ botId: "b" }).at(-1)!;
};
@@ -364,7 +365,7 @@ describe("预算(假宿主、假时钟)", () => {
it("规则每月 $3:用完就停下并暂停(执行中的推一句,「需要你」里一行),下个月 1 号 0 点(主人的时区)自动恢复", async () => {
const rule = await createRule();
- svc.updateRule(rule.id, { mode: "act", runBudgetUsd: 2 });
+ svc.updateRule(rule.id, { runBudgetUsd: 2 });
const day = async (d: string, usd: number[]) => {
await go(at(`${d}T08:00`));
await turn(undefined, (sid) => {
@@ -413,7 +414,7 @@ describe("预算(假宿主、假时钟)", () => {
});
it("「再给 $3」:本月预算用完暂停着的规则加了预算就接着按时间表跑;观察中的不推", async () => {
- const rule = await createRule();
+ const rule = await createRule({ mode: "observe" });
svc.updateRule(rule.id, { monthBudgetUsd: 0.2, runBudgetUsd: 1 });
await go(at("2026-11-03T08:00"));
await turn(undefined, (sid) => {
diff --git a/test/prompts.unit.test.ts b/test/prompts.unit.test.ts
index 3a9c2f1..d6798b9 100644
--- a/test/prompts.unit.test.ts
+++ b/test/prompts.unit.test.ts
@@ -162,8 +162,10 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [
["不逐步讲解:处理过程在界面里", "chat", ["之后不要逐步讲解", "「处理过程」"]],
["做完说清做了什么、结果在哪里", "chat", ["说清做了什么、结果在哪里", "present"]],
["如实报告:没做完就是没做完,失败就是失败", "chat", ["没做完就说没做完", "失败就说失败和原因", "没验证过的结果不要说成已完成"]],
- ["一次只问一个具体问题,选项用 ask_user_question", "chat", ["一次只问一个具体问题", "ask_user_question"]],
- ["已经让做的事不再确认", "chat", ["能自己判断的事不要问,已经让你做的事不要再确认"]],
+ // 产品负责人 2026-11-01:自动做,不要一直问。自己做决定并说一句选了什么;语言、格式、范围、风格从不问;只在三种情况问
+ ["自己做决定,说一句选了什么;语言、格式、范围、风格不问;已经让做的事不再确认", "chat", ["自己做决定,说一句选了什么", "语言、格式、范围、风格都不问", "已经让你做的事不要再确认"]],
+ ["只在猜错有代价、要用户才有的东西、不可撤回时问,一次一个问题,选项用 ask_user_question", "chat",
+ ["猜错会造成损失、花钱或白做大半", "登录、文件、密码", "不可撤回(付款、删除用户的数据、给别人发消息)", "一次一个具体问题", "ask_user_question"], ["需要用户决定时"]],
["不说空话", "chat", ["不说客套话和空话"]],
["IM 里回复要短", "chat", ["在微信、飞书里回复要短", "微信只显示纯文本"]],
["既不啰嗦也不沉默", "*", [], ["逐步汇报", "每一步都告诉用户", "详细说明每一步", "不要告诉用户你要做什么", "保持沉默"]],
@@ -177,20 +179,25 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [
["记忆:先 recall 再说不知道;不记密钥", "memory", ["先用 recall 查一下", "不要把密码、密钥、令牌、证件号写进记忆"]],
["每段第一条消息:渠道、记忆快照、交接、用户消息;人设和记忆说明不在这里", "segment",
["[对话渠道]\n微信私聊(手机上看,只显示纯文本)", "[长期记忆快照]", "- 用户叫小王", "[交接]", "[用户消息]\n继续"], ["[机器人设定]", "remember / forget / recall"]],
- ["生图:只在需要时问", "skill media", ["only when", "`confirm: false` because the user named that model", "`confirm: true` because the request is ambiguous", "ask_user_question"],
- ["so the user confirms the model before anything is generated", "they will be asked again"]],
- ["生图工具:默认模型、花费不高直接生成", "tool generate_image", ["generates right away", "\"confirm\""], ["Before anything is generated the user is asked"]],
- ["生视频工具:默认模型、花费不高直接生成", "tool generate_video", ["generates right away", "\"confirm\""], ["Before anything is generated the user is asked"]],
+ // 生图:直接生成,只在花费高(超过 $0.5)或设成每次都问时由应用问;不因为换了模型、要求不明确而问,代理自己也不问
+ ["生图:只在花费高或设成每次都问时问;代理按最合理的理解生成并说一句", "skill media", ["generates right away", "only when the estimated cost is high", "always ask", "most reasonable interpretation", "say in one line what you chose"],
+ ["confirm: true", "confirm: false", "ambiguous", "ask_user_question", "not the default one", "so the user confirms the model before anything is generated", "they will be asked again"]],
+ ["生图工具:直接生成,花费高才问;没有 confirm 参数", "tool generate_image", ["generates right away", "only a high estimated cost"], ["\"confirm\"", "With the default model", "Before anything is generated the user is asked"]],
+ ["生视频工具:直接生成,花费高才问;没有 confirm 参数", "tool generate_video", ["generates right away", "only a high estimated cost"], ["\"confirm\"", "With the default model", "Before anything is generated the user is asked"]],
// —— 后台任务(3a)——
["聊天代理:长活或用户说后台做才开任务,能马上答的不开;开了只说一句,不自己做", "tool task_start", ["more than a few minutes or many steps", "后台做", "not for what you can answer now", "前台做", "in one sentence", "do not do the work yourself"]],
["用户提到某个任务、回答它的问题时把话转给它", "tool task_message", ["when they refer to it", "answer its question", "next step", "resumes"]],
- // —— 任务的提问(3b):先自己定,要问就一次一个。有合理默认的尽早问、带 default,接着只做不依赖回答的部分,没回答就按默认;
- // 非用户定不可的先做完不依赖它的部分再问,问完结束这一轮 ——
- ["任务规则优先于聊天规则;能自己定的自己定并说明;要问就一次一个", "task", ["优先于上面的聊天规则", "选一个合理的做法", "在结果里说明", "needs_you", "一个问题"], ["ask_user_question"]],
- ["任务规则:有合理默认的尽早问、带 default,接着只做不依赖回答的部分,没回答就按默认", "task", ["有合理默认的尽早问", "default", "只做不依赖回答的部分", "做完还没回答就按默认"]],
- ["任务规则:非用户定不可的先做完不依赖它的部分再问,然后结束这一轮", "task", ["非用户定不可", "付款", "先做完不依赖它的部分再问", "结束这一轮"]],
- ["task_report:needs_you 马上问;带 default 接着做,先做完就按默认并说明;不带的回答是下一条消息,问完结束这一轮", "tool task_report",
- ["needs_you", "the app asks the user question now", "With default, keep working on what does not depend on the answer", "use default and say so in message", "only the user can decide", "their answer is your next message", "After done, failed or needs_you without default, end your turn", '"default"', "Omit it when only the user can decide"]],
+ // —— 任务的提问(3b;产品负责人 2026-11-01 收紧):自己做决定、在结果里说明;语言、格式、范围、风格从不问。只在猜错会造成损失、
+ // 花钱或白做大半,要用户才有的东西,或不可撤回时问,一次一个。猜错只会白做的尽早问、带 default,接着只做不依赖回答的部分,
+ // 没回答就按默认;其余的先做完不依赖回答的部分再问,问完结束这一轮 ——
+ ["任务规则优先于聊天规则;自己做决定并在结果里说明;语言、格式、范围、风格不问", "task",
+ ["优先于上面的聊天规则", "自己做决定", "在结果里说明选了什么", "语言、格式、范围、风格都不问", "用对话的语言", "选最合理的做法"], ["ask_user_question", "能自己定的就"]],
+ ["任务规则:只在三种情况报 needs_you 问一个问题", "task", ["needs_you", "一个问题", "猜错会造成损失、花钱或白做大半", "登录、文件、密码", "不可撤回(付款、删除用户的数据、给别人发消息)"]],
+ ["任务规则:猜错只会白做的尽早问、带 default,接着只做不依赖回答的部分,没回答就按默认", "task", ["猜错只会白做的", "尽早问", "default", "只做不依赖回答的部分", "做完还没回答就按默认"]],
+ ["任务规则:其余的先做完不依赖回答的部分再问,然后结束这一轮", "task", ["其余的先做完不依赖回答的部分再问", "结束这一轮"]],
+ ["task_report:needs_you 只在三种情况,其余自己定;马上问;带 default(少见)接着做,先做完就按默认并说明;不带的回答是下一条消息,问完结束这一轮", "tool task_report",
+ ["needs_you only if a wrong guess could cause harm, cost money or waste most of the work", "something only the user has", "the step cannot be undone", "decide everything else yourself", "what you chose",
+ "The app asks the user question now", "With default (rare), keep working on what does not depend on the answer", "use default and say so in message", "their answer is your next message", "After done, failed or needs_you without default, end your turn", '"default"', "Omit it when only the user can decide"]],
["任务:外部动作前后记日志(重启后靠它不重复做)", "task", [".task/journal.md"]],
["任务:做完或做不下去才说话,一句话,结果和在哪里;中途不汇报", "task", ["task_report", "done 或 failed", "不超过 300 字", "在哪里", "中途不用汇报", "不会发给用户"]],
["task_report:done / failed 的那句话是用户收到的,progress 不发;报完结束这一轮", "tool task_report", ["one line the user receives", "at most 300 characters", "never sent", "end your turn"]],
@@ -201,8 +208,9 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [
["预算用完、用户加了预算后接着做:上一步可能没做完,先查日志再重复外部动作", "task resume budget", ["used its budget", "the user has now added more", "sleep 600", "Before repeating any outside action", ".task/journal.md", "task_report"]],
["为聊天留预算暂停、恢复后接着做", "task resume reserve", ["keep the bot's remaining budget for chat", "stopped: none", ".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"]],
+ // —— 规则(3d):检查直接执行(产品负责人 2026-11-01;用户说先观察才观察),只在值得说时说一句;观察只看不动;执行最多可写工作区 ——
+ ["rule_create:用户原话原样;检查直接执行,用户说先观察才观察;提醒到点发那句;确认一句", "tool rule_create",
+ ["verbatim", "it acts right away", "tells the user only when it matters", "observe only when the user wants to watch first", "先观察", "only records what it would say", "kind remind", "Confirm in one sentence", "every 30m", "weekly mon,thu"], ["starts in observe mode"]],
["rule_update:用户要求时改模式(执行才发)、原话、时间表或删掉", "tool rule_update", ["when the user asks", "mode act (results are sent)", "observe (only records)", "off", "delete"]],
["background_pause:用户要求时暂停或恢复全部后台工作;暂停时任务、规则不跑,主动消息等着,聊天照常", "tool background_pause", ["Pause or resume", "when the user asks", "no task or rule runs", "pushed messages wait", "chat still works", '"paused"']],
["规则段(观察):优先于聊天规则;只看不动,本来要做的写进 would;值得说才说一句,只记下来;不报告就算失败", "rule observe",
@@ -223,10 +231,14 @@ describe.skipIf(!runtime)("提示词约定", () => {
for (const words of gone) expect(text.toLowerCase()).not.toContain(words.toLowerCase());
});
+ /**
+ * 产品负责人 2026-11-01(自动做,不要一直问):聊天规则和任务规则写清什么时候才问(猜错有代价、要用户才有的东西、不可撤回),
+ * 聊天规则 395 → 469、任务规则 481 → 549,两个上限跟着调高;只为这几句,别的不要往里加。
+ */
it("聊天规则、人设、任务规则和规则段都短", () => {
- expect(CHAT_RULES.length).toBeLessThan(440);
+ expect(CHAT_RULES.length).toBeLessThan(490);
expect(agentPersona({ computerUse: true }).length).toBeLessThan(180);
- expect(TASK_RULES.length).toBeLessThan(500);
+ expect(TASK_RULES.length).toBeLessThan(570);
expect(ruleRules("observe").length).toBeLessThan(300);
expect(ruleRules("act").length).toBeLessThan(300);
});
@@ -284,9 +296,11 @@ describe.skipIf(!runtime)("提示词约定", () => {
* 3d 加上 rule_create(819)、rule_update(467)和 task_list 多一句「and rules」后 10,049(工具 9,142)。上限高约 5%。
* 暂停开关 background_pause(280)之后 10,329(工具 9,422),还在上限之内,上限不变。
* 3e:task_start 加上 budget_usd(116)之后 10,445(工具 9,538),还在上限之内,上限不变。
+ * 少问(产品负责人 2026-11-01):生图、生视频去掉 confirm 参数,rule_create 加上 mode,聊天规则写清什么时候才问,
+ * 之后 10,145(提示词 981 + 工具 9,164),上限调低到 10,450。
* 缩短了就调低;要调高,在提交说明里写清原因。
*/
- const BUDGET = 10_550;
+ const BUDGET = 10_450;
it("我们的提示词加工具定义不超过字符数上限", async () => {
const prompt = agentPersona({ computerUse: true }).length + botPrompt({ name: "小蓝", persona: PERSONA, memory: true }).length;
const tools = JSON.stringify(await ourTools()).length;
@@ -298,8 +312,10 @@ describe.skipIf(!runtime)("提示词约定", () => {
* 3a 基线 1,255(规则 363 + task_report 892);3b 加上提问(needs_you、question、options 和怎么问的那条规则)后 1,533(规则 399 + task_report 1,134)。
* 问了还接着做(task_report 的 default,规则里有默认的尽早问、接着做,非用户定不可的先做完再问)之后 1,935
* (规则 481 + task_report 1,454):两种提问各一句是这个功能本身,上限跟着调高。
+ * 少问(产品负责人 2026-11-01):规则和 task_report 写清只在哪几种情况才问、其余自己定并在结果里说明,之后 2,177
+ * (规则 549 + task_report 1,628),上限跟着调高到 2,280。
*/
- const TASK_BUDGET = 2_030;
+ const TASK_BUDGET = 2_280;
it("任务会话多出来的提示词和工具不超过字符数上限", async () => {
const { task } = await loadPlugins();
const extra = TASK_RULES.length + JSON.stringify(task.tools).length;
diff --git a/test/retention.unit.test.ts b/test/retention.unit.test.ts
index 74c9fe6..d780bfc 100644
--- a/test/retention.unit.test.ts
+++ b/test/retention.unit.test.ts
@@ -1,8 +1,9 @@
/**
* 保留与清理、删除、导出、改预算(3f):TaskService 对着假宿主和假时钟。
* 30 天没动过的任务归档(不再列出、不能追加,等着的提问作废);运行记录只留 30 天(任务最近的那个 run 和本月的规则运行留着);
- * 有文件的文件夹第 27 天在「需要你」里说一次(不推送),至少 3 天后、满 30 天才删,连同 DSH 里的会话记录(开在代理进程里的下次再删);
- * 保留、又用了它都会重新算;知道了只是不再显示。状态都在库里:重启、应用关了很久都照样。删任务删文件夹。导出成 Markdown。
+ * 有文件的文件夹第 27 天定下清理的日期,至少 3 天后、满 30 天才删,连同 DSH 里的会话记录(开在代理进程里的下次再删)。
+ * 不问用户(产品负责人 2026-11-01):「需要你」里没有它,也没有系统通知;日期和「保留」在任务详情里。保留、又用了它都会重新算。
+ * 状态都在库里:重启、应用关了很久都照样。删任务删文件夹。导出成 Markdown。
*/
import fs from "node:fs";
import os from "node:os";
@@ -16,7 +17,7 @@ import { DEFAULT_SETTINGS } from "../src/agent/settings.js";
import { Outbox } from "../src/core/outbox.js";
import { Delivery } from "../src/core/delivery.js";
import { Store, type RunOutcome } from "../src/store/db.js";
-import { withLang } from "../src/i18n/index.js";
+import { Attention } from "../src/tasks/attention.js";
const TZ = "Asia/Shanghai";
const at = (s: string) => Date.parse(`${s}${s.length === 16 ? ":00" : ""}+08:00`);
@@ -117,7 +118,6 @@ describe("保留与清理(假宿主、假时钟)", () => {
}
return id;
};
- const cleanupItems = () => svc.attention().filter((i) => i.kind === "cleanup");
const sessionDirs = (id: string) => taskSessionDirs(host.home, id).length;
it("没文件的任务:30 天没动过就归档(不再列出、不能追加、会话记录删掉),不打扰用户;运行记录只留 30 天,最近的那个留着", async () => {
@@ -129,7 +129,7 @@ describe("保留与清理(假宿主、假时钟)", () => {
svc.retain();
expect(store.getTask(t)!.endReason).toBe("done");
expect(store.getRun("r_old")).toBeUndefined();
- expect(cleanupItems()).toEqual([]);
+ expect(svc.attention()).toEqual([]);
now += DAY_MS;
svc.retain();
expect(store.getTask(t)).toMatchObject({ endReason: "archived", cleanupAt: 0 });
@@ -139,16 +139,22 @@ describe("保留与清理(假宿主、假时钟)", () => {
expect(sessionDirs(t)).toBe(0);
expect((await svc.message(t, "再看看")).error).toBe("「整理下载目录」已归档,不能再追加;需要的话开个新任务。");
expect((await svc.retry(t)).error).toMatch(/已归档/);
- expect(cleanupItems()).toEqual([]);
+ expect(svc.attention()).toEqual([]);
});
- it("有文件的文件夹:第 27 天在「需要你」里说一次(不推送),满 30 天删掉文件夹和会话记录、归档;等着的提问作废", async () => {
+ it("有文件的文件夹:第 27 天定下日期(不问、不通知,任务详情里看得到),满 30 天删掉文件夹和会话记录、归档;等着的提问作废", async () => {
const t = ended("GPU 价格调研", now, { files: 3, outcome: "failed", sessions: [] });
// 换过一次会话(task-<id>-2):两份记录都要删
for (const s of [`task-${t}`, `task-${t}-2`]) (fs.mkdirSync(path.join(host.home, "sessions", "--p--", s), { recursive: true }), fs.writeFileSync(path.join(host.home, "sessions", "--p--", s, "v4.jsonl"), "{}\n"));
// 别的任务的记录不碰
fs.mkdirSync(path.join(host.home, "sessions", "--p--", `task-${t}x`), { recursive: true });
approvals.create({ kind: "question", botId: "b", conversationId: CONV, sessionId: `task-${t}`, tool: "task_report", detail: "要不要再查一家?", reason: "", payload: JSON.stringify([{ id: "answer", question: "要不要再查一家?" }]), taskId: t, runId: "", blocking: false, ttlMs: 0 });
+ // 「需要你」和系统通知:定下清理日期前后一样(只有这个失败了的任务那一行,早就有了)
+ const attention = new Attention({ store });
+ attention.addSource(() => svc.attention());
+ attention.takeNew();
+ const before = svc.attention();
+ const pushed = store.listOutbox({ limit: 100 }).map((r) => r.id);
now += KEEP_MS - WARN_MS - 3600_000;
svc.retain();
expect(store.getTask(t)!.cleanupAt).toBe(0);
@@ -156,12 +162,11 @@ describe("保留与清理(假宿主、假时钟)", () => {
svc.retain();
const due = store.getTask(t)!.cleanupAt;
expect(due).toBe(now + WARN_MS);
+ // 任务详情里有日期(和保留);「需要你」里没有多出什么,也没有系统通知、推送
expect(svc.get(t)!.cleanupAt).toBe(due);
- expect(cleanupItems()).toEqual([
- expect.objectContaining({ id: "cleanup:b", kind: "cleanup", botName: "小蓝", subject: "1 个任务文件夹 12月1日 删除", head: "1 个任务文件夹 12月1日 删除", line: "GPU 价格调研 30 天没动过了", severity: "warn", actions: ["keep", "dismiss"], since: now }),
- ]);
- // 只在应用里:出站队列里没有它
- expect(store.listOutbox({ limit: 100 }).filter((r) => r.id.includes("cleanup"))).toEqual([]);
+ expect(svc.attention()).toEqual(before);
+ expect(attention.takeNew()).toEqual([]);
+ expect(store.listOutbox({ limit: 100 }).map((r) => r.id)).toEqual(pushed);
// 再看一次:不会再定一次
now += DAY_MS;
svc.retain();
@@ -174,53 +179,33 @@ describe("保留与清理(假宿主、假时钟)", () => {
expect(taskSessionDirs(host.home, t)).toEqual([]);
expect(fs.existsSync(path.join(host.home, "sessions", "--p--", `task-${t}x`))).toBe(true);
expect(approvals.pendingForTask(t)).toEqual([]);
- expect(cleanupItems()).toEqual([]);
expect(svc.attention().filter((i) => i.taskId === t)).toEqual([]);
});
- it("保留:再算 30 天;定了清理之后又用了它(追加、改预算),清理取消", async () => {
+ it("保留(任务详情):再算 30 天,别的照样清理;定了清理之后又用了它(追加、改预算),清理取消", async () => {
const a = ended("A", now, { files: 1 });
const b = ended("B", now, { files: 1 });
now += KEEP_MS - WARN_MS;
svc.retain();
- expect(cleanupItems()[0].subject).toBe("2 个任务文件夹 12月1日 删除");
- expect(cleanupItems()[0].line).toBe("A和B 30 天没动过了");
- expect(withLang("en", () => cleanupItems()[0].line)).toBe("A and B haven't been used in 30 days");
- expect(svc.keepCleanup("b")).toBe(true);
- expect(store.getTask(a)!.cleanupAt).toBe(0);
- expect(cleanupItems()).toEqual([]);
+ expect([svc.get(a)!.cleanupAt, svc.get(b)!.cleanupAt]).toEqual([now + WARN_MS, now + WARN_MS]);
+ expect(svc.keepFolder(a)!.cleanupAt).toBe(0);
now += WARN_MS + DAY_MS;
svc.retain();
expect(store.getTask(a)).toMatchObject({ endReason: "done", cleanupAt: 0 });
- // 又过了 27 天:再说一次
+ expect(store.getTask(b)!.endReason).toBe("archived");
+ expect(fs.existsSync(path.join(host.ws, store.getTask(a)!.folder))).toBe(true);
+ expect(fs.existsSync(path.join(host.ws, store.getTask(b)!.folder))).toBe(false);
+ // 又过了 27 天:再定一次,还是至少 3 天后
now += KEEP_MS - WARN_MS;
svc.retain();
expect(store.getTask(a)!.cleanupAt).toBeGreaterThan(now);
- // 用了它:改预算(任务详情)→ 下次看时清理取消,那一行跟着消失
+ // 用了它:改预算(任务详情)→ 下次看时清理取消
await svc.setBudget(a, 3);
- await svc.setBudget(b, 3);
- svc.retain();
- expect([store.getTask(a)!.cleanupAt, store.getTask(b)!.cleanupAt]).toEqual([0, 0]);
- expect(cleanupItems()).toEqual([]);
- });
-
- it("知道了:这一行不再显示,到时照样清理;之后又有文件夹要清理时再出现", async () => {
- const a = ended("A", now, { files: 1 });
- now += KEEP_MS - WARN_MS;
svc.retain();
- expect(svc.dismissCleanup("b")).toBe(true);
- expect(cleanupItems()).toEqual([]);
- const b = ended("B", now - (KEEP_MS - WARN_MS) + DAY_MS, { files: 1 });
- now += DAY_MS;
- svc.retain();
- expect(cleanupItems().map((i) => i.subject)).toEqual(["2 个任务文件夹 12月1日 删除"]);
- now = store.getTask(a)!.cleanupAt;
- svc.retain();
- expect(store.getTask(a)!.endReason).toBe("archived");
- expect(store.getTask(b)!.endReason).toBe("done");
+ expect(store.getTask(a)!.cleanupAt).toBe(0);
});
- it("重启和应用关了很久:告诉过的记在库里;关了 60 天也要先说一次、至少 3 天后才删", async () => {
+ it("重启和应用关了很久:定下的日期记在库里;关了 60 天也要先定日期、至少 3 天后才删", async () => {
const t = ended("GPU 价格调研", now, { files: 2 });
now += 60 * DAY_MS;
svc.stop();
@@ -229,13 +214,13 @@ describe("保留与清理(假宿主、假时钟)", () => {
const due = store.getTask(t)!.cleanupAt;
expect(due).toBe(now + WARN_MS);
expect(fs.existsSync(path.join(host.ws, store.getTask(t)!.folder))).toBe(true);
- // 重启:不会再定一次,「需要你」那一行还在
+ // 重启:不会再定一次,任务详情里还是那个日期
now += DAY_MS;
svc.stop();
svc = make();
svc.start();
expect(store.getTask(t)!.cleanupAt).toBe(due);
- expect(cleanupItems()).toHaveLength(1);
+ expect(svc.get(t)!.cleanupAt).toBe(due);
// 关着过了清理时间:下次启动时删
svc.stop();
now = due + 10 * DAY_MS;
@@ -337,7 +322,7 @@ describe("保留与清理(假宿主、假时钟)", () => {
"",
].join("\n"),
);
- const rule = svc.createRule({ botId: "b", conversationId: CONV, title: "看 X 价格", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", schedule: { kind: "daily", time: "08:00", tz: TZ } }).rule!;
+ const rule = svc.createRule({ botId: "b", conversationId: CONV, title: "看 X 价格", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", mode: "observe", schedule: { kind: "daily", time: "08:00", tz: TZ } }).rule!;
store.insertEndedRun({ id: "r_x1", botId: "b", ruleId: rule.id, ruleVersion: 1, mode: "observe", cause: "schedule", outcome: "done", error: "", queuedAt: at("2026-11-01T08:00"), endedAt: at("2026-11-01T08:01") });
store.updateRun("r_x1", { costUsd: 0.03, permission: "read-only", report: { state: "done", summary: "X 现在 ¥199", message: "X 降价了,现在 ¥199", at: 0 } });
store.insertEndedRun({ id: "r_x0", botId: "b", ruleId: rule.id, ruleVersion: 1, mode: "observe", cause: "schedule", outcome: "skipped", error: "app_off", queuedAt: at("2026-10-31T08:00"), endedAt: at("2026-10-31T08:00") });
diff --git a/test/rules.integration.test.ts b/test/rules.integration.test.ts
index 2aa822b..9d1948a 100644
--- a/test/rules.integration.test.ts
+++ b/test/rules.integration.test.ts
@@ -1,7 +1,8 @@
/**
* 规则(3d)端到端:真实 DSH 子进程 + 脚本化的模型 + mock iLink(主人在微信里和自己的机器人聊)。
- * 退出演示:微信里说「每天 08:00 看 X 价格」,聊天代理 rule_create 建好规则(观察);「三天」到点各跑一次(把 next_run_at 拨到现在、
- * 叫醒定时器),运行记录读得懂,什么都没发;「需要你」里问要不要改为执行;改了之后命中时推一句,只推一次。
+ * 退出演示:微信里说「每天 08:00 看 X 价格,先观察」,聊天代理 rule_create 建好规则(用户要先观察,所以是观察;不说就直接执行);
+ * 「三天」到点各跑一次(把 next_run_at 拨到现在、叫醒定时器),运行记录读得懂,什么都没发;「需要你」里问要不要改为执行;
+ * 改了之后命中时推一句,只推一次。
* 另外:每次运行一个新会话;观察只读(写不了文件),执行可写工作区;规则会话的工具(观察去掉能改变什么的);检查用小模型、
* 那一句用主模型写;观察时要批准的自动拒绝、记下来,「需要你」里没有;事件触发走同一条路。
*/
@@ -48,7 +49,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (r
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" } } };
+ return done ? { text: "ACK-RULE:已建好规则:每天 08:00 看 X 价格,先观察几天,只记录不打扰你。" } : { tool: { name: "rule_create", args: { title: "看 X 价格", instruction: "每天 08:00 看看 X 的价格,低于 200 告诉我,先观察", schedule: "daily 08:00", mode: "observe" } } };
const p = /PING (\w+)/.exec(user);
if (p) return { text: `PONG-${p[1]}` };
return { text: "好的" };
@@ -154,14 +155,14 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (r
};
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");
+ 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 });
+ expect(rule).toMatchObject({ title: "看 X 价格", when: "每天 08:00", mode: "observe", state: { key: "observe", label: "观察中" }, instruction: "每天 08:00 看看 X 的价格,低于 200 告诉我,先观察", conversationId: CONV });
// 三天:观察。每次一个新会话,检查用小模型;写不了文件(只读);什么都不发
price(259);
const d1 = await tick(rule.id);
@@ -242,7 +243,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (r
});
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 r = app.tasks.createRule({ botId: "default", conversationId: CONV, title: "提权", instruction: "ESCALATE 看看系统", mode: "observe", 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");
@@ -260,7 +261,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (r
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 () => {
+ it("the rule editor's API: a new check from the UI acts unless observe is picked, a reminder acts; a bad schedule is refused; editing the words keeps the mode", 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 分钟");
@@ -268,19 +269,22 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (r
expect(((await badEn.json()) as any).error).toBe("The interval must be at least 15 minutes");
expect((await (await fetch(`${base}/amb/api/rules?bot=default`, { headers: { "x-amb-lang": "en" } })).json() as any).rules[0]).toMatchObject({ when: "Daily 08:00", state: { label: "Acting" } });
const c = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title: "看天气", instruction: "每个工作日早上看看会不会下雨", schedule: { kind: "daily", time: "07:30", days: [1, 2, 3, 4, 5] } } })).rule;
- expect(c).toMatchObject({ mode: "observe", when: "每个工作日 07:30", state: { key: "observe" } });
+ expect(c).toMatchObject({ mode: "act", when: "每个工作日 07:30", state: { key: "act" } });
+ const o = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", mode: "observe", title: "看风", instruction: "每天早上看看风大不大", schedule: { kind: "daily", time: "07:00" } } })).rule;
+ expect(o).toMatchObject({ mode: "observe", 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(edited).toMatchObject({ mode: "act", version: 2, state: { key: "act" } });
+ expect(edited).not.toHaveProperty("observeLeft");
+ for (const id of [c.id, o.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(r.rule).toMatchObject({ 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);
diff --git a/test/rules.unit.test.ts b/test/rules.unit.test.ts
index 29226d9..1cd1dfc 100644
--- a/test/rules.unit.test.ts
+++ b/test/rules.unit.test.ts
@@ -1,8 +1,9 @@
/**
* 规则(3d)的零件:时间表(解析、给人看的话、下一次 / 上一次、夏令时、宽限期、cron)、宿主的定时器、事件的过滤条件、数据目录锁,
- * 以及 TaskService 对着一个假宿主和一个假时钟:从观察开始、观察只记「本会发送」、3 次好的观察后在「需要你」里问要不要改为执行(失败、
- * 跳过的不算;不推送、不发系统通知;继续观察了这一版不再问,重启也一样;改了原话再观察 3 次再问)、执行时经出站队列发一句、
- * 改了原话先观察 1 次再回到执行、连续失败 3 次自动暂停(执行的推一句,观察的只在「需要你」里)、错过的按宽限期补跑一次或记为跳过、
+ * 以及 TaskService 对着一个假宿主和一个假时钟:新规则直接执行(用户说先观察才观察,产品负责人 2026-11-01)、观察只记「本会发送」、
+ * 用户选了观察的,3 次好的观察后在「需要你」里问要不要改为执行(失败、跳过的不算;不推送、不发系统通知;继续观察了这一版不再问,
+ * 重启也一样;改了原话再观察 3 次再问)、执行时经出站队列发一句、改了原话模式不变(不再先观察)、
+ * 连续失败 3 次自动暂停(执行的推一句,观察的只在「需要你」里)、错过的按宽限期补跑一次或记为跳过、
* 等名额超过宽限期跳过、固定提醒不进模型、重启后宽限期内重跑一次、运行记录、事件触发、时间上限、观察时的审批自动拒绝、
* 检查用小模型而那一句用主模型写、微信配额预留和续期提醒、/tasks 列出并关掉规则。
*/
@@ -344,6 +345,8 @@ describe("规则(假宿主、假时钟)", () => {
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();
+ /** 观察:用户说了先观察的检查 */
+ const OBSERVE = { mode: "observe" };
/** 拨钟,到点的开 run */
const go = async (t: number) => {
now = t;
@@ -365,23 +368,33 @@ describe("规则(假宿主、假时钟)", () => {
beforeEach(() => store.setAgentSession(CONV, "b", "chat-1"));
- it("rule_create:从观察开始,用户原话原样存,自己的文件夹;回复里有设计里那句话,微信加上 24 小时那句", async () => {
+ 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).toMatchObject({ kind: "check", mode: "act", 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("「已建好规则:每天 08:00 看 X 价格,有值得说的就告诉你。」");
+ expect(text).not.toContain("observe");
expect(text).toContain(tServer("rules.weixinNote"));
- expect(svc.getRuleView(rule.id)).toMatchObject({ when: "每天 08:00", state: { key: "observe", label: "观察中", dot: "" } });
+ expect(svc.getRuleView(rule.id)).toMatchObject({ when: "每天 08:00", state: { key: "act", label: "执行中", dot: "ok" } });
+ // 用户说先观察:聊天代理传 mode observe
+ const watch = await create("daily 09:00", OBSERVE);
+ expect(watch.rule).toMatchObject({ kind: "check", mode: "observe" });
+ expect(watch.text).toContain("in observe mode");
+ expect(watch.text).toContain("「已建好规则:每天 09:00 看 X 价格,先观察几天,只记录不打扰你。」");
+ expect(svc.getRuleView(watch.rule.id)).toMatchObject({ state: { key: "observe", label: "观察中", dot: "" } });
+ // 提醒没有观察:照样执行
+ const remind = await create("daily 10:00", { ...OBSERVE, kind: "remind", message: "喝水。" });
+ expect(remind.rule).toMatchObject({ kind: "remind", mode: "act" });
// 时间表说不清:照着错误改
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();
+ it("退出演示的单元版:用户要先观察,观察 3 天(只记「本会发送」,什么都不推),提示改为执行;改了之后命中时推一句(主模型写的)", async () => {
+ const { rule } = await create("daily 08:00", OBSERVE);
// 第 1 天:到点开一个新会话,第一条输入是规则、原话、这次是观察;检查用小模型
await go(at("2026-11-02T08:00"));
const p1 = host.prompts.at(-1)!;
@@ -436,7 +449,7 @@ describe("规则(假宿主、假时钟)", () => {
});
it("观察够了:这一版好好观察 3 次后「需要你」里问要不要改为执行(失败、跳过的不算),排在最后,算件数但不推送、不发系统通知", async () => {
- const { rule } = await create();
+ const { rule } = await create("daily 08:00", OBSERVE);
const ask = () => svc.ruleAttention().filter((a) => a.kind === "suggest");
await day("2026-11-02", report("done"));
await day("2026-11-03", report("failed", "X 的页面打不开"));
@@ -471,15 +484,15 @@ describe("规则(假宿主、假时钟)", () => {
expect(store.listOutbox({ limit: 100 })).toEqual([]);
const att = new Attention({ store });
att.addSource(() => svc.ruleAttention());
- att.addSource(() => [{ id: "cleanup:b", kind: "cleanup", botId: "b", botName: "小蓝", subject: "1 个任务文件夹 11月9日 删除", status: "", head: "1 个任务文件夹 11月9日 删除", line: "", since: now + H, severity: "warn", actions: ["keep", "dismiss"] }]);
- expect(att.list().map((a) => a.id)).toEqual(["cleanup:b", `suggest:${rule.id}`]);
+ att.addSource(() => [{ id: "login:b:weixin", kind: "login", botId: "b", botName: "小蓝", subject: "微信登录已过期", status: "", head: "微信登录已过期", line: "", since: now + H, severity: "err", actions: ["relogin"] }]);
+ expect(att.list().map((a) => a.id)).toEqual(["login:b:weixin", `suggest:${rule.id}`]);
expect(att.count()).toBe(2);
- expect(att.takeNew().map((a) => a.id)).toEqual(["cleanup:b"]);
+ expect(att.takeNew().map((a) => a.id)).toEqual(["login:b:weixin"]);
att.stop();
});
it("观察够了:改为执行、关掉、暂停、删掉就消失;继续观察了这一版不再问(重启也一样),改了原话再好好观察 3 次再问", async () => {
- const { rule } = await create();
+ const { rule } = await create("daily 08:00", OBSERVE);
const asks = () => svc.ruleAttention().filter((a) => a.kind === "suggest").length;
for (const d of ["2026-11-02", "2026-11-03", "2026-11-04"]) await day(d, report("done"));
expect(asks()).toBe(1);
@@ -494,7 +507,7 @@ describe("规则(假宿主、假时钟)", () => {
expect(asks()).toBe(0);
svc.updateRule(rule.id, { mode: "off" });
// 另一条:暂停了(本月预算用完)消失,删掉也消失
- const other = (await create("daily 09:00")).rule;
+ const other = (await create("daily 09:00", OBSERVE)).rule;
for (const d of ["2026-11-05", "2026-11-06", "2026-11-07"]) {
await go(at(`${d}T09:00`));
await turn(report("done"));
@@ -511,7 +524,7 @@ describe("规则(假宿主、假时钟)", () => {
expect(store.getKV(`rules:suggest-seen:${other.id}`)).toBeUndefined();
// 继续观察:这一版不再问,再好好观察一次也不问;重启后也一样
- const third = (await create("daily 10:00")).rule;
+ const third = (await create("daily 10:00", OBSERVE)).rule;
for (const d of ["2026-11-08", "2026-11-09", "2026-11-10"]) {
await go(at(`${d}T10:00`));
await turn(report("done"));
@@ -541,8 +554,7 @@ describe("规则(假宿主、假时钟)", () => {
});
it("完全权限的机器人:执行时最多可写工作区;只读的机器人:执行也只读", async () => {
- const { rule } = await create();
- svc.updateRule(rule.id, { mode: "act" });
+ await create();
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");
@@ -553,41 +565,38 @@ describe("规则(假宿主、假时钟)", () => {
expect(svc.sessionConfig({ sessionId: "task-x" }).error).toBeDefined();
});
- it("改原话:版本加 1,执行中的先观察 1 次再回到执行;只改时间表不动模式;正在跑的照原来的版本跑完", async () => {
+ it("改原话:版本加 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");
+ expect(store.getRule(rule.id)).toMatchObject({ version: 2, mode: "act" });
+ expect(store.getRule(rule.id)).not.toHaveProperty("observeLeft");
+ expect(svc.getRuleView(rule.id)!.state.key).toBe("act");
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 版、观察
+ // 下一次:第 2 版,照样执行,命中就发
await go(at("2026-11-03T08:00"));
expect(host.prompts.at(-1)!.text).toContain("低于 180");
- expect(host.prompts.at(-1)!.text).toContain("[这次]\n观察");
+ 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"));
+ expect(pushes()).toHaveLength(2);
+ expect(svc.ruleLog(rule.id)[0]).toMatchObject({ mode: "act", version: 2 });
+ // 观察中的改了原话:还是观察
+ const watch = (await create("daily 09:00", OBSERVE)).rule;
+ svc.updateRule(watch.id, { instruction: "每天看看 Y 的价格" });
+ expect(store.getRule(watch.id)).toMatchObject({ version: 2, mode: "observe" });
// 只改时间表:模式不变,下一次按新时间
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") });
+ expect(store.getRule(rule.id)).toMatchObject({ mode: "act", version: 2, nextRunAt: at("2026-11-03T09: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([]);
@@ -617,7 +626,7 @@ describe("规则(假宿主、假时钟)", () => {
});
it("观察中的规则连续失败 3 次也暂停,但什么都不推,只在「需要你」里", async () => {
- const { rule } = await create();
+ const { rule } = await create("daily 08:00", OBSERVE);
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([]);
@@ -779,7 +788,7 @@ describe("规则(假宿主、假时钟)", () => {
});
it("运行记录:新的在前,一次一行,可以往前翻;展开有报告、版本、权限;runLine 的几种说法", async () => {
- const { rule } = await create("every 15m");
+ const { rule } = await create("every 15m", OBSERVE);
for (let i = 0; i < 4; i++) {
await go(store.getRule(rule.id)!.nextRunAt);
await turn(report("done"));
@@ -802,7 +811,7 @@ describe("规则(假宿主、假时钟)", () => {
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 r = svc.createRule({ botId: "b", conversationId: CONV, title: "仓库新 issue", instruction: "有新 issue 时看看要不要我处理", mode: "observe", 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" } });
@@ -844,7 +853,7 @@ describe("规则(假宿主、假时钟)", () => {
});
it("没报告:提醒一次(规则的说法),还没有就失败;观察时要批准的自动拒绝、记成「需要批准」", async () => {
- const { rule } = await create();
+ const { rule } = await create("daily 08:00", OBSERVE);
await go(at("2026-11-02T08:00"));
svc.wouldNeedApproval(runsOf(rule.id)[0].id, "curl -X POST https://x.example/alert");
await turn();
@@ -860,7 +869,6 @@ describe("规则(假宿主、假时钟)", () => {
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)!;
@@ -877,7 +885,7 @@ describe("规则(假宿主、假时钟)", () => {
});
it("微信:执行中的规则(含提醒)每条留 1 条配额,观察中的不留;续期提醒列出窗口关了以后要跑的", async () => {
- const { rule } = await create();
+ const { rule } = await create("daily 08:00", OBSERVE);
expect(delivery.reserved("b", "weixin", "owner")).toBe(0);
svc.updateRule(rule.id, { mode: "act" });
expect(delivery.reserved("b", "weixin", "owner")).toBe(1);
@@ -896,12 +904,15 @@ describe("规则(假宿主、假时钟)", () => {
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, 执行中\./);
+ 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: "observe" } });
+ expect(up.text).toMatch(/^Updated rule 「看 X 价格」: 每天 08:00, 观察中\./);
+ await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_update", args: { rule: "X 价格", mode: "act" } });
+ // 改了原话:照样执行,不再说下一次只观察
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. 看 X 价格 · 观察中:每天 08:00\n发 /stop 编号 可停止。");
+ expect(re.text).toMatch(/^Updated rule 「看 X 价格」: 每天 08:00, 执行中\. Tell the user/);
+ expect(re.text).not.toContain("observes");
+ expect(svc.listText(CONV)).toBe("规则:\n1. 看 X 价格 · 执行中:每天 08:00\n发 /stop 编号 可停止。");
expect(svc.stopByIndex(CONV, 1, "weixin:owner")).toBe("已关闭规则「看 X 价格」。");
expect(store.getRule(rule.id)!.mode).toBe("off");
expect(svc.listText(CONV)).toBe("没有后台任务。");
@@ -914,7 +925,6 @@ describe("规则(假宿主、假时钟)", () => {
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 了"));
@@ -938,7 +948,6 @@ describe("规则(假宿主、假时钟)", () => {
]);
expect(normalizeSchedule({ kind: "every", minutes: 5 }, TZ, now, "en").error).toBe("The interval must be at least 15 minutes");
const { rule } = await create();
- svc.updateRule(rule.id, { mode: "act" });
await day("2026-11-02", report("done", "X 降到 199 了"));
await day("2026-11-03", report("done"));
withLang("en", () => {
@@ -962,7 +971,9 @@ describe("规则(假宿主、假时钟)", () => {
expect(svc.stopByIndex(CONV, 2, "weixin:owner")).toBe("Rule “看 X 价格” is off.");
expect(host.prompts.findLast((x) => x.sessionId.startsWith("rule-"))!.text).toContain("[规则]\n看 X 价格(每天 08:00)");
const made = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "Weather", instruction: "check the rain every weekday", schedule: "weekdays 07:30" } });
- expect(made.text).toContain("「Rule set: Weather, Weekdays 07:30. It watches quietly for a few days; switch it to act under Tasks.」");
+ expect(made.text).toContain("「Rule set: Weather, Weekdays 07:30. I'll tell you when something matters.」");
+ const watched = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "Wind", instruction: "watch the wind first", schedule: "weekdays 07:00", mode: "observe" } });
+ expect(watched.text).toContain("「Rule set: Wind, Weekdays 07:00. It watches quietly for a few days and sends nothing.」");
expect(made.text).toContain("WeChat lets the bot message you only within 24 hours of your last message.");
expect(svc.updateRule(rule.id, { title: " " }).error).toBe("Name can't be empty");
} finally {
@@ -972,9 +983,8 @@ describe("规则(假宿主、假时钟)", () => {
it("模拟 48 小时:三条规则(每天、每 30 分钟、一次性提醒),中间应用关了 3 小时;次数、跳过、推送都对", async () => {
const daily = (await create("daily 08:00")).rule;
- const half = (await create("every 30m")).rule;
+ const half = (await create("every 30m", OBSERVE)).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) {
diff --git a/test/tasks-view.e2e.test.ts b/test/tasks-view.e2e.test.ts
index 2dbd77e..8d321bf 100644
--- a/test/tasks-view.e2e.test.ts
+++ b/test/tasks-view.e2e.test.ts
@@ -1,11 +1,11 @@
/**
* 任务视图的接口(3f):真实的 App 和本机服务(代理关着,任务和规则直接写库)。
* GET /tasks?group= 按进行中 / 等你 / 结束了分组(归档了的不列,组名不对 400);详情里有来自、大小;改预算(加多少、改成多少、
- * 不对的金额、停了的任务);删除连同文件夹;保留文件夹(详情里、「需要你」里);打开文件夹只在桌面版;规则编辑器的预算;
- * 规则运行记录和任务导出成 Markdown(下载的文件名、按 ?lang= 的语言)。
+ * 不对的金额、停了的任务);删除连同文件夹;保留文件夹(只在详情里:清理不进「需要你」);打开文件夹只在桌面版;
+ * 规则编辑器的预算和模式(检查默认执行,可以选观察);规则运行记录和任务导出成 Markdown(下载的文件名、按 ?lang= 的语言)。
* 问了个有默认回答的问题、接着在做的任务:在进行中那组,「进行中,有个问题等你回答」;详情、「需要你」、对话里的卡片都有那一句
* 「不回复就按中文做」(按界面的语言)。
- * 观察够了的规则:「需要你」里问要不要改为执行;改为执行(同 PUT /rules/:id 切模式)、继续观察(这一版不再问)。
+ * 用户选了观察的规则观察够了:「需要你」里问要不要改为执行;改为执行(同 PUT /rules/:id 切模式)、继续观察(这一版不再问)。
*/
import fs from "node:fs";
import os from "node:os";
@@ -113,17 +113,12 @@ describe("任务视图的接口", () => {
expect((await api(`/tasks/nope/budget`, { method: "POST", body: { addUsd: 1 } })).status).toBe(404);
});
- it("保留文件夹:详情里的保留、「需要你」里的保留和知道了", async () => {
- app.store.updateTask(done, { cleanupAt: Date.now() + 3 * 86400_000 });
- const item = (await api("/attention")).data.items.find((i: any) => i.id === "cleanup:default");
- expect(item).toMatchObject({ kind: "cleanup", actions: ["keep", "dismiss"], line: "整理下载目录 30 天没动过了" });
- expect(item.head).toBe(item.subject);
- expect((await api("/attention/cleanup:default/dismiss", { method: "POST", body: {} })).data.items.find((i: any) => i.kind === "cleanup")).toBeUndefined();
- app.store.updateTask(failed, { cleanupAt: Date.now() + 4 * 86400_000 });
- expect((await api("/attention")).data.items.filter((i: any) => i.kind === "cleanup")).toHaveLength(1);
- await api("/attention/cleanup:default/keep", { method: "POST", body: {} });
- expect([app.store.getTask(done)!.cleanupAt, app.store.getTask(failed)!.cleanupAt]).toEqual([0, 0]);
- app.store.updateTask(done, { cleanupAt: Date.now() + 86400_000 });
+ it("保留文件夹:定了清理日期不进「需要你」,详情里有日期和保留", async () => {
+ const due = Date.now() + 3 * 86400_000;
+ app.store.updateTask(done, { cleanupAt: due });
+ expect((await api(`/tasks/${done}`)).data.task).toMatchObject({ cleanupAt: due });
+ expect((await api("/attention")).data.items.filter((i: any) => i.taskId === done || String(i.id).startsWith("cleanup"))).toEqual([]);
+ expect((await api("/attention/cleanup:default/keep", { method: "POST", body: {} })).status).toBe(409);
expect((await api(`/tasks/${done}/keep`, { method: "POST", body: {} })).data.task).toMatchObject({ cleanupAt: 0 });
});
@@ -135,11 +130,16 @@ describe("任务视图的接口", () => {
expect(md).toMatch(/^# 整理下载目录\n\nDone · about \$0\.00 of \$1\.00\n\n- From: WeChat · \d{4}-\d\d-\d\d \d\d:\d\d\n/);
expect(md).toContain("## Run 1 · Started · ");
const rule = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title: "看 X 价格", instruction: "每天早上看看 X 的价格", schedule: { kind: "daily", time: "08:00" }, runBudgetUsd: 0.2, monthBudgetUsd: 5 } })).data.rule;
- expect(rule).toMatchObject({ runBudgetUsd: 0.2, monthBudgetUsd: 5, mode: "observe" });
+ // 编辑器新建的检查默认执行;选了观察的才观察;别的模式不收
+ expect(rule).toMatchObject({ runBudgetUsd: 0.2, monthBudgetUsd: 5, mode: "act", state: { key: "act" } });
+ const watch = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", mode: "observe", title: "看 Y 价格", instruction: "每天早上看看 Y 的价格", schedule: { kind: "daily", time: "08:00" } } })).data.rule;
+ expect(watch).toMatchObject({ mode: "observe", state: { key: "observe", label: "观察中" } });
+ expect((await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", mode: "off", title: "x", instruction: "x", schedule: { kind: "daily", time: "08:00" } } })).status).toBe(400);
+ await api(`/rules/${watch.id}`, { method: "DELETE" });
expect((await api(`/rules/${rule.id}`, { method: "PUT", body: { runBudgetUsd: 0.15, monthBudgetUsd: 4 } })).data.rule).toMatchObject({ runBudgetUsd: 0.15, monthBudgetUsd: 4 });
expect((await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title: "x", instruction: "x", schedule: { kind: "daily", time: "08:00" }, monthBudgetUsd: 0 } })).status).toBe(400);
const zh = await (await fetch(`${base}/amb/api/rules/${rule.id}/export`)).text();
- expect(zh).toMatch(/^# 看 X 价格\n\n> 每天早上看看 X 的价格\n\n每天 08:00(Asia\/Shanghai) · 观察中 · 本月 约 \$0\.00 \/ \$4\.00\n\n导出于 .+\n\n## 运行记录\n\n还没有运行过。\n$/);
+ expect(zh).toMatch(/^# 看 X 价格\n\n> 每天早上看看 X 的价格\n\n每天 08:00(Asia\/Shanghai) · 执行中 · 本月 约 \$0\.00 \/ \$4\.00\n\n导出于 .+\n\n## 运行记录\n\n还没有运行过。\n$/);
const en = await (await fetch(`${base}/amb/api/rules/${rule.id}/export?lang=en`)).text();
expect(en).toContain("## Run log");
});
@@ -178,9 +178,9 @@ describe("问了还在做:有默认回答的提问", () => {
});
describe("观察够了的规则:「需要你」里问要不要改为执行", () => {
- /** 一条观察中的检查和它这一版的 n 次好好观察(直接写库;最近那次「本会发送」) */
+ /** 一条用户选了观察的检查和它这一版的 n 次好好观察(直接写库;最近那次「本会发送」) */
const observed = async (title: string, n: number): Promise<string> => {
- const rule = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title, instruction: `每天看看${title}`, schedule: { kind: "daily", time: "08:00" } } })).data.rule;
+ const rule = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", mode: "observe", title, instruction: `每天看看${title}`, schedule: { kind: "daily", time: "08:00" } } })).data.rule;
for (let i = 0; i < n; i++) {
const at = Date.now() - (n - i) * 86400_000;
const id = `r_${rule.id.slice(3, 9)}${String(i).padStart(6, "0")}`;
diff --git a/ui/components/rules.js b/ui/components/rules.js
index 95b74ac..6c6ce3d 100644
--- a/ui/components/rules.js
+++ b/ui/components/rules.js
@@ -1,7 +1,7 @@
-// 规则(3d):信息面板「任务」组里一条规则一行——时间表 · 标题,下面一句状态和下次运行(观察够了要不要改为执行,在「需要你」里问,
-// 从不推送)。点开是规则的详情:用户的原话、模式(观察 / 执行 / 关)、立即运行、编辑、删除,
+// 规则(3d):信息面板「任务」组里一条规则一行——时间表 · 标题,下面一句状态和下次运行(用户选了观察的,观察够了要不要改为执行,
+// 在「需要你」里问,从不推送)。点开是规则的详情:用户的原话、模式(观察 / 执行 / 关)、立即运行、编辑、删除,
// 和运行记录(一次一行:时间 · 模式 · 本会发送 / 保持安静 / 失败 / 跳过),每行再点开看报告、步骤、版本和权限;运行记录可以导出成
-// Markdown(3f)。编辑器里有每次、每月的预算(3f,检查才有)。
+// Markdown(3f)。编辑器里有每次、每月的预算(3f,检查才有);新建的检查还能选执行(默认)或观察。
// 健康时不多说话:状态是"点 + 文字"(绿 = 执行中、提醒,灰 = 观察中、关了,红 = 暂停了)。
import { useEffect, useState } from "preact/hooks";
import { html, Icon, Button, Seg, Sheet, Spinner } from "./ui.js";
@@ -141,7 +141,6 @@ export function RuleDetail({ rule, runs: given, onChanged }) {
<span class="grow"></span>
<${Button} size="sm" loading=${busy === "run"} disabled=${!!busy || !!rule.live || rule.mode === "off"} onClick=${runNow}>${t("rules.runNow")}<//>
</div>
- ${rule.mode === "act" && rule.observeLeft > 0 && html`<span class="hint">${t("rules.observeLeft", { count: rule.observeLeft })}</span>`}
${rule.kind === "check" && rule.mode === "observe" && html`<span class="hint">${t("rules.observeHelp")}</span>`}
<div class="actions">
<button type="button" class="text" onClick=${() => setEditing(true)}>${t("common.edit")}</button>
@@ -204,7 +203,7 @@ function convOptions(convs, current) {
/**
* 新建或编辑一条规则(对话框):名称、要做什么(用户的原话)或提醒的那句话、时间、发到哪个会话。
- * 新建的检查从观察开始;改了原话的执行中的规则先观察 1 次(服务端处理)。发到微信时说清 24 小时的限制。
+ * 新建的检查默认执行,也可以选先观察(之后在详情里切);改了原话模式不变。发到微信时说清 24 小时的限制。
* 对话框里不放下拉菜单(玻璃对话框会裁掉它):选项都用分段。时间表没改就不发,every 的起点不会被挪动。
*/
export function RuleEditor({ botId, rule, onClose, onSaved }) {
@@ -214,6 +213,8 @@ export function RuleEditor({ botId, rule, onClose, onSaved }) {
const [orig] = useState(() => formOf(rule?.trigger?.kind === "schedule" ? rule.trigger.schedule : undefined));
const [f, setF] = useState(orig);
const [conv, setConv] = useState(rule?.conversationId || "");
+ // 新建的检查:执行(默认)或观察
+ const [mode, setMode] = useState("act");
const [convs, setConvs] = useState(null);
const [busy, setBusy] = useState(false);
// 预算(3f):每次、每月(美元);没改就不发
@@ -244,8 +245,8 @@ export function RuleEditor({ botId, rule, onClose, onSaved }) {
};
const d = rule
? await api(`/rules/${encodeURIComponent(rule.id)}`, { method: "PUT", body })
- : await api("/rules", { method: "POST", body: { ...body, botId, kind } });
- toast(rule ? t("common.saved") : kind === "remind" ? t("rules.createdRemind") : t("rules.createdCheck"));
+ : await api("/rules", { method: "POST", body: { ...body, botId, kind, ...(kind === "check" ? { mode } : {}) } });
+ toast(rule ? t("common.saved") : kind === "remind" ? t("rules.createdRemind") : mode === "observe" ? t("rules.createdObserve") : t("rules.createdCheck"));
onSaved?.(d.rule);
} catch (e) {
failed(e);
@@ -277,6 +278,10 @@ export function RuleEditor({ botId, rule, onClose, onSaved }) {
<span class="t-label">${t("rules.to")}</span>
${!convs ? html`<${Spinner} />` : convs.length ? html`<${Seg} label=${t("rules.to")} options=${convOptions(convs, conv)} value=${conv} onChange=${setConv} />` : html`<span class="hint">${t("rules.noConvs")}</span>`}
</div>
+ ${!rule && !remind && html`<div class="rule-when">
+ <span class="t-label">${t("rules.modeLabel")}</span>
+ <${Seg} label=${t("rules.modeLabel")} options=${[["act", t("rules.mode.act")], ["observe", t("rules.mode.observe")]]} value=${mode} onChange=${setMode} />
+ </div>`}
${!remind && html`<div class="rule-when">
<span class="t-label">${t("rules.budget")}</span>
<div class="rule-when-row">
diff --git a/ui/design/gallery.js b/ui/design/gallery.js
index 6cb0eef..f3762eb 100644
--- a/ui/design/gallery.js
+++ b/ui/design/gallery.js
@@ -610,7 +610,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场
<${NeedsRow} count=${3} onClick=${() => {}} /><${NeedsRow} count=${2} on onClick=${() => {}} /><${NeedsRow} count=${0} />
</div>`}
<//>
- <${Demo} flush col title="列表" note="NeedItem:标题行是一句话,几个机器人时带上名字(「小蓝的「GPU 价格调研」在等你回答」)。等你回答 / 等你回答(任务接着在做,不回复就按默认)/ 等你批准 / 预算用完(再给 $1 继续?)/ 未送达 / 失败 / 规则本月预算用完 / 登录过期 / 预算留给聊天 / 清理文件夹 / 观察够了,要不要改为执行(不推送)">
+ <${Demo} flush col title="列表" note="NeedItem:标题行是一句话,几个机器人时带上名字(「小蓝的「GPU 价格调研」在等你回答」)。等你回答 / 等你回答(任务接着在做,不回复就按默认)/ 等你批准 / 预算用完(再给 $1 继续?)/ 未送达 / 失败 / 规则本月预算用完 / 登录过期 / 预算留给聊天 / 观察够了,要不要改为执行(不推送)">
${() => html`<div class="list needs-list">${NEEDS.map((it) => html`<${NeedItem} item=${it} multiBot onAct=${async () => {}} />`)}</div>`}
<//>
<//>
@@ -688,7 +688,6 @@ const NEEDS = [
{ id: "rb", kind: "rule", botName: "小蓝", subject: "规则「看 X 价格」", status: "本月预算用完", head: "规则「看 X 价格」本月预算用完了", line: "已用约 $3.00,下月自动恢复。再给 $3 继续?", since: Date.now() - 2 * 3600_000, severity: "warn", actions: ["continue"] },
{ id: "l", kind: "login", botName: "绿草", subject: "微信登录已过期", status: "", head: "微信登录已过期", line: "", since: Date.now() - 3 * 3600_000, severity: "err" },
{ id: "rs", kind: "budget", botName: "小蓝", subject: "后台工作已停", status: "", head: "后台工作已停", line: "机器人预算只剩约 $1.80(共 $10),留给聊天", since: Date.now() - 4 * 3600_000, severity: "warn", actions: ["open"] },
- { id: "c", kind: "cleanup", botName: "小蓝", subject: "2 个任务文件夹 11月4日 删除", status: "", head: "2 个任务文件夹 11月4日 删除", line: "整理下载目录和旧照片归档 30 天没动过了", since: Date.now() - 5 * 3600_000, severity: "warn", actions: ["keep", "dismiss"] },
{ id: "s", kind: "suggest", botName: "小蓝", subject: "规则「看 X 价格」已观察 3 次,需要你来决定是否执行", status: "", head: "规则「看 X 价格」已观察 3 次,需要你来决定是否执行", line: "本会发送:“X 降价了,现在 ¥199(昨天 ¥259)”", since: Date.now() - 6 * 3600_000, severity: "warn", actions: ["act", "dismiss"], ruleTitle: "看 X 价格" },
];
@@ -741,7 +740,7 @@ const at = (days, h, m = 0) => {
d.setHours(h, m, 0, 0);
return d.getTime();
};
-const rule = (o) => ({ botId: "b", kind: "check", mode: "observe", observeLeft: 0, failures: 0, channel: "weixin", message: "", trigger: { kind: "schedule" }, version: 1, ...o });
+const rule = (o) => ({ botId: "b", kind: "check", mode: "observe", failures: 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), monthUsd: 0.41, monthBudgetUsd: 3 }),
rule({ id: "g2", title: "issue 周报", when: "每周一 09:00", instruction: "每周一早上把仓库上周的 issue 汇总成三句话发给我", mode: "act", state: { key: "act", label: "执行中", dot: "ok" }, nextRunAt: at(3, 9) }),
diff --git a/ui/locales/en/botSettings.js b/ui/locales/en/botSettings.js
index d320055..3eab672 100644
--- a/ui/locales/en/botSettings.js
+++ b/ui/locales/en/botSettings.js
@@ -103,7 +103,7 @@ export default {
head: "Images and video",
confirm: "Confirm before generating",
alwaysSub: "Ask me which model to use before every generation",
- autoSub: "Generate right away when the default model works and the cost is low; ask first when switching models, above about $0.5, or when the request is unclear",
+ autoSub: "Ask me only when it would cost more than $0.5",
auto: "Ask when needed",
always: "Always ask",
},
diff --git a/ui/locales/en/needs.js b/ui/locales/en/needs.js
index 5096cf7..f5c0065 100644
--- a/ui/locales/en/needs.js
+++ b/ui/locales/en/needs.js
@@ -11,7 +11,6 @@ export default {
approveOnce: "Approve once",
deny: "Deny",
stop: "Stop",
- seen: "Got it",
relogin: "Scan again",
answerPlaceholder: "Your answer",
send: "Send",
@@ -19,7 +18,6 @@ export default {
dismiss: "Don't show again",
continue: "Continue",
raiseBudget: "Change budget",
- keep: "Keep",
toAct: "Switch to act",
keepObserving: "Keep observing",
};
diff --git a/ui/locales/en/onboarding.js b/ui/locales/en/onboarding.js
index 382d96b..84705a1 100644
--- a/ui/locales/en/onboarding.js
+++ b/ui/locales/en/onboarding.js
@@ -41,7 +41,7 @@ export default {
filter: "Filter models",
default: "Default model",
noMatch: "No matching models",
- mediaHint: "Default models for generating images and videos. You'll be asked before each generation and can switch then.",
+ mediaHint: "Default models for generating images and videos.",
image: "Image",
imageLabel: "Default image model",
video: "Video",
diff --git a/ui/locales/en/rules.js b/ui/locales/en/rules.js
index f2b67a6..b4c430a 100644
--- a/ui/locales/en/rules.js
+++ b/ui/locales/en/rules.js
@@ -26,14 +26,14 @@ export default {
words: "“{text}”",
modeLabel: "Mode",
runNow: "Run now",
- observeLeft: { one: "Observes {count} more time, then acts", other: "Observes {count} more times, then acts" },
observeHelp: "Observing sends nothing and changes no files, but can't block commands that go online.",
log: "Run log",
noRuns: "No runs yet",
earlier: "Earlier",
kinds: { daily: "Daily", weekdays: "Weekdays", weekly: "Weekly", every: "Every", once: "Once", cron: "cron" },
createdRemind: "Reminder set",
- createdCheck: "Rule set. It observes first",
+ createdCheck: "Rule set",
+ createdObserve: "Rule set. It observes first",
editTitle: "Edit rule",
newTitle: "New rule",
kind: "Type",
diff --git a/ui/locales/en/settings.js b/ui/locales/en/settings.js
index 7889cf8..d8748e7 100644
--- a/ui/locales/en/settings.js
+++ b/ui/locales/en/settings.js
@@ -223,12 +223,12 @@ export default {
},
imageModel: {
name: "Default image model",
- sub: "Used by default when a bot generates images. You'll confirm before each one",
+ sub: "Used by default when a bot generates images",
keys: "image picture generate model",
},
videoModel: {
name: "Default video model",
- sub: "Used by default when a bot generates videos. You'll confirm before each one",
+ sub: "Used by default when a bot generates videos",
keys: "video generate model",
},
autoModel: "Auto ({model})",
diff --git a/ui/locales/zh-CN/botSettings.js b/ui/locales/zh-CN/botSettings.js
index 1584a78..aa9dbd6 100644
--- a/ui/locales/zh-CN/botSettings.js
+++ b/ui/locales/zh-CN/botSettings.js
@@ -103,7 +103,7 @@ export default {
head: "生图 / 生视频",
confirm: "生成前确认",
alwaysSub: "每次生成前都问我用哪个模型",
- autoSub: "默认模型能用、花费不高时直接生成;换模型、预计超过 $0.5 或要求不明确时先问我",
+ autoSub: "预计花费超过 $0.5 时才问我",
auto: "需要时再问",
always: "每次都问",
},
diff --git a/ui/locales/zh-CN/needs.js b/ui/locales/zh-CN/needs.js
index 7c8f356..7e852c3 100644
--- a/ui/locales/zh-CN/needs.js
+++ b/ui/locales/zh-CN/needs.js
@@ -11,7 +11,6 @@ export default {
approveOnce: "批准一次",
deny: "拒绝",
stop: "停止",
- seen: "知道了",
relogin: "重新扫码",
answerPlaceholder: "你的回答",
send: "发送",
@@ -19,7 +18,6 @@ export default {
dismiss: "不再提示",
continue: "继续",
raiseBudget: "调整预算",
- keep: "保留",
toAct: "改为执行",
keepObserving: "继续观察",
};
diff --git a/ui/locales/zh-CN/onboarding.js b/ui/locales/zh-CN/onboarding.js
index 6e1f8da..a7f32a1 100644
--- a/ui/locales/zh-CN/onboarding.js
+++ b/ui/locales/zh-CN/onboarding.js
@@ -43,7 +43,7 @@ export default {
filter: "筛选模型",
default: "默认模型",
noMatch: "没有匹配的模型",
- mediaHint: "生成图片和视频时默认用的模型。每次生成前都会先问你,也可以当场换。",
+ mediaHint: "生成图片和视频时默认用的模型。",
image: "图片",
imageLabel: "默认图片模型",
video: "视频",
diff --git a/ui/locales/zh-CN/rules.js b/ui/locales/zh-CN/rules.js
index 3a4af8a..7877b72 100644
--- a/ui/locales/zh-CN/rules.js
+++ b/ui/locales/zh-CN/rules.js
@@ -26,14 +26,14 @@ export default {
words: "「{text}」",
modeLabel: "模式",
runNow: "立即运行",
- observeLeft: { other: "改了规则,先观察 {count} 次再执行" },
observeHelp: "观察时不发消息、不改文件,但拦不住命令联网。",
log: "运行记录",
noRuns: "还没有运行过",
earlier: "更早的",
kinds: { daily: "每天", weekdays: "工作日", weekly: "每周", every: "每隔", once: "一次", cron: "cron" },
createdRemind: "已建好提醒",
- createdCheck: "已建好规则,先观察",
+ createdCheck: "已建好规则",
+ createdObserve: "已建好规则,先观察",
editTitle: "编辑规则",
newTitle: "新规则",
kind: "类型",
diff --git a/ui/locales/zh-CN/settings.js b/ui/locales/zh-CN/settings.js
index 2527de7..f7b07b1 100644
--- a/ui/locales/zh-CN/settings.js
+++ b/ui/locales/zh-CN/settings.js
@@ -223,12 +223,12 @@ export default {
},
imageModel: {
name: "默认图片模型",
- sub: "机器人生成图片时默认选它,每次生成前都会让你确认",
+ sub: "机器人生成图片时默认选它",
keys: "图片 生图 画图 image 模型",
},
videoModel: {
name: "默认视频模型",
- sub: "机器人生成视频时默认选它,每次生成前都会让你确认",
+ sub: "机器人生成视频时默认选它",
keys: "视频 生视频 video 模型",
},
autoModel: "自动({model})",
diff --git a/ui/screens/needs-you.js b/ui/screens/needs-you.js
index 05a8c7c..669c9e8 100644
--- a/ui/screens/needs-you.js
+++ b/ui/screens/needs-you.js
@@ -3,8 +3,7 @@
// 没事时侧栏没有这一行,直接打开这一页只有一句「没有需要你处理的事」。状态是"点 + 文字":黄 = 等你,红 = 失败 / 登录过期。
// 预算(3e):任务预算用完是一个提问(「已用约 $1.00,再给 $1 继续?」继续 / 停止);规则本月预算用完可以继续;
// 机器人的预算留给聊天、后台工作停着的,去机器人设置调整预算。
-// 清理(3f):任务文件夹 30 天没动过、过几天删除的,一个机器人一行,可以保留或知道了(不推送,只在这里说一次)。
-// 观察够了的规则:问要不要改为执行(第二行是最近那次的「本会发送:…」),可以改为执行或继续观察;排在最后,不推送、不发系统通知。
+// 观察够了的规则(用户选了观察的):问要不要改为执行(第二行是最近那次的「本会发送:…」),可以改为执行或继续观察;排在最后,不推送、不发系统通知。
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { html, Icon, Button, Skeleton } from "../components/ui.js";
import { TaskDetail } from "../components/tasks.js";
@@ -89,8 +88,6 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin, onOpenB
${item.kind === "delivery" && item.actions.includes("retry") && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`}
${item.kind === "delivery" && item.actions.includes("dismiss") && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.dismiss")}</button>`}
${item.kind === "login" && html`<${Button} onClick=${() => onRelogin?.(item.botId)}>${t("needs.relogin")}<//>`}
- ${item.kind === "cleanup" && html`<${Button} loading=${busy === "keep"} disabled=${!!busy} onClick=${() => act("keep")}>${t("needs.keep")}<//>
- <button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.seen")}</button>`}
${item.kind === "suggest" && html`<${Button} loading=${busy === "act"} disabled=${!!busy} onClick=${async () => (await act("act")) && toast(t("rules.nowActs", { title: item.ruleTitle }))}>${t("needs.toAct")}<//>
<button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.keepObserving")}</button>`}
</div>