Skip to content

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

Phase 3a: background task core

Marlaeddfb75557c2
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.md
index c982645..f8725f3 100644
--- a/docs/design/background-tasks-and-proactive.md
+++ b/docs/design/background-tasks-and-proactive.md
@@ -1,6 +1,6 @@
# Background tasks and proactive rules (Phase 3 design)
-Status: **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/`.
+Status: **3a (task core) is built**: `src/tasks/`, `dsh-runtime/plugins/amb-tasks.mjs`, tests in `test/tasks.*.test.ts`. 3b–3f are still design. Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.
Feasibility evidence is in [Appendix A](#appendix-a-feasibility-answers-with-evidence). The spike that produced it is `scripts/spikes/p3-tasks/`.
## Summary
diff --git a/dsh-runtime/plugins/amb-control.mjs b/dsh-runtime/plugins/amb-control.mjs
index 9e9fbac..1c3b81a 100644
--- a/dsh-runtime/plugins/amb-control.mjs
+++ b/dsh-runtime/plugins/amb-control.mjs
@@ -14,6 +14,9 @@
// cancel {sessionId} cancel just this session's turn (agent.cancel), its subagents
// and the shell jobs the turn started
//
+// Ops this plugin does not know go to the handlers other plugins put on globalThis[Symbol.for('amb.control.handlers')]
+// (amb-tasks: task-quiet, task-stop), so there is one command channel per child.
+//
// Long shell commands move to background jobs (the host patches the shell timeouts); when one ends,
// tool-jobs wakes the idle session with its result and the host follows that turn like any other.
import { boundContextSummary, createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
@@ -254,7 +257,7 @@ export function apply(ctx) {
const run = async (cmd) => {
let out
try {
- const fn = handlers[cmd.op]
+ const fn = handlers[cmd.op] ?? globalThis[Symbol.for('amb.control.handlers')]?.[cmd.op]
if (!fn) throw new Error(`unknown command ${cmd.op}`)
out = { ok: true, result: await fn(cmd) }
} catch (e) {
diff --git a/dsh-runtime/plugins/amb-tasks.mjs b/dsh-runtime/plugins/amb-tasks.mjs
new file mode 100644
index 0000000..d9cc5dd
--- /dev/null
+++ b/dsh-runtime/plugins/amb-tasks.mjs
@@ -0,0 +1,252 @@
+// anymodel bot background tasks (MIT, part of anymodel bot).
+//
+// The host creates one DSH session per background task over the SDK (`task-<id>`, its own folder as working
+// directory) and owns tasks, runs and delivery. This plugin decorates those sessions on agent/created, which also
+// fires for sessions resumed after a restart:
+// - denies the chat-only tools (present, ask_user_question and the task tools; only registered names, since
+// tools.restrict throws on unknown ones),
+// - adds the task rules (AMB_TASK_RULES, written by the host) as the last system-prompt section,
+// - registers task_report, which reports the task's state to the host,
+// - refuses every tool call once the host has stopped the task.
+// Chat sessions get task_start / task_message / task_list; subagents get none of the task tools.
+//
+// Settling: when a task session goes idle the host asks `task-quiet` over the control channel (amb-control hands
+// the ops it does not know to this plugin). A session that still owns running background jobs or subagents is not
+// quiet; the plugin then watches it and posts /dsh/task-settled once it is idle with nothing running and nothing
+// queued for it, or stops its jobs AMB_TASK_SETTLE_MS (30 minutes) after its last turn and says which. `task-stop`
+// cancels the turn, its subagents and every job the session owns.
+import { defineTool } from '@deepseek-ai/dsh-tools'
+
+export const name = 'amb-tasks'
+export const inject = ['tools']
+
+/** Shared with amb-control: control-channel ops this plugin answers. */
+export const HANDLERS = Symbol.for('amb.control.handlers')
+export const CHAT_TOOLS = ['task_start', 'task_message', 'task_list']
+/** Tools a task session never gets (filtered to registered names before tools.restrict). */
+export const TASK_DENY = ['present', 'ask_user_question', 'rule_create', ...CHAT_TOOLS]
+export const SECTION = 'amb:task'
+/** After the bot's section (amb:bot, 20000): the task rules win over the chat rules. */
+export const ORDER = 20_100
+
+const SETTLE_MAX_MS = Number(process.env.AMB_TASK_SETTLE_MS) > 0 ? Number(process.env.AMB_TASK_SETTLE_MS) : 30 * 60_000
+const WATCH_MS = 1_000
+const live = (status) => status === 'running' || status === 'stopping'
+
+export const isTask = (id) => /^task-/.test(String(id ?? ''))
+
+function bridge() {
+ const url = process.env.AMB_BRIDGE_URL
+ const token = process.env.AMB_BRIDGE_TOKEN
+ if (!url || !token) return undefined
+ return async (path, body, signal) => {
+ const res = await fetch(url + path, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ signal,
+ })
+ if (!res.ok) throw new Error(`bridge ${path} ${res.status}`)
+ return res.json()
+ }
+}
+
+const TEXT_OUT = {
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
+ render: (_args, value) => [{ type: 'text', text: value.text }],
+}
+
+export function apply(ctx) {
+ const call = bridge()
+ const botId = process.env.AMB_BOT_ID ?? ''
+ const rules = process.env.AMB_TASK_RULES ?? ''
+ /** task sessions the host stopped: every tool call is refused */
+ const stopped = new Set()
+ /** task sessions being watched until they are quiet: id → { since, timer } */
+ const watching = new Map()
+
+ const agents = () => ctx.get('agents')
+ const jobs = () => ctx.get('jobs')
+ const sessionOf = (exec) => String(exec?.agent?.session?.id ?? exec?.agent?.id ?? '')
+
+ const host = async (path, body, signal) => {
+ if (!call) throw new Error('the app is not reachable')
+ const r = await call(path, { botId, ...body }, signal)
+ if (r?.error) throw new Error(String(r.error))
+ return { text: String(r?.text ?? '') }
+ }
+
+ // ---------- chat sessions: start, message and list background tasks ----------
+ if (call) {
+ const tool = (op) => (args, exec) => host('/dsh/task-tool', { sessionId: sessionOf(exec), op, args }, exec.signal)
+ ctx.tools.register(defineTool({
+ name: 'task_start',
+ description: 'Start a background task in its own session and folder; the user keeps chatting and the result is sent to this chat when done. Use it for work that clearly needs more than a few minutes or many steps (build, research, a report), or when the user asks for it in the background (后台做); not for what you can answer now, or when they want it done here (前台做). Then tell the user in one sentence what runs in the background; do not do the work yourself.',
+ parameters: {
+ title: { type: 'string', required: true, description: 'Short title in the user\'s language.' },
+ brief: { type: 'string', required: true, description: 'What to do and what result to give, at most 1,500 characters. The user\'s words and the recent chat are added automatically.' },
+ },
+ output: TEXT_OUT,
+ execute: tool('start'),
+ }))
+ ctx.tools.register(defineTool({
+ name: 'task_message',
+ description: 'Pass the user\'s message to one of their background tasks when they refer to it: a working task sees it at its next step, a finished one resumes with it.',
+ parameters: {
+ task: { type: 'string', required: true, description: 'Task id or part of its title.' },
+ text: { type: 'string', required: true, description: 'The message, in the user\'s words.' },
+ },
+ output: TEXT_OUT,
+ execute: tool('message'),
+ }))
+ ctx.tools.register(defineTool({
+ name: 'task_list',
+ description: 'List this chat\'s background tasks with their state and latest result.',
+ parameters: {},
+ output: TEXT_OUT,
+ execute: tool('list'),
+ }))
+ }
+
+ const known = (names) => {
+ const tools = ctx.get('tools') ?? ctx.tools
+ return names.filter((n) => {
+ try {
+ return tools.get(n) !== undefined
+ } catch {
+ return false
+ }
+ })
+ }
+
+ const reportTool = () => defineTool({
+ name: 'task_report',
+ description: 'Report this background task\'s state to the app. done: the task is finished. failed: you cannot finish it. For both, message is the one line the user receives (at most 300 characters, in their language): the result and where it is; files are files to send them. progress records progress and is never sent. After done or failed, end your turn.',
+ parameters: {
+ state: { type: 'string', required: true, enum: ['progress', 'done', 'failed'], description: 'done, failed, or progress.' },
+ summary: { type: 'string', required: true, description: 'What you did and found, for the record (not sent to the user).' },
+ message: { type: 'string', description: 'For done and failed: the one line for the user.' },
+ files: { type: 'array', items: { type: 'string' }, description: 'Paths of files to send to the user, relative to your folder.' },
+ },
+ output: TEXT_OUT,
+ execute: (args, exec) => host('/dsh/task-report', { sessionId: sessionOf(exec), ...args }, exec.signal),
+ })
+
+ // ---------- decorate task sessions (created over the SDK, or resumed after a restart) ----------
+ const decorated = new WeakSet()
+ ctx.on('agent/created', ({ agent }) => {
+ if (!agent || decorated.has(agent)) return
+ decorated.add(agent)
+ const id = String(agent.id ?? '')
+ try {
+ if (isTask(id)) {
+ const deny = known(TASK_DENY)
+ if (deny.length) agent.ctx.tools.restrict({ deny })
+ if (rules) agent.ctx.systemPrompt?.section({ name: SECTION, order: ORDER, interpolate: false, text: () => rules })
+ if (call) agent.ctx.tools.register(reportTool())
+ agent.ctx.tools.guard?.(() => (stopped.has(id) ? 'This background task was stopped by the user. Do not continue; end your turn.' : undefined))
+ } else if (agent.session?.header?.parentSession) {
+ // subagents (of chats and of tasks) do not start or manage tasks
+ const deny = known(CHAT_TOOLS)
+ if (deny.length) agent.ctx.tools.restrict({ deny })
+ }
+ } catch (e) {
+ ctx.logger?.warn?.(`amb-tasks: could not decorate ${id}: ${e?.message ?? e}`)
+ }
+ })
+
+ // ---------- settling and stop (control-channel ops) ----------
+ function descendants(agent) {
+ const registry = agents()
+ const out = []
+ const walk = (parent) => {
+ for (const a of registry?.list?.() ?? []) {
+ if (a !== parent && registry.isOwnedBy?.(a.id, parent)) {
+ out.push(a)
+ walk(a)
+ }
+ }
+ }
+ walk(agent)
+ return out
+ }
+ const runningJobs = (id) => (jobs()?.list(id) ?? []).filter((j) => j.owner === id && live(j.status))
+ const queued = (agent) => {
+ try {
+ return (agent.inbox?.nextTurn?.length ?? 0) + (agent.inbox?.nextStep?.length ?? 0)
+ } catch {
+ return 0
+ }
+ }
+ /** idle, no inbox, no running job or subagent */
+ const quiet = (agent) => agent.status === 'idle' && !queued(agent) && !runningJobs(String(agent.id)).length && !descendants(agent).some((a) => a.status === 'running')
+
+ async function killJobs(id, why) {
+ const registry = jobs()
+ const list = runningJobs(id)
+ const waits = list.map((j) => registry.wait(j.id, 5_000, id).catch(() => undefined))
+ for (const j of list) try { registry.kill(j.id, id, why) } catch {}
+ await Promise.all(waits)
+ return list.map((j) => String(j.description ?? j.command ?? j.id))
+ }
+
+ function unwatch(id) {
+ const w = watching.get(id)
+ if (w) clearTimeout(w.timer)
+ watching.delete(id)
+ }
+
+ /** Watch a task session until it is quiet twice in a row (a finished job wakes it a moment later), then report. */
+ function watch(id) {
+ if (watching.has(id)) return
+ const w = { since: Date.now(), calm: 0, timer: undefined }
+ watching.set(id, w)
+ const tick = async () => {
+ if (watching.get(id) !== w) return
+ const agent = agents()?.get(id)
+ let killedJobs = []
+ if (agent && agent.status !== 'idle') {
+ w.since = Date.now()
+ w.calm = 0
+ } else if (agent && !quiet(agent)) {
+ w.calm = 0
+ if (Date.now() - w.since < SETTLE_MAX_MS) return void (w.timer = setTimeout(tick, WATCH_MS))
+ killedJobs = await killJobs(id, 'the task stopped waiting for it')
+ for (const a of descendants(agent)) try { a.cancel({ kind: 'parent' }) } catch {}
+ } else if (agent && ++w.calm < 2) return void (w.timer = setTimeout(tick, WATCH_MS))
+ if (agent && agent.status !== 'idle') return void (w.timer = setTimeout(tick, WATCH_MS))
+ unwatch(id)
+ await call?.('/dsh/task-settled', { botId, sessionId: id, killedJobs }).catch(() => {})
+ }
+ w.timer = setTimeout(tick, WATCH_MS)
+ }
+
+ const handlers = (globalThis[HANDLERS] ??= {})
+ handlers['task-quiet'] = async ({ sessionId }) => {
+ const id = String(sessionId)
+ const agent = agents()?.get(id)
+ if (!agent || quiet(agent)) return { quiet: true }
+ watch(id)
+ return { quiet: false, jobs: runningJobs(id).map((j) => String(j.id)) }
+ }
+ handlers['task-stop'] = async ({ sessionId }) => {
+ const id = String(sessionId)
+ stopped.add(id)
+ unwatch(id)
+ const agent = agents()?.get(id)
+ if (!agent) return { running: false }
+ for (const child of descendants(agent)) try { child.cancel({ kind: 'parent' }) } catch {}
+ try { agent.cancel({ kind: 'user' }, { keepInbox: false }) } catch {}
+ const killed = await killJobs(id, 'stopped by the user').catch(() => [])
+ return { running: true, killed }
+ }
+
+ try {
+ ctx.on('agent/disposed', ({ agent }) => unwatch(String(agent?.id ?? '')))
+ ctx.on('dispose', () => {
+ for (const id of [...watching.keys()]) unwatch(id)
+ delete handlers['task-quiet']
+ delete handlers['task-stop']
+ })
+ } catch {}
+}
diff --git a/src/agent/bridge.ts b/src/agent/bridge.ts
index d69e66a..e876c5f 100644
--- a/src/agent/bridge.ts
+++ b/src/agent/bridge.ts
@@ -25,6 +25,8 @@ export interface BridgeHandlers {
control?: { poll(body: any, signal: AbortSignal): Promise<unknown>; result(body: any): void };
/** 服务端压缩:长会话的 /v1/responses 换上上游压缩过的历史(见 server-compaction.ts) */
compaction?: ServerCompaction;
+ /** amb-tasks 插件:task_report(report)、收尾结束(settled)、聊天代理的任务工具(tool) */
+ tasks?(route: "report" | "settled" | "tool", body: any): Promise<unknown>;
}
/** 模型代理的一次请求(故障排查的"测试代理"用它判断模型调用这一步) */
@@ -49,6 +51,7 @@ export const BOT_HEADER = "x-amb-bot";
* - /v1/*:模型代理(Chat Completions、Responses、Anthropic Messages),把令牌换成真实网关密钥(子进程环境里没有任何真实密钥)
* - /dsh/ask|wait|cancel:amb-bridge 插件的审批/提问长轮询
* - /dsh/control/poll|result:amb-control 插件取宿主的指令(中止、插话、换模型)并回报
+ * - /dsh/task-report|task-settled|task-tool:amb-tasks 插件(后台任务的报告、收尾结束、聊天代理的任务工具)
*/
export class AgentBridge {
readonly token = crypto.randomBytes(24).toString("base64url");
@@ -271,6 +274,9 @@ export class AgentBridge {
res.on("close", () => ac.abort());
out = await this.h.control.poll(body, ac.signal);
} else if (url === "/dsh/control/result" && this.h.control) out = (this.h.control.result(body), { ok: true });
+ else if (url === "/dsh/task-report" && this.h.tasks) out = await this.h.tasks("report", body);
+ else if (url === "/dsh/task-settled" && this.h.tasks) out = await this.h.tasks("settled", body);
+ else if (url === "/dsh/task-tool" && this.h.tasks) out = await this.h.tasks("tool", body);
else return void res.writeHead(404).end();
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(out));
}
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 48bab93..ba8a776 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -14,7 +14,7 @@ import { cuaConfig, cuaMcpEnv, discoverAppsCached, type CuaApp } from "./cua-dri
import { pwshPatchLines, pwshProbe } from "./pwsh.js";
import { DEFAULT_SETTINGS, permissionMode, type BotSettings } from "./settings.js";
import { acceptsImages } from "../llm/client.js";
-import { CUA_SKILL, MEDIA_SKILL, agentPersona, botPrompt } from "./prompts/index.js";
+import { CUA_SKILL, MEDIA_SKILL, TASK_RULES, agentPersona, botPrompt } from "./prompts/index.js";
const log = logger("agent.host");
@@ -169,6 +169,12 @@ export class ApiRejected extends Error {
}
}
+/** 后台任务的会话记录恢复不了(DSH 主目录里没有了或坏了):任务服务换一个新会话、重新交代 */
+export class ResumeFailed extends Error {}
+
+/** 设置变了、后台任务又一直在跑:最多等这么久就重启代理进程(任务随后恢复) */
+export const TASK_RESTART_WAIT_MS = 10 * 60_000;
+
/** 换接口重做时交给模型的话(上一条用户消息已经在会话里) */
export const RETRY_NOTE = "[系统提示]\n上一条用户消息因模型接口不兼容没有处理,现已换用其它接口。请直接处理上面那条用户消息。";
@@ -194,6 +200,8 @@ export interface AgentHostOptions {
apiFallbacks?: ApiFallbacks;
/** 代理自己醒来开了一轮(后台命令结束):调用方用 followTurn 跟踪它,把回复发到会话里 */
onWake?: (conversationId: string, sessionId: string) => void;
+ /** 后台任务会话(task-*)和它们子代理的通知:root 是任务会话 id(任务服务据此记步骤、判断这一轮结束) */
+ onTaskEvent?: (root: string, n: SdkNotification) => void;
}
export type HostState = "stopped" | "starting" | "running" | "backoff" | "error";
@@ -605,6 +613,12 @@ export class AgentHost {
private pwshPath: string | undefined;
/** 进入 runOnce 还没结束的回合(含还在等进程、等会话的):有就不在后台重启 */
private entering = 0;
+ /** 当前子进程里打开过的任务会话(子代理的通知按它们归属) */
+ private taskSessions = new Set<string>();
+ /** 正在跑一轮的任务会话:有就不为设置变化重启(最多等 TASK_RESTART_WAIT_MS) */
+ private taskBusy = new Set<string>();
+ /** 设置变了、等着重启的起点(0 = 没在等) */
+ private staleSince = 0;
constructor(private o: AgentHostOptions) {}
@@ -702,6 +716,9 @@ export class AgentHost {
// 宿主 → 代理进程的指令通道:按会话中止、插话、按会话选模型;长命令转后台后等它的结果
" - id: amb-control",
` name: ${yamlStr(path.join(this.o.runtimeDir, "plugins", "amb-control.mjs"))}`,
+ // 后台任务:聊天会话的 task_start / task_message / task_list;任务会话的限定工具、任务规则、task_report、收尾
+ " - id: amb-tasks",
+ ` name: ${yamlStr(path.join(this.o.runtimeDir, "plugins", "amb-tasks.mjs"))}`,
...this.computerUseLines(apps),
...this.fullAccessLines(),
"",
@@ -880,6 +897,8 @@ exec "$REAL" "$@"
AMB_BOT_ID: this.o.botId,
AMB_PROMPT_FILE: this.promptFile,
AMB_CONTROL_TOKEN: this.control.id,
+ // 任务会话的系统提示词段(amb-tasks 插件加在机器人段之后)
+ AMB_TASK_RULES: TASK_RULES,
};
// 时区:本进程设了 TZ 才传下去;没设就不设,子进程用系统时区(各平台都是,Windows 上 TZ 也只认 POSIX 写法)
if (process.env.TZ) env.TZ = process.env.TZ;
@@ -973,8 +992,8 @@ exec "$REAL" "$@"
if (!this.harness && !this.starting && this.state === "error" && Date.now() < this.retryAfter) {
throw new Error(`代理进程启动失败,${Math.ceil((this.retryAfter - Date.now()) / 60_000)} 分钟后再试(或在 设置 → 故障排查 里重启代理进程):${this.lastError}`);
}
- if (this.harness && this.sig !== this.settingsSig() && this.active === 0) {
- log.info("bot settings or PowerShell changed, restarting dsh", { bot: this.o.botId });
+ if (this.harness && this.sig !== this.settingsSig() && this.active === 0 && this.tasksAllowRestart()) {
+ log.info("bot settings or PowerShell changed, restarting dsh", { bot: this.o.botId, backgroundTasks: this.taskBusy.size });
await this.closeHarness();
}
if (this.harness) return this.harness;
@@ -1010,12 +1029,25 @@ exec "$REAL" "$@"
return `${r.provider}|${r.model}`;
}
+ /**
+ * 设置变了时,后台任务允不允许重启:没有任务在跑一轮就可以;一直有就最多等 TASK_RESTART_WAIT_MS,
+ * 之后照样重启(跑着的任务记为中断,随后带着恢复说明接着做)。
+ */
+ private tasksAllowRestart(): boolean {
+ if (!this.taskBusy.size) {
+ this.staleSince = 0;
+ return true;
+ }
+ this.staleSince ||= Date.now();
+ return Date.now() - this.staleSince >= TASK_RESTART_WAIT_MS;
+ }
+
/**
* 设置或 PowerShell 变了(比如内置 PowerShell 7 刚装好、或者坏了退回)而且空闲:在后台重启子进程,
* 下一条消息不用再等启动。正在跑的回合不打断,等下一条消息时由 ensure() 换。
*/
async restartIfStale(): Promise<void> {
- if (!this.harness || this.starting || this.active > 0 || this.entering > 0 || this.stopped || this.sig === this.settingsSig()) return;
+ if (!this.harness || this.starting || this.active > 0 || this.entering > 0 || this.stopped || this.sig === this.settingsSig() || !this.tasksAllowRestart()) return;
const model = this.model;
log.info("bot settings or PowerShell changed while idle, restarting dsh in the background", { bot: this.o.botId });
await this.closeHarness();
@@ -1137,6 +1169,8 @@ exec "$REAL" "$@"
if (this.harness !== harness) return;
this.harness = undefined;
this.opened.clear();
+ this.taskSessions.clear();
+ this.taskBusy.clear();
this.control.close();
this.endWakes();
if (this.stopped) return;
@@ -1202,6 +1236,8 @@ exec "$REAL" "$@"
const h = this.harness;
this.harness = undefined;
this.opened.clear();
+ this.taskSessions.clear();
+ this.taskBusy.clear();
this.control.close("代理进程已重启");
this.endWakes();
if (!h) return;
@@ -1330,7 +1366,7 @@ exec "$REAL" "$@"
if (input.signal?.aborted) throw stopReason(input.signal);
if (!(await this.useRoute(s.id, route))) {
// 指令通道不通、或补不进这个模型:没有别的回合在跑时,带上这个模型重启子进程;忙的时候不能让这个会话悄悄用错模型
- if (this.active > 0) throw new Error(`暂时无法切换到模型 ${input.model}(代理进程正忙,没能在运行中加上这个模型),请稍后再试`);
+ if (this.active > 0 || this.taskBusy.size > 0) throw new Error(`暂时无法切换到模型 ${input.model}(代理进程正忙,没能在运行中加上这个模型),请稍后再试`);
log.warn("restarting dsh to use a model it could not add at runtime", { bot: this.o.botId, model: input.model });
this.known.add(input.model);
await this.closeHarness();
@@ -1482,6 +1518,16 @@ exec "$REAL" "$@"
* 把这一轮的事件交给跟踪它的人。宿主发起的一轮在它第一次空闲之前不算。
*/
private tap(n: SdkNotification): void {
+ // 后台任务的会话:交给任务服务(它自己判断一轮什么时候结束),不当成聊天会话的醒来
+ const root = this.taskRoot(n);
+ if (root) {
+ if (n.method === "session.status" && n.params?.sessionId === root) {
+ if (n.params.status === "running") this.taskBusy.add(root);
+ else if (n.params.status === "idle") this.taskBusy.delete(root);
+ }
+ this.o.onTaskEvent?.(root, n);
+ return;
+ }
for (const w of this.wakes.values()) if (!w.ended && this.relates(n, w.sessionId)) w.push(n);
// 每个会话最近的回合号(代理自己醒来的那一轮是下一个)
const ev = n.method === "session.event" ? n.params?.event : undefined;
@@ -1515,6 +1561,66 @@ exec "$REAL" "$@"
}
}
+ /** 通知属于哪个任务会话(task-* 本身,或它的子代理);不属于任务就是 undefined */
+ private taskRoot(n: SdkNotification): string | undefined {
+ const sub = n.method === "subagent.started" || n.method === "subagent.finished";
+ const sid = String((sub ? n.params?.parentSessionId : n.params?.sessionId) ?? "");
+ if (!sid) return undefined;
+ if (sid.startsWith("task-")) return sid;
+ if (!this.taskSessions.size) return undefined;
+ const c = this.harness?.client;
+ if (typeof c?.isDescendantOf !== "function") return undefined;
+ for (const t of this.taskSessions) if (c.isDescendantOf(sid, t)) return t;
+ return undefined;
+ }
+
+ /**
+ * 把一条输入交给后台任务的会话(SDK:session/prompt),返回 DSH 的收件 id,不等这一轮结束:
+ * 这一轮的事件经 onTaskEvent 交给任务服务。会话第一次用时建出来(工作目录是任务文件夹,在工作区里,沙箱根仍是工作区);
+ * 在新的子进程里先 resume(失败抛 ResumeFailed)。任务用它自己的模型(按会话选,和聊天一样不用重启)。
+ */
+ async promptTask(o: { sessionId: string; folder: string; model: string; text: string; resume: boolean }): Promise<string> {
+ if (!o.model) throw new Error("没有可用的模型");
+ const route = await this.routeFor(o.model);
+ const h = await this.ensure(o.model);
+ this.taskSessions.add(o.sessionId);
+ if (!this.opened.has(o.sessionId)) {
+ if (o.resume) {
+ try {
+ await h.resumeSession(o.sessionId);
+ } catch (e) {
+ throw new ResumeFailed((e as Error).message);
+ }
+ } else {
+ fs.mkdirSync(o.folder, { recursive: true });
+ await h.session(o.sessionId).setWorkingDirectory(o.folder);
+ }
+ this.opened.add(o.sessionId);
+ }
+ if (!(await this.useRoute(o.sessionId, route))) throw new Error(`代理进程无法使用模型 ${o.model}`);
+ this.known.add(o.model);
+ return await h.client.prompt(o.sessionId, [{ type: "text", text: o.text }]);
+ }
+
+ /** 并进任务正在进行的一轮(agent.steer,id 是我们的输入 id,会话里的用户消息用同一个 id);会话空闲时返回 false */
+ async steerTask(sessionId: string, id: string, text: string): Promise<boolean> {
+ if (!this.control.connected) return false;
+ const r = await this.control.send<{ accepted?: boolean }>("steer", { sessionId, id, text, images: [] }, 15_000);
+ return !!r.accepted;
+ }
+
+ /** 停掉任务会话(amb-tasks:取消这一轮、子代理和它的所有后台命令,之后的工具调用一律拒绝) */
+ async stopTask(sessionId: string): Promise<void> {
+ if (!this.harness || !this.control.connected) return;
+ await this.control.send("task-stop", { sessionId }, 15_000);
+ }
+
+ /** 任务会话空闲时,还有没有它的后台命令、子代理在跑(插件在它们结束后报 task-settled);通道不通按安静算 */
+ async taskQuiet(sessionId: string): Promise<{ quiet: boolean; jobs?: string[] }> {
+ if (!this.harness || !this.control.connected) return { quiet: true };
+ return await this.control.send<{ quiet: boolean; jobs?: string[] }>("task-quiet", { sessionId }, 15_000);
+ }
+
/** 通知属于这个会话或它的子代理 */
private relates(n: SdkNotification, root: string): boolean {
const c = this.harness?.client;
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index 8236d84..fa53a33 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -11,6 +11,7 @@ import { ApiFallbacks, type ApiFallback } from "./api-fallback.js";
import type { MediaModel, MediaPlan, MediaService } from "./media.js";
import { APPROVAL_TTL_MS, ApprovalCenter, type QuestionItem } from "./approvals.js";
import { MemoryError, MemoryStore, type Scope } from "./memory.js";
+import type { TaskHost, TaskService } from "../tasks/service.js";
import { DEFAULT_SETTINGS, type BotSettings, type MediaConfirm } from "./settings.js";
import {
HANDOFF_SYSTEM,
@@ -154,6 +155,8 @@ export class AgentManager {
/** 服务端压缩(经 bridge 改写长会话的 Responses 请求);没有注入时为空 */
readonly serverCompaction: ServerCompaction | undefined;
+ /** 后台任务服务(App 建好后接上):插件的 task_report / task-settled / 聊天工具经 bridge 交给它,任务会话的通知也给它 */
+ tasks: TaskService | undefined;
constructor(private o: AgentManagerOptions) {
this.approvals = new ApprovalCenter(o.store, { ttlMs: o.approvalTtlMs });
@@ -182,6 +185,14 @@ export class AgentManager {
result: (b) => this.hosts.get(String(b?.botId ?? ""))?.control.result(b),
},
compaction: this.serverCompaction,
+ tasks: async (route, b) => {
+ const t = this.tasks;
+ if (!t || !this.hosts.has(String(b?.botId ?? ""))) return { error: "background tasks are not available" };
+ if (route === "report") return t.report(b);
+ if (route === "settled") return t.settled(b);
+ if (route === "tool") return t.chatTool(b);
+ return { error: "unknown route" };
+ },
});
this.memory = new MemoryStore(path.join(o.dataDir, "memory"));
this.apiFallbacks = new ApiFallbacks(path.join(o.dataDir, "dsh", "api-fallback.json"));
@@ -219,10 +230,13 @@ export class AgentManager {
apiInfo: this.o.apiInfo,
apiFallbacks: this.apiFallbacks,
onWake: (conv) => this.onWake?.(botId, conv),
+ onTaskEvent: (root, n) => this.tasks?.onEvent(botId, root, n),
});
- // 代理进程退出(中止宽限期内没停下、设置变化、崩溃、重启、停止):进程里的压缩跟着没了,不再等它
+ // 代理进程退出(中止宽限期内没停下、设置变化、崩溃、重启、停止):进程里的压缩跟着没了,不再等它;跑着的后台任务记为中断、排恢复
h.on((e) => {
- if (e.type === "exit") this.endCompaction((c) => c.botId === botId);
+ if (e.type !== "exit") return;
+ this.endCompaction((c) => c.botId === botId);
+ this.tasks?.onChildExit(botId);
});
this.hosts.set(botId, h);
}
@@ -607,6 +621,8 @@ export class AgentManager {
*/
private async mediaOp(b: any): Promise<{ text?: string; error?: string }> {
const botId = String(b?.botId ?? "");
+ // 后台任务里还不能生成(确认要问用户,3b 才有任务的提问)
+ if (String(b?.sessionId ?? "").startsWith("task-")) return { error: "生成图片和视频暂时只能在聊天里用,后台任务里不行;需要的话在结果里告诉用户。" };
if (!this.hosts.has(botId) || !this.activeConvs.get(botId)?.size) return { error: "unknown bot" };
const media = this.o.media;
if (!media) return { error: "生成图片和视频需要连接 Modelflare" };
@@ -865,9 +881,32 @@ export class AgentManager {
return ids;
}
+ /** 任务服务用的宿主接口:每个机器人的代理进程 */
+ taskHost(): TaskHost {
+ const self = this;
+ return {
+ get available() {
+ return self.available;
+ },
+ workspace: (botId) => this.host(botId).workspace,
+ settings: (botId) => this.settings(botId),
+ memoryPrefix: (botId, conv) => this.memoryPrefix(botId, conv),
+ prompt: (botId, o) => {
+ if (!this.available) return Promise.reject(new Error("代理模式不可用"));
+ return this.host(botId).promptTask(o);
+ },
+ steer: (botId, sessionId, id, text) => this.hosts.get(botId)?.steerTask(sessionId, id, text) ?? Promise.resolve(false),
+ stop: async (botId, sessionId) => void (await this.hosts.get(botId)?.stopTask(sessionId)),
+ quiet: (botId, sessionId) => this.hosts.get(botId)?.taskQuiet(sessionId) ?? Promise.resolve({ quiet: true }),
+ };
+ }
+
private resolveConversation(botId: string, sessionId: string): string {
const c = this.o.store.conversationForSession(sessionId);
if (c) return c;
+ // 后台任务会话:落到请求它的会话(3b 再把审批推给用户)
+ const task = this.tasks?.conversationOf(sessionId);
+ if (task) return task;
const active = [...(this.activeConvs.get(botId) ?? [])];
return active.length === 1 ? active[0] : "";
}
diff --git a/src/agent/prompts/index.ts b/src/agent/prompts/index.ts
index 12b8f26..6967b8e 100644
--- a/src/agent/prompts/index.ts
+++ b/src/agent/prompts/index.ts
@@ -1,7 +1,8 @@
/**
- * 交给代理模型的提示词都在这个目录:系统提示词(system.ts)、每段第一条消息(segment.ts)、技能说明(skills.ts)。
+ * 交给代理模型的提示词都在这个目录:系统提示词(system.ts)、每段第一条消息(segment.ts)、技能说明(skills.ts)、后台任务(tasks.ts)。
* 工具说明在 dsh-runtime/plugins/*.mjs 里,和工具定义放在一起。
*/
export * from "./system.js";
export * from "./segment.js";
export * from "./skills.js";
+export * from "./tasks.js";
diff --git a/src/agent/prompts/tasks.ts b/src/agent/prompts/tasks.ts
new file mode 100644
index 0000000..f89f1a2
--- /dev/null
+++ b/src/agent/prompts/tasks.ts
@@ -0,0 +1,76 @@
+/**
+ * 后台任务的提示词:任务会话的系统提示词段(amb-tasks 插件加在机器人段之后,优先于聊天规则)、任务的第一条输入、
+ * 重启后的恢复说明、没有报告时的提醒。改这里的文字要过 test/prompts.unit.test.ts(必须有、不能有的句子和长度上限)。
+ *
+ * 沟通规则改编自 dsh-superagent(MIT,DeepSeek)的 worker 提示词:只在做完、需要决定或做不下去时说话,一句话,不汇报进展。
+ */
+
+/** 任务会话的系统提示词段:名字与位置(排在机器人段 amb:bot 之后,同时冲突时以它为准) */
+export const TASK_SECTION = "amb:task";
+export const TASK_SECTION_ORDER = 20_100;
+
+/** 任务会话的规则 */
+export const TASK_RULES = [
+ "# 后台任务(优先于上面的聊天规则)",
+ "你在后台独立完成一个任务,用户不在旁边看,也不会回答问题。任务和用户的原话在第一条消息里;当前目录是这个任务的文件夹,产出的文件放在这里。",
+ "- 不要问用户:需要决定时自己选一个合理的做法,在结果里说明。",
+ "- 做会改变外部的事(发送、发帖、付款、删除、调用会改动东西的接口)之前和之后,各在 .task/journal.md 里追加一行。",
+ "- 做完或做不下去时调用 task_report:state 为 done 或 failed,message 是给用户的一句话(不超过 300 字:结果是什么、在哪里),files 列出要发给用户的文件。然后结束这一轮。",
+ "- 中途不用汇报;想记下进展可以报 progress,不会发给用户。",
+ "- 不调用 task_report,用户就收不到任何结果。",
+].join("\n");
+
+export interface TaskBriefInput {
+ title: string;
+ /** 用户的原话(原样) */
+ original: string;
+ /** 对话助手写的说明(最多 1500 字) */
+ brief: string;
+ /** 请求之前的最近几条对话 */
+ recent: Array<{ role: "user" | "assistant"; text: string }>;
+ /** 附件在工作区里的路径(inbox/…) */
+ attachments: string[];
+ /** 冻结的记忆快照;undefined = 关着记忆 */
+ memory?: string;
+ /** 任务文件夹(相对工作区) */
+ folder: string;
+}
+
+const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+
+/** 任务的第一条输入:用户原话在最前(说明不能替代原话),再是说明、最近的对话、附件、记忆快照 */
+export function taskBrief(o: TaskBriefInput): string {
+ const parts = [`[后台任务]\n${o.title}(文件夹 ${o.folder})`, `[用户的原话]\n${o.original.trim()}`];
+ if (o.brief.trim()) parts.push(`[对话助手的说明]\n${clip(o.brief.trim(), 1500)}`);
+ if (o.recent.length) parts.push(`[之前的对话]\n${o.recent.map((m) => `${m.role === "user" ? "用户" : "助手"}:${clip(m.text.replace(/\s+/g, " ").trim(), 300)}`).join("\n")}`);
+ if (o.attachments.length) parts.push(`[附件]\n${o.attachments.join("\n")}`);
+ if (o.memory !== undefined) parts.push(`[长期记忆快照]\n${o.memory.trim() || "(目前为空)"}`);
+ return parts.join("\n\n");
+}
+
+/** 用户原话里提到的工作区附件(inbox/…) */
+export function attachmentsOf(text: string): string[] {
+ return [...new Set(text.match(/inbox\/[^\s\]]+/g) ?? [])];
+}
+
+/**
+ * 重启后的第一条输入(给模型的,英文,和技能说明一样):上一步可能没做完,后台命令被停了;重复外部动作之前先看日志和外部系统。
+ * jobs:被停掉的后台命令(没有就是 none)。
+ */
+export function recoveryNote(jobs: string[]): string {
+ const list = jobs.length ? jobs.join("; ") : "none";
+ return `The app restarted while you were working on this task. Your last step may not have finished, and these background jobs were stopped: ${list}. 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.`;
+}
+
+/** 一轮结束了却没有 task_report:提醒一次 */
+export const NUDGE = "Report this task's state with task_report now: state done with a one-line message for the user if it is finished, failed with the reason if you cannot finish it. If there is still work to do, do it first and then report.";
+
+/** 上一轮出错(模型请求失败等):过一会儿接着做 */
+export function retryNote(error: string): string {
+ return `Your previous step failed with an error: ${clip(error.replace(/\s+/g, " "), 300)}. Continue the task from where you were, and report with task_report when it is done.`;
+}
+
+/** 会话没法恢复、换了新会话:从宿主记下的任务重新交代一遍 */
+export function rebrief(brief: string, last: string | undefined): string {
+ return `${brief}\n\n[说明]\n之前的会话记录丢了,这是重新交代。${last ? `上次的进展:${clip(last, 600)}。` : ""}先看看文件夹里已经有什么,再接着做。`;
+}
diff --git a/src/agent/settings.ts b/src/agent/settings.ts
index 0dfd4a7..3c85bdd 100644
--- a/src/agent/settings.ts
+++ b/src/agent/settings.ts
@@ -46,6 +46,8 @@ export interface BotSettings {
* (包括这把 Key 已经花掉的);关闭时与其他机器人共用本机的 Key。
*/
budget: { enabled: boolean; limitUsd: number };
+ /** 后台任务最多同时跑几个(聊天不占名额;见 tasks/slots.ts) */
+ taskSlots: number;
}
export const DEFAULT_SETTINGS: BotSettings = {
@@ -57,6 +59,7 @@ export const DEFAULT_SETTINGS: BotSettings = {
utilityModel: "",
avatar: "",
budget: { enabled: false, limitUsd: 5 },
+ taskSlots: 2,
};
export function normalizeSettings(raw: unknown): BotSettings {
@@ -67,6 +70,7 @@ export function normalizeSettings(raw: unknown): BotSettings {
const bg = r.budget && typeof r.budget === "object" ? r.budget : {};
const md = r.media && typeof r.media === "object" ? r.media : {};
const limit = Number(bg.limitUsd);
+ const slots = Number(r.taskSlots);
const b = (v: unknown, d: boolean) => (typeof v === "boolean" ? v : d);
return {
permission: r.permission === "readonly" || r.permission === "full" ? r.permission : "workspace",
@@ -90,6 +94,7 @@ export function normalizeSettings(raw: unknown): BotSettings {
enabled: b(bg.enabled, DEFAULT_SETTINGS.budget.enabled),
limitUsd: Number.isFinite(limit) && limit >= 0 && limit <= 100_000 ? Math.round(limit * 100) / 100 : DEFAULT_SETTINGS.budget.limitUsd,
},
+ taskSlots: Number.isInteger(slots) && slots >= 1 && slots <= 8 ? slots : DEFAULT_SETTINGS.taskSlots,
};
}
diff --git a/src/app.ts b/src/app.ts
index e0cbb8d..6523828 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -42,6 +42,7 @@ import { loadModelInfo, type ModelInfo } from "./account/model-info.js";
import { MediaService, pickDefault } from "./agent/media.js";
import { COMPACT_ENDPOINT, serverCompactionEnabled, type CompactEndpoint } from "./agent/server-compaction.js";
import type { BotSettings } from "./agent/settings.js";
+import { TaskService } from "./tasks/service.js";
const log = logger("app");
@@ -117,6 +118,8 @@ export class App {
readonly outbox: Outbox;
/** 谁能和机器人对话:主人 + 允许名单 + 使用请求 */
readonly access: AccessControl;
+ /** 后台任务:自己的会话和文件夹,结果经出站队列回到请求它的会话 */
+ readonly tasks: TaskService;
web: WebServer | undefined;
desktop: DesktopHooks | undefined;
/** Modelflare 账户(登录、余额、预算);start() 时创建,桌面外壳的钥匙串那时已就绪 */
@@ -211,6 +214,15 @@ export class App {
: undefined,
onNotice: (text) => this.notice("warn", text),
});
+ this.tasks = new TaskService({
+ store: this.store,
+ host: this.agent.taskHost(),
+ outbox: this.outbox,
+ defaultModel: () => this.config.llm.defaultModel,
+ route: (botId, model) => this.routeModel(botId, model),
+ maxBackground: config.agent.maxBackground,
+ });
+ this.agent.tasks = this.tasks;
this.runtime = new BotRuntime({
agent: this.agent,
store: this.store,
@@ -385,6 +397,7 @@ export class App {
/** 删除机器人时一并删掉它的预算 Key */
async deleteBot(botId: string): Promise<void> {
const bot = this.store.getBot(botId);
+ this.tasks.dropBot(botId);
await this.stopBot(botId);
await this.agent.stopBot(botId);
if (bot?.settings.budget.enabled && this.account.signedIn) {
@@ -445,6 +458,8 @@ export class App {
this.outbox.start();
for (const bot of this.store.listBots()) await this.startBot(bot.id);
if (interrupted.length) void this.tellInterrupted(interrupted);
+ // 后台任务:上次没跑完的记为中断、带着恢复说明接着做(渠道已经上线,结果能发出去)
+ if (this.agent.available) this.tasks.start();
if (!this.opts.noWeb) this.web = await startWebServer(this);
if (this.magpie) {
// 启动时和之后每小时核对一次启用的模型(新上架的加入,下架的移出)
@@ -502,6 +517,8 @@ export class App {
async stop(): Promise<void> {
// 先告诉运行时:之后因为退出而失败的回合不回复、不改用纯对话,留给下次启动提醒
this.runtime.shutdown();
+ // 后台任务不再开始新的 run;跑着的留在库里,下次启动时恢复
+ this.tasks.stop();
this.offPwsh?.();
if (this.accountTimer) clearInterval(this.accountTimer);
if (this.picksTimer) clearInterval(this.picksTimer);
diff --git a/src/config.ts b/src/config.ts
index d3bdfab..31c91d2 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -41,7 +41,8 @@ export interface AppConfig {
* 代理宿主:dsh = DeepSeek Harness(工具/沙箱/审批);off = 纯对话。
* pwsh(Windows):auto = 系统里没有能用的 PowerShell 7 时用应用内置的(自动安装);system = 改回系统默认,不用内置的。
*/
- agent: { mode: "dsh" | "off"; turnTimeoutMs: number; idleTimeoutMs: number; approvalTtlMs: number; pwsh: "auto" | "system" };
+ /** maxBackground:所有机器人加起来最多同时跑几个后台任务 */
+ agent: { mode: "dsh" | "off"; turnTimeoutMs: number; idleTimeoutMs: number; approvalTtlMs: number; pwsh: "auto" | "system"; maxBackground: number };
}
export function defaultDataDir(): string {
@@ -108,6 +109,7 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEn
idleTimeoutMs: num(env.AMB_AGENT_IDLE_TIMEOUT_MS, file.agent?.idleTimeoutMs ?? 10 * 60_000),
approvalTtlMs: num(env.AMB_APPROVAL_TTL_MS, file.agent?.approvalTtlMs ?? 10 * 60_000),
pwsh: file.agent?.pwsh === "system" ? "system" : "auto",
+ maxBackground: num(env.AMB_MAX_BACKGROUND, file.agent?.maxBackground ?? 4),
},
};
}
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index f23dcb0..34ee6c9 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -17,6 +17,7 @@ import { pwshProbe, pwshStatusLine } from "../agent/pwsh.js";
import { isBotProviderModel } from "../modelflare.js";
import type { ApprovalRow, Conversation } from "../store/db.js";
import type { AccessControl } from "./access.js";
+import { takeTaskNotes } from "../tasks/service.js";
const log = logger("runtime");
@@ -110,6 +111,8 @@ const HELP = [
"/new — 开始新的一段对话:旧对话归档并生成交接便条,长期记忆保留",
"/status — 查看当前模型、代理状态和正在处理的消息走到了哪一步",
"/stop — 中止正在处理的消息(只停这个会话,机器人的其它会话照常进行)",
+ "/tasks — 列出这个会话的后台任务",
+ "/stop <编号> — 停止 /tasks 里的一个后台任务",
"/help — 显示本帮助",
].join("\n");
@@ -398,10 +401,20 @@ export class BotRuntime {
if (bot) return { handled: true, ack: cmd === "/help" ? HELP : this.statusText(bot.id, convId, this.opts.store.getConversation(convId)?.model ?? "", bot.defaultModel) };
}
const agent = this.opts.agent;
+ const tasks = agent?.tasks;
+ // 后台任务:/tasks 列出,/stop 编号 停止一个(只读本地状态、不碰聊天回合,不进会话队列)
+ if (cmd === "/tasks") return { handled: true, ack: tasks ? tasks.listText(convId) : "后台任务只在代理模式下可用。" };
+ const stopTask = /^\/stop\s+(\d{1,2})$/.exec(cmd);
+ if (stopTask) return { handled: true, ack: tasks ? tasks.stopByIndex(convId, Number(stopTask[1]), `${ev.channel}:${ev.sender.id}`) : "后台任务只在代理模式下可用。" };
// /stop 必须插队:它要停的正是排在前面、卡住的那个回合(纯对话、代理还在启动时也算)
if (cmd === "/stop") {
const since = this.busySince(convId) ?? agent?.turnsInProgress.get(convId)?.since;
- if (since === undefined || !this.stop(convId)) return { handled: true, ack: "当前没有正在处理的消息。" };
+ if (since === undefined || !this.stop(convId)) {
+ // 没有在处理的消息,但有后台任务在跑:说一声怎么停它(/stop 不停后台任务)
+ const working = tasks?.working(convId) ?? [];
+ const hint = working.length ? `\n后台任务在进行:${working.map((t, i) => `${i + 1}. ${t.title}`).join(";")}。发 /stop 编号 可停止。` : "";
+ return { handled: true, ack: `当前没有正在处理的消息。${hint}` };
+ }
return { handled: true, ack: `正在中止上一条消息(已处理 ${fmtSecs(Date.now() - since)})…` };
}
if (!agent) return { handled: false };
@@ -434,7 +447,10 @@ export class BotRuntime {
const turn = a?.turnsInProgress.get(convId);
const busy = turn ? [busyLine(turn.since, turn.lastProgress, turn.activity.steps, !!a?.canSteer(convId))] : [];
const who = this.opts.access ? [this.opts.access.policyLine(botId)] : [];
- return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...who, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
+ // 这个会话有后台任务在进行时说一句(没有就不说)
+ const working = a?.tasks?.working(convId) ?? [];
+ const bg = working.length ? [`后台任务:${working.map((t) => `「${t.title}」${t.stage.label}`).join(",")}`] : [];
+ return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...who, ...host, ...(ps ? [ps] : []), ...busy, ...bg, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
}
/** 卡片按钮回调:批准/拒绝/选择选项。 */
@@ -532,7 +548,10 @@ export class BotRuntime {
}
}
if (signal.aborted) return await stoppedEarly();
- const input = store.getAgentSession(convId) ? text : firstInput(agent, botId, convId, text, place);
+ const first = store.getAgentSession(convId) ? text : firstInput(agent, botId, convId, text, place);
+ // 后台任务的结果发出去之后,下一条聊天消息带上那张便条:聊天代理知道发生了什么
+ const notes = takeTaskNotes(store, convId);
+ const input = notes ? `${notes}\n\n${first}` : first;
// runTurn 同步登记回合,之后的停止交给代理(TurnStopped,会重启代理进程)
const turn = agent.runTurn(botId, {
conversationId: convId,
diff --git a/src/store/db.ts b/src/store/db.ts
index ed0f9ae..1dd679b 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -164,8 +164,146 @@ export interface OutboxRow {
dismissed: boolean;
}
+/**
+ * 后台任务(见 docs/design/background-tasks-and-proactive.md 第 9 节):一个人要求的后台工作,有自己的 DSH 会话与文件夹。
+ * Report 是代理经 task_report 报来的状态:message 是给用户的一句话,summary 只给内部看。
+ */
+export type ReportState = "progress" | "needs_you" | "done" | "failed";
+export interface TaskReport {
+ state: ReportState;
+ summary: string;
+ message?: string;
+ files?: string[];
+ /** 3b:要问用户的一个问题 */
+ question?: { question: string; options?: string[]; multiSelect?: boolean };
+ at: number;
+}
+export interface TaskRow {
+ id: string;
+ botId: string;
+ conversationId: string;
+ /** 请求那条用户消息(messages.id) */
+ originMessageId: number;
+ /** 回复到哪条渠道消息(飞书 message_id);不是密钥 */
+ originRef: string;
+ title: string;
+ brief: string;
+ sessionId: string;
+ /** 相对工作区:tasks/<slug>-<id6> */
+ folder: string;
+ model: string;
+ /** 建任务时机器人的权限预设(快照) */
+ permission: string;
+ budgetUsd: number;
+ spentUsd: number;
+ /** 最近一次 Report */
+ report: TaskReport | undefined;
+ endedAt: number;
+ /** done | stopped | archived */
+ endReason: string;
+ stoppedBy: string;
+ createdAt: number;
+ updatedAt: number;
+}
+export type RunState = "queued" | "running" | "settling" | "ended";
+export type RunOutcome = "" | "done" | "needs_you" | "failed" | "budget" | "stopped" | "interrupted" | "skipped";
+export type RunCause = "launch" | "answer" | "followup" | "retry" | "continue" | "recover" | "schedule" | "manual";
+/** 一段工作(一次启动、回答、追加、重试、恢复):占着名额直到结束 */
+export interface RunRow {
+ id: string;
+ botId: string;
+ taskId: string;
+ ruleId: string;
+ ruleVersion: number;
+ mode: string;
+ sessionId: string;
+ cause: RunCause;
+ state: RunState;
+ outcome: RunOutcome;
+ report: TaskReport | undefined;
+ would: string;
+ /** ActivityStep[] JSON(最多 120 步) */
+ activity: string;
+ tokensIn: number;
+ tokensOut: number;
+ costUsd: number;
+ error: string;
+ /** 结果交给出站队列 / 写进会话时的确定 id(交过就不再交) */
+ delivery: string;
+ queuedAt: number;
+ startedAt: number;
+ endedAt: number;
+}
+export type InputKind = "brief" | "answer" | "followup" | "note" | "recovery" | "nudge" | "schedule";
+/** 宿主欠会话的一条输入:交给 DSH 时记下收件 id(delivered),会话里出现这条用户消息时记下 taken;重启后没 taken 的再交一次 */
+export interface RunInputRow {
+ id: string;
+ taskId: string;
+ ruleId: string;
+ runId: string;
+ kind: InputKind;
+ text: string;
+ fromPerson: boolean;
+ messageId: string;
+ deliveredAt: number;
+ takenAt: number;
+ createdAt: number;
+}
+
type Row = Record<string, unknown>;
+/** JSON 列 → 对象;坏的、空的都当没有 */
+function parseJson<T>(v: unknown): T | undefined {
+ if (v == null || v === "") return undefined;
+ try {
+ return JSON.parse(String(v)) as T;
+ } catch {
+ return undefined;
+ }
+}
+
+/** 按字段名改一行:cols 是字段 → 列名,布尔值存 0/1,对象存 JSON */
+function updateRow(db: DatabaseSync, table: string, cols: Record<string, string>, id: string, patch: Record<string, unknown>): void {
+ const keys = Object.keys(patch).filter((k) => k in cols && patch[k] !== undefined);
+ if (!keys.length) return;
+ const vals = keys.map((k) => {
+ const v = patch[k];
+ if (typeof v === "boolean") return v ? 1 : 0;
+ if (v && typeof v === "object") return JSON.stringify(v);
+ return v as string | number;
+ });
+ db.prepare(`UPDATE ${table} SET ${keys.map((k) => `${cols[k]} = ?`).join(", ")} WHERE id = ?`).run(...vals, id);
+}
+
+const TASK_COLS: Record<string, string> = {
+ originRef: "origin_ref",
+ title: "title",
+ sessionId: "session_id",
+ model: "model",
+ spentUsd: "spent_usd",
+ report: "report",
+ endedAt: "ended_at",
+ endReason: "end_reason",
+ stoppedBy: "stopped_by",
+ updatedAt: "updated_at",
+};
+const RUN_COLS: Record<string, string> = {
+ sessionId: "session_id",
+ state: "state",
+ outcome: "outcome",
+ report: "report",
+ would: "would",
+ activity: "activity",
+ tokensIn: "tokens_in",
+ tokensOut: "tokens_out",
+ costUsd: "cost_usd",
+ error: "error",
+ delivery: "delivery",
+ startedAt: "started_at",
+ endedAt: "ended_at",
+};
+const INPUT_COLS: Record<string, string> = { runId: "run_id", messageId: "message_id", deliveredAt: "delivered_at", takenAt: "taken_at" };
+
const SCHEMA = `
CREATE TABLE IF NOT EXISTS bots (
id TEXT PRIMARY KEY, name TEXT NOT NULL, system_prompt TEXT NOT NULL DEFAULT '',
@@ -219,6 +357,31 @@ CREATE TABLE IF NOT EXISTS outbox (
sent_at INTEGER NOT NULL DEFAULT 0, dismissed INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS outbox_status ON outbox(status, seq);
CREATE INDEX IF NOT EXISTS outbox_bot ON outbox(bot_id, status);
+CREATE TABLE IF NOT EXISTS tasks (
+ id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
+ origin_message_id INTEGER NOT NULL DEFAULT 0, origin_ref TEXT NOT NULL DEFAULT '',
+ title TEXT NOT NULL, brief TEXT NOT NULL, session_id TEXT NOT NULL, folder TEXT NOT NULL,
+ 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 '', ended_at INTEGER NOT NULL DEFAULT 0, end_reason TEXT NOT NULL DEFAULT '',
+ 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 INDEX IF NOT EXISTS tasks_conv ON tasks(conversation_id, created_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 '',
+ rule_version INTEGER NOT NULL DEFAULT 0, mode TEXT NOT NULL DEFAULT 'act', session_id TEXT NOT NULL,
+ cause TEXT NOT NULL, state TEXT NOT NULL, outcome TEXT NOT NULL DEFAULT '',
+ report TEXT NOT NULL DEFAULT '', would TEXT NOT NULL DEFAULT '', activity TEXT NOT NULL DEFAULT '',
+ 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 '', delivery 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 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, text TEXT NOT NULL, from_person INTEGER NOT NULL DEFAULT 0,
+ message_id TEXT NOT NULL DEFAULT '', delivered_at INTEGER NOT NULL DEFAULT 0, taken_at INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL);
+CREATE INDEX IF NOT EXISTS run_inputs_open ON run_inputs(task_id, taken_at);
`;
/** 旧库补列(CREATE TABLE IF NOT EXISTS 不会改已有表)。 */
@@ -370,6 +533,9 @@ export class Store {
this.db.prepare("DELETE FROM agent_sessions WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM access WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM outbox WHERE bot_id = ?").run(id);
+ this.db.prepare("DELETE FROM run_inputs WHERE task_id IN (SELECT id FROM tasks WHERE bot_id = ?)").run(id);
+ this.db.prepare("DELETE FROM runs WHERE bot_id = ?").run(id);
+ this.db.prepare("DELETE FROM tasks WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM bots WHERE id = ?").run(id);
}
@@ -777,6 +943,160 @@ export class Store {
pruneOutbox(now = Date.now()): void {
this.db.prepare("DELETE FROM outbox WHERE (status = 'sent' AND updated_at < ?) OR (status = 'gone' AND updated_at < ?)").run(now - 7 * 86400_000, now - 30 * 86400_000);
}
+
+ // ---------- 后台任务(tasks / runs / run_inputs,只由 TaskService 写,见 tasks/service.ts) ----------
+ private toTask(r: Row): TaskRow {
+ return {
+ id: String(r.id),
+ botId: String(r.bot_id),
+ conversationId: String(r.conversation_id),
+ originMessageId: Number(r.origin_message_id),
+ originRef: String(r.origin_ref),
+ title: String(r.title),
+ brief: String(r.brief),
+ sessionId: String(r.session_id),
+ folder: String(r.folder),
+ model: String(r.model),
+ permission: String(r.permission),
+ budgetUsd: Number(r.budget_usd),
+ spentUsd: Number(r.spent_usd),
+ report: parseJson<TaskReport>(r.report),
+ endedAt: Number(r.ended_at),
+ endReason: String(r.end_reason),
+ stoppedBy: String(r.stopped_by),
+ createdAt: Number(r.created_at),
+ updatedAt: Number(r.updated_at),
+ };
+ }
+ insertTask(t: Omit<TaskRow, "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy">): TaskRow {
+ this.db
+ .prepare(
+ `INSERT INTO tasks(id, bot_id, conversation_id, origin_message_id, origin_ref, title, brief, session_id, folder, model, permission, budget_usd, created_at, updated_at)
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(t.id, t.botId, t.conversationId, t.originMessageId, t.originRef, t.title, t.brief, t.sessionId, t.folder, t.model, t.permission, t.budgetUsd, t.createdAt, t.updatedAt);
+ return this.getTask(t.id)!;
+ }
+ getTask(id: string): TaskRow | undefined {
+ const r = this.db.prepare("SELECT * FROM tasks WHERE id = ?").get(id) as Row | undefined;
+ return r ? this.toTask(r) : undefined;
+ }
+ /** 任务会话(task-…)属于哪个任务 */
+ taskBySession(sessionId: string): TaskRow | undefined {
+ const r = this.db.prepare("SELECT * FROM tasks WHERE session_id = ?").get(sessionId) as Row | undefined;
+ return r ? this.toTask(r) : undefined;
+ }
+ updateTask(id: string, patch: Partial<Pick<TaskRow, "originRef" | "title" | "sessionId" | "model" | "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy" | "updatedAt">>): void {
+ updateRow(this.db, "tasks", TASK_COLS, id, patch);
+ }
+ /** open:还没结束(停止、归档)的;since:之后更新过的 */
+ listTasks(opts: { botId?: string; conversationId?: string; open?: boolean; since?: number; limit?: number } = {}): TaskRow[] {
+ const where: string[] = [];
+ const args: Array<string | number> = [];
+ if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
+ if (opts.conversationId) (where.push("conversation_id = ?"), args.push(opts.conversationId));
+ if (opts.open !== undefined) where.push(opts.open ? "ended_at = 0" : "ended_at > 0");
+ if (opts.since) (where.push("updated_at >= ?"), args.push(opts.since));
+ const sql = `SELECT * FROM tasks ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY created_at DESC LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 100))}`;
+ return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toTask(r));
+ }
+
+ private toRun(r: Row): RunRow {
+ return {
+ id: String(r.id),
+ botId: String(r.bot_id),
+ taskId: String(r.task_id),
+ ruleId: String(r.rule_id),
+ ruleVersion: Number(r.rule_version),
+ mode: String(r.mode),
+ sessionId: String(r.session_id),
+ cause: String(r.cause) as RunCause,
+ state: String(r.state) as RunState,
+ outcome: String(r.outcome) as RunOutcome,
+ report: parseJson<TaskReport>(r.report),
+ would: String(r.would),
+ activity: String(r.activity),
+ tokensIn: Number(r.tokens_in),
+ tokensOut: Number(r.tokens_out),
+ costUsd: Number(r.cost_usd),
+ error: String(r.error),
+ delivery: String(r.delivery),
+ queuedAt: Number(r.queued_at),
+ startedAt: Number(r.started_at),
+ endedAt: Number(r.ended_at),
+ };
+ }
+ insertRun(r: Pick<RunRow, "id" | "botId" | "taskId" | "sessionId" | "cause" | "queuedAt">): RunRow {
+ this.db
+ .prepare("INSERT INTO runs(id, bot_id, task_id, session_id, cause, state, queued_at) VALUES(?, ?, ?, ?, ?, 'queued', ?)")
+ .run(r.id, r.botId, r.taskId, r.sessionId, r.cause, r.queuedAt);
+ return this.getRun(r.id)!;
+ }
+ getRun(id: string): RunRow | undefined {
+ const r = this.db.prepare("SELECT * FROM runs WHERE id = ?").get(id) as Row | undefined;
+ return r ? this.toRun(r) : undefined;
+ }
+ updateRun(id: string, patch: Partial<Pick<RunRow, "sessionId" | "state" | "outcome" | "report" | "would" | "activity" | "tokensIn" | "tokensOut" | "costUsd" | "error" | "delivery" | "startedAt" | "endedAt">>): void {
+ updateRow(this.db, "runs", RUN_COLS, id, patch);
+ }
+ /** 一个任务的 runs(旧→新);不含活动记录(大) */
+ listRuns(opts: { taskId?: string; botId?: string; states?: RunState[]; limit?: number } = {}): RunRow[] {
+ const where: string[] = [];
+ const args: Array<string | number> = [];
+ if (opts.taskId) (where.push("task_id = ?"), args.push(opts.taskId));
+ if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
+ if (opts.states?.length) (where.push(`state IN (${opts.states.map(() => "?").join(", ")})`), args.push(...opts.states));
+ const sql = `SELECT id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, outcome, report, would, '' AS activity, tokens_in, tokens_out, cost_usd, error, delivery, queued_at, started_at, ended_at
+ FROM runs ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY queued_at, rowid LIMIT ${Math.max(1, Math.min(1000, opts.limit ?? 500))}`;
+ return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toRun(r));
+ }
+ /** 任务最近的一个 run(不含活动记录) */
+ latestRun(taskId: string): RunRow | undefined {
+ const r = this.db
+ .prepare("SELECT id, bot_id, task_id, rule_id, rule_version, mode, session_id, cause, state, outcome, report, would, '' AS activity, tokens_in, tokens_out, cost_usd, error, delivery, queued_at, started_at, ended_at FROM runs WHERE task_id = ? ORDER BY queued_at DESC, rowid DESC LIMIT 1")
+ .get(taskId) as Row | undefined;
+ return r ? this.toRun(r) : undefined;
+ }
+
+ private toInput(r: Row): RunInputRow {
+ return {
+ id: String(r.id),
+ taskId: String(r.task_id),
+ ruleId: String(r.rule_id),
+ runId: String(r.run_id),
+ kind: String(r.kind) as InputKind,
+ text: String(r.text),
+ fromPerson: Number(r.from_person) === 1,
+ messageId: String(r.message_id),
+ deliveredAt: Number(r.delivered_at),
+ takenAt: Number(r.taken_at),
+ createdAt: Number(r.created_at),
+ };
+ }
+ insertInput(i: Pick<RunInputRow, "id" | "taskId" | "runId" | "kind" | "text" | "fromPerson" | "createdAt"> & Partial<Pick<RunInputRow, "messageId" | "deliveredAt">>): RunInputRow {
+ this.db
+ .prepare("INSERT INTO run_inputs(id, task_id, run_id, kind, text, from_person, message_id, delivered_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)")
+ .run(i.id, i.taskId, i.runId, i.kind, i.text, i.fromPerson ? 1 : 0, i.messageId ?? "", i.deliveredAt ?? 0, i.createdAt);
+ return this.toInput(this.db.prepare("SELECT * FROM run_inputs WHERE id = ?").get(i.id) as Row);
+ }
+ updateInput(id: string, patch: Partial<Pick<RunInputRow, "runId" | "messageId" | "deliveredAt" | "takenAt">>): void {
+ updateRow(this.db, "run_inputs", INPUT_COLS, id, patch);
+ }
+ /** 会话还没收下的输入(旧→新):下一个 run 开始时交给它 */
+ openInputs(taskId: string): RunInputRow[] {
+ return (this.db.prepare("SELECT * FROM run_inputs WHERE task_id = ? AND taken_at = 0 ORDER BY created_at, rowid").all(taskId) as Row[]).map((r) => this.toInput(r));
+ }
+ listInputs(taskId: string): RunInputRow[] {
+ return (this.db.prepare("SELECT * FROM run_inputs WHERE task_id = ? ORDER BY created_at, rowid").all(taskId) as Row[]).map((r) => this.toInput(r));
+ }
+ /** 会话里出现了这条用户消息(DSH 收件 id):记下 taken;返回记下了几条 */
+ takeInputs(taskId: string, messageId: string, at = Date.now()): number {
+ return Number(this.db.prepare("UPDATE run_inputs SET taken_at = ? WHERE task_id = ? AND message_id = ? AND taken_at = 0").run(at, taskId, messageId).changes);
+ }
+ /** 任务的会话建过(交出去过输入):之后要 resume */
+ taskPrompted(taskId: string): boolean {
+ return !!this.db.prepare("SELECT 1 FROM run_inputs WHERE task_id = ? AND delivered_at > 0 LIMIT 1").get(taskId);
+ }
}
function parseSettings(v: unknown): BotSettings {
diff --git a/src/tasks/service.ts b/src/tasks/service.ts
new file mode 100644
index 0000000..67149e6
--- /dev/null
+++ b/src/tasks/service.ts
@@ -0,0 +1,880 @@
+/**
+ * 后台任务服务(设计文档第 1–3、9–11 节,3a 部分):任务、run 与输入的唯一写入者。
+ *
+ * - 一个任务一个 DSH 会话(task-<id>)和一个文件夹(工作区里的 tasks/<slug>-<id6>/),由宿主经 SDK 建、恢复、发消息;
+ * amb-tasks 插件给这些会话限定工具、加任务规则和 task_report。
+ * - run 是一段工作:排队 → 跑(占名额)→ 收尾(会话空了但还有后台命令或子代理:settling,仍占名额)→ 结束。
+ * 名额见 slots.ts;聊天从不占名额(人的通道)。
+ * - 一轮结束、会话安静下来时按代理最近的 Report 结束这个 run:done / failed 的那一句经出站队列发回请求它的会话
+ * (微信在 24 小时窗口内,飞书回复在请求那条消息下),网页写进会话历史。没有 Report 就提醒一次,还没有就算失败。
+ * - 宿主欠会话的每条输入都落库(交出去时记 DSH 收件 id,会话里出现这条用户消息时记 taken)。应用重启或代理进程退出时,
+ * 跑着的 run 记为 interrupted,给任务排一个恢复 run:先交一条恢复说明,没被会话收下的输入再交一次,收下过的不再交。
+ * - 停止只停这个任务(指令通道:取消这一轮、停它的后台命令、之后的工具调用一律拒绝),聊天和别的任务照常。
+ *
+ * 3b–3f 的缝:Report 的 needs_you / question、阶段表的"等你"几行、规则(rule_id)、花费(cost_usd、budget)。
+ */
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import type { Outbox } from "../core/outbox.js";
+import { ActivityLog, type ActivityStep } from "../agent/activity.js";
+import { ResumeFailed, deliverables } from "../agent/host.js";
+import { NUDGE, attachmentsOf, rebrief, recoveryNote, retryNote, taskBrief } from "../agent/prompts/index.js";
+import type { BotSettings } from "../agent/settings.js";
+import type { Conversation, InputKind, RunCause, RunInputRow, RunOutcome, RunRow, Store, TaskReport, TaskRow } from "../store/db.js";
+import { logger } from "../log.js";
+import { DEFAULT_MAX_BACKGROUND, pickRuns, priorityOf } from "./slots.js";
+import { taskStage, type Stage } from "./stage.js";
+
+const log = logger("tasks");
+
+/** 每个机器人同时在进行的任务上限:再多就拒绝 task_start */
+export const MAX_WORKING_TASKS = 10;
+/** 给用户的一句话上限 */
+export const MESSAGE_MAX = 300;
+/** 一轮出错后重试前等多久(设计:15、30、60 秒) */
+export const RETRY_DELAYS_MS = [15_000, 30_000, 60_000];
+
+/** 宿主这边能为任务做的事(AgentManager 实现;单元测试换成假的) */
+export interface TaskHost {
+ /** 代理模式可用 */
+ readonly available: boolean;
+ workspace(botId: string): string;
+ settings(botId: string): BotSettings;
+ memoryPrefix(botId: string, conversationId: string): string;
+ /**
+ * 把一条输入交给任务会话:第一次建会话(工作目录是任务文件夹),之后在新的代理进程里先 resume。返回 DSH 的收件 id。
+ * resume 失败(会话记录丢了)抛 ResumeFailed(host.ts)。
+ */
+ prompt(botId: string, o: { sessionId: string; folder: string; model: string; text: string; resume: boolean }): Promise<string>;
+ /** 并进正在进行的一轮(agent.steer);会话空闲时返回 false */
+ steer(botId: string, sessionId: string, id: string, text: string): Promise<boolean>;
+ /** 停掉这个会话:取消这一轮、它的子代理和后台命令,之后的工具调用一律拒绝 */
+ stop(botId: string, sessionId: string): Promise<void>;
+ /** 会话空闲时还有没有后台命令、子代理在跑;有就由插件在它们结束、会话再次空闲时报 task-settled */
+ quiet(botId: string, sessionId: string): Promise<{ quiet: boolean; jobs?: string[] }>;
+}
+
+/** DSH 的一条通知(SDK 的 session.event / session.status / subagent.*) */
+export interface TaskNotification {
+ method: string;
+ params: any;
+}
+
+export interface TaskServiceOptions {
+ store: Store;
+ host: TaskHost;
+ /** 微信、飞书的结果经出站队列发(没有就只写进会话历史) */
+ outbox?: Outbox;
+ /** 机器人没设模型时用的默认模型 */
+ defaultModel?: () => string;
+ /** 发给网关前限定到机器人用的 Key(同聊天) */
+ route?: (botId: string, model: string) => string;
+ maxBackground?: number;
+ now?: () => number;
+ retryDelaysMs?: number[];
+ /** 任务有变化(阶段、进展) */
+ onChange?: (taskId: string) => void;
+}
+
+/** 界面、/tasks 和 task_list 看到的任务 */
+export interface TaskView {
+ id: string;
+ botId: string;
+ conversationId: string;
+ channel: string;
+ title: string;
+ stage: Stage;
+ /** 最新进展:最近一次 Report 的那句话(给用户的,没有就是内部摘要的第一行) */
+ latest: string;
+ folder: string;
+ originMessageId: number;
+ createdAt: number;
+ updatedAt: number;
+ endedAt: number;
+ /** 跑了几个 run */
+ runs: number;
+ /** 正在跑的那个 run:开始时间与步数 */
+ live?: { runId: string; since: number; steps: number; current?: ActivityStep };
+}
+
+/** 一个在跑(或收尾中)的 run 的内存状态 */
+interface Live {
+ runId: string;
+ taskId: string;
+ botId: string;
+ sessionId: string;
+ activity: ActivityLog;
+ /** 会话正在跑一轮 */
+ busy: boolean;
+ /** 正在把输入交给会话(等代理进程、resume、session/prompt) */
+ starting: boolean;
+ /** 在问插件还有没有后台命令 */
+ checking: boolean;
+ /** 会话空了,等后台命令、子代理结束 */
+ settling: boolean;
+ /** 这个 run 里代理报的 done / failed */
+ final?: TaskReport;
+ nudged: boolean;
+ /** 最近一轮出的错 */
+ turnError?: string;
+ retries: number;
+ /** 等着重试(出错后过一会儿接着做) */
+ timer?: NodeJS.Timeout;
+ /** 会话里出现过的用户消息 id(收件 id 可能比 session/prompt 的回复先到) */
+ seen: Set<string>;
+ tokensIn: number;
+ tokensOut: number;
+}
+
+const hex = (n: number) => crypto.randomBytes(n).toString("hex");
+const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();
+
+/** 文件夹名里的 slug:标题里的字母数字(中文标题就是 task) */
+export function slugOf(title: string): string {
+ const s = title
+ .normalize("NFKD")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 24)
+ .replace(/-+$/, "");
+ return s || "task";
+}
+
+const NOTES = "task-notes:";
+
+/** 给聊天代理的便条:后台任务的结果发出去了,下一条聊天消息带上它(模型知道这件事,用户问"详细说说"时能接上) */
+export function takeTaskNotes(store: Store, conversationId: string): string {
+ const v = store.getKV(NOTES + conversationId);
+ if (!v) return "";
+ store.deleteKV(NOTES + conversationId);
+ try {
+ const list = JSON.parse(v) as string[];
+ return Array.isArray(list) ? list.join("\n") : "";
+ } catch {
+ return "";
+ }
+}
+
+export class TaskService {
+ /** runId → 在跑的 run */
+ private live = new Map<string, Live>();
+ /** 会话 id → 在跑的 run */
+ private bySession = new Map<string, Live>();
+ private started = false;
+ private closing = false;
+ /** 正在删除的机器人 */
+ private dropped = new Set<string>();
+
+ constructor(private o: TaskServiceOptions) {}
+
+ private get store(): Store {
+ return this.o.store;
+ }
+ private now(): number {
+ return (this.o.now ?? Date.now)();
+ }
+
+ // ---------- 生命周期 ----------
+
+ /** 启动:上次没跑完的 run 记为 interrupted 并排恢复;结束了却没送出的结果补送;开始排队的 run */
+ start(): void {
+ this.started = true;
+ this.closing = false;
+ this.recover(undefined, "应用重启");
+ for (const r of this.store.listRuns({ states: ["ended"] })) {
+ if (!r.delivery && (r.outcome === "done" || r.outcome === "failed") && r.taskId) {
+ const task = this.store.getTask(r.taskId);
+ if (task) this.deliver(task, r.id, r.outcome, r.report, r.error);
+ }
+ }
+ this.pump();
+ }
+
+ /** 应用退出:不再开始新的 run;跑着的留在库里(下次启动时恢复),步骤先存下 */
+ stop(): void {
+ this.closing = true;
+ for (const l of this.live.values()) {
+ clearTimeout(l.timer);
+ try {
+ this.store.updateRun(l.runId, { activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });
+ } catch {
+ /* 数据库可能已经关了 */
+ }
+ }
+ }
+
+ /** 删机器人之前:它的任务不再跑、不再恢复(不然停它的代理进程会触发恢复,又把进程拉起来) */
+ dropBot(botId: string): void {
+ this.dropped.add(botId);
+ for (const l of [...this.live.values()]) if (l.botId === botId) this.forget(l);
+ }
+
+ /** 代理进程退出(崩溃、设置变化后重启、手动重启):它上面跑着的 run 记为 interrupted,排恢复 */
+ onChildExit(botId: string): void {
+ if (this.closing || !this.started || this.dropped.has(botId)) return;
+ if (!this.store.listRuns({ botId, states: ["running", "settling"] }).length) return;
+ log.warn("agent process exited with background tasks running; recovering them", { bot: botId });
+ this.recover(botId, "代理进程退出");
+ this.pump();
+ }
+
+ /**
+ * 恢复(设计 3.restart):running / settling 的 run 记为 interrupted;任务没结束的排一个恢复 run,
+ * 第一条输入是恢复说明(被停掉的后台命令列在里面),之后是会话没收下的输入(收下过的不再交)。
+ */
+ private recover(botId: string | undefined, why: string): void {
+ for (const run of this.store.listRuns({ botId, states: ["running", "settling"] })) {
+ const l = this.live.get(run.id);
+ const steps: ActivityStep[] = l ? l.activity.steps : parseSteps(this.store.getRun(run.id)?.activity);
+ if (l) this.forget(l);
+ this.store.updateRun(run.id, { state: "ended", outcome: "interrupted", endedAt: this.now(), error: why, ...(l ? { activity: JSON.stringify(steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut } : {}) });
+ const task = run.taskId ? this.store.getTask(run.taskId) : undefined;
+ if (!task || task.endedAt) continue;
+ const jobs = steps.filter((s) => s.kind === "job" && s.status === "running").map((s) => clip(oneLine(s.summary || s.title), 120));
+ this.addInput(task.id, "recovery", recoveryNote(jobs), false);
+ if (!this.queuedRun(task.id)) this.enqueue(task, "recover");
+ this.changed(task.id);
+ }
+ }
+
+ // ---------- 建任务、追加、停止 ----------
+
+ /** 新任务(聊天代理的 task_start):用户原话、说明、最近的对话、附件和记忆快照作为第一条输入,排进队列 */
+ create(o: { botId: string; conversationId: string; title: string; brief: string; budgetUsd?: number }): { task?: TaskRow; error?: string } {
+ const conv = this.store.getConversation(o.conversationId);
+ const bot = this.store.getBot(o.botId);
+ if (!conv || !bot) return { error: "conversation not found" };
+ const title = clip(oneLine(o.title), 40);
+ if (!title) return { error: "title is required" };
+ const working = this.store.listTasks({ botId: o.botId, open: true, limit: 500 }).filter((t) => this.stage(t).group === "working").length;
+ if (working >= MAX_WORKING_TASKS) return { error: `This bot already has ${working} background tasks running; finish or stop one first (the user can send /tasks).` };
+ const msgs = this.store.listMessages(conv.id, 40);
+ const at = msgs.findLastIndex((m) => m.role === "user");
+ const origin = at >= 0 ? msgs[at] : undefined;
+ const recent = msgs
+ .slice(0, Math.max(0, at))
+ .filter((m) => m.role === "user" || m.role === "assistant")
+ .slice(-6)
+ .map((m) => ({ role: m.role as "user" | "assistant", text: m.content }));
+ const id = `t_${hex(6)}`;
+ const now = this.now();
+ const folder = `tasks/${slugOf(title)}-${id.slice(2, 8)}`;
+ const st = this.o.host.settings(o.botId);
+ const task = this.store.insertTask({
+ id,
+ botId: o.botId,
+ conversationId: conv.id,
+ originMessageId: origin?.id ?? 0,
+ originRef: conv.channel === "feishu" ? replyHandle(this.store, conv.id).messageId ?? "" : "",
+ title,
+ brief: clip(o.brief.trim(), 1500),
+ sessionId: `task-${id}`,
+ folder,
+ model: conv.model || bot.defaultModel || this.o.defaultModel?.() || "",
+ permission: st.permission,
+ budgetUsd: o.budgetUsd && o.budgetUsd > 0 ? Math.min(o.budgetUsd, 100) : 1,
+ createdAt: now,
+ updatedAt: now,
+ });
+ const text = taskBrief({
+ title,
+ original: origin?.content ?? o.brief,
+ brief: o.brief,
+ recent,
+ attachments: attachmentsOf(origin?.content ?? ""),
+ memory: st.memory.enabled ? this.o.host.memoryPrefix(o.botId, conv.id) : undefined,
+ folder,
+ });
+ this.addInput(task.id, "brief", text, true);
+ this.enqueue(task, "launch");
+ log.info("background task created", { bot: o.botId, task: id, conversationId: conv.id });
+ this.changed(id);
+ this.pump();
+ return { task };
+ }
+
+ /**
+ * 人的追加(task_message):任务在跑一轮就并进去(下一步看到);空着(收尾、等重试)就马上交给会话;
+ * 在排队就跟着这个 run 一起交;已完成或失败了就在同一个任务里开一个新 run(人的唤醒,排在前面)。停了的不接。
+ */
+ async message(taskId: string, text: string): Promise<{ how?: "steered" | "sent" | "queued" | "resumed"; error?: string }> {
+ const task = this.store.getTask(taskId);
+ if (!task) return { error: "task not found" };
+ if (task.endReason === "stopped") return { error: `「${task.title}」已停止,不能再追加;需要的话开个新任务。` };
+ const input = this.addInput(task.id, "followup", `[用户追加]\n${text.trim()}`, true);
+ const l = this.liveOf(task.id);
+ if (l) {
+ if (l.busy && !l.starting && (await this.o.host.steer(l.botId, l.sessionId, input.id, input.text).catch(() => false))) {
+ this.store.updateInput(input.id, { runId: l.runId, messageId: input.id, deliveredAt: this.now(), ...(l.seen.has(input.id) ? { takenAt: this.now() } : {}) });
+ this.reopen(l);
+ return { how: "steered" };
+ }
+ if (!l.busy && !l.starting && !l.checking) {
+ clearTimeout(l.timer);
+ l.timer = undefined;
+ void this.deliver_(l, [input]);
+ return { how: "sent" };
+ }
+ // 正在交上一条:这一轮空下来时交(checkSettle 先交没交出去的输入)
+ return { how: "queued" };
+ }
+ if (this.queuedRun(task.id)) return { how: "queued" };
+ if (task.endedAt) this.store.updateTask(task.id, { endedAt: 0, endReason: "", updatedAt: this.now() });
+ this.enqueue(task, "followup");
+ this.changed(task.id);
+ this.pump();
+ return { how: "resumed" };
+ }
+
+ /** 停止(/stop 编号、界面、聊天代理):只停这个任务,聊天和别的任务照常 */
+ async stopTask(taskId: string, by: string): Promise<boolean> {
+ const task = this.store.getTask(taskId);
+ if (!task || task.endReason === "stopped") return false;
+ const now = this.now();
+ this.store.updateTask(taskId, { endedAt: now, endReason: "stopped", stoppedBy: by, updatedAt: now });
+ for (const r of this.store.listRuns({ taskId, states: ["queued"] })) this.store.updateRun(r.id, { state: "ended", outcome: "stopped", endedAt: now });
+ const l = this.liveOf(taskId);
+ if (l) {
+ l.activity.end("已停止");
+ this.end(l, "stopped");
+ await this.o.host.stop(l.botId, l.sessionId).catch((e) => log.warn("stopping the task session failed", { task: taskId, message: (e as Error).message.slice(0, 200) }));
+ }
+ log.info("background task stopped", { task: taskId, by });
+ this.changed(taskId);
+ this.pump();
+ return true;
+ }
+
+ // ---------- 排队与名额 ----------
+
+ private enqueue(task: TaskRow, cause: RunCause): RunRow {
+ return this.store.insertRun({ id: `r_${hex(6)}`, botId: task.botId, taskId: task.id, sessionId: task.sessionId, cause, queuedAt: this.now() });
+ }
+
+ private queuedRun(taskId: string): RunRow | undefined {
+ return this.store.listRuns({ taskId, states: ["queued"] })[0];
+ }
+
+ private liveOf(taskId: string): Live | undefined {
+ for (const l of this.live.values()) if (l.taskId === taskId) return l;
+ return undefined;
+ }
+
+ private slots(botId: string): number {
+ return this.o.host.settings(botId).taskSlots;
+ }
+
+ /** 有空名额就开始排队的 run(人的唤醒在前,见 slots.ts) */
+ pump(): void {
+ if (!this.started || this.closing) return;
+ const queued = this.store.listRuns({ states: ["queued"] }).filter((r) => r.taskId && !this.dropped.has(r.botId));
+ if (!queued.length) return;
+ const running = this.store.listRuns({ states: ["running", "settling"] });
+ const picks = pickRuns(
+ queued.map((r) => ({ id: r.id, botId: r.botId, priority: priorityOf(r.cause), queuedAt: r.queuedAt })),
+ running,
+ { perBot: (b) => this.slots(b), global: this.o.maxBackground ?? DEFAULT_MAX_BACKGROUND },
+ );
+ for (const p of picks) void this.startRun(p.id);
+ }
+
+ /** 开始一个 run:先同步占住名额,再把没被会话收下的输入(恢复说明在最前)交给会话 */
+ private async startRun(runId: string): Promise<void> {
+ const run = this.store.getRun(runId);
+ if (!run || run.state !== "queued") return;
+ const task = this.store.getTask(run.taskId);
+ const now = this.now();
+ if (!task || task.endReason === "stopped") {
+ this.store.updateRun(runId, { state: "ended", outcome: "stopped", endedAt: now });
+ return;
+ }
+ this.store.updateRun(runId, { state: "running", startedAt: now, sessionId: task.sessionId });
+ const l: Live = {
+ runId,
+ taskId: task.id,
+ botId: task.botId,
+ sessionId: task.sessionId,
+ activity: new ActivityLog(undefined, task.model),
+ busy: false,
+ starting: false,
+ checking: false,
+ settling: false,
+ nudged: false,
+ retries: 0,
+ seen: new Set(),
+ tokensIn: 0,
+ tokensOut: 0,
+ };
+ this.live.set(runId, l);
+ this.bySession.set(task.sessionId, l);
+ this.changed(task.id);
+ const inputs = this.store.openInputs(task.id).sort((a, b) => Number(b.kind === "recovery") - Number(a.kind === "recovery"));
+ await this.deliver_(l, inputs.length ? inputs : [this.addInput(task.id, "nudge", NUDGE, false)]);
+ }
+
+ /**
+ * 把输入交给会话(一次 session/prompt,几条拼在一起):记下收件 id。代理进程起不来、会话恢复不了时按情况重试、
+ * 换新会话或让这个 run 失败。
+ */
+ private async deliver_(l: Live, inputs: RunInputRow[]): Promise<void> {
+ if (!inputs.length || this.live.get(l.runId) !== l) return;
+ const task = this.store.getTask(l.taskId);
+ if (!task) return;
+ l.starting = true;
+ l.settling = false;
+ if (inputs.some((i) => i.fromPerson)) this.reopen(l);
+ const text = inputs.map((i) => i.text).join("\n\n");
+ const folder = path.join(this.o.host.workspace(task.botId), task.folder);
+ const model = this.modelOf(task);
+ try {
+ let id: string;
+ try {
+ fs.mkdirSync(folder, { recursive: true });
+ id = await this.o.host.prompt(task.botId, { sessionId: l.sessionId, folder, model, text, resume: this.store.taskPrompted(task.id) });
+ } catch (e) {
+ if (!(e instanceof ResumeFailed)) throw e;
+ // 会话记录恢复不了:换一个新会话,从宿主记下的任务重新交代
+ const n = this.store.listRuns({ taskId: task.id }).length + 1;
+ const sessionId = `task-${task.id}-${n}`;
+ log.warn("task session could not be resumed; starting a new one", { task: task.id, sessionId, message: e.message.slice(0, 200) });
+ this.bySession.delete(l.sessionId);
+ l.sessionId = sessionId;
+ this.bySession.set(sessionId, l);
+ this.store.updateTask(task.id, { sessionId, updatedAt: this.now() });
+ this.store.updateRun(l.runId, { sessionId });
+ const brief = this.store.listInputs(task.id).find((i) => i.kind === "brief")?.text ?? task.brief;
+ const again = rebrief(brief, task.report?.message || task.report?.summary);
+ id = await this.o.host.prompt(task.botId, { sessionId, folder, model, text: `${again}\n\n${text}`, resume: false });
+ }
+ if (this.live.get(l.runId) !== l) {
+ // 交出去的时候任务被停了:输入已经到了会话里,再停一次(插件拒绝它之后的工具调用)
+ if (this.store.getTask(l.taskId)?.endReason === "stopped") await this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);
+ return;
+ }
+ const at = this.now();
+ for (const i of inputs) {
+ this.store.updateInput(i.id, { runId: l.runId, messageId: id, deliveredAt: at });
+ if (l.seen.has(id)) this.store.updateInput(i.id, { takenAt: at });
+ }
+ } catch (e) {
+ const msg = (e as Error).message;
+ if (this.live.get(l.runId) !== l) return;
+ log.warn("could not hand the task its input", { task: l.taskId, message: msg.slice(0, 300) });
+ l.starting = false;
+ if (this.o.host.available && l.retries < this.delays.length) {
+ const delay = this.delays[l.retries++];
+ l.timer = setTimeout(() => {
+ l.timer = undefined;
+ void this.deliver_(l, this.store.openInputs(l.taskId).filter((i) => !i.deliveredAt || i.runId === l.runId));
+ }, delay);
+ l.timer.unref?.();
+ return;
+ }
+ this.end(l, "failed", undefined, this.o.host.available ? "代理没能启动" : "代理不可用");
+ return;
+ } finally {
+ l.starting = false;
+ }
+ // 交出去的时候这一轮可能已经跑完了
+ if (!l.busy) void this.checkSettle(l);
+ }
+
+ private get delays(): number[] {
+ return this.o.retryDelaysMs ?? RETRY_DELAYS_MS;
+ }
+
+ /** 人又给了输入:之前报的 done / failed 不算了,等新的 Report */
+ private reopen(l: Live): void {
+ l.final = undefined;
+ l.nudged = false;
+ }
+
+ private modelOf(task: TaskRow): string {
+ const bot = this.store.getBot(task.botId);
+ const m = task.model || bot?.defaultModel || this.o.defaultModel?.() || "";
+ return m && this.o.route ? this.o.route(task.botId, m) : m;
+ }
+
+ private addInput(taskId: string, kind: InputKind, text: string, fromPerson: boolean): RunInputRow {
+ return this.store.insertInput({ id: `i_${hex(6)}`, taskId, runId: "", kind, text, fromPerson, createdAt: this.now() });
+ }
+
+ // ---------- 会话事件(宿主转来的 SDK 通知) ----------
+
+ /** root:任务会话 id(子代理的通知也归到它) */
+ onEvent(_botId: string, root: string, n: TaskNotification): void {
+ const l = this.bySession.get(root);
+ if (!l) return;
+ const p = n.params ?? {};
+ if (n.method === "subagent.started" || n.method === "subagent.finished") {
+ l.activity.apply(n.method.replace(".", "/"), p);
+ return;
+ }
+ if (p.sessionId !== root) return;
+ if (n.method === "session.status") {
+ if (p.status === "running") {
+ l.busy = true;
+ if (l.settling) {
+ // 后台命令结束,代理被叫醒:还是这个 run
+ l.settling = false;
+ this.store.updateRun(l.runId, { state: "running" });
+ }
+ } else if (p.status === "idle") {
+ l.busy = false;
+ void this.checkSettle(l);
+ }
+ return;
+ }
+ if (n.method !== "session.event") return;
+ const ev = p.event ?? {};
+ const data = ev.data ?? {};
+ const type = String(ev.type ?? "");
+ l.activity.apply(type, data, Number(ev.time) || this.now());
+ if (type === "user/message" && data.id) {
+ const id = String(data.id);
+ l.seen.add(id);
+ if (this.store.takeInputs(l.taskId, id, this.now())) this.changed(l.taskId);
+ } else if (type === "turn/start") l.turnError = undefined;
+ else if (type === "turn/end") {
+ if (data?.reason?.kind === "error") l.turnError = String(data.reason.error?.message ?? "unknown error");
+ this.store.updateRun(l.runId, { activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });
+ this.changed(l.taskId);
+ } else if (type === "assistant/message" && data.usage) {
+ l.tokensIn += Number(data.usage.inputTokens) || 0;
+ l.tokensOut += Number(data.usage.outputTokens) || 0;
+ }
+ }
+
+ /**
+ * 会话空了:交出去的输入都被收下了(不然是旧的空闲)、没有要交的了,就问插件还有没有后台命令、子代理;
+ * 没有就结束这个 run,有就收尾(settling),等插件报 task-settled。
+ */
+ private async checkSettle(l: Live): Promise<void> {
+ if (l.busy || l.starting || l.checking || l.timer || this.closing || this.live.get(l.runId) !== l) return;
+ const open = this.store.openInputs(l.taskId);
+ if (open.some((i) => i.deliveredAt && i.runId === l.runId)) return;
+ const waiting = open.filter((i) => !i.deliveredAt);
+ if (waiting.length) return void this.deliver_(l, waiting);
+ l.checking = true;
+ let q: { quiet: boolean; jobs?: string[] };
+ try {
+ q = await this.o.host.quiet(l.botId, l.sessionId);
+ } catch {
+ q = { quiet: true };
+ } finally {
+ l.checking = false;
+ }
+ if (this.live.get(l.runId) !== l || l.busy || l.starting) return;
+ if (q.quiet) return this.finish(l);
+ l.settling = true;
+ this.store.updateRun(l.runId, { state: "settling" });
+ this.changed(l.taskId);
+ }
+
+ /** 插件:收尾中的会话安静下来了(后台命令、子代理都结束了,或者收尾超时被停掉了) */
+ settled(b: any): { ok: true } {
+ const l = this.bySession.get(String(b?.sessionId ?? ""));
+ if (!l || l.busy || l.starting || l.checking) return { ok: true };
+ if (this.store.openInputs(l.taskId).some((i) => i.deliveredAt && i.runId === l.runId)) return { ok: true };
+ const killed = Array.isArray(b?.killedJobs) ? b.killedJobs.map(String) : [];
+ if (killed.length) log.info("task settling timed out; background jobs were stopped", { task: l.taskId, jobs: killed });
+ this.finish(l);
+ return { ok: true };
+ }
+
+ /**
+ * 一轮结束、会话安静:有 done / failed 就按它结束;出错了过一会儿接着做(最多 3 次);没报就提醒一次;还没有就失败。
+ */
+ private finish(l: Live): void {
+ if (this.live.get(l.runId) !== l) return;
+ if (l.final) return this.end(l, l.final.state === "done" ? "done" : "failed", l.final);
+ if (l.turnError && l.retries < this.delays.length) {
+ const error = l.turnError;
+ l.turnError = undefined;
+ const delay = this.delays[l.retries++];
+ log.warn("task turn failed; continuing after a pause", { task: l.taskId, inMs: delay, message: error.slice(0, 200) });
+ l.timer = setTimeout(() => {
+ l.timer = undefined;
+ void this.deliver_(l, [this.addInput(l.taskId, "note", retryNote(error), false)]);
+ }, delay);
+ l.timer.unref?.();
+ return;
+ }
+ if (!l.nudged) {
+ l.nudged = true;
+ void this.deliver_(l, [this.addInput(l.taskId, "nudge", NUDGE, false)]);
+ return;
+ }
+ if (l.turnError) log.warn("task failed after retries", { task: l.taskId, message: l.turnError.slice(0, 300) });
+ this.end(l, "failed", undefined, l.turnError ? "模型一直出错" : "没有给出结果");
+ }
+
+ /** 结束 run:存下步骤、结果;done / failed 发回会话;空出名额 */
+ private end(l: Live, outcome: RunOutcome, report?: TaskReport, error = ""): void {
+ if (this.live.get(l.runId) !== l) return;
+ this.forget(l);
+ const now = this.now();
+ this.store.updateRun(l.runId, { state: "ended", outcome, report, error, endedAt: now, activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });
+ const task = this.store.getTask(l.taskId);
+ if (task && outcome === "done") this.store.updateTask(task.id, { endedAt: now, endReason: "done", updatedAt: now });
+ else if (task) this.store.updateTask(task.id, { updatedAt: now });
+ if (task && (outcome === "done" || outcome === "failed")) this.deliver(task, l.runId, outcome, report, error);
+ log.info("background task run ended", { task: l.taskId, run: l.runId, outcome, ...(error ? { error } : {}) });
+ this.changed(l.taskId);
+ this.pump();
+ }
+
+ private forget(l: Live): void {
+ clearTimeout(l.timer);
+ l.timer = undefined;
+ this.live.delete(l.runId);
+ if (this.bySession.get(l.sessionId) === l) this.bySession.delete(l.sessionId);
+ }
+
+ // ---------- 送达 ----------
+
+ /**
+ * 把结果(或失败)发回请求它的会话:微信、飞书经出站队列(id 固定:task:<任务>:result|failure:<run>,同一 id 只发一次;
+ * 微信在发送时才查 24 小时窗口和配额),飞书回复在请求那条消息下;网页只写进会话历史。同时写进会话历史,
+ * 给聊天代理留一张便条。交过的 run 不再交(重启后补送也一样)。
+ */
+ private deliver(task: TaskRow, runId: string, outcome: "done" | "failed", report: TaskReport | undefined, error: string): void {
+ const run = this.store.getRun(runId);
+ if (!run || run.delivery) return;
+ const conv = this.store.getConversation(task.conversationId);
+ const purpose = outcome === "done" ? "result" : "failure";
+ const id = `task:${task.id}:${purpose}:${runId}`;
+ if (!conv) {
+ this.store.updateRun(runId, { delivery: `${id}:dropped` });
+ return;
+ }
+ const msg = oneLine(report?.message ?? "");
+ const text = outcome === "done" ? clip(msg, MESSAGE_MAX) || `「${task.title}」做好了。` : `⚠️「${task.title}」没做完:${clip(msg || error || "没有给出结果", MESSAGE_MAX)}`;
+ const files = outcome === "done" ? this.files(task, report?.files ?? []) : [];
+ if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.outbox) this.post(conv, task, id, text, files);
+ this.store.addMessage(conv.id, "assistant", files.length && conv.channel === "web" ? `${text}\n\n${files.map((f) => `- ${path.relative(this.o.host.workspace(task.botId), f)}`).join("\n")}` : text);
+ this.store.updateRun(runId, { delivery: id });
+ this.note(conv.id, outcome === "done" ? `[后台任务「${task.title}」已完成,已把结果发给用户] ${text}` : `[后台任务「${task.title}」失败了,已告诉用户] ${text}`);
+ }
+
+ /** 微信、飞书:写进出站队列(同步落库;渠道没上线时等它上线) */
+ private post(conv: Conversation, task: TaskRow, id: string, text: string, files: string[]): void {
+ const outbox = this.o.outbox!;
+ const channel = conv.channel as "weixin" | "feishu";
+ const replyTo = channel === "feishu" ? task.originRef || replyHandle(this.store, conv.id).messageId || "" : "";
+ const base = { botId: task.botId, channel, peerId: conv.peerId, replyTo };
+ void outbox.send({ ...base, id, kind: channel === "feishu" && !replyTo ? "notice" : "text", body: { text } });
+ if (channel === "feishu" && !replyTo) return;
+ files.forEach((f, i) => void outbox.send({ ...base, id: `${id}:file:${i}`, kind: "file", body: { path: f, name: path.basename(f) } }));
+ }
+
+ /** task_report 里的文件:先按任务文件夹找,再按工作区找;只交工作区里真实存在的文件 */
+ private files(task: TaskRow, list: string[]): string[] {
+ const ws = this.o.host.workspace(task.botId);
+ const folder = path.join(ws, task.folder);
+ return deliverables(
+ ws,
+ list.map((f) => {
+ const inFolder = path.resolve(folder, f);
+ return fs.existsSync(inFolder) ? inFolder : path.resolve(ws, f);
+ }),
+ );
+ }
+
+ private note(conversationId: string, line: string): void {
+ let list: string[] = [];
+ try {
+ list = JSON.parse(this.store.getKV(NOTES + conversationId) || "[]");
+ } catch {
+ list = [];
+ }
+ list.push(clip(line, 500));
+ this.store.setKV(NOTES + conversationId, JSON.stringify(list.slice(-5)));
+ }
+
+ // ---------- 插件经 bridge 来的 ----------
+
+ /** task_report:记下 Report;done / failed 在这一轮结束、会话安静后发给用户 */
+ report(b: any): { text?: string; error?: string } {
+ const l = this.bySession.get(String(b?.sessionId ?? ""));
+ if (!l) return { error: "This background task is not running any more (it was stopped or has ended). Stop working on it." };
+ const state = String(b?.state ?? "");
+ if (state === "needs_you") return { error: "You cannot ask the user from a background task. Decide yourself and say so in the result, or report failed with what you need from the user." };
+ if (state !== "progress" && state !== "done" && state !== "failed") return { error: "state must be progress, done or failed" };
+ const message = typeof b?.message === "string" ? oneLine(b.message) : "";
+ const report: TaskReport = {
+ state,
+ summary: clip(String(b?.summary ?? "").trim(), 2000),
+ ...(message ? { message: clip(message, MESSAGE_MAX) } : {}),
+ ...(Array.isArray(b?.files) && b.files.length ? { files: b.files.map(String).slice(0, 8) } : {}),
+ at: this.now(),
+ };
+ this.store.updateRun(l.runId, { report });
+ this.store.updateTask(l.taskId, { report, updatedAt: this.now() });
+ if (state !== "progress") l.final = report;
+ this.changed(l.taskId);
+ if (state === "progress") return { text: "Progress recorded (it is not sent to the user). Continue the task." };
+ return { text: `Recorded. End your turn now: the app sends your message to the user${state === "done" && !message ? " (you gave no message, so the user only hears that the task is done)" : ""}.` };
+ }
+
+ /** 聊天代理的工具:task_start / task_message / task_list */
+ async chatTool(b: any): Promise<{ text?: string; error?: string }> {
+ const botId = String(b?.botId ?? "");
+ const convId = this.store.conversationForSession(String(b?.sessionId ?? ""));
+ const conv = convId ? this.store.getConversation(convId) : undefined;
+ if (!conv || conv.botId !== botId) return { error: "Background tasks can only be managed from a chat with the user." };
+ const a = (b?.args ?? {}) as Record<string, unknown>;
+ switch (String(b?.op ?? "")) {
+ case "start": {
+ const r = this.create({ botId, conversationId: conv.id, title: String(a.title ?? ""), brief: String(a.brief ?? ""), budgetUsd: Number(a.budget_usd) || undefined });
+ if (!r.task) return { error: r.error };
+ return {
+ text: `Started background task ${r.task.id} 「${r.task.title}」 in folder ${r.task.folder}. In your reply, tell the user in one sentence what now runs in the background and that they will hear back when it is done; they can keep chatting. Do not do the task yourself.`,
+ };
+ }
+ case "message": {
+ const task = this.find(conv.id, String(a.task ?? ""));
+ if (!task) return { error: `No background task matches "${String(a.task ?? "")}". Call task_list to see them.` };
+ const r = await this.message(task.id, String(a.text ?? ""));
+ if (r.error) return { error: r.error };
+ const how = { steered: "It reaches the task at its next step.", sent: "The task picks it up now.", queued: "The task gets it when it starts.", resumed: "The finished task resumes with it." }[r.how!];
+ return { text: `Passed to 「${task.title}」. ${how} Tell the user in one short sentence.` };
+ }
+ case "list": {
+ const list = this.list({ conversationId: conv.id, limit: 10 });
+ if (!list.length) return { text: "This conversation has no background tasks." };
+ return { text: list.map((t) => `${t.id} 「${t.title}」 ${t.stage.label}${t.latest ? ` — ${t.latest}` : ""}`).join("\n") };
+ }
+ default:
+ return { error: "unknown task tool" };
+ }
+ }
+
+ /** 按 id 或标题里的字找这个会话的任务(新的在前) */
+ private find(conversationId: string, ref: string): TaskRow | undefined {
+ const r = ref.trim();
+ if (!r) return undefined;
+ const list = this.store.listTasks({ conversationId, limit: 50 });
+ return list.find((t) => t.id === r || t.sessionId === r) ?? list.find((t) => t.title.includes(r) || r.includes(t.title));
+ }
+
+ /** 任务会话所在的聊天(任务会话里的审批落到请求它的会话) */
+ conversationOf(sessionId: string): string | undefined {
+ return this.bySession.get(sessionId) ? this.store.getTask(this.bySession.get(sessionId)!.taskId)?.conversationId : this.store.taskBySession(sessionId)?.conversationId;
+ }
+
+ // ---------- 查看 ----------
+
+ private stage(task: TaskRow, run = this.store.latestRun(task.id)): Stage {
+ const delivery = run?.delivery && !run.delivery.endsWith(":dropped") ? this.o.store.getOutbox(run.delivery) : undefined;
+ const approval = this.store.listApprovals({ status: "pending", botId: task.botId, limit: 100 }).some((a) => a.sessionId === task.sessionId && a.kind === "approval");
+ return taskStage({ stopped: task.endReason === "stopped", undelivered: delivery?.status === "gone", waiting: approval ? "approval" : undefined, run });
+ }
+
+ view(task: TaskRow): TaskView {
+ const run = this.store.latestRun(task.id);
+ const l = run ? this.live.get(run.id) : undefined;
+ const r = task.report;
+ const conv = this.store.getConversation(task.conversationId);
+ return {
+ id: task.id,
+ botId: task.botId,
+ conversationId: task.conversationId,
+ channel: conv?.channel ?? "",
+ title: task.title,
+ stage: this.stage(task, run),
+ latest: r ? clip(oneLine(r.message || r.summary.split("\n")[0] || ""), 120) : "",
+ folder: task.folder,
+ originMessageId: task.originMessageId,
+ createdAt: task.createdAt,
+ updatedAt: task.updatedAt,
+ endedAt: task.endedAt,
+ runs: this.store.listRuns({ taskId: task.id }).length,
+ ...(l && run ? { live: { runId: run.id, since: run.startedAt, steps: l.activity.steps.length, current: l.activity.steps.findLast((s) => s.status === "running") } } : {}),
+ };
+ }
+
+ /** 任务列表:进行中、等你的在前,再按新旧 */
+ list(o: { botId?: string; conversationId?: string; limit?: number; since?: number } = {}): TaskView[] {
+ const rank = { working: 0, needs: 1, ended: 2 } as const;
+ return this.store
+ .listTasks({ botId: o.botId, conversationId: o.conversationId, limit: 200 })
+ .map((t) => this.view(t))
+ .filter((v) => !o.since || v.stage.group !== "ended" || v.updatedAt >= o.since)
+ .sort((a, b) => rank[a.stage.group] - rank[b.stage.group] || b.createdAt - a.createdAt)
+ .slice(0, o.limit ?? 50);
+ }
+
+ get(taskId: string): TaskView | undefined {
+ const t = this.store.getTask(taskId);
+ return t ? this.view(t) : undefined;
+ }
+
+ /** 一个 run 的步骤(在跑的用内存里的) */
+ activity(runId: string): ActivityStep[] {
+ const l = this.live.get(runId);
+ if (l) return l.activity.steps;
+ return parseSteps(this.store.getRun(runId)?.activity);
+ }
+
+ /** 每个机器人正在进行的任务数(侧栏"正在工作") */
+ background(): Record<string, number> {
+ const out: Record<string, number> = {};
+ for (const r of this.store.listRuns({ states: ["queued", "running", "settling"] })) out[r.botId] = (out[r.botId] ?? 0) + 1;
+ return out;
+ }
+
+ /** /tasks:这个会话的任务,带编号(/stop 编号 用同一个顺序) */
+ listText(conversationId: string): string {
+ const list = this.list({ conversationId, limit: 10, since: this.now() - 7 * 86400_000 });
+ if (!list.length) return "没有后台任务。";
+ const lines = list.map((t, i) => `${i + 1}. ${t.title} · ${t.stage.label}${t.latest ? `:${clip(t.latest, 40)}` : ""}`);
+ const working = list.findIndex((t) => t.stage.group === "working");
+ return ["后台任务:", ...lines, ...(working >= 0 ? ["发 /stop 编号 可停止。"] : [])].join("\n");
+ }
+
+ /** /stop 编号:立即记为停止(停会话在后台进行),返回给用户的话 */
+ stopByIndex(conversationId: string, n: number, by: string): string {
+ const list = this.list({ conversationId, limit: 10, since: this.now() - 7 * 86400_000 });
+ const t = list[n - 1];
+ if (!t) return `没有第 ${n} 个后台任务,发 /tasks 查看。`;
+ if (t.stage.group !== "working") return `「${t.title}」${t.stage.label}。`;
+ void this.stopTask(t.id, by);
+ return `已停止后台任务「${t.title}」。`;
+ }
+
+ /** 这个会话有没有正在进行的任务(/stop 不带编号时提示) */
+ working(conversationId: string): TaskView[] {
+ return this.list({ conversationId, limit: 10 }).filter((t) => t.stage.group === "working");
+ }
+
+ private changed(taskId: string): void {
+ try {
+ this.o.onChange?.(taskId);
+ } catch {
+ /* ignore */
+ }
+ }
+}
+
+function parseSteps(json: string | undefined): ActivityStep[] {
+ if (!json) return [];
+ try {
+ const v = JSON.parse(json);
+ return Array.isArray(v) ? v : [];
+ } catch {
+ return [];
+ }
+}
+
+/** 会话最近收到的那条消息的回复句柄(runtime 存在 KV 里) */
+function replyHandle(store: Store, conversationId: string): Record<string, string> {
+ try {
+ return JSON.parse(store.getKV(`reply-to:${conversationId}`) || "{}") ?? {};
+ } catch {
+ return {};
+ }
+}
diff --git a/src/tasks/slots.ts b/src/tasks/slots.ts
new file mode 100644
index 0000000..c182cee
--- /dev/null
+++ b/src/tasks/slots.ts
@@ -0,0 +1,63 @@
+/**
+ * 后台名额(设计文档第 3 节):每个机器人最多 taskSlots 个 run(默认 2),所有机器人加起来最多 maxBackground 个(默认 4)。
+ * run 在 running、settling 时占着名额。聊天回合从不占名额,也从不排进任务的队列(人的通道)。
+ * 人引起的唤醒(回答、批准、追加、重试、继续)可以多用每个机器人一个预留名额,并排在排队的工作前面。
+ * 先后:人的唤醒 → 新任务启动 → 重启后的恢复 → 规则(3d)。改编自 dsh-superagent 的 WorkerSlots(MIT)。
+ */
+import type { RunCause } from "../store/db.js";
+
+export type Priority = "person" | "launch" | "recover" | "rule";
+
+const ORDER: Record<Priority, number> = { person: 0, launch: 1, recover: 2, rule: 3 };
+
+/** run 的起因 → 先后 */
+export function priorityOf(cause: RunCause): Priority {
+ if (cause === "launch") return "launch";
+ if (cause === "recover") return "recover";
+ if (cause === "schedule") return "rule";
+ return "person";
+}
+
+export const DEFAULT_TASK_SLOTS = 2;
+export const DEFAULT_MAX_BACKGROUND = 4;
+
+export interface SlotLimits {
+ /** 这个机器人的名额 */
+ perBot(botId: string): number;
+ /** 所有机器人加起来 */
+ global: number;
+}
+
+export interface Waiting {
+ id: string;
+ botId: string;
+ priority: Priority;
+ queuedAt: number;
+}
+
+/** 按先后排好:人的唤醒在前,同一级按排队时间 */
+export function byPriority<T extends Waiting>(list: T[]): T[] {
+ return [...list].sort((a, b) => ORDER[a.priority] - ORDER[b.priority] || a.queuedAt - b.queuedAt);
+}
+
+/**
+ * 现在能开始哪些排队的 run:running 是正占着名额的(每个一项,给出机器人)。
+ * 人的唤醒可以多用本机器人一个名额,也不受总数限制(预留名额只给人);其余的受两个上限约束。
+ */
+export function pickRuns<T extends Waiting>(queued: T[], running: Array<{ botId: string }>, limits: SlotLimits): T[] {
+ const perBot = new Map<string, number>();
+ for (const r of running) perBot.set(r.botId, (perBot.get(r.botId) ?? 0) + 1);
+ let total = running.length;
+ const out: T[] = [];
+ for (const q of byPriority(queued)) {
+ const used = perBot.get(q.botId) ?? 0;
+ const person = q.priority === "person";
+ const cap = Math.max(0, limits.perBot(q.botId)) + (person ? 1 : 0);
+ if (used >= cap) continue;
+ if (!person && total >= limits.global) continue;
+ out.push(q);
+ perBot.set(q.botId, used + 1);
+ total++;
+ }
+ return out;
+}
diff --git a/src/tasks/stage.ts b/src/tasks/stage.ts
new file mode 100644
index 0000000..ec573e4
--- /dev/null
+++ b/src/tasks/stage.ts
@@ -0,0 +1,73 @@
+/**
+ * 任务的阶段(设计文档第 2 节的阶段表):从上往下,第一条符合的为准。任务自己定义阶段,不跟着 DSH 会话的状态走。
+ * 用户看到的只有这几种:进行中、等你、已完成、失败、已停止。改编自 dsh-superagent 的 core/stage.ts(MIT)。
+ */
+import type { RunOutcome, RunState } from "../store/db.js";
+
+export type StageKey =
+ | "stopped"
+ | "needs-you/delivery"
+ | "needs-you/answer"
+ | "needs-you/approval"
+ | "needs-you/budget"
+ | "failed"
+ | "ready"
+ | "working/queued"
+ | "working";
+
+/** 分组:进行中 / 等你 / 结束了 */
+export type StageGroup = "working" | "needs" | "ended";
+
+export interface Stage {
+ key: StageKey;
+ label: string;
+ group: StageGroup;
+}
+
+export interface StageInput {
+ /** 有人停了它 */
+ stopped: boolean;
+ /** 最近的结果 / 失败消息没送到会话(出站队列放弃了,或渠道要用户先做点什么) */
+ undelivered?: boolean;
+ /** 等用户回答(3b)或批准(阻塞着的审批) */
+ waiting?: "answer" | "approval";
+ /** 最近的 run(它的结果就是最近一次 Report 的状态:done / failed / needs_you) */
+ run?: { state: RunState; outcome: RunOutcome };
+}
+
+const STAGES: Record<StageKey, Stage> = {
+ stopped: { key: "stopped", label: "已停止", group: "ended" },
+ "needs-you/delivery": { key: "needs-you/delivery", label: "未送达", group: "needs" },
+ "needs-you/answer": { key: "needs-you/answer", label: "等你回答", group: "needs" },
+ "needs-you/approval": { key: "needs-you/approval", label: "等你批准", group: "needs" },
+ "needs-you/budget": { key: "needs-you/budget", label: "预算用完", group: "needs" },
+ failed: { key: "failed", label: "失败", group: "needs" },
+ ready: { key: "ready", label: "已完成", group: "ended" },
+ "working/queued": { key: "working/queued", label: "排队中", group: "working" },
+ working: { key: "working", label: "进行中", group: "working" },
+};
+
+export function stageOf(key: StageKey): Stage {
+ return STAGES[key];
+}
+
+/**
+ * 阶段表:
+ * 1 停止了 → 已停止;2 最近的消息没送到 → 未送达;3 有问题或审批在等 → 等你回答 / 等你批准;4 run 停在预算上 → 预算用完;
+ * 5 最近的 run 以失败结束(之后没有人的输入)→ 失败;6 以完成结束 → 已完成;7 有输入在等名额 → 排队中;8 其余 → 进行中。
+ * 人的输入(回答、追加、重试)会开新的 run,最近的 run 就不再是结束的那个;自动的输入(恢复)不越过 2–5。
+ */
+export function taskStage(i: StageInput): Stage {
+ if (i.stopped) return STAGES.stopped;
+ const run = i.run;
+ const ended = !run || run.state === "ended";
+ if (i.undelivered && ended) return STAGES["needs-you/delivery"];
+ if (i.waiting === "answer") return STAGES["needs-you/answer"];
+ if (i.waiting === "approval") return STAGES["needs-you/approval"];
+ if (ended && run?.outcome === "needs_you") return STAGES["needs-you/answer"];
+ if (ended && run?.outcome === "budget") return STAGES["needs-you/budget"];
+ if (ended && run?.outcome === "failed") return STAGES.failed;
+ if (ended && run?.outcome === "done") return STAGES.ready;
+ if (!run || run.state === "queued" || run.outcome === "interrupted" || run.outcome === "skipped") return STAGES["working/queued"];
+ return STAGES.working;
+}
diff --git a/src/web/server.ts b/src/web/server.ts
index dca8efb..8deea97 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -448,7 +448,39 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
return send(res, 200, { ok: true });
}
// busy:有消息在处理的机器人(纯对话、排队、代理还在启动都算),侧栏的"正在工作"
- if (p === "/agent" && m === "GET") return send(res, 200, { ...app.agent.status(), busy: [...new Set([...live.bots(), ...app.runtime.busyBots()])] });
+ // background:每个机器人正在进行的后台任务数
+ if (p === "/agent" && m === "GET") return send(res, 200, { ...app.agent.status(), busy: [...new Set([...live.bots(), ...app.runtime.busyBots()])], background: app.tasks.background() });
+ // —— 后台任务(3a:列表、详情、一个 run 的步骤、停止)——
+ if (seg[0] === "tasks") {
+ if (seg.length === 1 && m === "GET") {
+ const recent = url.searchParams.get("recent");
+ return send(res, 200, {
+ tasks: app.tasks.list({
+ botId: url.searchParams.get("bot") || undefined,
+ conversationId: url.searchParams.get("conversation") || undefined,
+ since: recent ? Date.now() - Math.min(30, Math.max(0, Number(recent) || 1)) * 86400_000 : undefined,
+ limit: Math.min(100, Number(url.searchParams.get("limit")) || 50),
+ }),
+ });
+ }
+ const task = seg[1] ? app.tasks.get(decodeURIComponent(seg[1])) : undefined;
+ if (!task) throw new HttpError(404, "任务不存在");
+ if (seg.length === 2 && m === "GET") {
+ const runs = app.store.listRuns({ taskId: task.id }).map((r) => ({ id: r.id, cause: r.cause, state: r.state, outcome: r.outcome, error: r.error, queuedAt: r.queuedAt, startedAt: r.startedAt, endedAt: r.endedAt, steps: app.tasks.activity(r.id).length }));
+ return send(res, 200, { task, runs });
+ }
+ if (seg.length === 5 && seg[2] === "runs" && seg[4] === "activity" && m === "GET") {
+ const run = app.store.getRun(decodeURIComponent(seg[3]));
+ if (!run || run.taskId !== task.id) throw new HttpError(404, "没有这次运行");
+ return send(res, 200, { steps: app.tasks.activity(run.id) });
+ }
+ if (seg.length === 3 && seg[2] === "stop" && m === "POST") {
+ const ok = await app.tasks.stopTask(task.id, "web");
+ if (!ok) throw new HttpError(409, "任务已经停止了");
+ return send(res, 200, { task: app.tasks.get(task.id) });
+ }
+ throw new HttpError(404, "not found");
+ }
// —— Windows:代理用的 PowerShell(对话空状态、设置 → 常规、故障排查)——
if (seg[0] === "pwsh") {
const view = () => ({ ...pwshProbe.snapshot(), dismissed: cfg.ui.pwshHintDismissed });
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index ae2e87d..46516bb 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -381,10 +381,10 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
const userTexts = (c: { body: any }) => (c.body.messages ?? []).filter((m: any) => m.role === "user").map((m: any) => textOf(m.content)) as string[];
const DEFAULT_PERSONA = "你是一个乐于助人的中文助手,回答简洁准确。";
/**
- * 系统提示词加工具定义的字符数上限(DSH 自己的部分 + 我们的人设、机器人段和工具;基线 32,208 = 提示词 3,310 + 工具 28,898,上限高约 5%)。
+ * 系统提示词加工具定义的字符数上限(DSH 自己的部分 + 我们的人设、机器人段和工具;基线 34,052 = 提示词 3,692 + 工具 30,360,其中后台任务的 task_start、task_message、task_list 约 1,460;上限高约 5%)。
* 缩短了就调低;要调高,在提交说明里写清原因。电脑操作的 MCP 工具随平台变化,不计入。
*/
- const SURFACE_BUDGET = 33_800;
+ const SURFACE_BUDGET = 35_800;
it("the system prompt has our persona and the bot's section, not DSH's coding persona; the segment's first message has channel and memory", async () => {
await chat("/reset");
diff --git a/test/prompts.unit.test.ts b/test/prompts.unit.test.ts
index 9c37d62..af13155 100644
--- a/test/prompts.unit.test.ts
+++ b/test/prompts.unit.test.ts
@@ -17,8 +17,14 @@ import {
agentPersona,
botIdentity,
botPrompt,
+ NUDGE,
+ TASK_RULES,
+ TASK_SECTION,
+ TASK_SECTION_ORDER,
placeLine,
+ recoveryNote,
segmentInput,
+ taskBrief,
} from "../src/agent/prompts/index.js";
import { AgentHost, locateDshRuntime } from "../src/agent/host.js";
import { normalizeSettings } from "../src/agent/settings.js";
@@ -30,15 +36,29 @@ const runtime = locateDshRuntime(findAppRoot());
/** 一个典型的用户人设(量长度用) */
const PERSONA = "你是一个乐于助人的中文助手,回答简洁准确。用户是一名独立开发者,平时用 TypeScript 和 Go,喜欢先看结论再看细节。";
-/** 用真实的 dsh-tools 加载我们的工具插件,拿到模型看到的工具定义 */
-async function ourTools(): Promise<Array<{ name: string; description: string; parameters: unknown }>> {
+type ToolDef = { name: string; description: string; parameters: unknown };
+const def = ({ name, description, parameters }: any): ToolDef => ({ name, description, parameters });
+
+/**
+ * 用真实的 dsh-tools 加载我们的工具插件,拿到模型看到的工具定义:聊天会话的(记忆、生图、后台任务的 task_start 等),
+ * 以及 amb-tasks 在任务会话建出来时给它的(task_report、任务规则段、去掉的工具)
+ */
+async function ourTools(): Promise<ToolDef[]> {
+ return (await loadPlugins()).chat;
+}
+async function loadPlugins(): Promise<{ chat: ToolDef[]; task: { tools: ToolDef[]; sections: any[]; deny: string[][] } }> {
const env = { ...process.env };
try {
- Object.assign(process.env, { AMB_BRIDGE_URL: "http://127.0.0.1:9", AMB_BRIDGE_TOKEN: "t", AMB_MEMORY: "1" });
+ Object.assign(process.env, { AMB_BRIDGE_URL: "http://127.0.0.1:9", AMB_BRIDGE_TOKEN: "t", AMB_MEMORY: "1", AMB_TASK_RULES: TASK_RULES });
const tools: any[] = [];
- const ctx = { tools: { register: (t: any) => tools.push(t) }, inject: () => {} };
- for (const f of ["amb-memory.mjs", "amb-media.mjs"]) (await import(path.join(runtime!, "plugins", f))).apply(ctx);
- return tools.map(({ name, description, parameters }) => ({ name, description, parameters }));
+ const created: Array<(e: any) => void> = [];
+ const ctx = { tools: { register: (t: any) => tools.push(t), get: (n: string) => tools.find((t) => t.name === n) ?? (n === "present" ? {} : undefined) }, inject: () => {}, on: (ev: string, fn: any) => ev === "agent/created" && created.push(fn), get: () => undefined };
+ for (const f of ["amb-memory.mjs", "amb-media.mjs", "amb-tasks.mjs"]) (await import(path.join(runtime!, "plugins", f))).apply(ctx);
+ // 任务会话建出来(或重启后恢复):amb-tasks 给它限定工具、加规则段、注册 task_report
+ const task = { tools: [] as ToolDef[], sections: [] as any[], deny: [] as string[][] };
+ const agent = { id: "task-t_1", ctx: { tools: { restrict: (f: any) => task.deny.push(f.deny), register: (t: any) => task.tools.push(def(t)), guard: () => {} }, systemPrompt: { section: (s: any) => task.sections.push(s) } } };
+ for (const fn of created) fn({ agent });
+ return { chat: tools.map(def), task };
} finally {
process.env = env;
}
@@ -62,6 +82,13 @@ async function parts(): Promise<Record<string, string>> {
"skill computer-use": CUA_SKILL,
"tool generate_image": tool("generate_image"),
"tool generate_video": tool("generate_video"),
+ "tool task_start": tool("task_start"),
+ "tool task_message": tool("task_message"),
+ task: TASK_RULES,
+ "task brief": taskBrief({ title: "GPU 价格调研", original: "帮我调研三家云的 GPU 价格", brief: "比较 A100 包月价", recent: [], attachments: [], memory: "", folder: "tasks/gpu-abc123" }),
+ "task recovery": recoveryNote(["sleep 600"]),
+ "task nudge": NUDGE,
+ "tool task_report": runtime ? JSON.stringify((await loadPlugins()).task.tools.find((t) => t.name === "task_report") ?? "") : "",
};
out["*"] = Object.values(out).join("\n\n");
return out;
@@ -97,6 +124,16 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [
["so the user confirms the model before anything is generated", "they will be asked again"]],
["生图工具:默认模型、花费不高直接生成", "tool generate_image", ["generates right away", "\"confirm\""], ["Before anything is generated the user is asked"]],
["生视频工具:默认模型、花费不高直接生成", "tool generate_video", ["generates right away", "\"confirm\""], ["Before anything is generated the user is asked"]],
+ // —— 后台任务(3a)——
+ ["聊天代理:长活或用户说后台做才开任务,能马上答的不开;开了只说一句,不自己做", "tool task_start", ["more than a few minutes or many steps", "后台做", "not for what you can answer now", "前台做", "in one sentence", "do not do the work yourself"]],
+ ["用户提到某个任务时把话转给它", "tool task_message", ["when they refer to it", "next step", "resumes"]],
+ ["任务规则优先于聊天规则;不问用户,自己决定并说明", "task", ["优先于上面的聊天规则", "不要问用户", "在结果里说明"], ["ask_user_question"]],
+ ["任务:外部动作前后记日志(重启后靠它不重复做)", "task", [".task/journal.md"]],
+ ["任务:做完或做不下去才说话,一句话,结果和在哪里;中途不汇报", "task", ["task_report", "done 或 failed", "不超过 300 字", "在哪里", "中途不用汇报", "不会发给用户"]],
+ ["task_report:done / failed 的那句话是用户收到的,progress 不发;报完结束这一轮", "tool task_report", ["one line the user receives", "at most 300 characters", "never sent", "end your turn"]],
+ ["任务的第一条输入:用户原话在前,说明在后", "task brief", ["[用户的原话]\n帮我调研三家云的 GPU 价格", "[对话助手的说明]\n比较 A100 包月价", "tasks/gpu-abc123"]],
+ ["恢复说明:被停的后台命令;重复外部动作之前先查日志和外部系统", "task recovery", ["The app restarted", "sleep 600", "Before repeating any outside action", ".task/journal.md", "task_report"]],
+ ["没报告时提醒一次:done 带一句话、failed 带原因", "task nudge", ["task_report", "done", "failed"]],
];
describe.skipIf(!runtime)("提示词约定", () => {
@@ -107,21 +144,42 @@ describe.skipIf(!runtime)("提示词约定", () => {
for (const words of gone) expect(text.toLowerCase()).not.toContain(words.toLowerCase());
});
- it("聊天规则和人设都短", () => {
+ it("聊天规则、人设和任务规则都短", () => {
expect(CHAT_RULES.length).toBeLessThan(440);
expect(agentPersona({ computerUse: true }).length).toBeLessThan(180);
+ expect(TASK_RULES.length).toBeLessThan(400);
+ });
+
+ it("任务会话:只去掉注册了的聊天专用工具,规则段在机器人段之后(优先),有 task_report;子代理拿不到任务工具", async () => {
+ const { task } = await loadPlugins();
+ // 只有 present 和三个任务工具是"注册了的":ask_user_question、rule_create 在这个假环境里没有,不能交给 restrict(它会抛错)
+ expect(task.deny).toEqual([["present", "task_start", "task_message", "task_list"]]);
+ expect(task.sections).toHaveLength(1);
+ expect(task.sections[0]).toMatchObject({ name: TASK_SECTION, order: TASK_SECTION_ORDER, interpolate: false });
+ expect(TASK_SECTION_ORDER).toBeGreaterThan(BOT_SECTION_ORDER);
+ expect(task.sections[0].text()).toBe(TASK_RULES);
+ expect(task.tools.map((t) => t.name)).toEqual(["task_report"]);
});
/**
- * 我们交给模型的部分:人设 + 机器人段(典型人设、开着记忆)+ 我们的工具定义(记忆、生图)。基线 7,145(提示词 907 + 工具 6,238),上限高约 5%。
+ * 我们交给模型的部分:人设 + 机器人段(典型人设、开着记忆)+ 我们的工具定义(记忆、生图、后台任务)。
+ * 基线 8,514(提示词 907 + 工具 7,607,其中 task_start、task_message、task_list 1,370),上限高约 5%。
* 缩短了就调低;要调高,在提交说明里写清原因。
*/
- const BUDGET = 7_500;
+ const BUDGET = 8_950;
it("我们的提示词加工具定义不超过字符数上限", async () => {
const prompt = agentPersona({ computerUse: true }).length + botPrompt({ name: "小蓝", persona: PERSONA, memory: true }).length;
const tools = JSON.stringify(await ourTools()).length;
expect(prompt + tools, `${prompt} characters of prompt and ${tools} of tools`).toBeLessThanOrEqual(BUDGET);
});
+
+ /** 任务会话在聊天会话之外多出来的:任务规则段 + task_report(去掉的工具不算)。基线 1,255(规则 363 + task_report 892),上限高约 5%。 */
+ const TASK_BUDGET = 1_320;
+ it("任务会话多出来的提示词和工具不超过字符数上限", async () => {
+ const { task } = await loadPlugins();
+ const extra = TASK_RULES.length + JSON.stringify(task.tools).length;
+ expect(extra, `${TASK_RULES.length} characters of rules and ${JSON.stringify(task.tools).length} of task_report`).toBeLessThanOrEqual(TASK_BUDGET);
+ });
});
describe("渠道说明与第一条消息", () => {
diff --git a/test/tasks.integration.test.ts b/test/tasks.integration.test.ts
new file mode 100644
index 0000000..229a5bc
--- /dev/null
+++ b/test/tasks.integration.test.ts
@@ -0,0 +1,288 @@
+/**
+ * 后台任务(3a)端到端:真实 DSH 子进程 + 脚本化的模型 + mock iLink(主人在微信里和自己的机器人聊)。
+ * 退出演示:微信里说「调研 Y」,聊天代理开一个后台任务,聊天照常回答;任务跑完,结果经出站队列回到同一个微信会话、只发一次;
+ * 任务跑到一半应用重启,带着恢复说明接着做,结果仍只发一次。另外:/stop 编号和界面的停止只停这个任务;
+ * 两个任务在跑时,聊天消息不排在它们后面(人的通道);收尾(后台命令)、没报告时的提醒、每种会话的工具。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import http from "node:http";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { locateDshRuntime } from "../src/agent/host.js";
+import { findAppRoot } from "../src/magpie/supervisor.js";
+import { listen, mockIlink } from "./helpers.js";
+
+const runtime = locateDshRuntime(findAppRoot());
+const hasBwrap = fs.existsSync("/usr/bin/bwrap");
+
+async function body(req: http.IncomingMessage): Promise<any> {
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
+}
+const textOf = (c: any): string => (typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => (typeof p === "string" ? p : (p?.text ?? ""))).join("") : "");
+type Step = { tool?: { name: string; args: any }; text?: string; hang?: boolean };
+
+describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("background tasks (real DSH, WeChat)", () => {
+ const OWNER = "[email protected]";
+ const CONV = `default:weixin:${OWNER}`;
+ let app: App;
+ let dataDir: string;
+ let llm: Awaited<ReturnType<typeof listen>>;
+ let ilink: Awaited<ReturnType<typeof mockIlink>>;
+ let base = "";
+ /** 每个模型请求:工具名、用户消息、是不是任务会话 */
+ const calls: Array<{ tools: string[]; users: string[]; task: boolean; at: number }> = [];
+ const hung: http.ServerResponse[] = [];
+
+ /** 脚本:聊天会话(没有 task_report)和任务会话(有)各自按最后一条带记号的用户消息走 */
+ function plan(messages: any[], tools: string[]): Step {
+ const task = tools.includes("task_report");
+ // DSH 在用户消息后面插"Current runtime context"那条:跳过它
+ let last = -1;
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user" && !/^Current runtime context/.test(textOf(messages[i].content))) { last = i; break; }
+ const user = textOf(messages[last]?.content);
+ const done = messages.slice(last + 1).filter((m) => m.role === "tool").length;
+ if (!task) {
+ const r = /RESEARCH (\w+)/.exec(user);
+ if (r) return done ? { text: `ACK-${r[1]}:好,后台开始调研,好了告诉你,你可以继续聊别的。` } : { tool: { name: "task_start", args: { title: `调研 ${r[1]}`, brief: `research ${r[1]} and write notes.md` } } };
+ const p = /PING (\w+)/.exec(user);
+ if (p) return { text: `PONG-${p[1]}` };
+ const l = /LISTTOOLS/.exec(user);
+ if (l) return { text: `CHATTOOLS<<${tools.join(",")}>>` };
+ return { text: "好的" };
+ }
+ // 任务会话:最近一条带记号的输入(第一条输入里是用户原话)
+ const all = messages.map((m, i) => ({ i, role: m.role, text: textOf(m.content) }));
+ const tag = /RESEARCH (\w+)/.exec(all.find((m) => m.role === "user" && /\[用户的原话\]/.test(m.text))?.text ?? "")?.[1] ?? "X";
+ // at:这一轮里前面已经有几次工具调用(报告是第 at+1 个)
+ const report = (message: string, at = 0): Step => (done > at ? { text: "已报告" } : { tool: { name: "task_report", args: { state: "done", summary: `notes for ${tag}`, message, files: tag.startsWith("FILE") ? ["notes.md"] : [] } } });
+ if (/The app restarted while you were working/.test(user)) return report(`RECOVERED-${tag}:调研好了,结论在 notes.md。`);
+ if (/^Report this task's state with task_report now/.test(user)) return report(`NUDGED-${tag}`);
+ if (/^background job /.test(user)) return report(`BGRESULT-${tag}`);
+ if (tag.startsWith("HANG")) return { hang: true };
+ if (tag.startsWith("TOOLS")) return done ? { text: `TASKTOOLS` } : report(`TASKTOOLS-${tag}<<${tools.join(",")}>>`);
+ if (tag.startsWith("QUIET")) return { text: "我做完了" }; // 不调用 task_report:宿主提醒一次
+ if (tag.startsWith("BG")) return done ? { text: "后台命令在跑" } : { tool: { name: "bash", args: { description: "run", command: "sleep 2 && echo bg-done", run_in_background: true } } };
+ // SLOW / FILE:跑一条几秒的命令写文件,再报告
+ if (done === 0) return { tool: { name: "bash", args: { description: "run", command: `sleep 3 && pwd > notes.md && echo found-${tag} >> notes.md && cat notes.md` } } };
+ return report(`RESULT-${tag}:调研好了,结论在 notes.md。`, 1);
+ }
+
+ const makeApp = () =>
+ new App(loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: ilink.url, AMB_DEFAULT_MODEL: "mock-agent", AMB_AGENT_PREWARM: "0" } }), {
+ printQrToTerminal: false,
+ weixinPollTimeoutMs: 1000,
+ });
+
+ beforeAll(async () => {
+ llm = await listen(async (req, res) => {
+ const url = req.url?.split("?")[0] ?? "";
+ if (url.endsWith("/models")) return void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ object: "list", data: [{ id: "mock-agent", object: "model" }] }));
+ const b = await body(req);
+ const tools = (b.tools ?? []).map((t: any) => t.function?.name ?? t.name);
+ const step: Step = b.tools ? plan(b.messages ?? [], tools) : { text: "标题" };
+ if (b.tools) calls.push({ tools, users: (b.messages ?? []).filter((m: any) => m.role === "user").map((m: any) => textOf(m.content)), task: tools.includes("task_report"), at: Date.now() });
+ 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: any) => res.write(`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", model: b.model, ...o })}\n\n`);
+ if (step.tool) {
+ send({ choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_" + Math.random().toString(36).slice(2, 8), type: "function", function: { name: step.tool.name, arguments: JSON.stringify(step.tool.args) } }] } }] });
+ send({ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] });
+ } else {
+ send({ choices: [{ index: 0, delta: { role: "assistant", content: step.text } }] });
+ send({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] });
+ }
+ send({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } });
+ res.end("data: [DONE]\n\n");
+ });
+ ilink = await mockIlink();
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-"));
+ app = makeApp();
+ // 主人已经扫码登录;渠道连到 mock iLink
+ app.store.createBot({ id: "default", name: "小蓝", weixinEnabled: true, settings: { avatar: "blue" } as any });
+ app.store.saveWeixinAccount({ botId: "default", botToken: "tok", ilinkBotId: "[email protected]", baseUrl: ilink.url, ownerUserId: OWNER });
+ await app.start();
+ base = app.web!.url.replace(/\/+$/, "");
+ }, 60_000);
+
+ afterAll(async () => {
+ for (const r of hung.splice(0)) r.destroy();
+ await app?.stop();
+ await llm?.close();
+ await ilink?.close();
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ const api = async (p: string, init?: RequestInit) => (await fetch(`${base}/amb/api${p}`, init)).json() as Promise<any>;
+ const waitFor = async (fn: () => boolean | Promise<boolean>, ms = 60_000) => {
+ for (const end = Date.now() + ms; Date.now() < end; await new Promise((r) => setTimeout(r, 100))) if (await fn()) return;
+ throw new Error("waitFor: timeout");
+ };
+ /** 发给主人的、以这段文字开头的微信消息 */
+ const sentTo = (text: string) => ilink.state.sent.filter((s) => s.to === OWNER && s.text.startsWith(text));
+ const taskOf = (tag: string) => app.tasks.list({ conversationId: CONV, limit: 100 }).find((t) => t.title === `调研 ${tag}`);
+ /** 在微信里请机器人后台调研:等它回了确认、任务建好 */
+ const research = async (tag: string) => {
+ ilink.push(OWNER, `RESEARCH ${tag}`);
+ await waitFor(() => sentTo(`ACK-${tag}`).length === 1);
+ await waitFor(() => !!taskOf(tag));
+ return taskOf(tag)!;
+ };
+ const stage = (tag: string) => taskOf(tag)?.stage.key;
+ /** 任务在跑一轮:模型请求挂着(HANG) */
+ const hanging = (tag: string) => calls.some((c) => c.task && c.users.some((u) => u.includes(`RESEARCH ${tag}`)));
+
+ it("demo: 'research Y' from WeChat runs in the background while chat continues; the result reaches the same chat once, through the outbox", async () => {
+ const host = app.agent.host("default");
+ const t = await research("SLOWY");
+ expect(t.stage.group).toBe("working");
+ expect(t.folder).toBe(`tasks/slowy-${t.id.slice(2, 8)}`);
+ // 任务在跑的时候聊天照常回答
+ await waitFor(() => calls.some((c) => c.task && c.users.some((u) => u.includes("RESEARCH SLOWY"))));
+ expect(stage("SLOWY")).toBe("working");
+ const t0 = Date.now();
+ ilink.push(OWNER, "PING during");
+ await waitFor(() => sentTo("PONG-during").length === 1);
+ expect(Date.now() - t0).toBeLessThan(10_000);
+ expect(stage("SLOWY")).toBe("working");
+ // 结果:一句话,经出站队列发回同一个微信会话,只发一次
+ await waitFor(() => sentTo("RESULT-SLOWY").length === 1);
+ await waitFor(() => stage("SLOWY") === "ready");
+ await new Promise((r) => setTimeout(r, 1500));
+ await app.outbox.idle();
+ expect(sentTo("RESULT-SLOWY")).toHaveLength(1);
+ const rows = app.store.listOutbox({ botId: "default", limit: 500 }).filter((r) => r.id.startsWith(`task:${t.id}:`));
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ status: "sent", channel: "weixin", peerId: OWNER });
+ expect(rows[0].id).toMatch(new RegExp(`^task:${t.id}:result:r_[0-9a-f]{12}$`));
+ // 任务在自己的文件夹里干活(在工作区里)
+ const notes = fs.readFileSync(path.join(host.workspace, t.folder, "notes.md"), "utf8");
+ expect(notes).toContain(path.join(host.workspace, t.folder));
+ expect(notes).toContain("found-SLOWY");
+ // 会话历史里有这句结果;聊天代理的下一条输入带着便条
+ expect(app.store.listMessages(CONV).map((m) => m.content)).toContain("RESULT-SLOWY:调研好了,结论在 notes.md。");
+ ilink.push(OWNER, "PING after");
+ await waitFor(() => sentTo("PONG-after").length === 1);
+ const after = calls.findLast((c) => !c.task && c.users.some((u) => u.includes("PING after")))!;
+ expect(after.users.at(-1)).toMatch(/^\[后台任务「调研 SLOWY」已完成,已把结果发给用户\] RESULT-SLOWY/);
+ // 一个 run,结果 done,有步骤;没有重启过代理进程
+ const d = await api(`/tasks/${t.id}`);
+ expect(d.runs.map((r: any) => [r.cause, r.state, r.outcome])).toEqual([["launch", "ended", "done"]]);
+ expect(d.runs[0].steps).toBeGreaterThan(2);
+ expect(d.task.stage).toMatchObject({ key: "ready", label: "已完成" });
+ expect(host.restarts).toBe(0);
+ }, 180_000);
+
+ it("each session kind gets its own tools: tasks report and never present, ask or start tasks; chats start tasks but cannot report", async () => {
+ ilink.push(OWNER, "LISTTOOLS");
+ await waitFor(() => sentTo("CHATTOOLS<<").length === 1);
+ const chatTools = /CHATTOOLS<<(.*)>>/.exec(sentTo("CHATTOOLS<<")[0].text)![1].split(",");
+ expect(chatTools).toEqual(expect.arrayContaining(["task_start", "task_message", "task_list", "present", "ask_user_question"]));
+ expect(chatTools).not.toContain("task_report");
+ await research("TOOLS1");
+ await waitFor(() => stage("TOOLS1") === "ready");
+ const taskTools = calls.find((c) => c.task && c.users.some((u) => u.includes("RESEARCH TOOLS1")))!.tools;
+ expect(taskTools).toContain("task_report");
+ for (const t of ["present", "ask_user_question", "task_start", "task_message", "task_list"]) expect(taskTools).not.toContain(t);
+ }, 120_000);
+
+ it("a turn that ends without task_report gets one nudge; a background job keeps the run settling until it ends", async () => {
+ await research("QUIET1");
+ await waitFor(() => sentTo("NUDGED-QUIET1").length === 1);
+ expect(stage("QUIET1")).toBe("ready");
+ const nudges = calls.filter((c) => c.task && c.users.some((u) => u.includes("RESEARCH QUIET1"))).at(-1)!.users.filter((u) => /^Report this task's state/.test(u));
+ expect(nudges).toHaveLength(1);
+ // 后台命令:这一轮没报告就结束了,但命令还在跑——run 收尾中(仍占名额),命令结束唤醒代理,它报告完才结束
+ const t = await research("BG1");
+ await waitFor(async () => (await api(`/tasks/${t.id}`)).runs[0]?.state === "settling", 30_000);
+ expect(stage("BG1")).toBe("working");
+ await waitFor(() => sentTo("BGRESULT-BG1").length === 1);
+ expect(stage("BG1")).toBe("ready");
+ expect(calls.filter((c) => c.task && c.users.some((u) => u.includes("RESEARCH BG1"))).at(-1)!.users.some((u) => /^Report this task's state/.test(u))).toBe(false);
+ }, 120_000);
+
+ it("the human lane: a chat message never waits behind 2 running tasks; a third task waits for a slot", async () => {
+ const a = await research("HANGA");
+ const b = await research("HANGB");
+ await waitFor(() => hanging("HANGA") && hanging("HANGB"));
+ expect([stage("HANGA"), stage("HANGB")]).toEqual(["working", "working"]);
+ const c = await research("HANGC");
+ expect(stage("HANGC")).toBe("working/queued");
+ expect(hanging("HANGC")).toBe(false);
+ const t0 = Date.now();
+ ilink.push(OWNER, "PING lane");
+ await waitFor(() => sentTo("PONG-lane").length === 1);
+ expect(Date.now() - t0).toBeLessThan(5_000);
+ expect([stage("HANGA"), stage("HANGB"), stage("HANGC")]).toEqual(["working", "working", "working/queued"]);
+ // 停掉一个,排队的那个接上
+ expect(await app.tasks.stopTask(a.id, "test")).toBe(true);
+ await waitFor(() => hanging("HANGC"));
+ expect(stage("HANGC")).toBe("working");
+ await app.tasks.stopTask(b.id, "test");
+ await app.tasks.stopTask(c.id, "test");
+ }, 180_000);
+
+ it("/stop <n> from WeChat and the UI stop button stop one task; chat and the agent process carry on", async () => {
+ const host = app.agent.host("default");
+ const pid = host.pid;
+ await research("HANGS1");
+ await waitFor(() => hanging("HANGS1"));
+ // /tasks 列出编号;/stop 1 停掉它(插队,不进会话队列)
+ ilink.push(OWNER, "/tasks");
+ await waitFor(() => sentTo("后台任务:").length >= 1);
+ expect(sentTo("后台任务:").at(-1)!.text).toMatch(/^后台任务:\n1\. 调研 HANGS1 · 进行中/);
+ ilink.push(OWNER, "/stop 1");
+ await waitFor(() => sentTo("已停止后台任务「调研 HANGS1」").length === 1);
+ await waitFor(() => stage("HANGS1") === "stopped");
+ ilink.push(OWNER, "PING stopped1");
+ await waitFor(() => sentTo("PONG-stopped1").length === 1);
+ // 界面的停止
+ const t2 = await research("HANGS2");
+ await waitFor(() => hanging("HANGS2"));
+ const r = await api(`/tasks/${t2.id}/stop`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ expect(r.task.stage.key).toBe("stopped");
+ ilink.push(OWNER, "PING stopped2");
+ await waitFor(() => sentTo("PONG-stopped2").length === 1);
+ // 停掉的任务不发任何东西;代理进程没重启
+ await new Promise((r) => setTimeout(r, 1000));
+ expect(ilink.state.sent.filter((s) => /HANGS[12]/.test(s.text) && !/已停止|ACK-/.test(s.text))).toEqual([]);
+ expect(host.pid).toBe(pid);
+ expect(host.state).toBe("running");
+ }, 180_000);
+
+ it("an app restart mid-task: the task resumes with the recovery note (once), and its result still arrives once", async () => {
+ const t = await research("HANGR");
+ await waitFor(() => hanging("HANGR"));
+ const sessionId = app.store.getTask(t.id)!.sessionId;
+ // 应用退出:跑着的 run 留在库里
+ await app.stop();
+ for (const r of hung.splice(0)) r.destroy();
+ // 重新启动(同一个数据目录):run 记为中断,排恢复;恢复说明是新 run 的第一条输入
+ app = makeApp();
+ await app.start();
+ base = app.web!.url.replace(/\/+$/, "");
+ await waitFor(() => sentTo("RECOVERED-HANGR").length === 1, 90_000);
+ await waitFor(() => stage("HANGR") === "ready");
+ const d = await api(`/tasks/${t.id}`);
+ expect(d.runs.map((r: any) => [r.cause, r.outcome])).toEqual([
+ ["launch", "interrupted"],
+ ["recover", "done"],
+ ]);
+ // 同一个会话恢复过来(历史里还有原来的任务说明),恢复说明只交了一次
+ expect(app.store.getTask(t.id)!.sessionId).toBe(sessionId);
+ const last = calls.filter((c) => c.task && c.users.some((u) => u.includes("RESEARCH HANGR"))).at(-1)!;
+ expect(last.users.filter((u) => /The app restarted while you were working/.test(u))).toHaveLength(1);
+ expect(last.users.filter((u) => u.includes("[用户的原话]\nRESEARCH HANGR"))).toHaveLength(1);
+ await new Promise((r) => setTimeout(r, 1500));
+ await app.outbox.idle();
+ expect(sentTo("RECOVERED-HANGR")).toHaveLength(1);
+ expect(app.store.listOutbox({ botId: "default", limit: 500 }).filter((r) => r.id.startsWith(`task:${t.id}:`))).toHaveLength(1);
+ // 重启前的任务结果没有被重发
+ expect(sentTo("RESULT-SLOWY")).toHaveLength(1);
+ }, 240_000);
+});
diff --git a/test/tasks.unit.test.ts b/test/tasks.unit.test.ts
new file mode 100644
index 0000000..b686bd2
--- /dev/null
+++ b/test/tasks.unit.test.ts
@@ -0,0 +1,571 @@
+/**
+ * 后台任务(3a)的零件:阶段表(一行一行)、名额(每个机器人、总数、人的预留名额与先后)、
+ * TaskService 对着一个假的宿主:建任务与第一条输入、一轮结束与收尾、Report、提醒、出错重试、追加、停止、
+ * 重启恢复(恢复说明在前、没收下的输入再交一次)、送达(出站队列 id 固定,只交一次)、/tasks 与 /stop 编号。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { taskStage, type StageInput } from "../src/tasks/stage.js";
+import { byPriority, pickRuns, priorityOf, type Waiting } from "../src/tasks/slots.js";
+import { TaskService, slugOf, takeTaskNotes, type TaskHost, type TaskNotification } from "../src/tasks/service.js";
+import { AgentHost, ResumeFailed } from "../src/agent/host.js";
+import { DEFAULT_SETTINGS, normalizeSettings } from "../src/agent/settings.js";
+import { NUDGE, TASK_RULES, recoveryNote, taskBrief } from "../src/agent/prompts/index.js";
+import { Outbox } from "../src/core/outbox.js";
+import { Store } from "../src/store/db.js";
+
+const flush = async (n = 5) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setImmediate(r));
+};
+
+describe("阶段表:第一条符合的为准", () => {
+ const run = (state: any, outcome: any = "") => ({ state, outcome });
+ const rows: Array<[string, StageInput, string, string]> = [
+ ["1 停止了,哪怕结果没送到", { stopped: true, undelivered: true, run: run("ended", "stopped") }, "stopped", "已停止"],
+ ["2 结果没送到", { stopped: false, undelivered: true, run: run("ended", "done") }, "needs-you/delivery", "未送达"],
+ ["2 失败消息没送到", { stopped: false, undelivered: true, run: run("ended", "failed") }, "needs-you/delivery", "未送达"],
+ ["3 等你回答", { stopped: false, waiting: "answer", run: run("running") }, "needs-you/answer", "等你回答"],
+ ["3 等你批准(阻塞着的审批)", { stopped: false, waiting: "approval", run: run("running") }, "needs-you/approval", "等你批准"],
+ ["3 run 以问题结束", { stopped: false, run: run("ended", "needs_you") }, "needs-you/answer", "等你回答"],
+ ["4 预算用完", { stopped: false, run: run("ended", "budget") }, "needs-you/budget", "预算用完"],
+ ["5 失败", { stopped: false, run: run("ended", "failed") }, "failed", "失败"],
+ ["6 已完成", { stopped: false, run: run("ended", "done") }, "ready", "已完成"],
+ ["7 排队中", { stopped: false, run: run("queued") }, "working/queued", "排队中"],
+ ["7 中断后等恢复", { stopped: false, run: run("ended", "interrupted") }, "working/queued", "排队中"],
+ ["8 进行中", { stopped: false, run: run("running") }, "working", "进行中"],
+ ["8 收尾中(后台命令还在跑)也是进行中", { stopped: false, run: run("settling") }, "working", "进行中"],
+ ["人的输入开了新 run:失败之后又在进行", { stopped: false, run: run("queued") }, "working/queued", "排队中"],
+ ["送达问题只在 run 结束后才算", { stopped: false, undelivered: true, run: run("running") }, "working", "进行中"],
+ ];
+ it.each(rows)("%s", (_name, input, key, label) => {
+ const s = taskStage(input);
+ expect([s.key, s.label]).toEqual([key, label]);
+ });
+ it("分组:进行中、等你、结束了", () => {
+ expect(taskStage({ stopped: false, run: run("running") }).group).toBe("working");
+ expect(taskStage({ stopped: false, run: run("ended", "failed") }).group).toBe("needs");
+ expect(taskStage({ stopped: false, run: run("ended", "done") }).group).toBe("ended");
+ expect(taskStage({ stopped: true }).group).toBe("ended");
+ });
+});
+
+describe("名额:每个机器人 2 个、总共 4 个,聊天不占;人的唤醒可多用一个、排在前面", () => {
+ const limits = { perBot: () => 2, global: 4 };
+ const q = (id: string, botId: string, priority: Waiting["priority"], queuedAt: number): Waiting => ({ id, botId, priority, queuedAt });
+ it("起因 → 先后", () => {
+ expect(["launch", "recover", "schedule", "followup", "answer", "retry", "continue", "manual"].map((c) => priorityOf(c as any))).toEqual(["launch", "recover", "rule", "person", "person", "person", "person", "person"]);
+ });
+ it("人的唤醒 → 启动 → 恢复 → 规则,同一级按排队时间", () => {
+ const list = [q("r", "a", "rule", 1), q("rec", "a", "recover", 2), q("l2", "a", "launch", 5), q("l1", "a", "launch", 3), q("p", "a", "person", 9)];
+ expect(byPriority(list).map((x) => x.id)).toEqual(["p", "l1", "l2", "rec", "r"]);
+ });
+ it("每个机器人最多 2 个", () => {
+ const picks = pickRuns([q("1", "a", "launch", 1), q("2", "a", "launch", 2), q("3", "a", "launch", 3)], [], limits);
+ expect(picks.map((x) => x.id)).toEqual(["1", "2"]);
+ expect(pickRuns([q("3", "a", "launch", 3)], [{ botId: "a" }, { botId: "a" }], limits)).toEqual([]);
+ });
+ it("所有机器人加起来最多 4 个", () => {
+ const running = [{ botId: "a" }, { botId: "a" }, { botId: "b" }];
+ expect(pickRuns([q("c1", "c", "launch", 1), q("c2", "c", "launch", 2)], running, limits).map((x) => x.id)).toEqual(["c1"]);
+ });
+ it("人的唤醒:本机器人多一个预留名额,也不受总数限制,并排在排队的启动前面", () => {
+ const running = [{ botId: "a" }, { botId: "a" }, { botId: "b" }, { botId: "b" }];
+ const picks = pickRuns([q("launch", "a", "launch", 1), q("answer", "a", "person", 5), q("answer2", "a", "person", 6)], running, limits);
+ expect(picks.map((x) => x.id)).toEqual(["answer"]);
+ });
+ it("名额空出来时,排在前面的先走", () => {
+ const picks = pickRuns([q("rec", "a", "recover", 1), q("launch", "a", "launch", 9)], [{ botId: "a" }], limits);
+ expect(picks.map((x) => x.id)).toEqual(["launch"]);
+ });
+ it("不同机器人各算各的", () => {
+ const picks = pickRuns([q("a1", "a", "launch", 1), q("b1", "b", "launch", 2)], [{ botId: "a" }, { botId: "a" }], limits);
+ expect(picks.map((x) => x.id)).toEqual(["b1"]);
+ });
+});
+
+describe("文件夹名与提示词", () => {
+ it("slug:标题里的字母数字,中文标题是 task", () => {
+ expect(slugOf("GPU 价格调研")).toBe("gpu");
+ expect(slugOf("Build the Quarterly Report deck!")).toBe("build-the-quarterly-repo");
+ expect(slugOf("季度报告")).toBe("task");
+ });
+ it("第一条输入:用户原话在最前,说明不能替代原话", () => {
+ const t = taskBrief({ title: "GPU 价格调研", original: "帮我调研三家云的 GPU 价格", brief: "比较 A100", recent: [{ role: "user", text: "你好" }], attachments: ["inbox/a.pdf"], memory: "- 用户在上海", folder: "tasks/gpu-abc123" });
+ expect(t.indexOf("[用户的原话]\n帮我调研三家云的 GPU 价格")).toBeLessThan(t.indexOf("[对话助手的说明]\n比较 A100"));
+ expect(t).toContain("[之前的对话]\n用户:你好");
+ expect(t).toContain("[附件]\ninbox/a.pdf");
+ expect(t).toContain("[长期记忆快照]\n- 用户在上海");
+ expect(t).toContain("tasks/gpu-abc123");
+ });
+ it("恢复说明:被停掉的后台命令、先看日志和外部系统再重复外部动作", () => {
+ expect(recoveryNote([])).toContain("these background jobs were stopped: none.");
+ expect(recoveryNote(["sleep 600"])).toContain("stopped: sleep 600.");
+ expect(recoveryNote([])).toContain("read `.task/journal.md`");
+ });
+});
+
+/** 假的宿主:记下交给会话的输入、插话、停止;安静与否按队列回答 */
+class FakeHost implements TaskHost {
+ available = true;
+ prompts: Array<{ botId: string; sessionId: string; folder: string; model: string; text: string; resume: boolean; id: string }> = [];
+ steers: Array<{ sessionId: string; id: string; text: string }> = [];
+ stops: string[] = [];
+ quiets: Array<{ quiet: boolean; jobs?: string[] }> = [];
+ steerOk = true;
+ failResume = false;
+ failPrompt = 0;
+ settingsValue = { ...DEFAULT_SETTINGS };
+ private n = 0;
+ constructor(readonly ws: string) {}
+ workspace() {
+ return this.ws;
+ }
+ settings() {
+ return this.settingsValue;
+ }
+ memoryPrefix() {
+ return "- 用户叫小王";
+ }
+ async prompt(botId: string, o: { sessionId: string; folder: string; model: string; text: string; resume: boolean }) {
+ if (this.failPrompt > 0) {
+ this.failPrompt--;
+ throw new Error("代理进程启动失败");
+ }
+ if (o.resume && this.failResume) throw new ResumeFailed("session not found");
+ const id = `msg-${++this.n}`;
+ this.prompts.push({ botId, ...o, id });
+ return id;
+ }
+ async steer(_botId: string, sessionId: string, id: string, text: string) {
+ this.steers.push({ sessionId, id, text });
+ return this.steerOk;
+ }
+ async stop(_botId: string, sessionId: string) {
+ this.stops.push(sessionId);
+ }
+ async quiet() {
+ return this.quiets.shift() ?? { quiet: true };
+ }
+}
+
+describe("TaskService(假宿主)", () => {
+ let store: Store;
+ let host: FakeHost;
+ let outbox: Outbox;
+ let svc: TaskService;
+ let ws: string;
+ const CONV = "b:weixin:owner";
+
+ const make = () => new TaskService({ store, host, outbox, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });
+ beforeEach(() => {
+ ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-unit-"));
+ store = new Store(":memory:");
+ store.createBot({ id: "b", name: "小蓝" });
+ store.ensureConversation("b", "weixin", "owner", "owner");
+ store.addMessage(CONV, "user", "早上好");
+ store.addMessage(CONV, "assistant", "早");
+ store.addMessage(CONV, "user", "帮我后台调研一下三家云的 GPU 价格 [文件 价目.pdf → inbox/20261031-x-价目.pdf]");
+ host = new FakeHost(ws);
+ outbox = new Outbox(store);
+ svc = make();
+ svc.start();
+ });
+ afterEach(() => {
+ svc.stop();
+ store.close();
+ fs.rmSync(ws, { recursive: true, force: true });
+ });
+
+ const ev = (sessionId: string, type: string, data: any = {}): TaskNotification => ({ method: "session.event", params: { sessionId, event: { type, data, time: Date.now() } } });
+ const status = (sessionId: string, s: "running" | "idle"): TaskNotification => ({ method: "session.status", params: { sessionId, status: s } });
+ /** 会话收下最近一次交给它的输入,跑一轮;during 在这一轮中间做点什么(报告、出错) */
+ const turn = async (sessionId: string, during?: () => void | Promise<void>, end: any = { kind: "completed" }) => {
+ const p = host.prompts.filter((x) => x.sessionId === sessionId).at(-1)!;
+ svc.onEvent("b", sessionId, status(sessionId, "running"));
+ svc.onEvent("b", sessionId, ev(sessionId, "turn/start", { turn: 1 }));
+ svc.onEvent("b", sessionId, ev(sessionId, "user/message", { id: p.id, role: "user", content: [{ type: "text", text: p.text }] }));
+ await during?.();
+ svc.onEvent("b", sessionId, ev(sessionId, "turn/end", { turn: 1, reason: end }));
+ svc.onEvent("b", sessionId, status(sessionId, "idle"));
+ await flush();
+ };
+ const start = (title = "GPU 价格调研") => {
+ const r = svc.create({ botId: "b", conversationId: CONV, title, brief: "比较三家云 A100 的包月价格" });
+ expect(r.error).toBeUndefined();
+ return r.task!;
+ };
+ const report = (sessionId: string, state: string, message = "", files?: string[]) => svc.report({ sessionId, state, summary: "查了三家", message, files });
+ const runs = (taskId: string) => store.listRuns({ taskId }).map((r) => [r.cause, r.state, r.outcome]);
+
+ it("建任务:自己的会话和文件夹,第一条输入有用户原话、说明、之前的对话、附件和记忆;交给会话时是新会话", async () => {
+ const t = start();
+ await flush();
+ expect(t.id).toMatch(/^t_[0-9a-f]{12}$/);
+ expect(t.sessionId).toBe(`task-${t.id}`);
+ expect(t.folder).toBe(`tasks/gpu-${t.id.slice(2, 8)}`);
+ expect(t.permission).toBe("workspace");
+ expect(t.model).toBe("mock-model");
+ expect(fs.existsSync(path.join(ws, t.folder))).toBe(true);
+ expect(host.prompts).toHaveLength(1);
+ const p = host.prompts[0];
+ expect(p).toMatchObject({ sessionId: t.sessionId, folder: path.join(ws, t.folder), resume: false, model: "mock-model" });
+ expect(p.text).toContain("[用户的原话]\n帮我后台调研一下三家云的 GPU 价格");
+ expect(p.text).toContain("[对话助手的说明]\n比较三家云 A100 的包月价格");
+ expect(p.text).toContain("用户:早上好\n助手:早");
+ expect(p.text).toContain("[附件]\ninbox/20261031-x-价目.pdf");
+ expect(p.text).toContain("- 用户叫小王");
+ expect(svc.get(t.id)!.stage.key).toBe("working");
+ expect(store.getTask(t.id)!.originMessageId).toBe(store.listMessages(CONV).at(-1)!.id);
+ });
+
+ it("一轮结束、会话安静:按 done 结束,那句话经出站队列发回原会话(id 固定),写进历史,给聊天代理留便条;只交一次", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId, () => void expect(report(t.sessionId, "done", "GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800。").text).toMatch(/^Recorded/));
+ expect(runs(t.id)).toEqual([["launch", "ended", "done"]]);
+ const run = store.listRuns({ taskId: t.id })[0];
+ const id = `task:${t.id}:result:${run.id}`;
+ expect(run.delivery).toBe(id);
+ const row = store.getOutbox(id)!;
+ expect(row).toMatchObject({ channel: "weixin", peerId: "owner", kind: "text", status: "pending", conversationId: CONV });
+ expect(row.body.text).toBe("GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800。");
+ expect(store.listMessages(CONV).at(-1)!.content).toBe(row.body.text);
+ expect(svc.get(t.id)!.stage.key).toBe("ready");
+ expect(store.getTask(t.id)!.endReason).toBe("done");
+ expect(takeTaskNotes(store, CONV)).toBe(`[后台任务「GPU 价格调研」已完成,已把结果发给用户] ${row.body.text}`);
+ expect(takeTaskNotes(store, CONV)).toBe("");
+ // 重启后不再交一次
+ svc.stop();
+ svc = make();
+ svc.start();
+ expect(store.listOutbox({ limit: 50 }).filter((r) => r.id.startsWith(`task:${t.id}`))).toHaveLength(1);
+ expect(store.listMessages(CONV).filter((m) => m.content === row.body.text)).toHaveLength(1);
+ });
+
+ it("失败:⚠️ 加任务名和原因;progress 只记下、不发", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId, () => {
+ expect(report(t.sessionId, "progress", "已比较两家").text).toMatch(/^Progress recorded/);
+ report(t.sessionId, "failed", "X 云的价格页要登录,我进不去");
+ });
+ expect(runs(t.id)).toEqual([["launch", "ended", "failed"]]);
+ expect(store.listMessages(CONV).at(-1)!.content).toBe("⚠️「GPU 价格调研」没做完:X 云的价格页要登录,我进不去");
+ expect(svc.get(t.id)!.stage.key).toBe("failed");
+ expect(store.listOutbox({ limit: 50 }).map((r) => r.id)).toEqual([`task:${t.id}:failure:${store.listRuns({ taskId: t.id })[0].id}`]);
+ });
+
+ it("问用户在 3a 不可用:needs_you 被拒,代理自己决定", async () => {
+ const t = start();
+ await flush();
+ expect(report(t.sessionId, "needs_you").error).toMatch(/cannot ask the user/);
+ expect(report(t.sessionId, "maybe").error).toMatch(/state must be/);
+ });
+
+ it("这一轮没报告:提醒一次;还没有就失败(没有给出结果)", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId);
+ expect(host.prompts.at(-1)!.text).toBe(NUDGE);
+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);
+ await turn(t.sessionId);
+ expect(runs(t.id)).toEqual([["launch", "ended", "failed"]]);
+ expect(store.listMessages(CONV).at(-1)!.content).toBe("⚠️「GPU 价格调研」没做完:没有给出结果");
+ });
+
+ it("这一轮出错:过一会儿带着错误接着做(最多 3 次)", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId, undefined, { kind: "error", error: { message: "upstream 503" } });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(host.prompts.at(-1)!.text).toMatch(/^Your previous step failed with an error: upstream 503\./);
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ expect(runs(t.id)).toEqual([["launch", "ended", "done"]]);
+ });
+
+ it("收尾:会话空了还有后台命令时占着名额(settling),插件报 settled 后才结束;没收下的输入时的空闲不算", async () => {
+ const t = start();
+ await flush();
+ // 旧的空闲(输入还没被收下):不结束
+ svc.onEvent("b", t.sessionId, status(t.sessionId, "idle"));
+ await flush();
+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);
+ host.quiets.push({ quiet: false, jobs: ["bash-1"] });
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ expect(runs(t.id)).toEqual([["launch", "settling", ""]]);
+ expect(svc.get(t.id)!.stage.key).toBe("working");
+ // 后台命令结束,代理被叫醒又跑一轮:还是这个 run
+ svc.onEvent("b", t.sessionId, status(t.sessionId, "running"));
+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);
+ expect(svc.settled({ sessionId: t.sessionId })).toEqual({ ok: true });
+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);
+ host.quiets.push({ quiet: false });
+ svc.onEvent("b", t.sessionId, status(t.sessionId, "idle"));
+ await flush();
+ expect(runs(t.id)).toEqual([["launch", "settling", ""]]);
+ svc.settled({ sessionId: t.sessionId, killedJobs: [] });
+ expect(runs(t.id)).toEqual([["launch", "ended", "done"]]);
+ });
+
+ it("名额:同一机器人第三个任务排队,前面的结束了它才开始;聊天从不经过这里", async () => {
+ const a = start("A");
+ const b = start("B");
+ const c = start("C");
+ await flush();
+ expect(host.prompts.map((p) => p.sessionId)).toEqual([a.sessionId, b.sessionId]);
+ expect([a, b, c].map((t) => svc.get(t.id)!.stage.key)).toEqual(["working", "working", "working/queued"]);
+ await turn(a.sessionId, () => void report(a.sessionId, "done", "A 好了"));
+ await flush();
+ expect(host.prompts.map((p) => p.sessionId)).toEqual([a.sessionId, b.sessionId, c.sessionId]);
+ expect(svc.background()).toEqual({ b: 2 });
+ });
+
+ it("名额是机器人设置:设成 1 就一次一个", async () => {
+ host.settingsValue = normalizeSettings({ taskSlots: 1 });
+ start("A");
+ start("B");
+ await flush();
+ expect(host.prompts).toHaveLength(1);
+ });
+
+ it("追加:在跑一轮就并进去(插话,id 就是输入 id);会话空着就马上交;已完成的在同一任务里开新 run(人的唤醒)", async () => {
+ const t = start();
+ await flush();
+ svc.onEvent("b", t.sessionId, status(t.sessionId, "running"));
+ expect(await svc.message(t.id, "报告用英文")).toEqual({ how: "steered" });
+ expect(host.steers).toEqual([{ sessionId: t.sessionId, id: expect.stringMatching(/^i_/), text: "[用户追加]\n报告用英文" }]);
+ const steered = store.listInputs(t.id).at(-1)!;
+ expect(steered).toMatchObject({ messageId: steered.id, fromPerson: true });
+ expect(steered.deliveredAt).toBeGreaterThan(0);
+ // 插话被收下
+ svc.onEvent("b", t.sessionId, ev(t.sessionId, "user/message", { id: steered.id }));
+ expect(store.listInputs(t.id).at(-1)!.takenAt).toBeGreaterThan(0);
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ expect(svc.get(t.id)!.stage.key).toBe("ready");
+ // 已完成:同一个任务、同一个会话再开一个 run
+ expect(await svc.message(t.id, "再加上 H100")).toEqual({ how: "resumed" });
+ await flush();
+ expect(runs(t.id)).toEqual([
+ ["launch", "ended", "done"],
+ ["followup", "running", ""],
+ ]);
+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: t.sessionId, text: "[用户追加]\n再加上 H100", resume: true });
+ expect(store.getTask(t.id)!.endedAt).toBe(0);
+ });
+
+ it("停止:只停这个任务(宿主停会话),不发任何消息;之后的报告被拒;停了的不能再追加;/stop 编号一样", async () => {
+ const a = start("A");
+ const b = start("B");
+ await flush();
+ svc.onEvent("b", a.sessionId, status(a.sessionId, "running"));
+ expect(await svc.stopTask(a.id, "web")).toBe(true);
+ expect(host.stops).toEqual([a.sessionId]);
+ expect(runs(a.id)).toEqual([["launch", "ended", "stopped"]]);
+ expect(svc.get(a.id)!.stage.key).toBe("stopped");
+ expect(store.getTask(a.id)).toMatchObject({ endReason: "stopped", stoppedBy: "web" });
+ expect(report(a.sessionId, "done", "x").error).toMatch(/not running any more/);
+ expect((await svc.message(a.id, "继续")).error).toMatch(/已停止,不能再追加/);
+ expect(store.listOutbox({ limit: 50 })).toEqual([]);
+ expect(await svc.stopTask(a.id, "web")).toBe(false);
+ // /tasks 与 /stop 编号:进行中的在前
+ expect(svc.listText(CONV)).toBe("后台任务:\n1. B · 进行中\n2. A · 已停止\n发 /stop 编号 可停止。");
+ expect(svc.stopByIndex(CONV, 2, "weixin:owner")).toBe("「A」已停止。");
+ expect(svc.stopByIndex(CONV, 1, "weixin:owner")).toBe("已停止后台任务「B」。");
+ await flush();
+ expect(svc.get(b.id)!.stage.key).toBe("stopped");
+ expect(svc.stopByIndex(CONV, 5, "weixin:owner")).toBe("没有第 5 个后台任务,发 /tasks 查看。");
+ expect(svc.listText("b:weixin:nobody")).toBe("没有后台任务。");
+ });
+
+ it("重启恢复:跑着的 run 记为中断,排恢复 run;恢复说明在最前(列出被停的后台命令),没被收下的输入再交,收下过的不再交;同一个会话 resume", async () => {
+ const t = start();
+ await flush();
+ const brief = host.prompts[0];
+ svc.onEvent("b", t.sessionId, status(t.sessionId, "running"));
+ svc.onEvent("b", t.sessionId, ev(t.sessionId, "user/message", { id: brief.id }));
+ // 这一轮把一条命令转到了后台;用户又追加了一条,还没交出去(会话忙)
+ svc.onEvent("b", t.sessionId, ev(t.sessionId, "tool/call", { callId: "c1", name: "bash", arguments: JSON.stringify({ command: "sleep 600" }) }));
+ svc.onEvent("b", t.sessionId, ev(t.sessionId, "tool/result", { message: { toolCallId: "c1", content: [{ type: "text", text: "[still running after 30000ms; moved to background job bash-7]" }] } }));
+ svc.onEvent("b", t.sessionId, ev(t.sessionId, "turn/end", { turn: 1, reason: { kind: "completed" } }));
+ host.steerOk = false;
+ await svc.message(t.id, "加上 H100");
+ // 应用退出又启动
+ svc.stop();
+ svc = make();
+ svc.start();
+ await flush();
+ expect(runs(t.id)).toEqual([
+ ["launch", "ended", "interrupted"],
+ ["recover", "running", ""],
+ ]);
+ const p = host.prompts.at(-1)!;
+ expect(p).toMatchObject({ sessionId: t.sessionId, resume: true });
+ expect(p.text.startsWith(recoveryNote(["sleep 600"]))).toBe(true);
+ expect(p.text).toContain("[用户追加]\n加上 H100");
+ expect(p.text).not.toContain("[用户的原话]");
+ expect(svc.get(t.id)!.stage.key).toBe("working");
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ expect(runs(t.id).at(-1)).toEqual(["recover", "ended", "done"]);
+ });
+
+ it("代理进程退出:同样中断、恢复;停了的、已完成的任务不动", async () => {
+ const a = start("A");
+ const b = start("B");
+ await flush();
+ await turn(b.sessionId, () => void report(b.sessionId, "done", "B 好了"));
+ svc.onEvent("b", a.sessionId, status(a.sessionId, "running"));
+ svc.onEvent("b", a.sessionId, ev(a.sessionId, "user/message", { id: host.prompts[0].id }));
+ svc.onChildExit("b");
+ await flush();
+ expect(runs(a.id)).toEqual([
+ ["launch", "ended", "interrupted"],
+ ["recover", "running", ""],
+ ]);
+ expect(runs(b.id)).toEqual([["launch", "ended", "done"]]);
+ expect(host.prompts.at(-1)!.text).toBe(recoveryNote([]));
+ });
+
+ it("会话记录恢复不了:换一个新会话,从宿主记下的说明重新交代", async () => {
+ const t = start();
+ await flush();
+ svc.onEvent("b", t.sessionId, ev(t.sessionId, "user/message", { id: host.prompts[0].id }));
+ svc.stop();
+ svc = make();
+ host.failResume = true;
+ svc.start();
+ await flush();
+ const p = host.prompts.at(-1)!;
+ expect(p.sessionId).toMatch(new RegExp(`^task-${t.id}-\\d+$`));
+ expect(p.resume).toBe(false);
+ expect(p.text).toContain("[用户的原话]\n帮我后台调研一下三家云的 GPU 价格");
+ expect(p.text).toContain("之前的会话记录丢了");
+ expect(store.getTask(t.id)!.sessionId).toBe(p.sessionId);
+ await turn(p.sessionId, () => void report(p.sessionId, "done", "好了"));
+ expect(svc.get(t.id)!.stage.key).toBe("ready");
+ });
+
+ it("代理暂时起不来:过一会儿再交;一直不行就失败并告诉用户", async () => {
+ host.failPrompt = 1;
+ const t = start();
+ await flush();
+ await new Promise((r) => setTimeout(r, 20));
+ expect(host.prompts).toHaveLength(1);
+ expect(svc.get(t.id)!.stage.key).toBe("working");
+ host.failPrompt = 10;
+ const u = start("U");
+ for (let i = 0; i < 6; i++) await new Promise((r) => setTimeout(r, 10));
+ expect(svc.get(u.id)!.stage.key).toBe("failed");
+ expect(store.listMessages(CONV).at(-1)!.content).toBe("⚠️「U」没做完:代理没能启动");
+ });
+
+ it("交付文件:只交工作区里真实存在的,先按任务文件夹找", async () => {
+ const t = start();
+ await flush();
+ fs.writeFileSync(path.join(ws, t.folder, "report.md"), "# GPU");
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了", ["report.md", "/etc/hostname", "missing.md"]));
+ const files = store.listOutbox({ limit: 50 }).filter((r) => r.kind === "file");
+ expect(files.map((f) => f.body.path)).toEqual([fs.realpathSync(path.join(ws, t.folder, "report.md"))]);
+ expect(files[0].id).toMatch(/^task:t_[0-9a-f]+:result:r_[0-9a-f]+:file:0$/);
+ });
+
+ it("聊天工具:只在用户的会话里;task_start 建任务,task_list 列出,task_message 按标题找", async () => {
+ store.setAgentSession(CONV, "b", "session-chat");
+ expect((await svc.chatTool({ botId: "b", sessionId: "task-x", op: "start", args: {} })).error).toMatch(/only be managed from a chat/);
+ const r = await svc.chatTool({ botId: "b", sessionId: "session-chat", op: "start", args: { title: "GPU 价格调研", brief: "调研" } });
+ expect(r.text).toMatch(/^Started background task t_[0-9a-f]{12} 「GPU 价格调研」/);
+ await flush();
+ expect((await svc.chatTool({ botId: "b", sessionId: "session-chat", op: "list", args: {} })).text).toMatch(/^t_[0-9a-f]{12} 「GPU 价格调研」 进行中$/);
+ const t = store.listTasks({ conversationId: CONV })[0];
+ svc.onEvent("b", t.sessionId, status(t.sessionId, "running"));
+ expect((await svc.chatTool({ botId: "b", sessionId: "session-chat", op: "message", args: { task: "GPU", text: "用英文" } })).text).toMatch(/^Passed to 「GPU 价格调研」\. It reaches the task at its next step\./);
+ expect((await svc.chatTool({ botId: "b", sessionId: "session-chat", op: "message", args: { task: "不存在", text: "x" } })).error).toMatch(/No background task matches/);
+ // 任务会话所在的聊天(任务里的审批落到这里)
+ expect(svc.conversationOf(t.sessionId)).toBe(CONV);
+ });
+
+ it("飞书:结果回复在请求那条消息下(出站队列);网页:只写进会话历史,不进出站队列", async () => {
+ const fs1 = store.ensureConversation("b", "feishu", "oc_1", "主人");
+ store.addMessage(fs1.id, "user", "后台调研一下 GPU 价格");
+ store.setKV(`reply-to:${fs1.id}`, JSON.stringify({ messageId: "om_req", chatId: "oc_1" }));
+ const f = svc.create({ botId: "b", conversationId: fs1.id, title: "GPU", brief: "" }).task!;
+ expect(f.originRef).toBe("om_req");
+ const web = store.ensureConversation("b", "web", "console", "控制台");
+ store.addMessage(web.id, "user", "后台整理发票");
+ const w = svc.create({ botId: "b", conversationId: web.id, title: "发票", brief: "" }).task!;
+ await flush();
+ // 之后又来了一条消息:飞书还是回复在请求那条下面
+ store.setKV(`reply-to:${fs1.id}`, JSON.stringify({ messageId: "om_later", chatId: "oc_1" }));
+ await turn(f.sessionId, () => void report(f.sessionId, "done", "GPU 好了"));
+ await turn(w.sessionId, () => void report(w.sessionId, "done", "发票好了"));
+ const rows = store.listOutbox({ limit: 50 });
+ expect(rows.map((r) => [r.channel, r.kind, r.replyTo, r.peerId, r.body.text])).toEqual([["feishu", "text", "om_req", "oc_1", "GPU 好了"]]);
+ expect(store.listMessages(web.id).at(-1)!.content).toBe("发票好了");
+ expect(svc.get(w.id)!.stage.key).toBe("ready");
+ });
+
+ it("出站队列放弃了(比如微信 24 小时窗口关了):阶段是未送达", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ const run = store.listRuns({ taskId: t.id })[0];
+ store.updateOutbox(run.delivery, { status: "gone", error: "对方超过 24 小时没有发消息,微信不再允许回复" });
+ expect(svc.get(t.id)!.stage).toMatchObject({ key: "needs-you/delivery", label: "未送达", group: "needs" });
+ });
+
+ it("任务会话里阻塞着的审批:阶段是等你批准", async () => {
+ const t = start();
+ await flush();
+ store.insertApproval({ id: "a1", code: "1234", kind: "approval", botId: "b", conversationId: CONV, sessionId: t.sessionId, tool: "bash", detail: "rm -rf build", reason: "", payload: "", createdAt: Date.now(), expiresAt: Date.now() + 60_000 });
+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/approval");
+ });
+
+ it("每个机器人最多 10 个进行中的任务", async () => {
+ host.settingsValue = normalizeSettings({ taskSlots: 8 });
+ for (let i = 0; i < 10; i++) start(`T${i}`);
+ expect(svc.create({ botId: "b", conversationId: CONV, title: "再来一个", brief: "" }).error).toMatch(/already has 10 background tasks/);
+ });
+});
+
+describe("宿主:补丁加载 amb-tasks,任务规则经环境变量交给插件;任务会话的通知交给任务服务", () => {
+ it("补丁与环境", () => {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-host-"));
+ const store = new Store(":memory:");
+ store.createBot({ id: "b", name: "小蓝" });
+ const host = new AgentHost({ botId: "b", dataDir, runtimeDir: "/rt", bridge: { url: "http://127.0.0.1:1", token: "t" } as any, store, settings: () => normalizeSettings({ computerUse: { enabled: false } }) });
+ try {
+ fs.mkdirSync(host.home, { recursive: true });
+ const text = fs.readFileSync((host as any).writePatch("m"), "utf8");
+ expect(text).toContain(' - id: amb-tasks\n name: "/rt/plugins/amb-tasks.mjs"\n');
+ expect((host as any).env().AMB_TASK_RULES).toBe(TASK_RULES);
+ } finally {
+ store.close();
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+ });
+
+ it("task-* 会话和它们子代理的通知不当成聊天的醒来,交给任务服务;记下哪些任务会话在跑一轮", () => {
+ const store = new Store(":memory:");
+ const seen: Array<[string, string]> = [];
+ const host = new AgentHost({ botId: "b", dataDir: os.tmpdir(), runtimeDir: "/rt", bridge: {} as any, store, onTaskEvent: (root, n) => seen.push([root, n.method]) });
+ (host as any).harness = { client: { isDescendantOf: (id: string, root: string) => id === "sub-1" && root === "task-t_1" } };
+ (host as any).taskSessions.add("task-t_1");
+ const tap = (n: any) => (host as any).tap(n);
+ tap({ method: "session.status", params: { sessionId: "task-t_1", status: "running" } });
+ expect((host as any).taskBusy.has("task-t_1")).toBe(true);
+ tap({ method: "subagent.started", params: { parentSessionId: "task-t_1", childSessionId: "sub-1" } });
+ tap({ method: "session.event", params: { sessionId: "sub-1", event: { type: "tool/call", data: {} } } });
+ tap({ method: "session.status", params: { sessionId: "task-t_1", status: "idle" } });
+ expect((host as any).taskBusy.size).toBe(0);
+ // 聊天会话的通知不归任务
+ tap({ method: "session.status", params: { sessionId: "session-chat", status: "running" } });
+ expect(seen).toEqual([
+ ["task-t_1", "session.status"],
+ ["task-t_1", "subagent.started"],
+ ["task-t_1", "session.event"],
+ ["task-t_1", "session.status"],
+ ]);
+ store.close();
+ });
+});
diff --git a/ui/components/tasks.js b/ui/components/tasks.js
new file mode 100644
index 0000000..2c87ee2
--- /dev/null
+++ b/ui/components/tasks.js
@@ -0,0 +1,108 @@
+// 后台任务(3a):对话里请求那条消息下面的任务胶囊「后台任务 · 标题 · 进行中 ›」,点开是最新进展、每次运行折叠的处理过程和停止;
+// 信息面板里一行一个任务。状态是"点 + 文字":绿 = 进行中,黄 = 等你,红 = 失败,灰 = 已完成 / 已停止。健康时不多占地方。
+import { useEffect, useState } from "preact/hooks";
+import { html, Icon } from "./ui.js";
+import { ActivityLine } from "./activity.js";
+import { api } from "../lib/api.js";
+import { failed, toast } from "../lib/store.js";
+import { fmtAgo, fmtDur } from "../lib/format.js";
+
+/** 阶段 → 状态点 */
+export function stageDot(stage) {
+ if (!stage) return "";
+ if (stage.key === "failed") return "err";
+ if (stage.group === "working") return "ok";
+ if (stage.group === "needs") return "warn";
+ return "";
+}
+
+/** 每次运行怎么来的 */
+const CAUSE = { launch: "开始", followup: "追加后继续", recover: "重启后继续", retry: "重试", continue: "继续", answer: "回答后继续", manual: "手动运行" };
+
+/** 运行一行:"第 2 次 · 重启后继续 · 3 分钟" */
+function runLabel(r, i, now) {
+ const ms = (r.endedAt || now) - (r.startedAt || r.queuedAt);
+ const tail = r.state === "queued" ? "排队中" : r.startedAt ? fmtDur(ms) : "";
+ return [`第 ${i + 1} 次`, CAUSE[r.cause] || r.cause, tail].filter(Boolean).join(" · ");
+}
+
+export async function stopTask(t) {
+ try {
+ await api(`/tasks/${encodeURIComponent(t.id)}/stop`, { method: "POST", body: {} });
+ toast(`已停止「${t.title}」`);
+ return true;
+ } catch (e) {
+ failed(e);
+ return false;
+ }
+}
+
+/** 任务的详情:最新进展、文件夹、每次运行(折叠的处理过程)、停止。working 时每 3 秒刷新 */
+export function TaskDetail({ task, onChanged }) {
+ const [d, setD] = useState(null);
+ const [stopping, setStopping] = useState(false);
+ const working = task.stage.group === "working";
+ useEffect(() => {
+ let on = true;
+ const load = () => api(`/tasks/${encodeURIComponent(task.id)}`).then((x) => on && setD(x)).catch(() => {});
+ load();
+ if (!working) return () => (on = false);
+ const t = setInterval(load, 3000);
+ return () => {
+ on = false;
+ clearInterval(t);
+ };
+ }, [task.id, working, task.updatedAt]);
+ const now = Date.now();
+ const runs = d?.runs || [];
+ const stop = async () => {
+ setStopping(true);
+ if (await stopTask(task)) onChanged?.();
+ setStopping(false);
+ };
+ return html`<div class="task-detail">
+ ${task.latest && html`<div class="task-line"><span class="t-label">最新进展</span><span class="v selectable">${task.latest}</span></div>`}
+ <div class="task-line"><span class="t-label">文件夹</span><span class="v mono selectable">${task.folder}</span></div>
+ ${runs.map(
+ (r, i) => html`<${ActivityLine} key=${r.id + (r.state === "ended" ? ":e" : "")} label=${runLabel(r, i, now)} live=${r.state === "running" || r.state === "settling"} count=${r.steps}
+ load=${() => api(`/tasks/${encodeURIComponent(task.id)}/runs/${encodeURIComponent(r.id)}/activity`).then((x) => x.steps)} />`,
+ )}
+ ${working && html`<div class="task-actions"><button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? "正在停止…" : "停止"}</button></div>`}
+ </div>`;
+}
+
+/** 对话里的任务胶囊:「后台任务 · 标题 · 进行中 ›」,点开看详情 */
+export function TaskChip({ task, onChanged }) {
+ const [open, setOpen] = useState(false);
+ const dot = stageDot(task.stage);
+ return html`<div class=${`task-chip${open ? " open" : ""}`}>
+ <button type="button" class="task-pill" aria-expanded=${open} title=${open ? "收起" : "查看后台任务"} onClick=${() => setOpen(!open)}>
+ <span class=${`dot ${dot}`} aria-hidden="true"></span>
+ <span class="k">后台任务</span><span class="sep">·</span><span class="t">${task.title}</span><span class="sep">·</span><span class="st">${task.stage.label}</span>
+ <${Icon} name="chevRight" size=${12} class="chev" />
+ </button>
+ ${open && html`<${TaskDetail} task=${task} onChanged=${onChanged} />`}
+ </div>`;
+}
+
+/** 信息面板里的一行:状态点 + 标题,下面一行是状态、什么时候开始的、最新进展;进行中的可以停止 */
+export function TaskRow({ task, onChanged, onOpen }) {
+ const [stopping, setStopping] = useState(false);
+ const working = task.stage.group === "working";
+ const when = working ? `${Math.max(1, Math.round((Date.now() - task.createdAt) / 60_000))} 分钟` : fmtAgo(task.endedAt || task.updatedAt);
+ const stop = async (e) => {
+ e.stopPropagation();
+ setStopping(true);
+ if (await stopTask(task)) onChanged?.();
+ setStopping(false);
+ };
+ return html`<div class="row compact task-row${onOpen ? " clickable" : ""}" role=${onOpen ? "button" : undefined} tabindex=${onOpen ? "0" : undefined}
+ onClick=${onOpen} onKeyDown=${(e) => onOpen && e.key === "Enter" && onOpen()}>
+ <span class=${`dot ${stageDot(task.stage)}`} aria-hidden="true"></span>
+ <div class="who">
+ <div class="name">${task.title}</div>
+ <div class="sub">${task.stage.label} · ${when}</div>
+ </div>
+ ${working && html`<button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? "停止中…" : "停止"}</button>`}
+ </div>`;
+}
diff --git a/ui/css/chat.css b/ui/css/chat.css
index 6d32d10..61d5d6e 100644
--- a/ui/css/chat.css
+++ b/ui/css/chat.css
@@ -304,4 +304,26 @@ button.act-head:active { background: var(--pill-hover); }
.send[aria-busy="true"] { cursor: progress; }
.send .spinner { width: 12px; height: 12px; }
.composer-disabled { pointer-events: auto; width: var(--col); margin: 0 auto var(--space-2); }
+
+/* —— 后台任务:请求那条消息的回复下面一个胶囊「后台任务 · 标题 · 进行中 ›」(静默填充,不描边);
+ 点开是最新进展、文件夹、每次运行折叠的处理过程(和回复上方的"用时"同一种写法)和停止 —— */
+.task-chip { display: grid; grid-template-columns: minmax(0, 1fr); justify-items: start; margin-top: var(--space-2); }
+.task-pill {
+ display: inline-flex; align-items: center; gap: var(--space-1-5); max-width: 100%; height: var(--ctl-md); padding: 0 var(--space-2-5) 0 var(--space-3);
+ border-radius: var(--r-full); background: var(--pill); font-size: var(--fs-sm); color: var(--fg-2);
+ transition: background var(--t-fast), color var(--t-fast), transform var(--t-fast);
+}
+.task-pill:hover { background: var(--pill-hover); color: var(--fg); }
+.task-pill:active { background: var(--pill-press); transform: scale(var(--press)); }
+.task-pill .t { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--fg); font-weight: var(--fw-medium); }
+.task-pill :is(.k, .sep, .st) { flex: none; }
+.task-pill .sep { color: var(--muted); }
+.task-pill .chev { flex: none; color: var(--muted); transition: transform var(--t-fast); }
+.task-detail { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--space-2); width: 100%; margin-top: var(--space-3); }
+.task-line { display: flex; align-items: baseline; gap: var(--space-2); font-size: var(--fs-sm); color: var(--fg-2); }
+.task-line .t-label { flex: none; min-width: 4em; }
+.task-line .v { min-width: 0; overflow-wrap: anywhere; }
+.task-line .v.mono { font-family: var(--code); font-size: var(--fs-xs); }
+.task-detail .activity, .task-detail .work-line { margin-bottom: 0; }
+.task-actions { display: flex; justify-content: flex-start; }
}
diff --git a/ui/main.js b/ui/main.js
index e612bee..f6dfa39 100644
--- a/ui/main.js
+++ b/ui/main.js
@@ -132,6 +132,8 @@ function App() {
const [previews, setPreviews] = useState({});
const [pending, setPending] = useState({});
const [agentWorking, setAgentWorking] = useState({});
+ // 有后台任务在进行的机器人:侧栏头像也是"工作中"(不算对话在忙,对话页不因此去接进行中的消息)
+ const [bgWorking, setBgWorking] = useState({});
const [localWorking, setLocalWorking] = useState({});
const [infoOpen, setInfoOpen] = useState(false);
const [palette, setPalette] = useState(false);
@@ -212,6 +214,9 @@ function App() {
for (const [id, h] of Object.entries(a.hosts || {})) map[id] = Number(h.activeTurns || 0) > 0;
for (const id of a.busy || []) map[id] = true;
setAgentWorking(map);
+ const bg = {};
+ for (const [id, n] of Object.entries(a.background || {})) if (Number(n) > 0) bg[id] = true;
+ setBgWorking(bg);
})
.catch(() => {}),
[],
@@ -219,9 +224,9 @@ function App() {
useInterval(pollWorking, 3000, connected);
const working = useMemo(() => {
const m = { ...agentWorking };
- for (const [k, v] of Object.entries(localWorking)) if (v) m[k] = true;
+ for (const src of [bgWorking, localWorking]) for (const [k, v] of Object.entries(src)) if (v) m[k] = true;
return m;
- }, [agentWorking, localWorking]);
+ }, [agentWorking, bgWorking, localWorking]);
const wantWorking = useRef({});
const onWorking = useCallback((id, on) => {
wantWorking.current[id] = on;
diff --git a/ui/screens/chat.js b/ui/screens/chat.js
index 2c6190d..12016ed 100644
--- a/ui/screens/chat.js
+++ b/ui/screens/chat.js
@@ -7,6 +7,7 @@ import { Markdown, Linkified } from "../components/markdown.js";
import { ModelPicker, shortModel, sameModel } from "../components/model-picker.js";
import { PwshHint } from "../components/pwsh-hint.js";
import { ActivityLine, currentStep, upsertStep } from "../components/activity.js";
+import { TaskChip } from "../components/tasks.js";
import { api, attachChat, streamChat } from "../lib/api.js";
import { confirmSheet, failed, saved } from "../lib/store.js";
import { fmtSep, fmtClock, fmtDur } from "../lib/format.js";
@@ -18,6 +19,7 @@ const COMMANDS = [
["/reset", "清空本会话上下文"],
["/status", "查看当前模型、运行方式和处理进度"],
["/stop", "中止正在处理的消息"],
+ ["/tasks", "列出后台任务(/stop 编号 停止一个)"],
["/help", "显示全部命令"],
];
// 文件权限(输入框左下角,参考 Codex 的权限胶囊):机器人设置里的同一项,预设在 lib/perms.js
@@ -219,6 +221,9 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
const attachRef = useRef(null);
// 处理中又发的消息(并进正在进行的回复)结束后重新读一次历史:存下的顺序是两条用户消息、一条回复
const reloadAfter = useRef(false);
+ // 这个会话的后台任务(胶囊挂在请求它的那条消息的回复下面);任务结束时结果写进了历史,重新读一次
+ const [tasks, setTasks] = useState([]);
+ const taskGroups = useRef({});
// ended:刚接着的那条消息结束了 { since, ms },存下的回复照样显示"用时"(和一直停在这页时一样)
const load = useCallback(async (ended) => {
@@ -266,6 +271,35 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
}, [serverBusy]);
useEffect(() => () => onWorking(bot.id, false), []);
+ const loadTasks = useCallback(
+ () =>
+ api(`/tasks?conversation=${encodeURIComponent(`${bot.id}:web:console`)}&limit=20`)
+ .then((d) => {
+ if (!mounted.current) return;
+ const list = d.tasks || [];
+ const finished = list.some((t) => taskGroups.current[t.id] === "working" && t.stage.group !== "working");
+ taskGroups.current = Object.fromEntries(list.map((t) => [t.id, t.stage.group]));
+ setTasks(list);
+ if (finished && !following.current) load();
+ })
+ .catch(() => {}),
+ [bot.id, load],
+ );
+ const tasksWorking = tasks.some((t) => t.stage.group === "working");
+ useEffect(() => {
+ taskGroups.current = {};
+ setTasks([]);
+ loadTasks();
+ }, [bot.id]);
+ // 回复结束(可能刚开了一个任务)就看一次;有任务在进行时 3 秒一次,否则 15 秒
+ useEffect(() => {
+ if (!generating) loadTasks();
+ }, [generating]);
+ useEffect(() => {
+ const t = setInterval(loadTasks, tasksWorking ? 3000 : 15000);
+ return () => clearInterval(t);
+ }, [loadTasks, tasksWorking]);
+
// 只有用户本来就在底部附近时才跟随新内容;否则亮出"回到底部"
useLayoutEffect(() => {
const el = scroller.current;
@@ -537,6 +571,22 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
];
// —— 渲染 ——
+ /** 任务胶囊挂在哪一项后面:请求那条用户消息之后的第一条回复;那一轮还在进行时挂在进行中的回复后面 */
+ const chipsAfter = useMemo(() => {
+ const map = new Map();
+ const list = items || [];
+ for (const t of [...tasks].sort((a, b) => a.createdAt - b.createdAt)) {
+ const i = list.findIndex((x) => x.mid === t.originMessageId);
+ let at;
+ if (i >= 0) at = list.find((x, k) => k > i && !(x.kind === "msg" && x.role === "user")) ?? list[i];
+ else if (list.some((x) => x.live)) at = list.findLast((x) => x.turn);
+ if (!at) continue;
+ map.set(at.id, [...(map.get(at.id) || []), t]);
+ }
+ return map;
+ }, [items, tasks]);
+
+ const chips = (it) => (chipsAfter.get(it.id) || []).map((t) => html`<${TaskChip} key=${t.id} task=${t} onChanged=${loadTasks} />`);
const rows = useMemo(() => {
const out = [];
let prev = null;
@@ -556,6 +606,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
: html`${(it.live || it.workedMs || it.steps) && html`<${WorkLine} live=${it.live} stopping=${it.live && stopping} text=${it.text} startedAt=${it.startedAt} workedMs=${it.workedMs}
steps=${it.activity} count=${it.steps} load=${it.mid ? loadActivity(it.mid) : undefined} />`}
${it.text && html`<div class="msg"><${Markdown} text=${it.text} /></div>`}
+ ${chips(it)}
${!it.live && html`<${MsgActions} text=${it.text} at=${it.at} />`}`}
</div>`);
} else if (it.kind === "prompt") {
@@ -568,10 +619,12 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
<${ErrorNotice} text=${it.text} onRetry=${it.retry ? () => send(it.retry) : undefined} onFixKey=${() => onOpenSettings("modelflare", "connection")} />
</div>`);
}
+ // 回复下面直接挂在同一行里(在复制按钮之前);挂在卡片、文件、出错提示后面时自成一行
+ if (!(it.kind === "msg" && it.role === "assistant") && chipsAfter.has(it.id)) out.push(html`<div class="msg-row assistant cont" key=${"task-" + it.id}>${chips(it)}</div>`);
prev = it;
}
return out;
- }, [items, generating, stopping]);
+ }, [items, generating, stopping, chipsAfter]);
const empty = items && items.length === 0;
// 头像跟着对话走:等你批准 > 还没出字(思考)/ 出字了(回复)> 你在输入(在听)
diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.js
index 268f662..50333e3 100644
--- a/ui/screens/info-panel.js
+++ b/ui/screens/info-panel.js
@@ -7,6 +7,7 @@ import { api } from "../lib/api.js";
import { confirmSheet, failed, saved, toast } from "../lib/store.js";
import { fmtAgo, fmtDur, fmtTime } from "../lib/format.js";
import { CHANNEL_NAME } from "../lib/access.js";
+import { TaskRow } from "../components/tasks.js";
export function usePoll(fn, ms, deps = []) {
const [data, setData] = useState(null);
@@ -256,6 +257,9 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {
const [appr, , reloadAppr] = usePoll(() => api(`/approvals?status=pending&bot=${encodeURIComponent(bot.id)}`), 4000, [bot.id]);
const [convs] = usePoll(() => api(`/conversations?bot=${encodeURIComponent(bot.id)}`), 8000, [bot.id]);
const [access, , reloadAccess] = usePoll(() => api(`/bots/${encodeURIComponent(bot.id)}/access`), 4000, [bot.id]);
+ // 后台任务:只列还没结束的(进行中、等你的);一个都没有时不显示这一组
+ const [taskData, , reloadTasks] = usePoll(() => api(`/tasks?bot=${encodeURIComponent(bot.id)}&limit=20`), 4000, [bot.id]);
+ const tasks = (taskData?.tasks || []).filter((t) => t.stage.group !== "ended");
const [viewing, setViewing] = useState(null);
const pending = (appr && appr.approvals) || [];
return html`<aside class="panel" aria-label="信息面板">
@@ -283,6 +287,10 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {
<button type="button" class="text" style="justify-self:start" onClick=${reloadAppr}>刷新</button></div>`
: html`<div class="list"><div class="row"><span class="hint">没有待处理的审批</span></div></div>`}
+ ${tasks.length > 0 && html`<div class="list-head">任务</div>
+ <div class="list">${tasks.slice(0, 8).map((t) => html`<${TaskRow} key=${t.id} task=${t} onChanged=${reloadTasks}
+ onOpen=${() => (t.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === t.conversationId) || null))} />`)}</div>`}
+
<${Undelivered} botId=${bot.id} />
<${MemorySection} botId=${bot.id} />