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.

docs(design): background tasks, proactive rules and "needs you" (Phase 3)

Marlaa505f68645e9
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.md
new file mode 100644
index 0000000..6900f93
--- /dev/null
+++ b/docs/design/background-tasks-and-proactive.md
@@ -0,0 +1,843 @@
+# Background tasks and proactive rules (Phase 3 design)
+
+Status: **design for discussion. Nothing here is built yet.** Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.
+Feasibility evidence is in [Appendix A](#appendix-a-feasibility-answers-with-evidence). The spike that produced it is `scripts/spikes/p3-tasks/`.
+
+## Summary
+
+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.
+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:
+
+- **Five new concepts:** Task, Rule, Run, Report and Attention. We don't add Trigger, Eval, Ticket or Subscription; a personal assistant has one owner and explicit requests (see [Domain model](#1-domain-model)).
+- **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.
+- **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.
+
+## 0. Goals, non-goals and principles
+
+**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.
+- Transparency that costs no attention. The user can always look, and we push only what needs them.
+
+**Non-goals (Phase 3)**
+
+- Multi-user teams, delegation between bots, and event sources other than time. Polling covers "watch X" for now.
+- Exactly-once side effects outside AnyModelBot. The host can make its own effects (deliveries, cards) idempotent. Effects the agent causes, such as sending an email from a CLI, are made safe on a best-effort basis with a journal and a recovery note (see [restart](#restart-recovery)).
+
+**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.
+- **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.**
+
+## 1. Domain model
+
+```mermaid
+flowchart LR
+ P[Person's message] -->|chat agent: task_start| T[Task]
+ R[Rule] -->|schedule fires| RR[Run]
+ T -->|launch / answer / retry / recover| TR[Run]
+ TR --> REP[Report]
+ RR --> REP
+ REP -->|done + message| D[Delivery to origin conversation]
+ REP -->|needs_you / failed| A[Attention]
+ A -->|person answers| T
+```
+
+| 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. |
+| **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), `summary` (internal) and `files`. | 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?" |
+
+**Rejected concepts.** Superagent's model is shaped for a team on GitHub and Feishu. This table lists what we leave out.
+
+| Rejected | Reason |
+| --- | --- |
+| Trigger, Thread, Eval, Decision | A personal assistant gets explicit requests from its owner. The chat agent decides whether a request is background work (`task_start`), and that is the "eval". Proactive judgement lives inside a Rule run, recorded in its Report. |
+| Mandate as an entity | Its job is done by fields on Task and Rule: origin, permission snapshot, budget, mode and rule version. |
+| Ticket and Assignment as two names for tasks | We keep the split, as **Task** and **Run**. The Run also covers rule firings. |
+| Subscription | Routing is the origin conversation, plus explicit quote or thread replies (see [routing](#follow-ups-and-routing)). |
+| Watcher or Reminder as separate concepts | A watcher is a Rule on an interval. A reminder is a Rule whose run only delivers a fixed text. |
+| Notification or Delivery as a domain concept | Delivery is an outbox, which is an implementation detail. |
+
+## 2. States and transitions
+
+**Task stage.** The first matching row wins. The user-visible states are the ones the PO named: working, needs you, ready, failed and stopped.
+
+| # | Stage | Condition | Label (zh) | Group |
+| --- | --- | --- | --- | --- |
+| 1 | `stopped` | A person stopped it | ๅทฒๅœๆญข | ended |
+| 2 | `needs-you/delivery` | Its latest result, question or failure message has not reached the conversation: it failed 3 times, or it is held because the channel needs the person (WeChat window closed or no quota) | ๆœช้€่พพ | needs you |
+| 3 | `needs-you/answer` | An open question or approval | ็ญ‰ไฝ ๅ›ž็ญ” ยท ็ญ‰ไฝ ๆ‰นๅ‡† | needs you |
+| 4 | `needs-you/budget` | A run stopped at the task budget | ้ข„็ฎ—็”จๅฎŒ | needs you |
+| 5 | `failed` | The latest Report is `failed` or the launch failed, and no person's input since | ๅคฑ่ดฅ | needs you |
+| 6 | `ready` | The latest Report is `done`, and no input since | ๅทฒๅฎŒๆˆ | ended (resumable) |
+| 7 | `working/queued` | Inputs wait, but no run holds a slot | ๆŽ’้˜Ÿไธญ | working |
+| 8 | `working` | Otherwise | ่ฟ›่กŒไธญ | working |
+
+A person's input after rows 3โ€“6 (an answer, a follow-up, "retry" or "continue") starts a new Run. The task then moves to row 7 or 8. Automatic inputs, such as a job wake-up or a recovery after restart, never lift rows 2โ€“5. Recovery applies only to runs that were running.
+
+**Run.** `queued โ†’ running โ‡„ settling โ†’ ended`.
+
+| Outcome | Meaning |
+| --- | --- |
+| `done` | Ended with a `done` Report, with or without a message |
+| `needs_you` | Ended with a question; the task waits |
+| `failed` | Ended with a `failed` Report, an error after 3 transient retries, or no Report after one nudge |
+| `budget` | Cancelled at the run or task budget |
+| `stopped` | A person stopped the task |
+| `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.
+
+```mermaid
+stateDiagram-v2
+ [*] --> working: task_start
+ working --> needs_you: Report needs_you / approval
+ working --> ready: Report done (delivered)
+ working --> failed: Report failed / errors
+ working --> needs_you: budget reached
+ needs_you --> working: person answers / raises budget
+ failed --> working: person retries or replies
+ ready --> working: person follow-up (resume)
+ working --> stopped: person stops
+ needs_you --> stopped: person stops
+ ready --> [*]: archived after retention
+```
+
+## 3. Execution
+
+```mermaid
+flowchart TB
+ subgraph Host["Host (Electron main / Node)"]
+ TS[TaskService<br/>tasks, rules, runs, inputs]
+ SCH[Scheduler<br/>host timers]
+ SL[Slots<br/>per bot + global]
+ OB[Outbox<br/>per-channel rules]
+ AC[ApprovalCenter<br/>questions & approvals]
+ SUB[Session watcher<br/>client.subscribe]
+ end
+ subgraph Child["DSH child (one per bot, sdk profile)"]
+ CHAT[chat sessions]
+ TASK[task-* sessions]
+ RULE[rule-* sessions]
+ PLG[amb-tasks.mjs<br/>decorate ยท task_report ยท settled]
+ end
+ SCH --> TS --> SL -->|SDK: session/prompt, setWorkingDirectory, resume| TASK
+ SL -->|P1: steer / cancel / model| TASK
+ PLG -->|bridge: /dsh/task-report, /dsh/task-settled, /dsh/task-config| TS
+ TASK & RULE -->|session.event / session.status for every session| SUB --> TS
+ TS --> OB --> CH[WeChat / Feishu / Web]
+ TS --> AC
+```
+
+### Sessions and folders
+
+- **One session per task:** `task-<id>`. The host creates, resumes and prompts it through the SDK it already uses: `harness.session(id)`, `setWorkingDirectory(folder)`, `client.prompt` and `resumeSession`. This makes the SDK server the single owner of the session registry, and it drains the session at shutdown. Don't mix this with plugin-side `agents.create` for the same id: both work, but two owners would collide.
+- **One fresh session per rule run:** `rule-<id>-<n>`. Continuity comes from the host, which includes the last 3 Reports in the run input, and from the rule's folder in act mode. This keeps context bounded, and observe and act runs get different permissions.
+- **Folders** live in the bot workspace: `tasks/<slug>-<id6>/` and `rules/<slug>/`. They must be inside it, because DSH's `workspace-write` root and our bwrap shim both cover only the bot workspace. A folder is a convention, not a security boundary. Every session in the bot shares one sandbox root, the same as in superagent.
+- **Decoration.** On `agent/created`, `amb-tasks.mjs` recognizes the `task-` or `rule-` prefix and fetches its config from the host (`/dsh/task-config`). It then:
+ - denies tools with `agent.ctx.tools.restrict({ deny })`. The list always includes `present`, `ask_user_question`, `task_start` and `rule_create`, plus the per-mode lists in [permissions](#7-permissions). It must contain only registered names: `restrict` throws on an unknown tool.
+ - adds a system-prompt section with the task brief and the work and communication rules.
+ - registers `task_report`.
+ - guards every tool once the task has ended.
+
+ It does this for sessions created through the SDK and for sessions resumed after a restart (spike A.2).
+- **Brief.** The task's first input contains:
+ - the user's original message, verbatim;
+ - the chat agent's brief (at most 1,500 characters);
+ - the last 6 messages of the conversation;
+ - paths of attachments under `inbox/`;
+ - the bot's memory prefix, as `firstInput` builds it today.
+
+ A brief never replaces the original words.
+
+### How a request becomes a task
+
+The chat agent gets `task_start({ title, brief })`. Its prompt section says to start a task when:
+
+- the work clearly needs more than a few minutes or many steps (build, research, a report), or
+- the user asks for it in the background.
+
+It says not to start one for something the agent can answer now. The agent's reply confirms in one sentence what it will do, for example ใ€Œๅฅฝ๏ผŒๅŽๅฐๅผ€ๅง‹่ฐƒ็ ”ไธ‰ๅฎถไบ‘็š„ GPU ไปทๆ ผ๏ผŒๅฅฝไบ†ๅ‘Š่ฏ‰ไฝ ใ€‚ใ€. The confirmation is part of the chat reply, not an extra message. The host refuses `task_start` when the bot has 10 open tasks, when there is no budget, or (in groups) when the sender is not allowed; the group rule is an open question tied to P2's allowlist. The desktop or web "new task" button creates a task the same way.
+
+### Follow-ups and routing
+
+A person's message reaches a task only by explicit reference:
+
+- **Feishu:** a thread reply to the task's message, or a card button.
+- **WeChat:** a quote (ๅผ•็”จ) of the task's message. We store the sent text in the outbox and match the quote against it.
+- **Any channel:** the chat agent calls `task_message({ task, text })` when the user names the task ("GPU ้‚ฃไธชๆ”นๆˆ่‹ฑๆ–‡").
+
+A follow-up while the task is working is **steered** into it (P1) and lands at its next step. A follow-up to a done task resumes it under the same task. Quoting a task's message also adds the task's latest Report to the chat turn, so "่ฏฆ็ป†่ฏด่ฏด" is answered by the chat agent from the report without waking the task.
+
+### Concurrency and the reserved human lane
+
+- **Human lane:** chat turns keep working as today. Each conversation has its serial queue, and conversations run in parallel. They never take a task slot and never enter a task's queue. Tasks never enter a conversation's queue.
+- **Background lane:** at most `taskSlots` runs per bot (default 2), and at most `maxBackground` across all bots (default 4). A run holds its slot while `running` or `settling`.
+- **Reserved slot:** a wake caused by a person may use one extra slot per bot and goes ahead of queued work. Person-caused wakes are an answer, an approval, a follow-up, "retry" and "continue". The priority order is person wake, then task launch, then recovery, then rule run. A rule run that waits longer than its grace period is `skipped`.
+- **No measured DSH cap:** the spike ran two task turns and a chat turn in one process at once (A.2). The real limits are the shared model rate limit, CPU and memory for tool processes, and the bot's budget. These are what `taskSlots` protects.
+
+### Background jobs, subagents and settling
+
+When a turn ends, the session can still own shell jobs or subagents. While it does, the Run is `settling` and keeps its slot. DSH wakes the session in a new turn when a job ends (`tool-jobs` `completionDelivery: wakeup`, A.4). When the session is idle and nothing runs for it in the background, the plugin posts `/dsh/task-settled` and the Run ends with its Report. This is the same pattern as superagent's `untilQuiet`.
+
+Settling lasts at most 30 minutes after a turn ends. After that, its jobs are killed and the session is told so at its next turn. If a turn ends without a `task_report`, the host sends one nudge ("report your state with task_report"). If there is still no Report, the Run ends `failed` ("ๆฒกๆœ‰็ป™ๅ‡บ็ป“ๆžœ").
+
+### Stop, steer and model (dependency: P1)
+
+- **Stop** uses P1's `cancel(sessionId)`. The task's jobs are killed and its subagents released (superagent's `stopBackground`), and its tools are guarded. Today's only stop is `AgentHost.closeHarness()`, which kills chat and every task of the bot.
+- **Steer** uses P1's `steer(sessionId, text)` for follow-ups.
+- **Model:** a task keeps the model it started with (P1's per-session model). Without it, `AgentHost.ensure()` would restart DSH on a chat model switch, and it already waits for `active === 0`. Task runs must count as active.
+
+### Restart recovery
+
+The spike shows that a restart keeps some things and loses others (A.5):
+
+- **Survives:** session history, each session's working directory, and the files in the folder.
+- **Lost:**
+ - the running turn: its user message never reaches the model again;
+ - messages still queued in the inbox;
+ - background jobs, killed without a completion notice;
+ - in-process subagents;
+ - pending approvals: `ApprovalCenter.start()` expires them.
+
+The host therefore stores everything it owes a session, and recovers like this:
+
+1. **At start, and on every DSH child exit:** each Run in `running` or `settling` ends `interrupted`.
+2. **For each such task:** a `recover` Run is queued, oldest task first and subject to slots. Tasks that wait for a person (stages 2โ€“5) stay as they were, with one exception. A task blocked on an approval lost that approval with its turn, so it is recovered, and the agent asks again if it still needs to.
+3. **Inputs:** an input the session never took (no `user/message` event with its message id was seen) is delivered again. An input it took is never delivered again.
+4. **The recovery note** is the first message of the new Run. It is model-facing and in English, like our skills:
+
+ > The app restarted while you were working on this task. Your last step may not have finished, and these background jobs were stopped: {jobs}. Before repeating any outside action (sending, posting, paying, deleting, or calling an API that changes something), read `.task/journal.md`, check your folder and check the outside system. Then continue and report with task_report.
+
+5. **The journal:** the task prompt asks the agent to append one line to `.task/journal.md` before and after each outside action. This is best effort: the host can't see the agent's external effects.
+6. **The host's own effects are idempotent.** Delivery ids are stable (`<task>:<purpose>:<run>`). A delivery marked `sent` is never sent again. Reports are keyed by `(run, seq)`.
+7. **Rule runs** that were interrupted are rerun once if they are still inside their grace period. Otherwise they are `skipped`.
+8. **Settings restarts:** today a settings change restarts DSH only when the bot is idle. With tasks running, it waits up to 10 minutes for a safe point (no run mid-turn). Then it restarts and the runs recover.
+
+## 4. Scheduling: the host owns it
+
+**Decision: the host owns scheduling.** Reasons, with details in A.1:
+
+- **It can't load.** `@deepseek-ai/dsh-schedule` needs `sessionController`, which the `sdk` profile doesn't load. Adding the session controller pulls in the Web API stack (`fileUploads` and more).
+- **It fires into the original session as a user message, and nobody sees the result.** It calls `agent.followup` with source `schedule`. The host reads a session only during `run()`, so the result of that turn would never reach the user.
+- **It runs only while the DSH child runs.** We start the child lazily and restart it often. The host lives in the tray.
+- **It lacks what rules need:** observe mode, an attention budget, per-channel delivery, a cost cap and a user-visible run log. It is managed by the model (`schedule_*` tools), not by the user.
+
+**Schedule kinds.**
+
+- `once(at)`
+- `daily(time, weekdays?)`
+- `weekly(days, time)`
+- `every(N minutes)`, with N โ‰ฅ 15
+- `cron`, under "advanced"
+
+The time zone is the system's IANA zone, stored on the rule when it is created. The schedule is shown back in words for confirmation, for example ใ€Œๆฏไธชๅทฅไฝœๆ—ฅ 08:00๏ผˆAsia/Shanghai๏ผ‰ใ€.
+
+**Mechanics.**
+
+- `rules.next_run_at` holds the next time, and a single timer is set for the earliest one.
+- When Electron's `powerMonitor` reports a resume or a clock change, the host recomputes.
+- A firing creates a Run with cause `schedule`, which then waits for a slot.
+
+**Missed runs.** The app may have been off or asleep at the due time. A run missed by less than its grace period runs once, at start. The grace period is the smaller of half the interval and 2 h. Anything older is recorded as `skipped (app not running)`. We never catch up a backlog.
+
+**Authoring.**
+
+- 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 ไปทๆ ผใ€‚ๅ…ˆ่ง‚ๅฏŸๅ‡ ๅคฉ๏ผŒๅช่ฎฐๅฝ•ไธๆ‰“ๆ‰ฐไฝ ๏ผ›ๅœจใ€ŒไปปๅŠกใ€้‡Œๅฏไปฅๆ”นๆˆๆ‰ง่กŒใ€‚ใ€
+
+## 5. Observe mode
+
+| | Observe | Act |
+| --- | --- | --- |
+| Runs on schedule | yes | yes |
+| Sandbox | `read-only` (per session; `amb-permission` needs a per-session preset map) | the rule's cap (see [permissions](#7-permissions)) |
+| Tools | denied: acting tools (computer use, `generate_image` and `generate_video`, `remember` and `forget`, `present`, `task_start`, `rule_create`) | per rule |
+| Approvals | rejected automatically, recorded as "would need approval: โ€ฆ" | โ†’ needs you (TTL 1 h) |
+| 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 observed runs, the rule row shows a quiet hint ใ€Œๅทฒ่ง‚ๅฏŸ 3 ๆฌก ยท ๆ”นไธบๆ‰ง่กŒ๏ผŸใ€. The hint is never pushed. The user switches in the UI 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.
+- **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.
+
+## 6. Transparency without noise
+
+The PO's guidance: "provide enough transparency for users about what the (proactive) agent is doing, but not very verbose." The rule we follow is that the user can **always look**, and we push **only** what needs them.
+
+### What the user can always see, quietly
+
+Nothing below is ever pushed. It lives in the tasks view, the bot's info panel and the task detail.
+
+| For | Shown |
+| --- | --- |
+| Task | Title; stage dot and label; how long; cost so far (็บฆ $0.08 / $1.00); the first line of the latest Report as ๆœ€ๆ–ฐ่ฟ›ๅฑ•; the origin (channel, time and the user's words); the folder (with an "open" action); runs, each with its folded ๅค„็†่ฟ‡็จ‹ |
+| Rule | The user's words; schedule in words; mode; **last run** (time and outcome); **next run**; cost this month; the run log |
+| Rule run (observe) | ใ€Œๆœฌไผšๅ‘้€๏ผšโ€œโ€ฆโ€ใ€, ใ€ŒๆœฌไผšไฟๆŒๅฎ‰้™ใ€ or ใ€Œๆœฌไผšๅš๏ผšโ€ฆใ€; cost; steps |
+| Rule run (act) | ใ€Œๅทฒๅ‘้€๏ผšโ€œโ€ฆโ€ใ€ (with the delivery state) or ใ€ŒไฟๆŒๅฎ‰้™ใ€; cost; steps |
+
+### What is pushed, and only that
+
+| 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 or an approval, one at a time per conversation | A question the agent could answer with a reasonable default; 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.
+
+### Message shapes
+
+Every pushed message is one line, with an optional second line only for a blocker or a limit. Details are on demand: the user quotes or replies ใ€Œ่ฏฆๆƒ…ใ€, or opens the desktop view. Use no internal ids, no technical detail and no plans. Write in the language of the conversation. Emoji: only the existing โ“ for questions and โš ๏ธ for failures, which WeChat and Feishu need as markers. None for results. The UI strips them, per `ui/design/README.md`.
+
+| Purpose | WeChat (text) | Feishu (card) | Web / desktop |
+| --- | --- | --- | --- |
+| 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" |
+| 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 ไปทๆ ผ่ฐƒ็ ”๏ผšๆŠฅๅ‘Š็”จไธญๆ–‡่ฟ˜ๆ˜ฏ่‹ฑๆ–‡๏ผŸใ€ | | |
+
+### Communication rules and attention budget per channel
+
+These rules apply to every pushed message. Replies within a user's active chat turn are not affected.
+
+- **Coalescing:** messages for the same conversation due within 2 minutes merge into one message.
+- **Quiet hours,** default 22:00โ€“08:00 local time. Results and rule hits wait until the end of quiet hours. A question waits too, unless the user wrote to that conversation in the last 10 minutes.
+- **Daily cap on unsolicited messages,** per bot per conversation: **WeChat 3**, **Feishu 5**. Beyond the cap, results and rule hits roll into one digest at the next allowed time. Questions count toward the cap; once it is reached, a question waits in "needs you" instead of being pushed. A reply to a question doesn't count.
+- **One open pushed question per conversation.** Other tasks' questions wait in "needs you" until the first is answered. This keeps bare-number replies unambiguous on WeChat.
+- **Answering a task question.** On WeChat, a message is an answer only when it quotes the question, starts with its 4-digit code, or is a bare option number or label while the question is the bot's latest message. Anything else is ordinary chat. Today, any text answers a pending question (`ApprovalCenter.handleReply`). That is fine for a chat question with a turn waiting on it, but wrong for a task question that can wait for hours.
+- **Feishu:** reply in the thread of the request message when one exists. Results and questions are cards.
+- **Web/desktop:** an OS notification only for "needs you" items and for results the user asked for, only when the window isn't focused, and at most one per item. The tray badge is the needs-you count.
+
+### WeChat: the hard constraint
+
+iLink lets a bot message a user only with a `context_token` from that user's inbound message. AnyModelBot already treats this as hard.
+
+- In `src/channels/weixin/quota.ts`, each inbound message resets a **24 h window with 10 sends** (`QUOTA_PER_INBOUND`, `QUOTA_WINDOW_MS`). Once the window is over, `remaining()` is 0.
+- `WeixinChannel.notifyOwner()` gives up without a token or quota.
+- The upstream `openclaw-weixin` plugin also asks the user to "ensure the recipient has recently messaged the bot" for scheduled delivery.
+
+We have not verified whether iLink accepts a send without a fresh token. We must not rely on it, because that risks restrictions on the user's bot account.
+
+What follows:
+
+1. **A task result can be pushed only while the window opened by the user's latest message is open and has quota.** Most tasks finish well within 24 h.
+2. **A rule can't reach a WeChat user who hasn't written to the bot in the last 24 h.** No design changes that. We only choose what happens instead:
+ - **Reserve quota.** Each live task or act-mode rule bound to a WeChat peer reserves 1 send, and an open question 1 more, up to 3 in total. Chat replies use `remaining โˆ’ reserved`. The existing long-reply truncation note already handles running out.
+ - **Hold, don't drop.** A delivery that can't go out is held, with the reason `window_closed` or `quota`. It shows in "needs you" as ใ€Œ1 ๆก็ป“ๆžœ็ญ‰ไฝ ๅœจๅพฎไฟก้‡Œๅ‘ๆกๆถˆๆฏๆ‰่ƒฝ้€่พพใ€, with [ๅœจ่ฟ™้‡ŒๆŸฅ็œ‹]. It also gets one desktop notification.
+ - **Piggyback.** On the user's next inbound message, held items for that peer go out first, merged into one ใ€Œไฝ ไธๅœจๆ—ถ๏ผšโ€ฆใ€ message. Then the chat reply follows.
+ - **No keep-alive pings.** A ใ€Œ็ช—ๅฃๅฟซๅ…ณไบ†ใ€ message would be pure noise.
+ - **Be honest when a rule is created.** If a rule delivers to WeChat, the rule editor and the creation reply say ใ€Œๅพฎไฟกๅชๅœจไฝ  24 ๅฐๆ—ถๅ†…ๅ‘่ฟ‡ๆถˆๆฏๆ—ถๆ‰่ƒฝไธปๅŠจๅ‘็ป™ไฝ ๏ผ›ๅฆๅˆ™ไผšๅœจไฝ ไธ‹ๆฌกๅ‘ๆถˆๆฏๆ—ถไธ€่ตท้€ๅˆฐ๏ผŒๅนถๆ˜พ็คบๅœจๆกŒ้ข็ซฏใ€‚ใ€ For time-critical rules they suggest Feishu or desktop as the destination.
+ - **Fit one message.** A pushed message must fit one WeChat message (at most 4,000 characters; we aim for at most 300) and is never split.
+
+### Activity steps (ๅค„็†่ฟ‡็จ‹)
+
+Tasks reuse `ActivityLog` (`src/agent/activity.ts`) unchanged.
+
+- **Feeding:** a long-lived SDK subscription (`client.subscribe`, re-attached after every DSH start) feeds the task and rule sessions' events into one `ActivityLog` per Run.
+- **Storage:** `runs.activity` uses the same JSON as `messages.activity`. The cap is 120 steps per run, keeping the last 120 plus a count of dropped steps.
+- **Web:** live steps stream the way `LiveTurn` does today. The task detail shows runs as ใ€Œ็ฌฌ 2 ๆฌก ยท ๅ›ž็ญ”ๅŽ็ปง็ปญ ยท 9 ๆญฅ ยท 3 ๅˆ†้’Ÿใ€, each folded like the chat's ็”จๆ—ถ line.
+- **Chat:** the request message's task chip expands to the same folded steps.
+- **WeChat and Feishu:** steps are never pushed. ใ€Œ่ฏฆๆƒ…ใ€ returns the Report's summary in one message.
+- **Related fix:** today a chat turn that leaves a background job running stops being observed at idle. The job's wake-up turn is never delivered. The same subscription fixes this for chat sessions.
+
+### Auditing a rule
+
+Each rule has a run log, newest first, with one line per run: time, mode, outcome, cost.
+
+- ไปŠๅคฉ 08:00 ยท ่ง‚ๅฏŸ ยท ๆœฌไผšๅ‘้€๏ผšโ€œX ้™ไปทไบ†๏ผŒ็Žฐๅœจ ยฅ199๏ผˆๆ˜จๅคฉ ยฅ259๏ผ‰โ€ ยท ็บฆ $0.03
+- ๆ˜จๅคฉ 08:00 ยท ่ง‚ๅฏŸ ยท ๆœฌไผšไฟๆŒๅฎ‰้™๏ผˆยฅ259๏ผ‰ ยท ็บฆ $0.02
+- ๅ‰ๅคฉ 08:00 ยท ๅคฑ่ดฅ๏ผš้กต้ขๆ‰“ไธๅผ€๏ผˆๅทฒ้‡่ฏ• 3 ๆฌก๏ผ‰ ยท ็บฆ $0.01
+- 10/27 08:00 ยท ่ทณ่ฟ‡๏ผš็”ต่„‘ๆฒกๅผ€
+
+Expanding a row shows the Report (summary, message, would-do), the steps, the rule version it ran under and the permission it had. The log is kept for 90 days and is exportable as Markdown.
+
+### Calm defaults
+
+| Setting | Default |
+| --- | --- |
+| New rule mode | observe (except fixed reminders) |
+| 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 |
+| 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 % |
+| Observe โ†’ act hint | after 3 observed runs, shown in place, never pushed |
+| Desktop notifications | needs-you only, window unfocused, once per item |
+
+### Mock-ups
+
+These use `ui/design/README.md`:
+
+- grouping is a `--well` list (`.list`) with `--line-2` between rows, without borders or nesting;
+- small labels are `.t-label`;
+- state is a **dot plus text** (`.dot`): green for working, amber for needs you, red for failed, grey for done, off or observe;
+- no emoji;
+- **nothing is drawn when healthy.**
+
+**Sidebar.** A "้œ€่ฆไฝ " row appears above the bots only when the count is above 0. Bot avatars already have `working` (ๅŽๅฐไปปๅŠก) and `waiting` (็ญ‰ไฝ ๆ‰นๅ‡†) states.
+
+```
+โ”Œ side โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
+โ”‚ [ๆ–ฐๅปบ] [ไปปๅŠก] โ”‚ โ† ไปปๅŠก: icon button, opens the tasks view
+โ”‚ โŒ• ๆœ็ดข โ”‚
+โ”‚ โ— ้œ€่ฆไฝ  3 โ”‚ โ† only when > 0 (amber dot, .badge.count warn)
+โ”‚ (ๅฐ่“) ๅฐ่“ 2ๅˆ†้’Ÿ โ”‚ โ† avatar state "waiting"
+โ”‚ GPU ไปทๆ ผ่ฐƒ็ ”็ญ‰ไฝ ๅ›ž็ญ” 1 โ”‚
+โ”‚ (็บข้ญ”) ็บข้ญ” ๆญฃๅœจๅทฅไฝœโ€ฆ โ”‚ โ† avatar state "working", 1 task running
+โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
+```
+
+**Needs you** (main pane). Each row is self-contained, and its actions are inline.
+
+```
+้œ€่ฆไฝ 
+โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
+โ”‚ โ— ๅฐ่“ ยท GPU ไปทๆ ผ่ฐƒ็ ” ยท ็ญ‰ไฝ ๅ›ž็ญ” 2 ๅˆ†้’Ÿๅ‰ โ”‚
+โ”‚ ๆŠฅๅ‘Š็”จไธญๆ–‡่ฟ˜ๆ˜ฏ่‹ฑๆ–‡๏ผŸ โ”‚
+โ”‚ [ไธญๆ–‡] [่‹ฑๆ–‡] [ๅ›žๅคโ€ฆ] โ”‚
+โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚
+โ”‚ โ— ๅฐ่“ ยท ๆธ…็†ๆ—งๆž„ๅปบ ยท ็ญ‰ไฝ ๆ‰นๅ‡† 5 ๅˆ†้’Ÿๅ‰ โ”‚
+โ”‚ rm -rf build/ โ”‚
+โ”‚ [ๆ‰นๅ‡†ไธ€ๆฌก] [ๆ‹’็ป] โ”‚
+โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚
+โ”‚ โ— ็บข้ญ” ยท ่ง„ๅˆ™ใ€Œๆฏๆ—ฅ issue ๅทกๆฃ€ใ€่ฟž็ปญๅคฑ่ดฅ 3 ๆฌก๏ผŒๅทฒๆš‚ๅœ 08:00 โ”‚ red dot
+โ”‚ GitHub ่ฟ”ๅ›ž 401๏ผšไปค็‰Œๅฏ่ƒฝ่ฟ‡ๆœŸไบ† โ”‚
+โ”‚ [้‡่ฏ•] [ๆ‰“ๅผ€่ง„ๅˆ™] โ”‚
+โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚
+โ”‚ โ— ๅฐ่Œ ยท 1 ๆก็ป“ๆžœๆœช้€่พพๅพฎไฟก ๆ˜จๅคฉ โ”‚
+โ”‚ ไฝ  24 ๅฐๆ—ถๅ†…ๆฒกๅœจๅพฎไฟก้‡Œๅ‘ๆถˆๆฏ๏ผŒๅพฎไฟกไธๅ…่ฎธๆœบๅ™จไบบๅ…ˆๅ‘ใ€‚ โ”‚
+โ”‚ ๅœจๅพฎไฟก้‡Œ็ป™ๅฎƒๅ‘ไปปๆ„ไธ€ๆกๆถˆๆฏๅณๅฏๆ”ถๅˆฐใ€‚ โ”‚
+โ”‚ [ๅœจ่ฟ™้‡ŒๆŸฅ็œ‹] โ”‚
+โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚
+โ”‚ โ— ็ปฟ่‰ ยท ๅพฎไฟก็™ปๅฝ•ๅทฒ่ฟ‡ๆœŸ ไปŠๅคฉ โ”‚ red dot
+โ”‚ [้‡ๆ–ฐๆ‰ซ็ ] โ”‚
+โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
+```
+
+Order: questions and approvals first (time-sensitive), then failures, then deliveries, then the system (logins, stuck turns, budget). 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.
+
+```
+ไปปๅŠก [ๅ…จ้ƒจๆœบๅ™จไบบ โ–พ] [ๆ–ฐไปปๅŠก]
+่ฟ›่กŒไธญ
+โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
+โ”‚ โ— GPU ไปทๆ ผ่ฐƒ็ ” ๅฐ่“ ยท 12 ๅˆ†้’Ÿ ยท ็บฆ $0.08 โ€บ โ”‚ green
+โ”‚ โ— ๅญฃๅบฆๆŠฅๅ‘Š PPT ๅฐ่“ ยท ็ญ‰ไฝ ๅ›ž็ญ” โ€บ โ”‚ amber
+โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
+่ง„ๅˆ™
+โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
+โ”‚ โ—‹ ๆฏๅคฉ 08:00 ยท ็œ‹ X ไปทๆ ผ ่ง‚ๅฏŸไธญ ยท ไธ‹ๆฌก ๆ˜Žๅคฉ 08:00 โ€บ โ”‚ grey
+โ”‚ ๅทฒ่ง‚ๅฏŸ 3 ๆฌก ยท ๆ”นไธบๆ‰ง่กŒ๏ผŸ โ”‚ quiet hint, text button
+โ”‚ โ— ๆฏๅ‘จไธ€ 09:00 ยท issue ๅ‘จๆŠฅ ๆ‰ง่กŒไธญ ยท ไธŠๆฌก ๅ‘จไธ€ ยท ่ฏดไบ† 1 ๅฅ โ€บ โ”‚
+โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
+ๅทฒๅฎŒๆˆ ยท ๆœ€่ฟ‘ 7 ๅคฉ
+โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
+โ”‚ โ—‹ ๆ•ด็†ไธ‹่ฝฝ็›ฎๅฝ• ๅฐ่“ ยท ๆ˜จๅคฉ 18:20 ยท ็บฆ $0.02 โ€บ โ”‚
+โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
+```
+
+**Task detail** (the same pane, or a sheet on narrow windows):
+
+```
+GPU ไปทๆ ผ่ฐƒ็ ” [ๅœๆญข]
+โ— ่ฟ›่กŒไธญ ยท 12 ๅˆ†้’Ÿ ยท ็บฆ $0.08 / $1.00
+ๆฅ่‡ช ๅพฎไฟก ยท ไฝ  10:02 ใ€Œๅธฎๆˆ‘่ฐƒ็ ”ไธ€ไธ‹ไธ‰ๅฎถไบ‘็š„ GPU ไปทๆ ผโ€ฆใ€
+ๆœ€ๆ–ฐ่ฟ›ๅฑ• ๅทฒๆฏ”่พƒ 3 ๅฎถ๏ผŒๆญฃๅœจๆ ธๅฏน B ไบ‘็š„ๅŒ…ๅนดไปท
+ๆ–‡ไปถๅคน tasks/gpu-prices-3f2a1c [ๆ‰“ๅผ€]
+่ฟ่กŒ
+ ็ฌฌ 1 ๆฌก ยท ๅผ€ๅง‹ ยท 34 ๆญฅ ยท 12 ๅˆ†้’Ÿ โ–ธ (folded ๅค„็†่ฟ‡็จ‹)
+```
+
+**Rule detail:**
+
+```
+ๆฏๅคฉ 08:00 ยท ็œ‹ X ไปทๆ ผ [่ง‚ๅฏŸ | ๆ‰ง่กŒ] [็ซ‹ๅณ่ฟ่กŒ]
+ใ€Œๆฏๅคฉๆ—ฉไธŠ็œ‹็œ‹ X ็š„ไปทๆ ผ๏ผŒ้™ๅˆฐ 200 ไปฅไธ‹ๅ‘Š่ฏ‰ๆˆ‘ใ€
+ไธ‹ๆฌก ๆ˜Žๅคฉ 08:00 ยท ๆœฌๆœˆ ็บฆ $0.41 / $3.00 ยท ๅ‘ๅˆฐ ๅพฎไฟก๏ผˆ24 ๅฐๆ—ถ็ช—ๅฃ๏ผ‰
+่ฟ่กŒ่ฎฐๅฝ•
+ ไปŠๅคฉ 08:00 ๆœฌไผšๅ‘้€๏ผšโ€œX ้™ไปทไบ†๏ผŒ็Žฐๅœจ ยฅ199๏ผˆๆ˜จๅคฉ ยฅ259๏ผ‰โ€ ็บฆ $0.03 โ€บ
+ ๆ˜จๅคฉ 08:00 ๆœฌไผšไฟๆŒๅฎ‰้™๏ผˆยฅ259๏ผ‰ ็บฆ $0.02 โ€บ
+```
+
+**Bot info panel:** a "ไปปๅŠก" group (a `.list`) after ๆธ ้“ and ๅพ…ๅฎกๆ‰น, with open tasks and rules in one compact row each. It is absent when the bot has neither.
+
+## 7. Permissions
+
+| Work | Sandbox | Approvals | Denied tools (only those registered) |
+| --- | --- | --- | --- |
+| Chat (today) | bot preset | card in chat, TTL 10 min | none |
+| Task (a person asked) | bot preset, snapshotted at creation | โ†’ needs you, TTL 12 h, one at a time; the DSH call keeps waiting; the slot is released while it waits | `present`, `ask_user_question` (use `task_report`), `task_start`, `rule_create` |
+| Rule run, observe | `read-only` | rejected automatically, recorded | the above plus computer use, `generate_image` and `generate_video`, `remember` and `forget` |
+| Rule run, act | `min(bot preset, workspace-write)`; the user can grant "use the bot's preset" per rule | โ†’ needs you, TTL 1 h, then rejected and the run fails | computer use and media unless enabled on the rule |
+
+Notes:
+
+- **Full permission.** A task on a bot with full permission inherits it, because the user chose it. The rm -rf gate (`amb-delete-gate.mjs`) still asks, and its question goes to "needs you". A rule never gets full permission by default.
+- **The read fence, the bwrap shim and the stripped environment** (no real keys) apply unchanged: task sessions run in the same child.
+- **Bridge lookups must know task sessions.**
+ - `AgentManager.resolveConversation` falls back to "the only active chat". A task session's approval would go to the wrong conversation. It needs a session-to-task-to-conversation lookup.
+ - `mediaOp` refuses when no chat turn is active, so tasks can't generate media until it is changed.
+ - `amb-permission.mjs` forces the bot preset onto every session. It needs a per-session preset for observe and act runs.
+
+## 8. Cost controls
+
+- **Estimate:** usage comes from the `assistant/message` events the subscription already sees, multiplied by Modelflare's reference price (`src/account/model-info.ts`). It is stored on `runs` and summed on `tasks` and `rules`. It is labelled ใ€Œ็บฆใ€, because the bill is authoritative.
+- **Budgets:**
+ - **Per task** (default $1.00, adjustable when it is created or later): at 100 %, the turn is cancelled (P1), the stage becomes `needs-you/budget` and the needs-you item reads ใ€Œๅทฒ็”จ็บฆ $1.00๏ผŒๅ†็ป™ $1 ็ปง็ปญ๏ผŸใ€.
+ - **Per rule run** (default $0.10): the run ends `budget`.
+ - **Per rule per month** (default $3.00): the rule pauses, and a needs-you item appears.
+- **Protecting chat.** When a bot has a Modelflare budget key (`setBotBudget`), background runs stop once its remaining balance falls below 20 % of the limit. The rest stays for chat, and one needs-you item says so. Low account balance uses the existing alert.
+- **Time caps:** a task gets 4 h of running time, not counting time waiting for a person. Settling lasts at most 30 minutes after a turn ends. A rule run gets 15 minutes.
+- **Model choice:** a task uses the conversation's model. A rule may use the bot's `utilityModel` when it is set (Q5).
+
+## 9. Data model (sqlite, `src/store/db.ts`)
+
+Each kind of state has one writer:
+
+- **TaskService** writes tasks, rules, runs and inputs.
+- **The Outbox** writes deliveries.
+- **ApprovalCenter** writes approvals.
+
+```sql
+CREATE TABLE IF NOT EXISTS tasks (
+ id TEXT PRIMARY KEY, -- t_<12 hex>
+ bot_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
+ origin_message_id INTEGER NOT NULL DEFAULT 0, -- messages.id of the request
+ origin_ref TEXT NOT NULL DEFAULT '', -- channel handle to reply under (Feishu message_id); never a secret
+ title TEXT NOT NULL, brief TEXT NOT NULL,
+ session_id TEXT NOT NULL, folder TEXT NOT NULL, -- task-<id>, tasks/<slug>-<id6>
+ model TEXT NOT NULL DEFAULT '', permission TEXT NOT NULL,
+ budget_usd REAL NOT NULL, spent_usd REAL NOT NULL DEFAULT 0,
+ report TEXT NOT NULL DEFAULT '', -- latest Report JSON
+ ended_at INTEGER NOT NULL DEFAULT 0, end_reason TEXT NOT NULL DEFAULT '', -- done|stopped|archived
+ stopped_by TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
+CREATE INDEX IF NOT EXISTS tasks_open ON tasks(bot_id, ended_at);
+
+CREATE TABLE IF NOT EXISTS rules (
+ id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
+ title TEXT NOT NULL, instruction TEXT NOT NULL, -- 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
+ 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,
+ next_run_at INTEGER NOT NULL DEFAULT 0, failures INTEGER NOT NULL DEFAULT 0,
+ paused_reason TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
+CREATE INDEX IF NOT EXISTS rules_due ON rules(mode, next_run_at);
+
+CREATE TABLE IF NOT EXISTS runs (
+ id TEXT PRIMARY KEY, bot_id TEXT NOT NULL,
+ task_id TEXT NOT NULL DEFAULT '', rule_id TEXT NOT NULL DEFAULT '', -- exactly one is set
+ rule_version INTEGER NOT NULL DEFAULT 0, mode TEXT NOT NULL DEFAULT 'act',
+ session_id TEXT NOT NULL,
+ cause TEXT NOT NULL, -- launch|answer|followup|retry|continue|recover|schedule|manual
+ state TEXT NOT NULL, -- queued|running|settling|ended
+ outcome TEXT NOT NULL DEFAULT '', -- done|needs_you|failed|budget|stopped|interrupted|skipped
+ report TEXT NOT NULL DEFAULT '', would TEXT NOT NULL DEFAULT '',
+ activity TEXT NOT NULL DEFAULT '', -- ActivityStep[] JSON (โ‰ค120 + dropped count)
+ tokens_in INTEGER NOT NULL DEFAULT 0, tokens_out INTEGER NOT NULL DEFAULT 0, cost_usd REAL NOT NULL DEFAULT 0,
+ error TEXT NOT NULL DEFAULT '',
+ queued_at INTEGER NOT NULL, started_at INTEGER NOT NULL DEFAULT 0, ended_at INTEGER NOT NULL DEFAULT 0);
+CREATE INDEX IF NOT EXISTS runs_live ON runs(state, queued_at);
+CREATE INDEX IF NOT EXISTS runs_task ON runs(task_id, queued_at);
+CREATE INDEX IF NOT EXISTS runs_rule ON runs(rule_id, queued_at);
+
+-- What the host owes a session. It survives restarts, because DSH drops queued inbox messages (A.5).
+CREATE TABLE IF NOT EXISTS run_inputs (
+ id TEXT PRIMARY KEY, task_id TEXT NOT NULL DEFAULT '', rule_id TEXT NOT NULL DEFAULT '', run_id TEXT NOT NULL DEFAULT '',
+ kind TEXT NOT NULL, -- brief|answer|followup|note|recovery|nudge|schedule
+ text TEXT NOT NULL, from_person INTEGER NOT NULL DEFAULT 0,
+ message_id TEXT NOT NULL DEFAULT '', -- DSH inbox id once handed over
+ delivered_at INTEGER NOT NULL DEFAULT 0, taken_at INTEGER NOT NULL DEFAULT 0, -- taken = seen as user/message
+ created_at INTEGER NOT NULL);
+CREATE INDEX IF NOT EXISTS run_inputs_open ON run_inputs(task_id, taken_at);
+
+-- Outbox for pushed messages. If P2's outbox lands first, these columns move there.
+CREATE TABLE IF NOT EXISTS deliveries (
+ id TEXT PRIMARY KEY, -- stable: <task|rule run>:<purpose>[:n]
+ bot_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
+ task_id TEXT NOT NULL DEFAULT '', rule_id TEXT NOT NULL DEFAULT '', run_id TEXT NOT NULL DEFAULT '',
+ purpose TEXT NOT NULL, -- result|question|approval|failure|rule|digest|reminder
+ text TEXT NOT NULL, files TEXT NOT NULL DEFAULT '[]', card TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'pending', -- pending|held|sent|dropped
+ held_reason TEXT NOT NULL DEFAULT '', -- quiet_hours|window_closed|quota|daily_cap|channel_down|question_open
+ attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT NOT NULL DEFAULT '',
+ due_at INTEGER NOT NULL, sent_at INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL);
+CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);
+```
+
+`approvals` gets new columns (via the existing `COLUMNS` migration list):
+
+| Column | Meaning |
+| --- | --- |
+| `task_id` | The task that owns the request |
+| `run_id` | The run that raised it |
+| `blocking INTEGER` | 1 means a DSH call is waiting for the answer; 0 means a task question whose answer becomes a new input |
+| `expires_at = 0` (existing column) | No expiry |
+
+`ApprovalCenter.start()` stops expiring non-blocking task questions on restart. Per-bot settings (`taskSlots`, quiet hours, daily caps) go into the existing `bots.settings` JSON (`BotSettings`). `maxBackground` goes into the app config.
+
+## 10. API
+
+**HTTP** (`/amb/api`, same style as `src/web/server.ts`):
+
+| Route | Does |
+| --- | --- |
+| `GET /tasks?bot=&group=working\|needs\|ended` | List with stage, cost and the latest line |
+| `POST /tasks` `{botId, conversationId?, text, budgetUsd?}` | New task from the desktop |
+| `GET /tasks/:id` | Detail: origin, Report, runs (without steps), inputs, delivery state |
+| `GET /tasks/:id/runs/:run/activity` | Steps of one run |
+| `POST /tasks/:id/stop` ยท `/retry` ยท `/continue {text}` ยท `/budget {addUsd}` ยท `/archive` | Person actions |
+| `GET /rules?bot=` ยท `POST /rules {botId, conversationId, text}` (returns a draft: words, schedule, mode) ยท `PUT /rules/:id` ยท `DELETE /rules/:id` | Rules |
+| `POST /rules/:id/run` | Run now, in the rule's mode |
+| `GET /rules/:id/runs?before=` | Run log |
+| `GET /attention` | "Needs you" across bots: `{id, kind, botId, subject, line, actions[], since, severity}` |
+| `POST /attention/:id/:action` | answer, approve, deny, retry, open, dismiss (only for kinds that can be dismissed) |
+| `GET /agent` (existing) | Adds `attention: n` and `background: {botId: n}` so the 3 s and 6 s UI polls cover the sidebar |
+
+**Model-facing tools.** The plugin registers them by session kind.
+
+| Tool | Session | Shape |
+| --- | --- | --- |
+| `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 |
+| `task_report` | task and rule | `{state: progress\|needs_you\|done\|failed, summary, message?, question?: {question, options?, multiSelect?}, files?, would?}` |
+
+**Bridge** (child โ†’ host; the existing loopback with a per-launch token):
+
+- `POST /dsh/task-config {sessionId}` โ†’ `{kind, deny[], section, permission}`
+- `POST /dsh/task-report {sessionId, ...Report}`
+- `POST /dsh/task-settled {sessionId, killedJobs[]}`
+- `/dsh/ask` (existing) resolves task sessions to their task and conversation.
+
+**Control channel** (host โ†’ child; **P1**):
+
+- `steer(sessionId, text)`
+- `cancel(sessionId, {keepInbox})`
+- `setModel(sessionId, model)`
+- `inject(sessionId, text)`, which adds to history without waking the session. Used to give the chat session a note such as ใ€Œ[ๅŽๅฐไปปๅŠกใ€ŒXใ€ๅทฒๅฎŒๆˆ] โ€ฆใ€ when a result is delivered. Without it, the note is prefixed to the next chat input.
+- Optionally `stopBackground(sessionId)`: kill the session's jobs and release its subagents. The plugin can do this when it sees a cancel.
+
+## 11. Failure modes
+
+| Failure | Behaviour |
+| --- | --- |
+| DSH child crashes or is restarted (settings, `/stop` before P1) | Runs are `interrupted`; `recover` runs start when the child is back; untaken inputs are delivered again; a recovery note is sent ([restart](#restart-recovery)) |
+| App quits or the machine sleeps mid-run | Same as above at the next start; rules follow the missed-run policy |
+| `resumeSession` fails (history corrupt or missing) | New session `task-<id>-2`, briefed from the host's task record and the last Reports; the run log notes it |
+| Model provider 408, 429 or 5xx, or a network error | 3 retries with backoff (15, 30, 60 s); then `failed` โ†’ needs you |
+| Turn ends without a `task_report` | One nudge; then `failed` (ใ€Œๆฒกๆœ‰็ป™ๅ‡บ็ป“ๆžœใ€) |
+| Task loops without progress | The run's time cap and budget stop it; needs you |
+| Job runs forever | Killed 30 minutes after the turn ended; the session is told at its next turn |
+| Approval or question never answered | Blocking approval: rejected at its TTL; the task fails with ใ€Œๆ‰นๅ‡†่ถ…ๆ—ถใ€. Task question: stays in needs-you; no reminders; the task is archived after 14 days (Q9) |
+| Delivery fails (Feishu API, channel logged out) | Retries at 5 s doubling to 300 s; after 3 failures: needs-you `delivery`. Dropped only when the conversation no longer exists |
+| WeChat window closed or no quota | Held, piggybacked on the next inbound, shown in needs-you ([WeChat](#wechat-the-hard-constraint)) |
+| A rule floods (bad instruction) | Coalescing, the daily cap, then a digest; 3 failures in a row pause it; the monthly budget pauses it |
+| Rule edited during a run | The run finishes under its recorded version; the next run uses the new version |
+| 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 |
+| Disk growth (task folders, DSH session JSONL) | Retention: archive done tasks after 30 days, and offer to delete their folders and sessions; sizes are shown in the task detail (Q9) |
+
+## 12. Testing strategy
+
+- **Unit:**
+ - the stage function, row by row, like superagent's `stage.spec.ts`;
+ - next-run computation, including DST, time zones, `powerMonitor` resume and the missed-run grace;
+ - Outbox rules: quiet hours, caps, coalescing, the WeChat window, quota reservation and piggyback;
+ - slots, including the reserved person slot and priority order;
+ - Report validation;
+ - the recovery planner: which runs restart and which inputs are delivered again;
+ - `handleReply` routing for task questions (quote, code, bare number, ordinary chat).
+- **Integration against the real DSH and a mock model**, extending `test/agent.integration.test.ts` and `scripts/spikes/p3-tasks`:
+ - a task gets its own folder and ends `done` with its result delivered;
+ - question โ†’ answer โ†’ resume;
+ - stopping one task while chat and another task continue (needs P1);
+ - a job wake while settling;
+ - restart mid-run: the recovery note arrives once and no input is duplicated;
+ - the model-facing tool surface per session kind (no `present` or `ask_user_question` in tasks; `task_report` present; observe denies acting tools);
+ - an approval from a task session lands on the right conversation.
+- **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).
+
+## 13. Phased build plan
+
+Estimates are in developer-days and include tests.
+
+| Phase | Scope | Exit demo | Estimate | Depends on |
+| --- | --- | --- | --- | --- |
+| **3a Task core** | `tasks`, `runs` and `run_inputs` tables; TaskService; `amb-tasks.mjs` (decorate, `task_report`, settled); SDK session watcher; `task_start`, `task_message` and `task_list`; slots and the human lane; stages; result delivery to Web and Feishu, and to WeChat within the window; stop; restart recovery; task chip in chat; minimal list in the info panel | "Research Y" from WeChat runs in the background while chat continues, survives an app restart, and the result arrives in the same chat | 8 | **P1** (cancel, steer, per-session model) |
+| **3b Questions and needs-you** | Non-blocking task questions on approval cards (`approvals` columns); approvals from task sessions routed to the right conversation; the needs-you view and sidebar row; tray badge and OS notification; WeChat quote and code answer routing | A task asks ใ€Œไธญๆ–‡่ฟ˜ๆ˜ฏ่‹ฑๆ–‡๏ผŸใ€ on WeChat; the user answers by number; the task continues. Needs-you lists it on desktop and is empty after | 5 | 3a |
+| **3c Delivery and attention budget** | Outbox (or P2's); quiet hours; per-channel caps; coalescing and digest; WeChat quota reservation, hold and piggyback; delivery retries; failed-delivery attention | A result due at 23:00 arrives at 08:00. With the WeChat window closed, it waits, shows in needs-you, and arrives before the reply to the user's next message | 4 | 3a; coordinate with P2 |
+| **3d Rules and observe mode** | `rules` table; host Scheduler with missed-run policy; fresh session per run; observe (read-only, would-have-said) and act; fixed reminders; `rule_create` and the rule editor; run log; observeโ†’act hint; automatic pause | ใ€Œๆฏๅคฉ 08:00 ็œ‹ X ไปทๆ ผใ€ runs 3 days in observe with a readable log, then switches to act and pushes one line on a hit | 8 | 3a, 3c |
+| **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.
+
+## 14. Open questions for the product owner
+
+1. **Who decides "background"?** Is it the chat agent (`task_start` when work is long), only an explicit phrase from the user (ใ€ŒๅŽๅฐๅšใ€), or both? Proposal: the agent decides and says so in its reply, and the user can say ใ€Œ็›ดๆŽฅๅšใ€ to keep the work in chat.
+2. **Concurrency defaults:** 2 background runs per bot and 4 overall?
+3. **Budget defaults:** task $1.00, rule run $0.10, rule $3.00 per month. At the limit, should we ask (proposal) or stop silently?
+4. **Quiet hours:** 22:00โ€“08:00 by default? Should they be per user or per bot? Should questions also wait?
+5. **Models for rules:** should rules use the bot's `utilityModel` (cheaper) when it is set?
+6. **Fixed reminders:** do ใ€Œๆ˜Žๅคฉ 3 ็‚นๆ้†’ๆˆ‘โ€ฆใ€ reminders skip observe mode, as proposed? They involve no judgement.
+7. **Observe โ†’ act:** should we suggest act after 3 observed runs? Should editing a rule's instruction send it back to observe?
+8. **WeChat:** is it acceptable that a proactive result waits for the user's next WeChat message once the 24 h window is closed, while showing on desktop? Or should rules require Feishu or desktop as their destination? We recommend no keep-alive pings.
+9. **Retention:** how long do we keep done tasks, their folders, DSH sessions and run logs? Proposal: 30 days for tasks and 90 days for run logs, with a disk-usage line.
+10. **Groups:** in Feishu groups, who may start tasks and rules? Only allowed senders (P2's allowlist)? Who receives the questions?
+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?
+
+## 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:
+
+- `profile: "sdk"`;
+- a generated patch inserting `llm-pi-ai` provider `magpie`, `dsh-tool-ask-user` and `dsh-tool-present`;
+- a replaced environment with `DSH_PERMISSION_MODE=workspace-write`;
+- bwrap available;
+- a scripted Chat Completions mock as the model.
+
+A stand-in plugin, `spike-tasks.mjs`, runs in the child and plays the role of P1's control channel. Numbers below are from a run on Linux on 2026-10-31. DSH started in about 1โ€“2 s.
+
+### A.1 Can `@deepseek-ai/dsh-schedule` run under `sdk`? How does it fire?
+
+**No, not without importing the Web stack. And even if it ran, it isn't what we need. Answer: the host owns scheduling.**
+
+- Variant `schedule` inserts `@deepseek-ai/dsh-schedule`. DSH reports `schedule (@deepseek-ai/dsh-schedule): pending (waiting for service: sessionController)`, and `ctx.get('schedule')` is undefined.
+- The `sdk` profile (`dsh-base` + `dsh-sdk-app`) has no `sessionController` and no `workspaceRegistry`. Those come from `dsh-api-session-controller` and `dsh-workspace`, which only `dsh-web-app` loads.
+- Variant `schedule2` also inserts `dsh-workspace` and `dsh-api-session-controller`. The workspace service comes up, but the controller is `pending (waiting for service: fileUploads)`. It needs the rest of the Web API stack: `fileUploads`, `remoteAccess`, `typert` and so on. Its `static inject` lists 12 services.
+- **How it fires** (`dsh-schedule/lib/types/runtime.js`):
+ - one timer to the nearest due task;
+ - on fire, `sessionController.resolveAgent(task.sessionId)` restores the **original** session, `agent.followup(createUserMessage({ source: { kind: 'schedule' } }))` posts the reminder and `sessions.flush()` persists it;
+ - due recurring reminders of one session are delivered as one batch;
+ - on startup, all due tasks fire.
+
+ So a reminder becomes a model turn in the session that created it. In our setup that is a chat session the host only watches during `run()`, so the turn's output would reach no channel. It also has no observe mode, no attention budget and no per-channel rules, and the model manages it through the `schedule_*` tools.
+
+### A.2 Can a plugin create extra sessions with their own folders, run them concurrently, and stop or resume each one?
+
+**Yes. Stopping one session needs P1's control channel; the spike stands in for it.**
+
+- **Services under `sdk`:** present are `agents`, `sessions`, `sessionPersistence`, `workingDirectory`, `jobs`, `subagents`, `tools`, `systemPrompt`, `permissionPresets`, `storageDomain`, `loader` and `sessionProjections`. Absent are `sessionController`, `workspaceRegistry`, `agentPresets` and `schedule`. So `ctx.sessionController.create` and `ctx.workspaceRegistry` are **not available**. Instead:
+ - **In process:** `ctx.agents.create({ sessionId, meta: { cwd }, agentOptions })`, which is what the SDK server itself calls. Created `task-a` in `workspace/tasks/a`.
+ - **Over the SDK we already use:** `harness.session('task-b').setWorkingDirectory(dir)` followed by `run` or `prompt`. Created `task-b` in `workspace/tasks/b`. **Recommended:** a single owner, which also drains the session at shutdown.
+- **Own folder:** `pwd` in each session printed its own folder. `out-A.txt` and `out-B.txt` were written there under the `workspace-write` sandbox, because both folders are inside the bot workspace.
+- **Concurrency:** two task turns, each running `sleep 4` in bash, plus one chat turn. The chat replied in **63 ms**, and both task turns finished at **4.1 s** (concurrent, not 8 s).
+- **Stop one:** `agent.cancel({kind:'user'})` on `task-a` made it idle in **6 ms**. `task-b` still finished its own slow turn, and chat answered afterwards. The SDK protocol has no cancel or steer (`dsh-sdk-jsonrpc-server` handles only `initialize`, `session/prompt`, `resume`, `wait`, `working-directory get/set` and `shutdown`). That is why P1 is a hard dependency.
+- **Resume:** after closing and restarting DSH, `ctx.agents.resume({ resumeSessionId })` (in process) and `harness.resumeSession('task-b')` (SDK) both restored the sessions. Their working directories were kept.
+- **The host sees every session:** the SDK client's general `subscribe()` received `session.status` and `turn/*` notifications for `task-a`, a session the plugin created. "The runtime notifies for every session in its context" (`dsh-sdk-client`). A long-lived subscription can therefore observe tasks without `run()`.
+- **Per-session tools and prompt** (needed for Q3):
+ - `agent.ctx.tools.restrict({ deny: ['present', 'ask_user_question'] })` removed both tools from `task-a`'s model requests only; chat still had all 27.
+ - `agent.ctx.tools.register({ name: 'task_report', โ€ฆ })` added a tool to `task-a` only, and the call reached the plugin.
+ - `agent.ctx.systemPrompt.section(โ€ฆ)` added a prompt section.
+ - Doing this in an `agent/created` listener also covers sessions created over the SDK and sessions resumed after a restart: `task-b` and the resumed `task-a` both lacked the two tools.
+ - Gotcha: `restrict` throws on a tool name that isn't registered, for example `present` when the patch doesn't insert it. Deny lists must be filtered to known tools, as superagent's `workOnly` does.
+- **Limits:** we found no session cap in DSH. The real limits are:
+ - the shared model rate limit and key budget (one bridge, one key per bot);
+ - CPU and memory for tool processes;
+ - the shared sandbox root (the folder is a convention);
+ - DSH restarts end every session of the bot.
+
+### A.3 Agent presets: do they work under `sdk`, and do task workers need them?
+
+**They can be made to work, but they can't remove tools under `sdk`, so we don't need them.** Per-session `tools.restrict` and `systemPrompt.section` (A.2) do the job.
+
+- `agentPresets` is absent under `sdk`.
+- Variant `preset` inserts `@deepseek-ai/dsh-agent-preset-registry`, whose dependencies `loader` and `sessionProjections` are present, and one `@deepseek-ai/dsh-agent-preset`. The registry comes up. A session the plugin creates with `agents.create({ โ€ฆ, setup: ctx => presets.mount(ctx, 'amb-task') })` reports `composedPreset = 'amb-task'`.
+- The model still saw every globally registered tool. The only difference from chat (25 vs 27 tools) came from the `deny` hook. A preset adds a scoped plugin group, but under `sdk`, `dsh-base` registers the tools globally, and a preset can't remove them.
+- Sessions the SDK creates never mount a preset: `ctx.agents.create` is called without `setup`.
+- Superagent needs presets because it runs under the Web profile, where tools come from the preset. Its worker preset sets 5-second shell and job-wait limits. We can set per-call timeouts in the prompt or the tool guard if we ever need them.
+
+### A.4 Background jobs and subagents: can a task stay busy until they finish, and be woken by them?
+
+**Woken, yes. "Busy", the host or plugin has to compute.**
+
+- `BG-A` started `sleep 3; echo bgdone-A` with `run_in_background`. The turn ended, and the session became idle with the job still `running` (`jobs.list`).
+- When the job finished, DSH opened a **new turn** on its own after **3.1 s**. `dsh-tool-jobs` uses `completionDelivery: 'wakeup'` โ†’ `owner.followup(notice)`. The model received ใ€Œbackground job โ€ฆ finished [status: completed, exit code: 0]ใ€.
+- The host's subscription saw `running โ†’ turn/start โ†’ turn/end โ†’ idle โ†’ running โ†’ turn/start โ†’ turn/end โ†’ idle`.
+- Because DSH reports "idle" while jobs run, a Run must stay `settling` while `jobs.list()` shows owned running jobs or `subagents.waitForChildren(agent)` is pending. This is superagent's `untilQuiet`. The SDK's own `session/wait` already waits for subagents, but not for jobs.
+- The same mechanism means that today a chat session's background job wakes a turn after `run()` has returned. That reply reaches no one ([activity](#activity-steps-ๅค„็†่ฟ‡็จ‹)).
+
+### A.5 Persistence: what survives a restart, and what must the host store?
+
+Just before closing DSH, `task-a` was mid-turn (`HANG-A2`, a hung model call) with one more message queued (`QUEUED-A`) and a 600 s background job running. After restart and resume:
+
+| | Survived | Evidence |
+| --- | --- | --- |
+| Session history up to the last finished turn | yes | Later requests contained `TOOLS-A`, `PWD-A`, `SLOW-A`, `REPORT-A`, `BG-A`, the job notice and `LONGBG-A` |
+| Working directory per session | yes | Resumed `cwd` was `tasks/a` and `tasks/b` |
+| Files in the folder | yes | `out-A.txt` and `out-B.txt` were still there |
+| The interrupted turn's message (`HANG-A2`) | **no** | Absent from later model context. Likewise `HANG-A`, whose turn was cancelled earlier |
+| Queued inbox message (`QUEUED-A`) | **no** | After resume, `inbox: 0`, and it never reached the model |
+| Background job | **no** | `jobs.list` was empty after restart; no completion or kill notice reached the session |
+| Automatic continuation | **no** | No model request after resume until the host sent one |
+| Subagents | no (in process, per code) | `dsh-subagent-spawn-in-process` |
+| Pending approvals and questions | no | `ApprovalCenter.start()` expires them; the DSH call that waited for them is gone |
+| Plugin decoration (deny, tools, prompt) | re-applied | `agent/created` fires on resume (A.2) |
+
+**The host must store:**
+
+- tasks, rules and runs with their state;
+- every input with its delivered and taken markers. "Taken" is a `user/message` event with that message id; the spike shows untaken inputs are lost;
+- which runs were in flight, so they can be marked interrupted and get a recovery note;
+- the session id and folder;
+- Reports and the run log;
+- deliveries with stable ids;
+- questions and approvals with task ownership;
+- cost.
+
+DSH keeps only conversation history and the working directory.
+
+## Appendix B. What we take from dsh-superagent
+
+| Superagent | Here |
+| --- | --- |
+| Ticket stage table, first match wins (`core/stage.ts`) | The Task stage table ([section 2](#2-states-and-transitions)) |
+| Assignment; restart โ†’ "host restarted" + recovery note, oldest first | Run with outcome `interrupted` + `recover` run + recovery note |
+| `WorkerSlots` with an extra slot for a person's message, wakes before launches | Background slots with a reserved person slot and priority |
+| Background work holds the slot; 30-minute limit after a turn; job ends wake the worker (`executor/background.ts`) | Run `settling`; same limit; same mechanism through `dsh-tool-jobs` |
+| Inputs delivered or read; untaken inputs delivered again after a restart (`inputsRead`) | `run_inputs.delivered_at` and `taken_at` |
+| Accept mode `observe`: "would accept" recorded, nothing accepted | Rule `observe`: "would have said or done" recorded, nothing sent |
+| `human_action`: one structured question; the main session forwards it unchanged | `task_report.question` โ†’ Attention โ†’ card |
+| Communication prompt: message only for ready, decision or inability; one sentence; no progress | [Push rules](#what-is-pushed-and-only-that) and the task prompt section |
+| Worker tools exclude asking, presenting and scheduling; tools refused after the end (`WORK_TOOLS`, guard) | `restrict({deny})` and a guard, per session kind |
+| Panel: "does anything need me now?" first; healthy takes no space | Needs-you view and sidebar row |
+| Left out | Sources, Triggers, Threads, Eval, Mandate revalidation, Subscriptions, GitHub PR life cycle, Policy versions |
diff --git a/scripts/spikes/p3-tasks/driver.mjs b/scripts/spikes/p3-tasks/driver.mjs
new file mode 100644
index 0000000..fa1c305
--- /dev/null
+++ b/scripts/spikes/p3-tasks/driver.mjs
@@ -0,0 +1,256 @@
+// Phase 3 feasibility spike (evidence for docs/design/background-tasks-and-proactive.md, appendix A).
+// Starts the pinned DSH the way src/agent/host.ts does (sdk profile, generated patch, replaced env) against a
+// scripted Chat Completions mock, and probes what background tasks need. Not product code; never shipped.
+// Usage: node scripts/spikes/p3-tasks/driver.mjs [base|schedule|schedule2|preset] [runtimeDir]
+// base extra sessions with own folders, concurrency, per-session cancel, tool surface, job wake, restart
+// schedule @deepseek-ai/dsh-schedule inserted under the sdk profile
+// schedule2 dsh-schedule plus dsh-workspace and dsh-api-session-controller
+// preset dsh-agent-preset-registry and one preset, mounted on a session the plugin creates
+import http from 'node:http'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+
+const here = path.dirname(new URL(import.meta.url).pathname)
+const variant = process.argv[2] ?? 'base'
+const runtime = path.resolve(process.argv[3] ?? path.join(here, '../../../dsh-runtime'))
+const { DeepSeekHarness } = await import(pathToFileURL(path.join(runtime, 'node_modules/@deepseek-ai/dsh-sdk-client/lib/index.js')).href)
+
+const log = (...a) => console.log(new Date().toISOString().slice(11, 23), ...a)
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+const textOf = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((p) => p?.text ?? '').join('') : '')
+
+// ---------- scripted model ----------
+const requests = []
+const hung = []
+function plan(messages, tools) {
+ let i = messages.length - 1
+ while (i >= 0 && !(messages[i].role === 'user' && /[A-Z]+-[A-Z0-9]+/.test(textOf(messages[i].content)))) i--
+ const user = textOf(messages[i]?.content)
+ const after = messages.slice(i + 1)
+ const toolResults = after.filter((m) => m.role === 'tool').map((m) => textOf(m.content))
+ const laterUser = after.filter((m) => m.role === 'user').map((m) => textOf(m.content))
+ const m = /([A-Z]+)-([A-Z0-9]+)/.exec(user)
+ const [kind, tag] = m ? [m[1], m[2]] : ['', '']
+ if (kind === 'HANG') return { hang: true }
+ if (kind === 'TOOLS') return { text: `TOOLS-${tag}<<${tools.join(',')}>>` }
+ if (kind === 'PING') return { text: `PONG-${tag}` }
+ const bash = (command, extra = {}) => ({ tool: { name: 'bash', args: { description: 'run', command, ...extra } } })
+ if (kind === 'PWD') return toolResults.length ? { text: `PWD-${tag}<<${toolResults.join('|')}>>` } : bash(`pwd && echo hi > out-${tag}.txt && ls`)
+ if (kind === 'SLOW') return toolResults.length ? { text: `SLOWDONE-${tag}` } : bash(`sleep 4; echo slow-${tag}`, { timeoutMs: 20000 })
+ if (kind === 'BG') {
+ if (laterUser.some((t) => /bgdone|job/i.test(t))) return { text: `SAWJOB-${tag}<<${laterUser.join('|').slice(0, 300)}>>` }
+ return toolResults.length ? { text: `BGSTARTED-${tag}` } : bash(`sleep 3; echo bgdone-${tag}`, { run_in_background: true })
+ }
+ if (kind === 'LONGBG') return toolResults.length ? { text: `LONGBGSTARTED-${tag}` } : bash(`sleep 600`, { run_in_background: true })
+ if (kind === 'REPORT') return toolResults.length ? { text: `REPORTED-${tag}` } : { tool: { name: 'task_report', args: { state: 'ready', summary: `done ${tag}` } } }
+ return { text: `OK-${kind}-${tag}` }
+}
+const llm = http.createServer(async (req, res) => {
+ let raw = ''
+ for await (const c of req) raw += c
+ const url = req.url.split('?')[0]
+ if (url.endsWith('/models')) return void res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ object: 'list', data: [{ id: 'mock-agent', object: 'model' }] }))
+ const b = JSON.parse(raw || '{}')
+ const tools = (b.tools ?? []).map((t) => t.function?.name ?? t.name)
+ const step = b.tools ? plan(b.messages ?? [], tools) : { text: 'title' }
+ const lastUser = textOf((b.messages ?? []).filter((m) => m.role === 'user').at(-1)?.content).slice(0, 120)
+ requests.push({ at: Date.now(), lastUser, users: (b.messages ?? []).filter((m) => m.role === 'user').map((m) => textOf(m.content).slice(0, 40)), tools, step, toolOut: (b.messages ?? []).filter((m) => m.role === 'tool').map((m) => textOf(m.content).slice(0, 200)) })
+ if (step.hang) return void hung.push(res)
+ if (!b.stream) return void res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ choices: [{ message: { role: 'assistant', content: step.text ?? '' }, finish_reason: 'stop' }] }))
+ res.writeHead(200, { 'content-type': 'text/event-stream' })
+ const send = (o) => res.write(`data: ${JSON.stringify({ id: 'c1', object: 'chat.completion.chunk', model: b.model, ...o })}\n\n`)
+ if (step.tool) {
+ send({ choices: [{ index: 0, delta: { role: 'assistant', tool_calls: [{ index: 0, id: 'call_' + Math.random().toString(36).slice(2, 8), type: 'function', function: { name: step.tool.name, arguments: JSON.stringify(step.tool.args) } }] } }] })
+ send({ choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] })
+ } else {
+ send({ choices: [{ index: 0, delta: { role: 'assistant', content: step.text } }] })
+ send({ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })
+ }
+ send({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } })
+ res.end('data: [DONE]\n\n')
+})
+await new Promise((r) => llm.listen(0, '127.0.0.1', r))
+const llmUrl = `http://127.0.0.1:${llm.address().port}`
+
+// ---------- DSH child, as host.ts starts it ----------
+const root = fs.mkdtempSync(path.join(os.tmpdir(), `amb-p3-${variant}-`))
+const home = path.join(root, 'dsh'), workspace = path.join(root, 'workspace')
+fs.mkdirSync(home, { recursive: true }); fs.mkdirSync(workspace, { recursive: true })
+const portFile = path.join(home, 'spike-port')
+const y = JSON.stringify
+const patch = [
+ '- id: llm-pi-ai', ' config:', ' providers:', ' magpie:', ' displayName: anymodel', ' api: openai-completions',
+ ` baseURL: ${y(llmUrl + '/v1')}`, ' apiKeyEnv: AMB_MAGPIE_KEY', ' models:', ' - id: "mock-agent"', ' name: "mock-agent"',
+ ' contextWindow: 128000', ' maxTokens: 16000',
+ '- insert:', ' - id: spike-tasks', ` name: ${y(path.join(here, 'spike-tasks.mjs'))}`,
+ // as host.ts: the sdk profile has neither tool by default
+ ' - id: amb-tool-ask-user', " name: '@deepseek-ai/dsh-tool-ask-user'", ' - id: amb-present', " name: '@deepseek-ai/dsh-tool-present'",
+ ...(variant === 'schedule' ? [' - id: schedule', " name: '@deepseek-ai/dsh-schedule'"] : []),
+ ...(variant === 'schedule2' ? [' - id: workspace', " name: '@deepseek-ai/dsh-workspace'", ' - id: session-controller', " name: '@deepseek-ai/dsh-api-session-controller'",
+ ' - id: schedule', " name: '@deepseek-ai/dsh-schedule'", ' - id: tool-schedule', " name: '@deepseek-ai/dsh-tool-schedule'"] : []),
+ ...(variant === 'preset' ? [
+ ' - id: agent-preset-registry', " name: '@deepseek-ai/dsh-agent-preset-registry'", ' config:', ' default: amb-task',
+ ' - id: amb-task-preset', " name: '@deepseek-ai/dsh-agent-preset'", ' config:', ' id: amb-task', ' name: amb task', ' description: spike', ' order: 90',
+ ' plugins:', ' - id: time-context', " name: '@deepseek-ai/dsh-time-context'",
+ ] : []),
+ '',
+].join('\n')
+const patchFile = path.join(home, 'amb.patch.yml')
+fs.writeFileSync(patchFile, patch)
+const env = {
+ PATH: process.env.PATH, HOME: home, LANG: 'C.UTF-8', DSH_PERMISSION_MODE: 'workspace-write', AMB_MAGPIE_KEY: 'spike-key',
+ SPIKE_PORT_FILE: portFile, SPIKE_RUNTIME: runtime,
+}
+const harness = () => new DeepSeekHarness({ profile: 'sdk', patches: [patchFile], dshHome: home, env, cwd: workspace, processCwd: workspace,
+ provider: 'magpie', model: 'mock-agent', initializeTimeoutMs: 180000, shutdownTimeoutMs: 3000 })
+
+async function ctl(route, body = {}) {
+ for (let i = 0; i < 100 && !fs.existsSync(portFile); i++) await sleep(100)
+ const port = fs.readFileSync(portFile, 'utf8')
+ const r = await fetch(`http://127.0.0.1:${port}/${route}`, { method: 'POST', body: JSON.stringify(body) })
+ const j = await r.json()
+ if (!r.ok) throw new Error(`${route}: ${j.error}`)
+ return j
+}
+/** Host-side view: every session's status notifications reach the client, also for sessions the plugin created. */
+function watch(h) {
+ const seen = []
+ const sub = h.client.subscribe((n) => n.method === 'session.status' || (n.method === 'session.event' && ['turn/start', 'turn/end'].includes(n.params?.event?.type)))
+ ;(async () => { try { for await (const n of sub) seen.push({ t: Date.now(), m: n.method, id: n.params.sessionId, s: n.params.status ?? n.params.event.type }) } catch {} })()
+ return { seen, close: () => sub.close() }
+}
+async function until(fn, ms = 30000, label = 'condition') {
+ const t0 = Date.now()
+ while (Date.now() - t0 < ms) { if (await fn()) return Date.now() - t0; await sleep(100) }
+ throw new Error(`timeout waiting for ${label}`)
+}
+const reqFor = (re) => requests.filter((r) => re.test(r.lastUser) || r.step?.text && re.test(r.step.text))
+const textFor = (re) => requests.filter((r) => r.step?.text && re.test(r.step.text)).map((r) => r.step.text)
+const results = {}
+
+let h = harness()
+const t0 = Date.now()
+await h.start()
+log('dsh initialized in', Date.now() - t0, 'ms; variant', variant)
+const w = watch(h)
+results.probe = await ctl('probe')
+log('services', results.probe)
+
+if (variant === 'base') {
+ const dirA = path.join(workspace, 'tasks', 'a'), dirB = path.join(workspace, 'tasks', 'b')
+ // Task A: created in-process by the plugin, with tools denied, a prompt section and a host tool.
+ results.createA = await ctl('create', { sessionId: 'task-a', cwd: dirA, deny: ['present', 'ask_user_question'], section: 'You are working on a background task.', reportTool: true })
+ // Task B: created over the SDK the host already uses (session handle + working directory), no plugin call.
+ const sb = h.session('task-b')
+ results.createB = { cwd: await sb.setWorkingDirectory(dirB).catch(async (e) => { fs.mkdirSync(dirB, { recursive: true }); return sb.setWorkingDirectory(dirB) }) }
+ const chat = h.session('chat-1')
+ results.toolsB = (await sb.run('TOOLS-B')).finalResponse
+
+ // 1. tool surface per session
+ await ctl('followup', { sessionId: 'task-a', text: 'TOOLS-A' })
+ const rChat = await chat.run('TOOLS-CHAT')
+ await until(() => textFor(/TOOLS-A/).length, 30000, 'TOOLS-A')
+ const toolsA = reqFor(/TOOLS-A/)[0].tools, toolsChat = reqFor(/TOOLS-CHAT/)[0].tools
+ results.tools = { task: toolsA, chat: toolsChat, taskLacks: toolsChat.filter((t) => !toolsA.includes(t)), taskOnly: toolsA.filter((t) => !toolsChat.includes(t)) }
+ log('tools', results.tools.taskLacks, results.tools.taskOnly, rChat.finalResponse)
+
+ // 2. own folder per session
+ await ctl('followup', { sessionId: 'task-a', text: 'PWD-A' })
+ const rB = await sb.run('PWD-B')
+ await until(() => textFor(/PWD-A<</).length, 30000, 'PWD-A')
+ results.folders = { a: textFor(/PWD-A<</)[0], b: rB.finalResponse, aFile: fs.existsSync(path.join(dirA, 'out-A.txt')), bFile: fs.existsSync(path.join(dirB, 'out-B.txt')) }
+ log('folders', results.folders)
+
+ // 3. concurrency: two slow task turns and a chat turn at once
+ const c0 = Date.now()
+ await ctl('followup', { sessionId: 'task-a', text: 'SLOW-A' })
+ const slowB = sb.run('SLOW-B')
+ const ping = await chat.run('PING-1')
+ const pingMs = Date.now() - c0
+ await slowB
+ await until(() => textFor(/SLOWDONE-A/).length, 30000, 'SLOW-A')
+ results.concurrency = { chatReplyMs: pingMs, bothSlowDoneMs: Date.now() - c0, chat: ping.finalResponse }
+ log('concurrency', results.concurrency)
+
+ // 4. cancel one session while another works
+ await ctl('followup', { sessionId: 'task-a', text: 'HANG-A' })
+ const slowB2 = sb.run('SLOW-B2')
+ await until(async () => (await ctl('status', { ids: ['task-a'] }))['task-a'].status === 'running', 10000, 'task-a running')
+ await ctl('cancel', { sessionId: 'task-a' })
+ const cancelMs = await until(async () => (await ctl('status', { ids: ['task-a'] }))['task-a'].status === 'idle', 10000, 'task-a idle after cancel')
+ const b2 = await slowB2
+ const ping2 = await chat.run('PING-2')
+ results.cancel = { taskAIdleAfterMs: cancelMs, taskBStillFinished: b2.finalResponse, chatAfter: ping2.finalResponse }
+ log('cancel', results.cancel)
+
+ // 5. report tool registered for task-a only
+ await ctl('followup', { sessionId: 'task-a', text: 'REPORT-A' })
+ await until(() => textFor(/REPORTED-A/).length, 30000, 'REPORT-A')
+ results.report = (await ctl('events')).filter((e) => e.type === 'report')
+ log('report', results.report)
+
+ // 6. a background job keeps the session's work alive past idle and wakes it when it ends
+ const j0 = Date.now()
+ await ctl('followup', { sessionId: 'task-a', text: 'BG-A' })
+ await until(() => textFor(/BGSTARTED-A/).length, 30000, 'BG started')
+ await until(async () => (await ctl('status', { ids: ['task-a'] }))['task-a'].status === 'idle', 10000, 'idle after BG start')
+ const jobsWhileIdle = await ctl('jobs', { sessionId: 'task-a' })
+ await until(() => textFor(/SAWJOB-A/).length, 30000, 'job wake')
+ results.jobs = { jobsWhileIdle, wokeAfterMs: Date.now() - j0, wakeText: textFor(/SAWJOB-A/)[0]?.slice(0, 200),
+ hostSawStatuses: w.seen.filter((e) => e.id === 'task-a' && e.t >= j0).map((e) => e.s) }
+ log('jobs', results.jobs)
+
+ // 7. restart: a hung turn, a queued message and a long job are in flight when the app closes DSH
+ await ctl('followup', { sessionId: 'task-a', text: 'LONGBG-A' })
+ await until(() => textFor(/LONGBGSTARTED-A/).length, 30000, 'long bg')
+ await until(async () => (await ctl('status', { ids: ['task-a'] }))['task-a'].status === 'idle', 10000, 'idle')
+ await ctl('followup', { sessionId: 'task-a', text: 'HANG-A2' })
+ await until(async () => (await ctl('status', { ids: ['task-a'] }))['task-a'].status === 'running', 10000, 'running')
+ await ctl('followup', { sessionId: 'task-a', text: 'QUEUED-A' })
+ const before = { status: await ctl('status', { ids: ['task-a', 'task-b'] }), jobs: await ctl('jobs', { sessionId: 'task-a' }) }
+ w.close()
+ await h.close()
+ for (const r of hung.splice(0)) r.destroy()
+ fs.rmSync(portFile, { force: true })
+ log('closed DSH; restarting')
+ const nReq = requests.length
+ h = harness()
+ await h.start()
+ const w2 = watch(h)
+ const resumedViaPlugin = await ctl('resume', { sessionId: 'task-a' })
+ const resumedB = await h.resumeSession('task-b')
+ const cwdB = await resumedB.getWorkingDirectory()
+ await sleep(3000)
+ const after = { status: await ctl('status', { ids: ['task-a'] }), jobs: await ctl('jobs', { sessionId: 'task-a' }),
+ newModelRequests: requests.slice(nReq).map((r) => r.lastUser), hostSaw: w2.seen.map((e) => `${e.id}:${e.s}`) }
+ // what the resumed task remembers: ask it to list what it saw
+ const rA = await (async () => { await ctl('followup', { sessionId: 'task-a', text: 'PING-AFTER' }); await until(() => textFor(/PONG-AFTER/).length, 30000, 'after'); return textFor(/PONG-AFTER/)[0] })()
+ const lastReq = reqFor(/PING-AFTER/)[0]
+ await ctl('followup', { sessionId: 'task-a', text: 'TOOLS-A2' })
+ await until(() => textFor(/TOOLS-A2/).length, 30000, 'TOOLS-A2')
+ results.toolsAfterRestart = textFor(/TOOLS-A2/)[0]
+ results.createdEvents = (await ctl('events')).filter((e) => e.type === 'created').map((e) => e.id)
+ results.restart = { before, resumedViaPlugin, cwdB, after, firstReplyAfterRestart: rA,
+ historyHasQueued: requests.some((r) => r.at > 0 && /QUEUED-A/.test(r.lastUser)), historyAfterRestart: lastReq?.users }
+ log('restart', JSON.stringify(results.restart, null, 1))
+ w2.close()
+}
+
+if (variant === 'preset') {
+ const dir = path.join(workspace, 'tasks', 'p')
+ results.preset = await ctl('create', { sessionId: 'task-p', cwd: dir, preset: 'amb-task' })
+ await ctl('followup', { sessionId: 'task-p', text: 'TOOLS-P' })
+ const chat = await h.session('chat-p').run('TOOLS-PCHAT')
+ await until(() => textFor(/TOOLS-P<</).length, 30000, 'TOOLS-P')
+ const tp = reqFor(/TOOLS-P</)[0]?.tools ?? reqFor(/TOOLS-P$/)[0]?.tools, tc = reqFor(/TOOLS-PCHAT/)[0].tools
+ results.presetTools = { sameAsChat: JSON.stringify([...tp].sort()) === JSON.stringify([...tc].sort()), presetCount: tp.length, chatCount: tc.length }
+ log('preset', results.preset, results.presetTools, chat.finalResponse)
+}
+
+await h.close()
+llm.close()
+fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(results, null, 2))
+log('done; results in', path.join(root, 'result.json'), '; stderr tail:', (h.client.stderrTail ?? []).slice(-5))
+process.exit(0)
diff --git a/scripts/spikes/p3-tasks/spike-tasks.mjs b/scripts/spikes/p3-tasks/spike-tasks.mjs
new file mode 100644
index 0000000..4c05f9e
--- /dev/null
+++ b/scripts/spikes/p3-tasks/spike-tasks.mjs
@@ -0,0 +1,117 @@
+// Phase 3 spike plugin (see driver.mjs), loaded into the DSH child like dsh-runtime/plugins/amb-*.mjs.
+// It answers loopback HTTP requests from the driver so the driver can probe in-process services and create,
+// prompt, steer, cancel, resume and inspect extra sessions. Not product code: a stand-in for P1's host->child
+// control channel, and for the task decoration a real amb-tasks plugin would do on agent/created.
+import http from 'node:http'
+import fs from 'node:fs'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+
+export const name = 'spike-tasks'
+
+const SERVICES = ['agents', 'sessions', 'sessionPersistence', 'workingDirectory', 'jobs', 'subagents', 'tools', 'systemPrompt',
+ 'permissionPresets', 'storageDomain', 'loader', 'sessionProjections',
+ 'sessionController', 'workspaceRegistry', 'agentPresets', 'schedule']
+
+export function apply(ctx) {
+ const portFile = process.env.SPIKE_PORT_FILE
+ const runtime = process.env.SPIKE_RUNTIME
+ if (!portFile || !runtime) return
+ const llm = import(pathToFileURL(path.join(runtime, 'node_modules/@deepseek-ai/dsh-llm/lib/index.js')).href)
+ const events = []
+ ctx.on('agent/status', ({ agent, status }) => { events.push({ t: Date.now(), type: 'status', id: String(agent.id), status }) })
+ ctx.on('session/event', (session, event) => {
+ if (['turn/start', 'turn/end', 'tool/call', 'user/message'].includes(event.type)) {
+ events.push({ t: Date.now(), type: event.type, id: String(session.id), source: event.data?.source?.kind, name: event.data?.name })
+ }
+ })
+
+ const agentOf = (id) => ctx.get('agents')?.get(id)
+ // Decorate every task session when DSH publishes it: created by this plugin, by the SDK, or resumed after a restart.
+ const decorated = new WeakSet()
+ ctx.on('agent/created', ({ agent }) => {
+ events.push({ t: Date.now(), type: 'created', id: String(agent.id) })
+ if (!String(agent.id).startsWith('task-') || decorated.has(agent)) return
+ decorated.add(agent)
+ agent.ctx.tools.restrict({ deny: ['present', 'ask_user_question'] })
+ })
+ const routes = {
+ async probe() {
+ await ctx.get('loader')?.await?.()
+ return Object.fromEntries(SERVICES.map((s) => [s, ctx.get(s) !== undefined]))
+ },
+ async create({ sessionId, cwd, deny, section, reportTool, preset }) {
+ fs.mkdirSync(cwd, { recursive: true })
+ const presets = ctx.get('agentPresets')
+ const handle = await ctx.get('agents').create({
+ sessionId,
+ meta: { cwd, ...(preset ? { agentPreset: preset } : {}) },
+ agentOptions: { provider: 'magpie', model: 'mock-agent' },
+ ...(preset && presets ? { setup: async (agentCtx) => { await presets.mount(agentCtx, preset) } } : {}),
+ })
+ const agent = handle.agent
+ if (deny?.length && !decorated.has(agent)) agent.ctx.tools.restrict({ deny })
+ if (section) agent.ctx.systemPrompt.section({ name: 'spike-task', order: 9999, text: section })
+ if (reportTool) {
+ agent.ctx.tools.register({
+ name: 'task_report',
+ description: 'Report the task state to the app.',
+ parameters: { type: 'object', properties: { state: { type: 'string' }, summary: { type: 'string' } }, required: ['state'] },
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_a, v) => [{ type: 'text', text: JSON.stringify(v) }] },
+ execute: async (args) => { events.push({ t: Date.now(), type: 'report', id: sessionId, ...args }); return { ok: true } },
+ })
+ }
+ return { id: String(agent.id), cwd: await ctx.get('workingDirectory').ensure(agent), composedPreset: presets?.composedPreset?.(agent.ctx) }
+ },
+ async followup({ sessionId, text }) {
+ const { createUserMessage } = await llm
+ const agent = agentOf(sessionId)
+ if (!agent) throw new Error('no agent ' + sessionId)
+ const message = createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
+ agent.followup(message)
+ return { messageId: message.id }
+ },
+ async steer({ sessionId, text }) {
+ const { createUserMessage } = await llm
+ const message = createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
+ agentOf(sessionId).steer(message)
+ return { messageId: message.id }
+ },
+ async cancel({ sessionId, keepInbox }) {
+ agentOf(sessionId).cancel({ kind: 'user' }, { keepInbox: !!keepInbox })
+ return {}
+ },
+ async status({ ids }) {
+ const out = {}
+ for (const id of ids) {
+ const a = agentOf(id)
+ out[id] = a ? { status: a.status, inbox: a.inbox.nextTurn.length + a.inbox.nextStep.length, cwd: await ctx.get('workingDirectory').ensure(a) } : null
+ }
+ return out
+ },
+ async jobs({ sessionId }) {
+ return (ctx.get('jobs')?.list(sessionId) ?? []).map((j) => ({ id: j.id, owner: j.owner, status: j.status }))
+ },
+ async resume({ sessionId }) {
+ const handle = await ctx.get('agents').resume({ resumeSessionId: sessionId, agentOptions: { provider: 'magpie', model: 'mock-agent' } })
+ const a = handle.agent
+ return { status: a.status, inbox: a.inbox.nextTurn.length + a.inbox.nextStep.length, cwd: await ctx.get('workingDirectory').ensure(a) }
+ },
+ async events() { return events.splice(0) },
+ }
+
+ const server = http.createServer(async (req, res) => {
+ let body = ''
+ for await (const c of req) body += c
+ const fn = routes[(req.url || '/').slice(1)]
+ try {
+ if (!fn) throw new Error('no route ' + req.url)
+ const out = await fn(JSON.parse(body || '{}'))
+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(out ?? {}))
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: String(e?.stack ?? e) }))
+ }
+ })
+ server.listen(0, '127.0.0.1', () => { fs.writeFileSync(portFile, String(server.address().port)) })
+ ctx.on('dispose', () => server.close())
+}