🤖 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.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
Phase 3e: cost controls
Marla98fdc32b1a67
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.mdindex 6e2d72f..2f0c8d9 100644--- a/docs/design/background-tasks-and-proactive.md+++ b/docs/design/background-tasks-and-proactive.md@@ -1,6 +1,6 @@# Background tasks and proactive rules (Phase 3 design)-Status: **3a–3d are built**: tasks, questions and needs-you, delivery, and rules with observe mode (`src/tasks/`, `src/core/delivery.ts`, `dsh-runtime/plugins/amb-tasks.mjs`; tests in `test/tasks.*`, `test/delivery.*`, `test/rules.*`). 3e–3f are still design. Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.+Status: **3a–3e are built**: tasks, questions and needs-you, delivery, rules with observe mode, and cost controls (`src/tasks/`, `src/core/delivery.ts`, `dsh-runtime/plugins/amb-tasks.mjs`; tests in `test/tasks.*`, `test/delivery.*`, `test/rules.*`, `test/cost.*`). 3f is 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@@ -524,6 +524,15 @@ Notes:- **Time caps:** a task gets 4 h of running time, not counting time waiting for a person. Settling lasts at most 30 minutes after a turn ends. A rule run gets 15 minutes.- **Model choice:** a task uses the conversation's model. A rule may use the bot's `utilityModel` when it is set (Q5).+As built (3e, `src/tasks/cost.ts` and the 「花费与预算」 part of `TaskService`):++- **Prices.** `estimateRates` in `src/account/model-info.ts` adds cache-read and cache-write prices (`cache_ratio`, `create_cache_ratio`) and, for tiered models, the base tier. The model picker's reference price is unchanged. A model with no price (external endpoint, not in the catalog, offline) is not estimated, so its budgets never trigger; the time cap still applies.+- **What counts.** Every `assistant/message` with usage in the task or rule session and in its subagents, priced by the model that answered. A request that was already in flight when the host cancelled the turn is still added to that run.+- **Task budget.** The question is an ordinary non-blocking task question (tool `task_budget`, options 继续 / 停止), so it is pushed, answered by number, quote or code, shown in needs-you and on Feishu cards like any other. The stage stays `needs-you/budget`. 「继续」 adds $1; a written amount (「再给 3 美元」) adds that much; other words are passed to the task with the extra budget; 「停止」 stops it. `POST /tasks/:id/budget {addUsd}` does the same and withdraws the question. A person's input that arrives while the task is over budget is kept and the question is asked again. The cancel uses a new control op, `task-cancel`, which stops the turn, its subagents and jobs but, unlike `task-stop`, leaves the session usable.+- **Rule budgets.** A run over $0.10 ends `budget` and counts as one failure (three in a row pause the rule as before). At $3 in a month the rule pauses (`paused_reason = budget`); an act-mode rule pushes one line, once per month and budget level. It resumes on the 1st at 00:00 in the owner's time zone, or when 「继续」 in needs-you raises its monthly budget by $3 (kept for later months).+- **Reserve.** The bot's key limit and remaining balance are read every 5 minutes (and after a budget change); estimated background spend since the last read is subtracted. Below 20 %: running task turns are cancelled and their tasks wait (排队中) with a resume note, rule runs are skipped (「跳过:机器人预算留给聊天」), and `task_start` is refused. One needs-you row per bot with background work links to the bot's budget setting. It is not pushed.+- **Time cap.** 4 h per task run, minus the time a blocking approval in that run waited. At the cap the turn is cancelled and the run fails (「运行超过 4 小时,已停下」), which is pushed like any failure; retry starts a new run with a fresh cap.+## 9. Data model (sqlite, `src/store/db.ts`)Each kind of state has one writer:diff --git a/dsh-runtime/plugins/amb-tasks.mjs b/dsh-runtime/plugins/amb-tasks.mjsindex cc9d99a..e230811 100644--- a/dsh-runtime/plugins/amb-tasks.mjs+++ b/dsh-runtime/plugins/amb-tasks.mjs@@ -23,7 +23,8 @@// 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.+// cancels the turn, its subagents and every job the session owns. `task-cancel` does the same but leaves the session+// usable (the host stopped it at its budget or time cap, and continues it later).import { defineTool } from '@deepseek-ai/dsh-tools'export const name = 'amb-tasks'@@ -103,6 +104,7 @@ export function apply(ctx) {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.' },anytime: { type: 'boolean', description: 'true only when the user asked to be told the moment it is done, even at night. Otherwise a result that is ready during their quiet hours waits until morning.' },+ budget_usd: { type: 'number', description: 'Only when the user names a spending limit, in US dollars. Default 1.' },},output: TEXT_OUT,execute: tool('start'),@@ -336,17 +338,20 @@ export function apply(ctx) {watch(id)return { quiet: false, jobs: runningJobs(id).map((j) => String(j.id)) }}- handlers['task-stop'] = async ({ sessionId }) => {+ /** Cancel the turn, its subagents and the session's jobs; `stop` also refuses every later tool call. */+ async function halt(sessionId, stop, why) {const id = String(sessionId)- stopped.add(id)+ if (stop) 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(() => [])+ const killed = await killJobs(id, why).catch(() => [])return { running: true, killed }}+ handlers['task-stop'] = ({ sessionId }) => halt(sessionId, true, 'stopped by the user')+ handlers['task-cancel'] = ({ sessionId }) => halt(sessionId, false, 'the app paused the task')try {ctx.on('agent/disposed', ({ agent }) => {@@ -359,6 +364,7 @@ export function apply(ctx) {for (const id of [...watching.keys()]) unwatch(id)delete handlers['task-quiet']delete handlers['task-stop']+ delete handlers['task-cancel']})} catch {}}diff --git a/src/account/model-info.ts b/src/account/model-info.tsindex 9c5a027..37d3ab0 100644--- a/src/account/model-info.ts+++ b/src/account/model-info.ts@@ -12,6 +12,8 @@ export interface ModelInfo {tools?: boolean;reasoning?: boolean;price?: { input?: number; output?: number; perCall?: number };+ /** 后台任务、规则估算花费用的单价(3e):比 price 多了缓存命中 / 写入,阶梯计费的取基础那一档 */+ rates?: Rates;/** 支持的接口(目录的 supported_endpoint_types:openai、openai-response、openai-response-compact、anthropic、gemini…) */endpoints?: string[];}@@ -31,6 +33,9 @@ export interface PricingEntry {model_ratio?: number;model_price?: number;completion_ratio?: number;+ /** 缓存命中价 = 输入价 × cache_ratio;写入缓存 = 输入价 × create_cache_ratio */+ cache_ratio?: number;+ create_cache_ratio?: number;enable_groups?: string[];billing_mode?: string;pricing_rules?: unknown;@@ -44,18 +49,33 @@ export interface PricingCatalog {usable_group?: Record<string, unknown>;}+/** 估算花费用的单价(美元 / 百万 tokens) */+export interface Rates {+ input: number;+ output: number;+ cacheRead?: number;+ cacheWrite?: number;+}+const round = (n: number) => Math.round(n * 10_000) / 10_000;+const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);-/** 一个模型的起步参考价;算不出来(复杂计费、没有可用分组)时 undefined */-export function referencePrice(entry: PricingEntry, catalog: PricingCatalog): ModelInfo["price"] {- if (entry.billing_mode || entry.pricing_rules) return undefined;+/** 分组倍率:可用公开分组里最低的 × 模型售价倍率;没有可用分组时 undefined */+function factorOf(entry: PricingEntry, catalog: PricingCatalog): number | undefined {const ratios = (entry.enable_groups ?? []).filter((g) => !catalog.usable_group || g in catalog.usable_group).map((g) => catalog.group_ratio?.[g]).filter((r): r is number => typeof r === "number" && Number.isFinite(r) && r >= 0);if (!ratios.length) return undefined;const sale = Number(entry.sale_price_multiplier) > 0 ? Number(entry.sale_price_multiplier) : 1;- const factor = Math.min(...ratios) * sale;+ return Math.min(...ratios) * sale;+}++/** 一个模型的起步参考价;算不出来(复杂计费、没有可用分组)时 undefined */+export function referencePrice(entry: PricingEntry, catalog: PricingCatalog): ModelInfo["price"] {+ if (entry.billing_mode || entry.pricing_rules) return undefined;+ const factor = factorOf(entry, catalog);+ if (factor === undefined) return undefined;if (entry.quota_type === 1) return typeof entry.model_price === "number" ? { perCall: round(entry.model_price * factor) } : undefined;if (entry.quota_type !== 0) return undefined;const base = typeof entry.input_price === "number" ? entry.input_price : Number(entry.model_ratio) * 2;@@ -64,6 +84,44 @@ export function referencePrice(entry: PricingEntry, catalog: PricingCatalog): Moreturn { input: round(base * factor), ...(Number.isFinite(output) ? { output: round(base * output * factor) } : {}) };}+/**+ * 估算花费用的单价(后台任务、规则的预算,3e):同样按可用分组里最低的倍率;比参考价多了缓存命中、写入的价,+ * 阶梯计费的取基础那一档(没有条件的那档,长上下文更贵的那档不算:估算写「约」,账单为准)。按次计费的不给。+ */+export function estimateRates(entry: PricingEntry, catalog: PricingCatalog): Rates | undefined {+ if (entry.quota_type !== 0) return undefined;+ const factor = factorOf(entry, catalog);+ if (factor === undefined) return undefined;+ const tiers = (entry.pricing_rules as { tiers?: Array<{ conditions?: unknown; unit_prices?: Record<string, unknown> }> } | undefined)?.tiers;+ const tier = Array.isArray(tiers) ? (tiers.find((t) => !t?.conditions) ?? tiers[0]) : undefined;+ if (tier?.unit_prices) {+ const u = tier.unit_prices;+ const input = num(u.input);+ if (input === undefined) return undefined;+ const cacheRead = num(u.cache_read);+ const cacheWrite = num(u.cache_write);+ return {+ input: round(input * factor),+ output: round((num(u.output) ?? input) * factor),+ ...(cacheRead !== undefined ? { cacheRead: round(cacheRead * factor) } : {}),+ ...(cacheWrite !== undefined ? { cacheWrite: round(cacheWrite * factor) } : {}),+ };+ }+ if (entry.billing_mode || entry.pricing_rules) return undefined;+ const base = typeof entry.input_price === "number" ? entry.input_price : Number(entry.model_ratio) * 2;+ if (!Number.isFinite(base) || base < 0) return undefined;+ const input = base * factor;+ const completion = num(entry.completion_ratio);+ const cacheRead = num(entry.cache_ratio);+ const cacheWrite = num(entry.create_cache_ratio);+ return {+ input: round(input),+ output: round(input * (completion ?? 1)),+ ...(cacheRead !== undefined ? { cacheRead: round(input * cacheRead) } : {}),+ ...(cacheWrite !== undefined ? { cacheWrite: round(input * cacheWrite) } : {}),+ };+}+export async function loadModelInfo(o: {baseUrl: string;apiKey: string;@@ -96,6 +154,8 @@ export async function loadModelInfo(o: {for (const entry of catalog?.data ?? []) {const price = referencePrice(entry, catalog!);if (price) out[entry.model_name] = { ...out[entry.model_name], price };+ const rates = estimateRates(entry, catalog!);+ if (rates) out[entry.model_name] = { ...out[entry.model_name], rates };// 没有 Key(拿不到 model-profiles)时,上下文长度用公开目录里的if (Number(entry.context_window) > 0 && !out[entry.model_name]?.context) out[entry.model_name] = { ...out[entry.model_name], context: Number(entry.context_window) };if (Array.isArray(entry.supported_endpoint_types)) out[entry.model_name] = { ...out[entry.model_name], endpoints: entry.supported_endpoint_types.map(String) };diff --git a/src/agent/approvals.ts b/src/agent/approvals.tsindex dc1bcd9..8903ab4 100644--- a/src/agent/approvals.ts+++ b/src/agent/approvals.ts@@ -100,7 +100,7 @@ export class ApprovalCenter {/** 启动:上次运行遗留的阻塞请求(DSH 那次调用已经不在了)一律视为拒绝;任务的提问留着。之后定时清理过期。 */start(): void {for (const r of this.store.listApprovals({ status: "pending", limit: 500 })) {- if (r.blocking) this.store.decideApproval(r.id, "expired", "restart");+ if (r.blocking) this.store.decideApproval(r.id, "expired", "restart", "", this.now());}this.timer ??= setInterval(() => this.sweep(), 5000);this.timer.unref?.();@@ -184,7 +184,8 @@ export class ApprovalCenter {}private finish(id: string, status: Exclude<ApprovalRow["status"], "pending">, by: string, result = ""): boolean {- const ok = this.store.decideApproval(id, status, by, result);+ // 决定的时间按审批中心的时钟(任务的时间上限要扣掉等批准的那段,3e)+ const ok = this.store.decideApproval(id, status, by, result, this.now());if (ok) {const row = this.store.getApproval(id)!;log.info(`${row.kind} ${row.code} → ${status}`, { by });diff --git a/src/agent/host.ts b/src/agent/host.tsindex 02cb758..7f8182d 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -1690,6 +1690,12 @@ exec "$REAL" "$@"await this.control.send("task-stop", { sessionId }, 15_000);}+ /** 停下任务会话的这一轮(amb-tasks:取消它、子代理和它的后台命令),会话之后还能接着用:预算用完、时间到了(3e) */+ async cancelTask(sessionId: string): Promise<void> {+ if (!this.harness || !this.control.connected) return;+ await this.control.send("task-cancel", { sessionId }, 15_000);+ }+/** 任务会话空闲时,还有没有它的后台命令、子代理在跑(插件在它们结束后报 task-settled);通道不通按安静算 */async taskQuiet(sessionId: string): Promise<{ quiet: boolean; jobs?: string[] }> {if (!this.harness || !this.control.connected) return { quiet: true };diff --git a/src/agent/manager.ts b/src/agent/manager.tsindex 82787f0..4e84c6f 100644--- a/src/agent/manager.ts+++ b/src/agent/manager.ts@@ -926,6 +926,7 @@ export class AgentManager {},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)),+ cancel: async (botId, sessionId) => void (await this.hosts.get(botId)?.cancelTask(sessionId)),quiet: (botId, sessionId) => this.hosts.get(botId)?.taskQuiet(sessionId) ?? Promise.resolve({ quiet: true }),runEnded: (botId) => void this.hosts.get(botId)?.restartIfStale().catch(() => undefined),};diff --git a/src/agent/prompts/tasks.ts b/src/agent/prompts/tasks.tsindex 2bca727..1766920 100644--- a/src/agent/prompts/tasks.ts+++ b/src/agent/prompts/tasks.ts@@ -63,6 +63,16 @@ export function recoveryNote(jobs: string[]): string {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.`;}+/**+ * 被宿主停下之后接着做(3e,给模型的,英文):budget = 任务的预算用完停下、用户加了预算;reserve = 机器人的预算快用完时+ * 为了给聊天留着而暂停、现在恢复了。和恢复说明一样:上一步可能没做完,后台命令被停了,重复外部动作之前先查。+ */+export function resumeNote(why: "budget" | "reserve", jobs: string[]): string {+ const list = jobs.length ? jobs.join("; ") : "none";+ const head = why === "budget" ? "This task was stopped when it used its budget, and the user has now added more." : "The app paused this task to keep the bot's remaining budget for chat, and has now resumed it.";+ return `${head} Your last step may not have finished, and these background jobs were stopped: ${list}. Before repeating any outside action, read \`.task/journal.md\` and check your folder. 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.";diff --git a/src/app.ts b/src/app.tsindex fb7d2ca..b73e1fd 100644--- a/src/app.ts+++ b/src/app.ts@@ -39,7 +39,7 @@ import {} from "./modelflare.js";import { AccountManager } from "./account/manager.js";import { AccountVault, type SecretBox } from "./account/vault.js";-import { loadModelInfo, type ModelInfo } from "./account/model-info.js";+import { loadModelInfo, type ModelInfo, type Rates } 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";@@ -153,6 +153,8 @@ export class App {private picksTimer: NodeJS.Timeout | undefined;private modelInfoCache: { at: number; data: Record<string, ModelInfo> } | undefined;private modelInfoLoading: Promise<Record<string, ModelInfo>> | undefined;+ /** 各机器人预算 Key 的总额与余额(每 5 分钟随余额一起读;后台工作在剩下不到 20% 时停下,3e) */+ private botBudgetCache: { at: number; data: Record<string, { limitUsd: number; remainUsd: number }> } | undefined;/** 数据目录锁(命令行、Docker:同一个数据目录只能一个宿主,调度器开始之前拿) */private lock: DataDirLock | undefined;@@ -253,6 +255,13 @@ export class App {() => {},),timeZone: opts.timeZone,+ // 花费按 Modelflare 目录的参考价估算(缓存的那份;没读过就先不算,顺手去读)+ rates: (model) => this.ratesOf(model),+ botBudget: (botId) => {+ const c = this.botBudgetCache;+ const b = c?.data[botId];+ return c && b && this.store.getBot(botId)?.settings.budget.enabled ? { ...b, at: c.at } : undefined;+ },});this.agent.tasks = this.tasks;this.ruleEvents = new RuleEvents(this.tasks);@@ -456,7 +465,45 @@ export class App {const bot = this.store.getBot(botId);if (!bot) throw new Error(t("app.bot_not_found"));await this.account.setBotBudget(bot.id, bot.name, budget);- return this.store.updateBot(botId, { settings: { ...bot.settings, budget } })!;+ const out = this.store.updateBot(botId, { settings: { ...bot.settings, budget } })!;+ // 调高了预算:留给聊天而停着的后台工作马上接着来+ void this.refreshBotBudgets();+ return out;+ }++ /**+ * 读各机器人预算 Key 的总额与余额(登录了、有机器人开着预算时)。任务服务按它决定后台工作要不要为聊天停下;+ * 读到了就告诉它(预算回来了,等着的开始)。读不到就留着上一次的。+ */+ async refreshBotBudgets(): Promise<void> {+ if (!this.account?.signedIn || !this.store.listBots().some((b) => b.settings.budget.enabled)) {+ if (this.botBudgetCache) {+ this.botBudgetCache = undefined;+ this.tasks.budgetsChanged();+ }+ return;+ }+ try {+ const keys = await this.account.botBudgets();+ const data: Record<string, { limitUsd: number; remainUsd: number }> = {};+ for (const [botId, k] of Object.entries(keys)) {+ if (k.limit_usd === null || !(k.limit_usd > 0)) continue;+ data[botId] = { limitUsd: k.limit_usd, remainUsd: k.status === "exhausted" ? 0 : Math.max(0, Number(k.remain_usd ?? k.limit_usd - k.used_usd)) };+ }+ this.botBudgetCache = { at: Date.now(), data };+ this.tasks.budgetsChanged();+ } catch (e) {+ log.warn("reading bot budgets failed", { message: (e as Error).message.slice(0, 200) });+ }+ }++ /** 估算花费用的单价:缓存的 Modelflare 目录里这个模型的(去掉内置网关的 provider 前缀,再试最后一段);没读过就去读,这次先没有 */+ private ratesOf(model: string): Rates | undefined {+ const c = this.modelInfoCache;+ if (!c || Date.now() - c.at > 3600_000) void this.modelInfo().catch(() => undefined);+ if (!c) return undefined;+ const bare = bareModel(model);+ return (c.data[bare] ?? c.data[bare.split("/").pop() ?? bare])?.rates;}/** 删除机器人时一并删掉它的预算 Key */@@ -526,8 +573,11 @@ export class App {this.delivery.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.agent.available) {+ this.tasks.start();+ void this.modelInfo().catch(() => undefined);+ }if (!this.opts.noWeb) this.web = await startWebServer(this);if (this.magpie) {// 启动时和之后每小时核对一次启用的模型(新上架的加入,下架的移出)@@ -550,6 +600,7 @@ export class App {// 余额与低余额提醒:启动后读一次,之后每 5 分钟一次const tick = () => {if (this.account.signedIn || this.magpie?.modelflareInfo().connected) void this.account.refresh();+ void this.refreshBotBudgets();};setTimeout(tick, 3000).unref();this.accountTimer = setInterval(tick, 5 * 60_000);diff --git a/src/i18n/messages/rules.ts b/src/i18n/messages/rules.tsindex f674053..207640f 100644--- a/src/i18n/messages/rules.ts+++ b/src/i18n/messages/rules.ts@@ -49,6 +49,15 @@ export const zh = {whyPaused: "后台工作已暂停",whyTimeout: "超时",whyApprovalTimeout: "批准超时",+ // 花费与预算(3e):运行记录、「需要你」、推送、接口的报错+ whyRunBudget: "超出单次预算",+ whyMonthBudget: "本月预算用完",+ whyReserve: "机器人预算留给聊天",+ budgetStopped: "停下:{why}",+ monthPaused: "本月预算用完",+ monthLine: "已用约 {spent},下月自动恢复。再给 {add} 继续?",+ monthPush: "⚠️ 规则「{title}」本月预算用完(约 {spent}),已暂停,下月自动恢复。",+ monthUsed: "本月预算已用完(约 {spent})",// 「需要你」subject: "规则「{title}」",failingPaused: { other: "连续失败 {count} 次,已暂停" },@@ -131,6 +140,14 @@ export const en: Catalog<typeof zh> = {whyPaused: "background work was paused",whyTimeout: "timed out",whyApprovalTimeout: "approval timed out",+ whyRunBudget: "over the per-run budget",+ whyMonthBudget: "this month's budget is used up",+ whyReserve: "the bot's budget is kept for chat",+ budgetStopped: "Stopped: {why}",+ monthPaused: "Monthly budget used up",+ monthLine: "Used about {spent}; resumes next month. Add {add} and continue?",+ monthPush: "⚠️ Rule “{title}” used this month's budget (about {spent}) and is paused until next month.",+ monthUsed: "This month's budget is used up (about {spent})",subject: "Rule “{title}”",failingPaused: { one: "Failed {count} time in a row, paused", other: "Failed {count} times in a row, paused" },failing: { one: "Failed {count} time in a row", other: "Failed {count} times in a row" },diff --git a/src/i18n/messages/tasks.ts b/src/i18n/messages/tasks.tsindex 4b95e35..b2dfb98 100644--- a/src/i18n/messages/tasks.ts+++ b/src/i18n/messages/tasks.ts@@ -42,6 +42,15 @@ export const zh = {chWeb: "对话",notifyTitle: "{name} 需要你",trayTitle: { other: "{product} · {count} 件事需要你" },+ // 花费与预算(3e)+ budgetAsk: "已用约 {spent},再给 {add} 继续?",+ budgetGo: "继续",+ budgetStop: "停止",+ badBudget: "金额不对",+ timeCap: "运行超过 {hours} 小时,已停下",+ reserveStep: "预算留给聊天",+ reserveSubject: "后台工作已停",+ reserveLine: "机器人预算只剩约 {remain}(共 {limit}),留给聊天",} satisfies Catalog;export const en: Catalog<typeof zh> = {@@ -85,4 +94,12 @@ export const en: Catalog<typeof zh> = {chWeb: "Chat",notifyTitle: "{name} needs you",trayTitle: { one: "{product} · {count} thing needs you", other: "{product} · {count} things need you" },+ budgetAsk: "Used about {spent}. Add {add} and continue?",+ budgetGo: "Continue",+ budgetStop: "Stop",+ badBudget: "That amount doesn't work",+ timeCap: "ran for over {hours} hours and was stopped",+ reserveStep: "Budget kept for chat",+ reserveSubject: "Background work stopped",+ reserveLine: "The bot's budget is down to about {remain} of {limit}; the rest is kept for chat",};diff --git a/src/store/db.ts b/src/store/db.tsindex 081e9dd..1542126 100644--- a/src/store/db.ts+++ b/src/store/db.ts@@ -233,6 +233,7 @@ export interface TaskRow {model: string;/** 建任务时机器人的权限预设(快照) */permission: string;+ /** 预算(美元,默认 1;用完时停下问「再给 $1 继续?」)与估算的已花费用(各个 run 的 cost_usd 之和) */budgetUsd: number;spentUsd: number;/** 最近一次 Report */@@ -325,8 +326,11 @@ export interface RuleRow {nextRunAt: number;/** 连续失败几次(成功一次清零;3 次自动暂停) */failures: number;- /** 暂停的原因:failures;空 = 没暂停 */+ /** 暂停的原因:failures(连续失败)、budget(本月预算用完,下个月自动恢复);空 = 没暂停 */pausedReason: string;+ /** 每次运行的预算、每月的预算(美元,3e);本月花了多少从 runs 汇总 */+ runBudgetUsd: number;+ monthBudgetUsd: number;/** 不受免打扰和每天上限限制(固定提醒:时间是用户定的) */anytime: boolean;createdAt: number;@@ -363,6 +367,7 @@ const TASK_COLS: Record<string, string> = {title: "title",sessionId: "session_id",model: "model",+ budgetUsd: "budget_usd",spentUsd: "spent_usd",report: "report",endedAt: "ended_at",@@ -400,6 +405,8 @@ const RULE_COLS: Record<string, string> = {nextRunAt: "next_run_at",failures: "failures",pausedReason: "paused_reason",+ runBudgetUsd: "run_budget_usd",+ monthBudgetUsd: "month_budget_usd",anytime: "anytime",updatedAt: "updated_at",};@@ -517,6 +524,9 @@ const COLUMNS: Array<[string, string, string]> = [// 规则(3d)执行时的审批["approvals", "rule_id", "TEXT NOT NULL DEFAULT ''"],["runs", "permission", "TEXT NOT NULL DEFAULT ''"],+ // 规则的预算(3e):每次运行、每月+ ["rules", "run_budget_usd", "REAL NOT NULL DEFAULT 0.1"],+ ["rules", "month_budget_usd", "REAL NOT NULL DEFAULT 3"],];export class Store {@@ -930,10 +940,10 @@ export class Store {return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toApproval(r));}/** 只在 pending 时生效,返回是否更新成功(防止重复决定)。 */- decideApproval(id: string, status: Exclude<ApprovalStatus, "pending">, decidedBy: string, result = ""): boolean {+ decideApproval(id: string, status: Exclude<ApprovalStatus, "pending">, decidedBy: string, result = "", at = Date.now()): boolean {const res = this.db.prepare("UPDATE approvals SET status = ?, decided_by = ?, result = ?, decided_at = ? WHERE id = ? AND status = 'pending'")- .run(status, decidedBy, result, Date.now(), id);+ .run(status, decidedBy, result, at, id);return Number(res.changes) > 0;}@@ -1215,9 +1225,13 @@ export class Store {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 {+ updateTask(id: string, patch: Partial<Pick<TaskRow, "originRef" | "title" | "sessionId" | "model" | "budgetUsd" | "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy" | "updatedAt">>): void {updateRow(this.db, "tasks", TASK_COLS, id, patch);}+ /** 任务又花了一点(每次模型请求的估算加上去) */+ addTaskSpent(id: string, usd: number): void {+ if (usd > 0) this.db.prepare("UPDATE tasks SET spent_usd = spent_usd + ? WHERE id = ?").run(usd, id);+ }/** open:还没结束(停止、归档)的;since:之后更新过的 */listTasks(opts: { botId?: string; conversationId?: string; open?: boolean; since?: number; limit?: number } = {}): TaskRow[] {const where: string[] = [];@@ -1375,20 +1389,29 @@ export class Store {nextRunAt: Number(r.next_run_at),failures: Number(r.failures),pausedReason: String(r.paused_reason),+ runBudgetUsd: Number(r.run_budget_usd ?? 0.1),+ monthBudgetUsd: Number(r.month_budget_usd ?? 3),anytime: Number(r.anytime) === 1,createdAt: Number(r.created_at),updatedAt: Number(r.updated_at),};}- insertRule(r: Omit<RuleRow, "version" | "failures" | "pausedReason" | "observeLeft"> & Partial<Pick<RuleRow, "version" | "observeLeft">>): RuleRow {+ insertRule(+ r: Omit<RuleRow, "version" | "failures" | "pausedReason" | "observeLeft" | "runBudgetUsd" | "monthBudgetUsd"> & Partial<Pick<RuleRow, "version" | "observeLeft" | "runBudgetUsd" | "monthBudgetUsd">>,+ ): RuleRow {this.db.prepare(- `INSERT INTO rules(id, bot_id, conversation_id, title, instruction, message, kind, trigger_spec, mode, observe_left, folder, version, next_run_at, anytime, created_at, updated_at)- VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ `INSERT INTO rules(id, bot_id, conversation_id, title, instruction, message, kind, trigger_spec, mode, observe_left, folder, version, next_run_at, anytime, created_at, updated_at, run_budget_usd, month_budget_usd)+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,)- .run(r.id, r.botId, r.conversationId, r.title, r.instruction, r.message, r.kind, JSON.stringify(r.trigger), r.mode, r.observeLeft ?? 0, r.folder, r.version ?? 1, r.nextRunAt, r.anytime ? 1 : 0, r.createdAt, r.updatedAt);+ .run(r.id, r.botId, r.conversationId, r.title, r.instruction, r.message, r.kind, JSON.stringify(r.trigger), r.mode, r.observeLeft ?? 0, r.folder, r.version ?? 1, r.nextRunAt, r.anytime ? 1 : 0, r.createdAt, r.updatedAt, r.runBudgetUsd ?? 0.1, r.monthBudgetUsd ?? 3);return this.getRule(r.id)!;}+ /** 规则从 since 起(按该跑的时间)花了多少:本月的花费 */+ ruleSpent(ruleId: string, since: number): number {+ const r = this.db.prepare("SELECT COALESCE(SUM(cost_usd), 0) AS s FROM runs WHERE rule_id = ? AND queued_at >= ?").get(ruleId, since) as Row | undefined;+ return Number(r?.s ?? 0);+ }getRule(id: string): RuleRow | undefined {const r = this.db.prepare("SELECT * FROM rules WHERE id = ?").get(id) as Row | undefined;return r ? this.toRule(r) : undefined;diff --git a/src/tasks/attention.ts b/src/tasks/attention.tsindex 0c5f0c0..293022d 100644--- a/src/tasks/attention.ts+++ b/src/tasks/attention.ts@@ -12,16 +12,23 @@ import { questionsOf, type QuestionItem } from "../agent/approvals.js";import type { AttentionItem as DeliveryItem } from "../core/delivery.js";import { logger } from "../log.js";import { t as tr } from "../i18n/index.js";+import { BUDGET_TOOL } from "./cost.js";const log = logger("attention");-/** question / approval:在等你回答、批准;failed:任务失败了;rule:规则连续失败(暂停了);delivery:结果没送到;login:渠道登录过期了 */-export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login";-/** answer、approve、deny、retry(任务再试 / 消息再发)、stop、dismiss(不再提示)、relogin(去重新扫码)、open(打开对话) */-export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open";+/**+ * question / approval:在等你回答、批准(任务预算用完时的「再给 $1 继续?」也是 question);failed:任务失败了;+ * rule:规则连续失败或本月预算用完(暂停了);delivery:结果没送到;login:渠道登录过期了;budget:机器人的预算留给聊天,后台工作停着+ */+export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login" | "budget";+/**+ * answer、approve、deny、retry(任务再试 / 消息再发)、stop、dismiss(不再提示)、relogin(去重新扫码)、+ * open(打开对话;budget 是打开机器人设置的预算)、continue(加预算接着做:任务 $1,规则每月 $3)+ */+export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open" | "continue";export interface AttentionItem {- /** 稳定 id:approval:<id>、task:<id>、rule:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道> */+ /** 稳定 id:approval:<id>、task:<id>、rule:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道>、reserve:<bot>(预算留给聊天) */id: string;kind: AttentionKind;botId: string;@@ -47,8 +54,8 @@ export interface AttentionItem {export type AttentionSource = () => AttentionItem[];-/** 排序:提问和审批在前(等着的事),再是失败、没送到,最后是系统的(登录);同一类旧的在前 */-const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3 };+/** 排序:提问和审批在前(等着的事),再是失败、没送到,最后是系统的(登录、预算);同一类旧的在前 */+const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3, budget: 3 };const NOTIFIED = "attention:notified";@@ -186,7 +193,8 @@ export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[botId: r.botId,botName: store.getBot(r.botId)?.name ?? r.botId,subject: task?.title ?? (rule ? tr("rules.subject", { title: rule.title }) : (channelLabel(channel) ?? tr("tasks.chWeb"))),- status: r.kind === "approval" ? tr("tasks.stageApproval") : tr("tasks.stageAnswer"),+ // 任务预算用完时问的那个:状态是预算用完(第二行就是「已用约 $1.00,再给 $1 继续?」)+ status: r.kind === "approval" ? tr("tasks.stageApproval") : r.tool === BUDGET_TOOL ? tr("tasks.stageBudget") : tr("tasks.stageAnswer"),line: line.length > 300 ? line.slice(0, 299) + "…" : line,since: r.createdAt,severity: "warn",diff --git a/src/tasks/cost.ts b/src/tasks/cost.tsnew file mode 100644index 0000000..e618697--- /dev/null+++ b/src/tasks/cost.ts@@ -0,0 +1,58 @@+/**+ * 花费与预算(设计文档第 8 节,3e):估算一次运行花了多少、各级预算的默认值。+ *+ * - 估算:任务、规则会话的订阅已经看到的 assistant/message 事件带着这次模型请求的用量(DSH 的 inputTokens 不含缓存命中和写入,+ * 它们另算 cacheReadTokens、cacheWriteTokens),乘上 Modelflare 的参考价(account/model-info.ts 的 rates,美元 / 百万 tokens)。+ * 存在 runs.cost_usd 上,任务累加到 tasks.spent_usd,规则按月从 runs 汇总。界面上写「约」:账单为准。+ * - 拿不到价格(外部端点、目录里没有这个模型、离线)就不算,预算也就不起作用;时间上限照常。+ */+import type { Rates } from "../account/model-info.js";++export type { Rates };++/** 任务的预算(建任务时、之后都能改) */+export const TASK_BUDGET_USD = 1;+/** 预算用完时「再给 $1 继续?」每次加多少 */+export const TASK_BUDGET_STEP_USD = 1;+/** 一个任务的预算最多到多少(防手滑) */+export const TASK_BUDGET_MAX_USD = 1000;+/** 规则每次运行的预算 */+export const RULE_RUN_BUDGET_USD = 0.1;+/** 规则每月的预算;用完暂停,「再给 $3」每次加多少 */+export const RULE_MONTH_BUDGET_USD = 3;+/** 机器人有 Modelflare 预算 Key 时:剩下的不到总额的这一份就停后台工作,留给聊天 */+export const RESERVE_SHARE = 0.2;+/** 任务每次运行最多跑多久(不算等人批准的时间) */+export const TASK_RUN_CAP_MS = 4 * 3600_000;++/** 预算用完时问用户的那个提问(审批中心里 tool 记成它,回答由任务服务处理,不交给模型) */+export const BUDGET_TOOL = "task_budget";++/** DSH assistant/message 事件里的用量(一次模型请求) */+export interface Usage {+ inputTokens?: number;+ outputTokens?: number;+ cacheReadTokens?: number;+ cacheWriteTokens?: number;+}++const n = (v: unknown) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : 0);++/** 一次模型请求的花费(美元);没有价格就是 0。缓存命中、写入没有单独的价时按输入价算(宁可多估) */+export function costOf(u: Usage | undefined, r: Rates | undefined): number {+ if (!u || !r) return 0;+ const input = n(r.input);+ const usd = n(u.inputTokens) * input + n(u.outputTokens) * n(r.output ?? input) + n(u.cacheReadTokens) * (r.cacheRead ?? input) + n(u.cacheWriteTokens) * (r.cacheWrite ?? input);+ return usd / 1_000_000;+}++/** 给人看的金额:$1.00、$0.08;不到半分的写 <$0.01 */+export function usdText(v: number): string {+ if (v > 0 && v < 0.005) return "<$0.01";+ return `$${v.toFixed(2)}`;+}++/** 加预算时的金额:$1、$3、$0.50 */+export function stepText(v: number): string {+ return Number.isInteger(v) ? `$${v}` : `$${v.toFixed(2)}`;+}diff --git a/src/tasks/rules.ts b/src/tasks/rules.tsindex d0d6364..dce4044 100644--- a/src/tasks/rules.ts+++ b/src/tasks/rules.ts@@ -1,8 +1,9 @@/*** 规则(3d)的纯函数部分:状态、给人看的一行、每种模式的权限和去掉的工具。写库的是任务服务(service.ts,唯一的写入者)。*- * 状态(第一条符合的为准):暂停了(连续失败 3 次)→ 已暂停;关了 → 已关闭;一次性的跑过了 → 已结束;提醒 → 提醒;- * 观察中(含改了原话后先观察的那一次)→ 观察中;其余 → 执行中。状态是"点 + 文字":红 = 暂停,绿 = 执行中、提醒,灰 = 观察、关闭、结束。+ * 状态(第一条符合的为准):暂停了(连续失败 3 次、本月预算用完)→ 已暂停;关了 → 已关闭;一次性的跑过了 → 已结束;提醒 → 提醒;+ * 观察中(含改了原话后先观察的那一次)→ 观察中;其余 → 执行中。状态是"点 + 文字":红 = 连续失败暂停,黄 = 本月预算用完暂停,+ * 绿 = 执行中、提醒,灰 = 观察、关闭、结束。* 给人看的文字跟着语言(src/i18n 的 rules.*);跳过、失败的原因存成代码(RUN_ERROR),显示时再翻。*/import type { OutboxRow, RuleMode, RuleRow, RunRow } from "../store/db.js";@@ -50,13 +51,13 @@ export function rulePermission(mode: "observe" | "act", botPreset: string): "reaexport interface RuleState {key: "paused" | "off" | "done" | "remind" | "observe" | "act";label: string;- /** 状态点:err 红、ok 绿、空 = 灰 */- dot: "" | "ok" | "err";+ /** 状态点:err 红、warn 黄、ok 绿、空 = 灰 */+ dot: "" | "ok" | "warn" | "err";}export function ruleState(rule: RuleRow, live = false, l: Lang = currentLang()): RuleState {const s = (key: RuleState["key"], label: MessageKey, dot: RuleState["dot"]): RuleState => ({ key, label: tl(l, label), dot });- if (rule.pausedReason) return s("paused", "rules.statePaused", "err");+ if (rule.pausedReason) return s("paused", "rules.statePaused", rule.pausedReason === "budget" ? "warn" : "err");if (rule.mode === "off") return s("off", "rules.stateOff", "");if (!live && !rule.nextRunAt && rule.trigger.kind === "schedule") return s("done", "rules.stateDone", "");if (rule.kind === "remind") return s("remind", "rules.stateRemind", "ok");@@ -89,6 +90,12 @@ export interface RuleView {/** 这一版好好观察过几次 */observed: number;failures: number;+ /** 暂停的原因:failures / budget;空 = 没暂停 */+ pausedReason: string;+ /** 本月估算花了多少、每月的预算、每次的预算(美元) */+ monthUsd: number;+ monthBudgetUsd: number;+ runBudgetUsd: number;folder: string;version: number;createdAt: number;@@ -114,6 +121,10 @@ export const RUN_ERROR = {modelErrors: "model_errors",agentFailed: "agent_failed",agentUnavailable: "agent_unavailable",+ /** 3e:超出单次预算、本月预算用完、机器人的预算留给聊天 */+ runBudget: "run_budget",+ monthBudget: "month_budget",+ reserve: "reserve",} as const;/** 原因 → 词条:规则自己的,和任务共用的那几种(tasks.*,和任务失败时的说法一样) */@@ -129,6 +140,9 @@ const WHY: Record<string, MessageKey> = {model_errors: "tasks.modelKeptFailing",agent_failed: "tasks.agentDidntStart",agent_unavailable: "tasks.agentUnavailable",+ run_budget: "rules.whyRunBudget",+ month_budget: "rules.whyMonthBudget",+ reserve: "rules.whyReserve",};/** 存下来的原因给人看:认得的翻成当前语言,其余(模型自己说的)原样 */@@ -184,7 +198,7 @@ export function runLine(run: RunRow, kind: RuleRow["kind"], carrier?: OutboxRow,case "stopped":return tl(l, "tasks.stageStopped");case "budget":- return tl(l, "tasks.stageBudget");+ return run.error ? tl(l, "rules.budgetStopped", { why: errorText(run.error, l) }) : tl(l, "tasks.stageBudget");case "done":break;default:@@ -222,6 +236,8 @@ export interface RuleRunView {/** 那次的权限:只读 / 可写工作区 */permission: string;steps: number;+ /** 估算花了多少(美元) */+ costUsd: number;startedAt: number;endedAt: number;}diff --git a/src/tasks/service.ts b/src/tasks/service.tsindex d080932..4b8313d 100644--- a/src/tasks/service.ts+++ b/src/tasks/service.ts@@ -19,7 +19,11 @@* 排队、名额、收尾、提醒、重试;不同的是结束之后(见「规则」一节):观察只记「本会发送」,执行时那一句经出站队列发出去,* 连续失败 3 次自动暂停。定时器在 scheduler.ts,错过的按宽限期补跑一次或记为跳过。*- * 3e–3f 的缝:花费(cost_usd、budget)。+ * - 花费(3e,设计第 8 节):会话里每次模型请求的用量按参考价估算(cost.ts),记在 run 上、累加到任务上,规则按月汇总。+ * 任务的预算(默认 $1)用完时取消这一轮(指令通道,之后还能接着用),问用户「已用约 $1.00,再给 $1 继续?」(一个提问:+ * 推给会话、在「需要你」里,回答「继续」加预算接着做,「停止」停掉);规则每次运行 $0.10(这次以 budget 结束,算一次失败),+ * 每月 $3(暂停,「需要你」里一行,下个月自动恢复)。机器人有 Modelflare 预算 Key 时,剩下的不到 20% 就停后台工作,留给聊天。+ * 任务每次运行最多 4 小时(等人批准的时间不算),到了算失败。*/import crypto from "node:crypto";import fs from "node:fs";@@ -30,15 +34,28 @@ import { ActivityLog, type ActivityStep } from "../agent/activity.js";import { ResumeFailed, deliverables } from "../agent/host.js";import { answerLine, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";import { actionCardSpec } from "../channels/feishu/transport.js";-import { NUDGE, RULE_NUDGE, RULE_RERUN, RULE_RESULT_SYSTEM, attachmentsOf, rebrief, recoveryNote, retryNote, ruleBrief, ruleResultInput, ruleRules, taskBrief } from "../agent/prompts/index.js";+import { NUDGE, RULE_NUDGE, RULE_RERUN, RULE_RESULT_SYSTEM, attachmentsOf, rebrief, recoveryNote, resumeNote, retryNote, ruleBrief, ruleResultInput, ruleRules, taskBrief } from "../agent/prompts/index.js";import type { BotSettings } from "../agent/settings.js";import type { ApprovalRow, Conversation, InputKind, RuleKind, RuleMode, RuleRow, RuleTrigger, RunCause, RunInputRow, RunOutcome, RunRow, Store, TaskReport, TaskRow } from "../store/db.js";import type { AttentionItem } from "./attention.js";import { logger } from "../log.js";import { localParts, systemTimeZone } from "../core/quiet.js";+import {+ BUDGET_TOOL,+ RESERVE_SHARE,+ RULE_MONTH_BUDGET_USD,+ TASK_BUDGET_MAX_USD,+ TASK_BUDGET_STEP_USD,+ TASK_BUDGET_USD,+ TASK_RUN_CAP_MS,+ costOf,+ stepText,+ usdText,+ type Rates,+} from "./cost.js";import { DEFAULT_MAX_BACKGROUND, pickRuns, priorityOf } from "./slots.js";import { taskStage, type Stage } from "./stage.js";-import { MAX_GRACE_MS, graceOf, nextRun, latestRun, parseSchedule, type Schedule } from "./schedule.js";+import { MAX_GRACE_MS, graceOf, localTime, nextRun, latestRun, parseSchedule, type Schedule } from "./schedule.js";import { Scheduler } from "./scheduler.js";import { matchesFilter, type RuleEvent } from "./rule-events.js";import {@@ -101,6 +118,8 @@ export interface TaskHost {steer(botId: string, sessionId: string, id: string, text: string): Promise<boolean>;/** 停掉这个会话:取消这一轮、它的子代理和后台命令,之后的工具调用一律拒绝 */stop(botId: string, sessionId: string): Promise<void>;+ /** 停下这一轮(取消、停它的子代理和后台命令),会话之后还能接着用:预算用完、时间到了、给聊天留预算(3e) */+ cancel(botId: string, sessionId: string): Promise<void>;/** 会话空闲时还有没有后台命令、子代理在跑;有就由插件在它们结束、会话再次空闲时报 task-settled */quiet(botId: string, sessionId: string): Promise<{ quiet: boolean; jobs?: string[] }>;/** 这个机器人的一个 run 结束了:代理进程完全空闲、开过的会话又多了,就换一个新的(host.ts restartIfStale) */@@ -135,6 +154,14 @@ export interface TaskServiceOptions {timeZone?: string;/** 规则一次运行最长多久(测试注入) */ruleRunCapMs?: number;+ /** 任务一次运行最长多久,不算等人批准的时间(默认 4 小时;测试注入) */+ taskRunCapMs?: number;+ /** 多久看一次任务的时间上限(默认 1 分钟) */+ capCheckMs?: number;+ /** 估算花费的单价(模型 → 美元 / 百万 tokens;同步,取应用缓存的 Modelflare 目录);没有就不估算 */+ rates?: (model: string) => Rates | undefined;+ /** 机器人的 Modelflare 预算 Key(总额、还剩多少、什么时候读的);没开预算就是 undefined */+ botBudget?: (botId: string) => { limitUsd: number; remainUsd: number; at: number } | undefined;}/** 界面、/tasks 和 task_list 看到的任务 */@@ -154,6 +181,9 @@ export interface TaskView {endedAt: number;/** 跑了几个 run */runs: number;+ /** 估算已花的、预算(美元) */+ spentUsd: number;+ budgetUsd: number;/** 正在跑的那个 run:开始时间与步数 */live?: { runId: string; since: number; steps: number; current?: ActivityStep };}@@ -192,10 +222,19 @@ interface Live {seen: Set<string>;tokensIn: number;tokensOut: number;+ /** 这个 run 估算花了多少(美元) */+ costUsd: number;+ /** 按哪个模型的价估算(事件里没说是哪个模型时) */+ priceModel: string;+ /** 宿主让它停下的原因(预算、时间上限、给聊天留预算):交输入时正好停了,再取消一次 */+ halted?: Halt;/** 规则观察时要批准的事(自动拒绝了,记成「需要批准:…」) */would?: string[];}+/** 宿主让一个 run 停下:任务的预算、时间上限;规则的单次、本月预算;机器人的预算留给聊天 */+type Halt = "budget" | "cap" | "run" | "month" | "reserve";+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();@@ -221,6 +260,16 @@ export function slugOf(title: string): string {const NOTES = "task-notes:";+/** 预算用完时的回答:不要了 */+const STOP_WORDS = /^(停止|停|不用了?|不要了?|算了|取消|stop|no|cancel)[。.!!]*$/i;+/** 只写了一个金额(「再给 $3」里的 3) */+const AMOUNT_ONLY = /^\s*(?:再给|加|给它)?\s*\$?\s*(\d+(?:\.\d+)?)\s*(?:美元|美金|刀|块|dollars?|usd)?\s*$/i;+const amountIn = (text: string) => {+ const m = /(\d+(?:\.\d+)?)/.exec(text);+ const v = m ? Number(m[1]) : NaN;+ return v > 0 && v <= 100 ? v : undefined;+};+/** 给聊天代理的便条:后台任务的结果发出去了,下一条聊天消息带上它(模型知道这件事,用户问"详细说说"时能接上) */export function takeTaskNotes(store: Store, conversationId: string): string {const v = store.getKV(NOTES + conversationId);@@ -244,6 +293,14 @@ export class TaskService {/** 正在删除的机器人 */private dropped = new Set<string>();private unlisten: (() => void) | undefined;+ /** 隔一会儿看一次任务的时间上限 */+ private capTimer: NodeJS.Timeout | undefined;+ /** 机器人从上次读预算 Key 之后又估算花了多少(读到新的就从零算):快到 20% 时不用等下一次读 */+ private botSpend = new Map<string, { at: number; usd: number }>();+ /** 机器人从什么时候起预算不够、后台工作停着(「需要你」里那一行的时间) */+ private reserveSince = new Map<string, number>();+ /** 刚被宿主停下的会话:取消到达之前已经发出去的那次模型请求,花费照样记到这个 run 上(几分钟内) */+ private halted = new Map<string, { runId: string; taskId: string; botId: string; model: string; until: number }>();/** 宿主的定时器:规则到点开 run(scheduler.ts) */readonly scheduler: Scheduler;@@ -261,7 +318,7 @@ export class TaskService {.filter((r) => r.nextRunAt >= after).map((r) => ({ label: r.title, at: r.nextRunAt, kind: r.kind === "remind" ? ("reminder" as const) : ("rule" as const) })),);- this.scheduler = new Scheduler({ next: () => this.store.nextRuleDue(), fire: (now) => this.fireDue(now), now: () => this.now() });+ this.scheduler = new Scheduler({ next: () => this.nextWake(), fire: (now) => this.fireDue(now), now: () => this.now() });}private get store(): Store {@@ -290,6 +347,10 @@ export class TaskService {} else if (r.outcome === "needs_you" && r.report?.question) {const task = this.store.getTask(r.taskId);if (task && task.endReason !== "stopped" && this.store.latestRun(task.id)?.id === r.id) this.ask(task, r.id, r.report.question);+ } else if (r.outcome === "budget") {+ // 停在预算上、还没问出去就退出了:补问一次+ const task = this.store.getTask(r.taskId);+ if (task && task.endReason !== "stopped" && this.store.latestRun(task.id)?.id === r.id) this.askBudget(task, r.id);}}for (const conv of new Set((this.o.approvals?.pendingAll() ?? []).filter((r) => r.taskId).map((r) => r.conversationId))) this.pushNext(conv);@@ -297,19 +358,24 @@ export class TaskService {this.pump();// 定时器最后开:应用没开时错过的规则,宽限期内的补跑一次,更早的记为跳过this.scheduler.start();+ clearInterval(this.capTimer);+ this.capTimer = setInterval(() => this.checkCaps(), this.o.capCheckMs ?? 60_000);+ this.capTimer.unref?.();}/** 应用退出:不再开始新的 run;跑着的留在库里(下次启动时恢复),步骤先存下 */stop(): void {this.closing = true;this.scheduler.stop();+ clearInterval(this.capTimer);+ this.capTimer = undefined;this.unlisten?.();this.unlisten = undefined;for (const l of this.live.values()) {clearTimeout(l.timer);clearTimeout(l.capTimer);try {- this.store.updateRun(l.runId, { activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });+ this.store.updateRun(l.runId, { activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut, costUsd: l.costUsd });} catch {/* 数据库可能已经关了 */}@@ -340,7 +406,7 @@ export class TaskService {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 } : {}) });+ 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, costUsd: l.costUsd } : {}) });if (run.ruleId) {this.recoverRule(run);continue;@@ -391,7 +457,7 @@ export class TaskService {folder,model: conv.model || bot.defaultModel || this.o.defaultModel?.() || "",permission: st.permission,- budgetUsd: o.budgetUsd && o.budgetUsd > 0 ? Math.min(o.budgetUsd, 100) : 1,+ budgetUsd: o.budgetUsd && o.budgetUsd > 0 ? Math.min(o.budgetUsd, 100) : TASK_BUDGET_USD,anytime: !!o.anytime,createdAt: now,updatedAt: now,@@ -545,10 +611,26 @@ export class TaskService {return true;}- /** 有空名额就开始排队的 run(人的唤醒在前,见 slots.ts);后台工作暂停了的机器人不开始新的 */+ /**+ * 机器人的预算快用完了:任务的排着等(加了预算、读到的余额回到 20% 以上再开始);规则的这次记为跳过(预算留给聊天)。+ * 返回 true = 现在不开始+ */+ private heldByReserve(run: RunRow): boolean {+ if (!this.reserve(run.botId)) return false;+ if (run.ruleId) {+ this.store.updateRun(run.id, { state: "ended", outcome: "skipped", error: RUN_ERROR.reserve, endedAt: this.now() });+ log.info("rule run skipped: the bot's budget is kept for chat", { rule: run.ruleId, run: run.id });+ this.changed(run.ruleId);+ }+ return true;+ }++ /** 有空名额就开始排队的 run(人的唤醒在前,见 slots.ts);后台工作暂停了、预算留给聊天的机器人不开始新的 */pump(): void {if (!this.started || this.closing) return;- const queued = this.store.listRuns({ states: ["queued"] }).filter((r) => (r.taskId || (r.ruleId && !this.skipStale(r))) && !this.dropped.has(r.botId) && !this.heldByPause(r));+ const queued = this.store+ .listRuns({ states: ["queued"] })+ .filter((r) => (r.taskId || (r.ruleId && !this.skipStale(r))) && !this.dropped.has(r.botId) && !this.heldByPause(r) && !this.heldByReserve(r));if (!queued.length) return;// 等批准的 run 让出名额(DSH 那次调用照样等着,批了就接着做)const blocked = new Set((this.o.approvals?.pendingAll() ?? []).filter((a) => a.taskId && a.blocking && a.kind === "approval").map((a) => a.taskId));@@ -572,6 +654,14 @@ export class TaskService {this.store.updateRun(runId, { state: "ended", outcome: "stopped", endedAt: now });return;}+ // 预算已经用完(预算用完后又来了回答、追加):不交给会话,输入留着,再问一次要不要加预算+ if (task.spentUsd >= task.budgetUsd) {+ this.store.updateRun(runId, { state: "ended", outcome: "budget", startedAt: now, endedAt: now, sessionId: task.sessionId });+ log.info("background task is over its budget; asking before it continues", { task: task.id, run: runId });+ this.askBudget(task, runId);+ this.changed(task.id);+ return;+ }this.store.updateRun(runId, { state: "running", startedAt: now, sessionId: task.sessionId });const l: Live = {runId,@@ -592,6 +682,8 @@ export class TaskService {seen: new Set(),tokensIn: 0,tokensOut: 0,+ costUsd: 0,+ priceModel: task.model || this.store.getBot(task.botId)?.defaultModel || this.o.defaultModel?.() || "",};this.live.set(runId, l);this.bySession.set(task.sessionId, l);@@ -638,6 +730,8 @@ export class TaskService {if (this.live.get(l.runId) !== l) {// 交出去的时候任务被停了(规则被删了、超时了):输入已经到了会话里,再停一次(插件拒绝它之后的工具调用)if (l.ruleId || this.store.getTask(l.taskId)?.endReason === "stopped") await this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);+ // 预算用完、时间到了、给聊天留预算:再取消一次这一轮(会话之后还要接着用)+ else if (l.halted) await this.o.host.cancel(l.botId, l.sessionId).catch(() => undefined);return;}const at = this.now();@@ -705,13 +799,17 @@ export class TaskService {/** root:任务会话 id(子代理的通知也归到它) */onEvent(_botId: string, root: string, n: TaskNotification): void {const l = this.bySession.get(root);- if (!l) return;+ if (!l) return this.lateUsage(root, n);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 (p.sessionId !== root) {+ // 子代理的模型请求也算进花费(它的步骤不进这个 run 的处理过程)+ if (n.method === "session.event" && p.event?.type === "assistant/message" && p.event.data?.usage) this.usage(l, p.event.data);+ return;+ }if (n.method === "session.status") {if (p.status === "running") {l.busy = true;@@ -739,12 +837,192 @@ export class TaskService {} 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.store.updateRun(l.runId, { activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut, costUsd: l.costUsd });this.changed(l.taskId || l.ruleId);- } else if (type === "assistant/message" && data.usage) {- l.tokensIn += Number(data.usage.inputTokens) || 0;- l.tokensOut += Number(data.usage.outputTokens) || 0;+ } else if (type === "assistant/message" && data.usage) this.usage(l, data);+ }++ // ---------- 花费与预算(3e) ----------++ /**+ * 一次模型请求的用量(assistant/message):按参考价估算,记在 run 上(马上落库:本月的花费从库里汇总)、加到任务上,+ * 再看各级预算。事件里有回答的模型就按它的价(子代理可能用别的模型),没有就按这个 run 的模型。+ */+ private usage(l: Live, data: any): void {+ const u = data.usage ?? {};+ l.tokensIn += (Number(u.inputTokens) || 0) + (Number(u.cacheReadTokens) || 0) + (Number(u.cacheWriteTokens) || 0);+ l.tokensOut += Number(u.outputTokens) || 0;+ const model = String(data.message?.source?.model ?? "");+ const usd = costOf(u, (model ? this.o.rates?.(model) : undefined) ?? (l.priceModel ? this.o.rates?.(l.priceModel) : undefined));+ if (usd > 0) {+ l.costUsd += usd;+ if (l.taskId) this.store.addTaskSpent(l.taskId, usd);+ const b = this.o.botBudget?.(l.botId);+ if (b) {+ const cur = this.botSpend.get(l.botId);+ this.botSpend.set(l.botId, { at: b.at, usd: (cur?.at === b.at ? cur.usd : 0) + usd });+ }}+ this.store.updateRun(l.runId, { tokensIn: l.tokensIn, tokensOut: l.tokensOut, costUsd: l.costUsd });+ if (usd <= 0) return;+ this.changed(l.taskId || l.ruleId);+ this.checkBudgets(l);+ }++ /**+ * 花了钱之后看预算(第一条超了的为准):机器人的预算要留给聊天 → 停下这个机器人所有的后台 run;+ * 任务的预算用完 → 停下、问要不要加;规则本月的、这次的预算用完 → 停下(本月的还要暂停规则)。+ * 已经报了 done / failed、只差收尾的不停(下一次开始前再看)。+ */+ private checkBudgets(l: Live): void {+ if (this.live.get(l.runId) !== l || this.closing) return;+ if (this.reserve(l.botId)) return this.holdForReserve(l.botId);+ if (l.final) return;+ if (l.taskId) {+ const task = this.store.getTask(l.taskId);+ if (task && task.spentUsd >= task.budgetUsd) this.halt(l, "budget");+ return;+ }+ const rule = this.store.getRule(l.ruleId);+ if (!rule) return;+ if (this.monthSpent(rule) >= rule.monthBudgetUsd) this.halt(l, "month");+ else if (l.costUsd >= rule.runBudgetUsd) this.halt(l, "run");+ }++ /**+ * 让一个 run 停下:取消这一轮(任务的会话之后还要接着用:只取消不封;规则的每次一个新会话,直接停掉)。+ * 任务:预算用完 → budget,问要不要加;时间到了 → 失败(告诉用户,可以重试);给聊天留预算 → 中断,排一个 run 等预算回来。+ * 规则:budget 结束,原因是单次 / 本月 / 留给聊天。+ */+ private halt(l: Live, why: Halt): void {+ if (this.live.get(l.runId) !== l) return;+ l.halted = why;+ const now = this.now();+ this.halted.set(l.sessionId, { runId: l.runId, taskId: l.taskId, botId: l.botId, model: l.priceModel, until: now + 10 * 60_000 });+ if (l.ruleId) {+ l.activity.end(errorText(why === "run" ? RUN_ERROR.runBudget : why === "month" ? RUN_ERROR.monthBudget : RUN_ERROR.reserve), now);+ log.warn("rule run stopped at a budget", { rule: l.ruleId, run: l.runId, why, costUsd: Math.round(l.costUsd * 10_000) / 10_000 });+ this.end(l, "budget", undefined, why === "run" ? RUN_ERROR.runBudget : why === "month" ? RUN_ERROR.monthBudget : RUN_ERROR.reserve);+ void this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);+ return;+ }+ const jobs = l.activity.steps.filter((s) => s.kind === "job" && s.status === "running").map((s) => clip(oneLine(s.summary || s.title), 120));+ if (why === "budget") {+ l.activity.end(tr("tasks.stageBudget"), now);+ log.warn("background task used its budget; stopping it and asking the user", { task: l.taskId, run: l.runId, spentUsd: Math.round((this.store.getTask(l.taskId)?.spentUsd ?? 0) * 10_000) / 10_000 });+ this.end(l, "budget");+ } else if (why === "cap") {+ const error = tr("tasks.timeCap", { hours: Math.round((this.o.taskRunCapMs ?? TASK_RUN_CAP_MS) / 3600_000) || 1 });+ l.activity.end(error, now);+ log.warn("background task run hit its time cap; stopping it", { task: l.taskId, run: l.runId });+ this.end(l, "failed", undefined, error);+ } else {+ l.activity.end(tr("tasks.reserveStep"), now);+ log.warn("background task paused: the bot's budget is kept for chat", { task: l.taskId, run: l.runId });+ this.end(l, "interrupted", undefined, RUN_ERROR.reserve);+ const task = this.store.getTask(l.taskId);+ if (task && !task.endedAt) {+ this.addInput(task.id, "recovery", resumeNote("reserve", jobs), false);+ if (!this.queuedRun(task.id)) this.enqueue(task, "recover");+ this.changed(task.id);+ }+ }+ void this.o.host.cancel(l.botId, l.sessionId).catch((e) => log.warn("cancelling the task's turn failed", { task: l.taskId, message: (e as Error).message.slice(0, 200) }));+ }++ /** 停下之后才到的用量(取消到达之前已经发出去的请求):记到停下的那个 run 和任务上,不再看预算 */+ private lateUsage(root: string, n: TaskNotification): void {+ const h = this.halted.get(root);+ const ev = n.params?.event;+ if (!h || n.method !== "session.event" || ev?.type !== "assistant/message" || !ev.data?.usage) return;+ if (this.now() > h.until) return void this.halted.delete(root);+ const model = String(ev.data.message?.source?.model ?? "");+ const usd = costOf(ev.data.usage, (model ? this.o.rates?.(model) : undefined) ?? (h.model ? this.o.rates?.(h.model) : undefined));+ const run = usd > 0 ? this.store.getRun(h.runId) : undefined;+ if (!run) return;+ this.store.updateRun(run.id, { costUsd: run.costUsd + usd });+ if (h.taskId) this.store.addTaskSpent(h.taskId, usd);+ const b = this.o.botBudget?.(h.botId);+ const cur = this.botSpend.get(h.botId);+ if (b) this.botSpend.set(h.botId, { at: b.at, usd: (cur?.at === b.at ? cur.usd : 0) + usd });+ this.changed(h.taskId || run.ruleId);+ }++ /** 机器人的预算要留给聊天:它在跑的后台 run 都停下(已经报了结果、只差收尾的除外) */+ private holdForReserve(botId: string): void {+ for (const l of [...this.live.values()]) if (l.botId === botId && !l.final) this.halt(l, "reserve");+ this.changed(botId);+ }++ /**+ * 机器人的 Modelflare 预算 Key 快用完了:剩下的(上次读到的余额减去之后估算花掉的)不到总额的 20%,就返回还剩多少、总额。+ * 没开预算(或没登录)是 undefined。+ */+ reserve(botId: string): { remainUsd: number; limitUsd: number } | undefined {+ const b = this.o.botBudget?.(botId);+ if (!b || !(b.limitUsd > 0)) {+ this.reserveSince.delete(botId);+ return undefined;+ }+ const spent = this.botSpend.get(botId);+ const remain = b.remainUsd - (spent?.at === b.at ? spent.usd : 0);+ if (remain >= RESERVE_SHARE * b.limitUsd) {+ this.reserveSince.delete(botId);+ return undefined;+ }+ if (!this.reserveSince.has(botId)) this.reserveSince.set(botId, this.now());+ return { remainUsd: Math.max(0, remain), limitUsd: b.limitUsd };+ }++ /** 应用读到了新的预算 Key 余额(或改了预算):预算回来了,等着的开始;「需要你」跟着变 */+ budgetsChanged(): void {+ this.pump();+ this.scheduler.wake();+ this.changed("");+ }++ /**+ * 时间上限(每分钟看一次):任务一次运行最多 4 小时,等人批准的时间不算(approvals 里这个 run 阻塞着的那几段)。+ * 已经报了结果、只差收尾的不算(收尾最多 30 分钟,插件管)。+ */+ checkCaps(now = this.now()): void {+ if (!this.started || this.closing) return;+ for (const [sid, h] of this.halted) if (now > h.until) this.halted.delete(sid);+ const cap = this.o.taskRunCapMs ?? TASK_RUN_CAP_MS;+ for (const l of [...this.live.values()]) {+ if (l.ruleId || l.final || this.live.get(l.runId) !== l) continue;+ const run = this.store.getRun(l.runId);+ if (!run?.startedAt) continue;+ if (now - run.startedAt - this.waitedMs(l.runId, now) >= cap) this.halt(l, "cap");+ }+ }++ /** 这个 run 里等人批准(或回答阻塞着的提问)一共等了多久 */+ private waitedMs(runId: string, now: number): number {+ let ms = 0;+ for (const a of this.store.listApprovals({ runId, limit: 100 })) if (a.blocking) ms += Math.max(0, Math.min(now, a.decidedAt || now) - a.createdAt);+ return ms;+ }++ /** 本月(主人的时区)从几号几点开始;next = 下个月 1 号 0 点 */+ private monthStart(now: number, next = false): number {+ const p = localParts(now, this.timeZone);+ const mo = next ? (p.mo === 12 ? 1 : p.mo + 1) : p.mo;+ const y = next && p.mo === 12 ? p.y + 1 : p.y;+ return localTime(y, mo, 1, 0, this.timeZone);+ }++ /** 规则本月(主人的时区)估算花了多少 */+ private monthSpent(rule: RuleRow, now = this.now()): number {+ return this.store.ruleSpent(rule.id, this.monthStart(now));+ }++ /** 定时器下次醒来:最早该跑的规则;有规则因为本月预算暂停着,还有下个月 1 号(到时自动恢复) */+ private nextWake(): number {+ const due = this.store.nextRuleDue();+ if (!this.store.listRules().some((r) => r.pausedReason === "budget")) return due;+ const month = this.monthStart(this.now(), true);+ return due ? Math.min(due, month) : month;}/**@@ -819,12 +1097,13 @@ export class TaskService {if (l.ruleId) return this.endRule(l, outcome, report, error);this.forget(l);const now = this.now();- this.store.updateRun(l.runId, { state: "ended", outcome, report, error, endedAt: now, activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });+ this.store.updateRun(l.runId, { state: "ended", outcome, report, error, endedAt: now, activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut, costUsd: l.costUsd });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);if (task && outcome === "needs_you" && report?.question) this.ask(task, l.runId, report.question);+ if (task && outcome === "budget") this.askBudget(task, l.runId);log.info("background task run ended", { task: l.taskId, run: l.runId, outcome, ...(error ? { error } : {}) });this.changed(l.taskId);this.pump();@@ -955,6 +1234,11 @@ export class TaskService {const a = (b?.args ?? {}) as Record<string, unknown>;switch (String(b?.op ?? "")) {case "start": {+ const low = this.reserve(botId);+ if (low)+ return {+ error: `This bot's Modelflare budget is almost used up (about ${usdText(low.remainUsd)} of ${stepText(low.limitUsd)} left) and the rest is kept for chat, so no background task can start. Tell the user in one sentence; they can raise the bot's budget in its settings.`,+ };const r = this.create({ botId, conversationId: conv.id, title: String(a.title ?? ""), brief: String(a.brief ?? ""), budgetUsd: Number(a.budget_usd) || undefined, anytime: a.anytime === true });if (!r.task) return { error: r.error };if (this.paused(botId))@@ -1050,14 +1334,78 @@ export class TaskService {this.pushNext(row.conversationId);}- /** 用户回答了任务的提问:回答成为任务的新输入(人的唤醒:预留名额、排在前面) */+ /** 用户回答了任务的提问:回答成为任务的新输入(人的唤醒:预留名额、排在前面);预算的那个由任务服务自己处理 */private answered(task: TaskRow, row: ApprovalRow): void {+ if (row.tool === BUDGET_TOOL) return this.budgetAnswered(task, row);const q = questionsOf(row)[0]?.question ?? row.detail;const input = this.addInput(task.id, "answer", `[用户回答了你的问题]\n问题:${q}\n回答:${answerLine(row) || "(没有写)"}`, true);log.info("the user answered a background task's question", { task: task.id, by: row.decidedBy });void this.wake(task, input, "answer");}+ /**+ * 任务的预算用完了(3e):问用户「已用约 $1.00,再给 $1 继续?」——一个不阻塞、不过期的提问(选项:继续 / 停止),+ * 和任务的提问走同一条路:推给请求它的会话(一个会话一次一个)、在「需要你」里、回编号或引用回答。一个任务同时只问一个。+ */+ private askBudget(task: TaskRow, runId: string): void {+ const a = this.o.approvals;+ if (!a || a.pendingForTask(task.id).some((r) => r.tool === BUDGET_TOOL)) return;+ const spent = this.store.getTask(task.id)?.spentUsd ?? task.spentUsd;+ const question = tr("tasks.budgetAsk", { spent: usdText(spent), add: stepText(TASK_BUDGET_STEP_USD) });+ const go = tr("tasks.budgetGo");+ const stop = tr("tasks.budgetStop");+ const item: QuestionItem = { id: "budget", question, options: [{ label: go }, { label: stop }] };+ a.create({ kind: "question", botId: task.botId, conversationId: task.conversationId, sessionId: task.sessionId, tool: BUDGET_TOOL, detail: question, reason: "", payload: JSON.stringify([item]), taskId: task.id, runId, blocking: false, ttlMs: 0 });+ log.info("background task asks the user for more budget", { task: task.id, run: runId });+ this.note(task.conversationId, `[后台任务「${task.title}」预算用完,在等用户决定:${question}(${go} / ${stop})。用户在聊天里回答它时,用 task_message 转给这个任务]`);+ }++ /**+ * 用户回答了要不要加预算:选「停止」或说不要了 → 停掉任务;选「继续」→ 加 $1 接着做;自己写的:有金额就加那么多,+ * 别的话连同加预算一起交给任务(「继续,改成英文」)。+ */+ private budgetAnswered(task: TaskRow, row: ApprovalRow): void {+ const [go, stop] = (questionsOf(row)[0]?.options ?? []).map((o) => o.label);+ const said = answerLine(row).trim();+ const by = row.decidedBy || "user";+ if (said === stop || STOP_WORDS.test(said)) {+ log.info("the user stopped a background task at its budget", { task: task.id, by });+ void this.stopTask(task.id, by);+ return;+ }+ const custom = said && said !== go ? said : "";+ const amount = custom ? amountIn(custom) : undefined;+ const extra = custom && !AMOUNT_ONLY.test(custom) ? custom : "";+ void this.addBudget(task.id, amount ?? TASK_BUDGET_STEP_USD, by, extra);+ }++ /**+ * 加预算(「需要你」里的继续、预算提问的回答、POST /tasks/:id/budget):预算加上 addUsd(加完还不够已花的,就从已花的再加);+ * 停在预算上的任务接着做(人的唤醒:continue run,第一条是说明),还在等的那个预算提问作废。没停的只是把预算调高。+ */+ async addBudget(taskId: string, addUsd: number = TASK_BUDGET_STEP_USD, by = "web", text = ""): Promise<{ task?: TaskView; error?: string }> {+ const task = this.store.getTask(taskId);+ if (!task) return { error: "task not found" };+ if (task.endReason === "stopped") return { error: tr("tasks.stoppedShort", { title: task.title }) };+ const add = Number(addUsd);+ if (!Number.isFinite(add) || add <= 0 || add > 100) return { error: tr("tasks.badBudget") };+ const raised = task.budgetUsd + add;+ const budget = Math.round(Math.min(TASK_BUDGET_MAX_USD, raised > task.spentUsd ? raised : task.spentUsd + add) * 100) / 100;+ this.store.updateTask(task.id, { budgetUsd: budget, updatedAt: this.now() });+ log.info("background task budget raised", { task: task.id, budgetUsd: budget, by });+ for (const r of this.o.approvals?.pendingForTask(task.id) ?? []) if (r.tool === BUDGET_TOOL) this.o.approvals!.cancel(r.id, by);+ const last = this.store.latestRun(task.id);+ if (last?.state === "ended" && last.outcome === "budget") {+ const jobs = parseSteps(this.store.getRun(last.id)?.activity)+ .filter((s) => s.kind === "job" && s.cut)+ .map((s) => clip(oneLine(s.summary || s.title), 120));+ const input = this.addInput(task.id, "followup", `${resumeNote("budget", jobs)}${text ? `\n\n[用户追加]\n${text.trim()}` : ""}`, true);+ await this.wake(this.store.getTask(task.id)!, input, "continue");+ }+ this.changed(task.id);+ return { task: this.get(task.id) };+ }+/*** 推给请求它的会话(微信、飞书;网页的提问卡片就在对话里):一个会话同时只推一个,前一个没回答,后面的只在"需要你"里等,* 微信里光回编号才不会认错。按主动消息的规则推(core/delivery.ts:免打扰、每天上限;问题不合并):排着的、留着的都算推了。@@ -1100,7 +1448,8 @@ export class TaskService {quotes: (row, quote) => !!row.taskId && quotes(this.store.getOutbox(askId(row))?.body.text ?? "", quote, questionsOf(row)[0]?.question ?? row.detail),answered: (row) => {const t = this.store.getTask(row.taskId);- return t ? tr("tasks.continuing", { title: t.title }) : undefined;+ // 预算用完时回了「停止」:说停了+ return t ? tr(t.endReason === "stopped" ? "tasks.stoppedTask" : "tasks.continuing", { title: t.title }) : undefined;},};}@@ -1150,19 +1499,25 @@ export class TaskService {return hits.length === 1 ? hits[0] : undefined;}- /** "需要你"里任务那一份:失败、预算用完(提问和审批由审批中心那一份给,没送到的由出站队列那一份给:core/delivery.ts) */+ /**+ * "需要你"里任务那一份:失败的;预算用完的(平常由审批中心那一份给:那个「再给 $1 继续?」的提问;这里只在它不在时补上);+ * 机器人的预算留给聊天、后台工作停着的(一个机器人一行,没有后台工作时不提)。+ * 提问和审批由审批中心那一份给,没送到的由出站队列那一份给(core/delivery.ts)。+ */attention(): AttentionItem[] {const out: AttentionItem[] = [];const since = this.now() - 7 * 86400_000;const tasks = [...this.store.listTasks({ open: true, limit: 200 }), ...this.store.listTasks({ open: false, since, limit: 100 })];+ const asking = new Set((this.o.approvals?.pendingAll() ?? []).filter((a) => a.tool === BUDGET_TOOL).map((a) => a.taskId));for (const t of tasks) {const run = this.store.latestRun(t.id);const st = this.stage(t, run);if (st.key !== "failed" && st.key !== "needs-you/budget") continue;+ if (st.key === "needs-you/budget" && asking.has(t.id)) continue;const bot = this.store.getBot(t.botId);const conv = this.store.getConversation(t.conversationId);const r = run?.report ?? t.report;- const line = st.key === "failed" ? r?.message || run?.error || tr("tasks.noResult") : r?.message || r?.summary.split("\n")[0] || "";+ const line = st.key === "failed" ? r?.message || run?.error || tr("tasks.noResult") : tr("tasks.budgetAsk", { spent: usdText(t.spentUsd), add: stepText(TASK_BUDGET_STEP_USD) });out.push({id: `task:${t.id}`,kind: "failed",@@ -1173,23 +1528,46 @@ export class TaskService {line: clip(oneLine(line), 200),since: run?.endedAt || t.updatedAt,severity: st.key === "failed" ? "err" : "warn",- actions: ["retry", "stop"],+ actions: st.key === "failed" ? ["retry", "stop"] : ["continue", "stop"],conversationId: t.conversationId,channel: conv?.channel ?? "",taskId: t.id,});}+ for (const bot of this.store.listBots()) {+ const low = this.reserve(bot.id);+ if (!low || !this.hasBackground(bot.id)) continue;+ out.push({+ id: `reserve:${bot.id}`,+ kind: "budget",+ botId: bot.id,+ botName: bot.name,+ subject: tr("tasks.reserveSubject"),+ status: "",+ line: tr("tasks.reserveLine", { remain: usdText(low.remainUsd), limit: stepText(low.limitUsd) }),+ since: this.reserveSince.get(bot.id) ?? this.now(),+ severity: "warn",+ actions: ["open"],+ });+ }return out;}+ /** 这个机器人有没有后台工作:排着、在跑的 run,或开着的规则 */+ private hasBackground(botId: string): boolean {+ return this.store.listRuns({ botId, states: ["queued", "running", "settling"], limit: 1 }).length > 0 || this.store.listRules({ botId }).some((r) => r.mode !== "off" && !r.pausedReason);+ }+// ---------- 查看 ----------private stage(task: TaskRow, run = this.store.latestRun(task.id)): Stage {// 结果没送到:留着等对方发消息、一直失败、放弃了(合进摘要的看那一条);排着等早上的、在「需要你」里不再提示的不算const delivery = run?.delivery && !run.delivery.endsWith(":dropped") ? this.o.store.carrierOutbox(run.delivery) : undefined;- // 它在等的:任务会话(或子代理)里的审批、它报的提问+ // 它在等的:任务会话(或子代理)里的审批、它报的提问(预算用完时的那个提问不算:阶段是预算用完)const now = this.now();- const rows = this.store.listApprovals({ status: "pending", botId: task.botId, limit: 200 }).filter((a) => (a.taskId === task.id || a.sessionId === task.sessionId) && (a.expiresAt === 0 || a.expiresAt > now));+ const rows = this.store+ .listApprovals({ status: "pending", botId: task.botId, limit: 200 })+ .filter((a) => (a.taskId === task.id || a.sessionId === task.sessionId) && a.tool !== BUDGET_TOOL && (a.expiresAt === 0 || a.expiresAt > now));const waiting = rows.some((a) => a.kind === "approval") ? "approval" : rows.length ? "answer" : undefined;return taskStage({ stopped: task.endReason === "stopped", undelivered: needsPerson(delivery), waiting, run });}@@ -1213,6 +1591,8 @@ export class TaskService {updatedAt: task.updatedAt,endedAt: task.endedAt,runs: this.store.listRuns({ taskId: task.id }).length,+ spentUsd: task.spentUsd,+ budgetUsd: task.budgetUsd,...(l && run ? { live: { runId: run.id, since: run.startedAt, steps: l.activity.steps.length, current: l.activity.steps.findLast((s) => s.status === "running") } } : {}),};}@@ -1386,11 +1766,21 @@ export class TaskService {* 改规则(界面、rule_update)。改原话:版本加 1;执行中的检查先观察 1 次再回到执行(决定 7)。只改时间表:模式不变。* 改模式:重新开的清掉连续失败和暂停。正在跑的那次照它开始时的版本跑完。*/- updateRule(id: string, patch: { title?: string; instruction?: string; message?: string; schedule?: Schedule; mode?: RuleMode; conversationId?: string }): { rule?: RuleRow; error?: string } {+ updateRule(+ id: string,+ patch: { title?: string; instruction?: string; message?: string; schedule?: Schedule; mode?: RuleMode; conversationId?: string; runBudgetUsd?: number; monthBudgetUsd?: number },+ ): { rule?: RuleRow; error?: string } {const rule = this.store.getRule(id);if (!rule) return { error: "rule not found" };const now = this.now();const next: Partial<RuleRow> = { updatedAt: now };+ // 预算(3e):每次、每月;本月预算调高了、因此暂停着的,下次定时器醒来时接着跑+ for (const k of ["runBudgetUsd", "monthBudgetUsd"] as const) {+ if (patch[k] === undefined) continue;+ const v = Number(patch[k]);+ if (!Number.isFinite(v) || v <= 0 || v > TASK_BUDGET_MAX_USD) return { error: tr("tasks.badBudget") };+ next[k] = Math.round(v * 100) / 100;+ }if (patch.title !== undefined) {const t = clip(oneLine(patch.title), 40);if (!t) return { error: tr("rules.nameEmpty") };@@ -1437,10 +1827,11 @@ export class TaskService {return { rule: this.store.getRule(id) };}- /** 暂停的规则重新开(「需要你」里的重试):清掉连续失败,接着按时间表跑,并马上跑一次 */+ /** 暂停的规则重新开(「需要你」里的重试):清掉连续失败,接着按时间表跑,并马上跑一次(本月预算用完暂停的要先加预算) */resumeRule(id: string): { error?: string } {const rule = this.store.getRule(id);if (!rule) return { error: "rule not found" };+ if (rule.pausedReason === "budget" && this.monthSpent(rule) >= rule.monthBudgetUsd) return { error: tr("rules.monthUsed", { spent: usdText(this.monthSpent(rule)) }) };if (rule.pausedReason || rule.failures) {const mode = rule.mode === "off" ? (rule.kind === "remind" ? "act" : "observe") : rule.mode;this.store.updateRule(id, { failures: 0, pausedReason: "", mode, nextRunAt: this.nextFor({ trigger: rule.trigger, mode, pausedReason: "" }, this.now()), updatedAt: this.now() });@@ -1455,6 +1846,8 @@ export class TaskService {if (rule.mode === "off") return { error: tr("rules.isOff") };if (this.paused(rule.botId)) return { error: tr("rules.isPaused") };if (this.ruleBusy(id)) return { error: tr("rules.isRunning") };+ if (rule.kind === "check" && this.reserve(rule.botId)) return { error: tr("rules.whyReserve") };+ if (rule.kind === "check" && this.monthSpent(rule) >= rule.monthBudgetUsd) return { error: tr("rules.monthUsed", { spent: usdText(this.monthSpent(rule)) }) };this.fireRule(rule, "manual", this.now());this.pump();return {};@@ -1486,6 +1879,7 @@ export class TaskService {*/fireDue(now = this.now()): void {if (!this.started || this.closing) return;+ this.resumeMonth(now);for (const rule of this.store.dueRules(now)) {if (this.dropped.has(rule.botId) || rule.trigger.kind !== "schedule") continue;const s = rule.trigger.schedule;@@ -1502,6 +1896,11 @@ export class TaskService {this.skipRun(rule, last, RUN_ERROR.paused);continue;}+ // 机器人的预算留给聊天:检查跳过(固定提醒不花钱,照发)+ if (rule.kind === "check" && this.reserve(rule.botId)) {+ this.skipRun(rule, last, RUN_ERROR.reserve);+ continue;+ }this.fireRule(rule, "schedule", last);}this.pump();@@ -1522,6 +1921,10 @@ export class TaskService {this.skipRun(rule, now, RUN_ERROR.paused);continue;}+ if (rule.kind === "check" && this.reserve(rule.botId)) {+ this.skipRun(rule, now, RUN_ERROR.reserve);+ continue;+ }if (this.fireRule(rule, "event", now, { source, event })) out.push(rule.id);}if (out.length) {@@ -1541,6 +1944,11 @@ export class TaskService {return undefined;}if (rule.kind === "remind") return this.remind(rule, cause, at);+ // 本月的预算已经用完(预算调低了、这个月里又改回开着):不跑,暂停到下个月+ if (this.monthSpent(rule) >= rule.monthBudgetUsd) {+ this.pauseForMonth(rule);+ return undefined;+ }const mode = runMode(rule);const id = `r_${hex(6)}`;const run = this.store.insertRun({ id, botId: rule.botId, taskId: "", ruleId: rule.id, ruleVersion: rule.version, mode, sessionId: `rule-${rule.id}-${id.slice(2)}`, cause, queuedAt: at });@@ -1646,6 +2054,8 @@ export class TaskService {seen: new Set(),tokensIn: 0,tokensOut: 0,+ costUsd: 0,+ priceModel: model,would: [],};this.live.set(run.id, l);@@ -1698,7 +2108,7 @@ export class TaskService {this.forget(l);const now = this.now();const would = [report?.would ?? "", ...(l.would ?? []).map((d) => `${WOULD_APPROVAL}${d}`)].filter(Boolean).join("\n");- this.store.updateRun(l.runId, { state: "ended", outcome, report, would, error, endedAt: now, activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut });+ this.store.updateRun(l.runId, { state: "ended", outcome, report, would, error, endedAt: now, activity: JSON.stringify(l.activity.steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut, costUsd: l.costUsd });for (const a of this.o.approvals?.pendingAll().filter((x) => x.ruleId && x.runId === l.runId) ?? []) this.o.approvals!.cancel(a.id, "run ended");const rule = this.store.getRule(l.ruleId);if (rule) this.afterRuleRun(rule, l.runId, l.mode, outcome, report, error);@@ -1710,7 +2120,8 @@ export class TaskService {/*** 一次运行之后:成功清零连续失败,改了原话后先观察的那一次跑完了就回到执行;有要说的那一句(观察时是「本会发送」)用主模型写,- * 执行时发出去。失败加 1,连续 3 次自动暂停:执行中的规则推一句 ⚠️,观察中的只在「需要你」里。+ * 执行时发出去。失败加 1(超出单次预算也算),连续 3 次自动暂停:执行中的规则推一句 ⚠️,观察中的只在「需要你」里。+ * 最后看本月的预算:用完了就暂停到下个月。*/private afterRuleRun(rule: RuleRow, runId: string, mode: "observe" | "act", outcome: RunOutcome, report: TaskReport | undefined, error: string): void {const run = this.store.getRun(runId);@@ -1719,18 +2130,67 @@ export class TaskService {if (mode === "observe" && rule.mode === "act" && rule.observeLeft > 0 && run?.ruleVersion === rule.version) patch.observeLeft = rule.observeLeft - 1;this.store.updateRule(rule.id, patch);if (report?.message) void this.ruleResult(rule, runId, mode, report);- return;+ } else if (outcome === "failed" || (outcome === "budget" && error === RUN_ERROR.runBudget)) {+ const failures = rule.failures + 1;+ if (failures < RULE_FAILS_TO_PAUSE) this.store.updateRule(rule.id, { failures });+ else {+ this.store.updateRule(rule.id, { failures, pausedReason: "failures", nextRunAt: 0 });+ log.warn("rule paused after failing in a row", { rule: rule.id, failures });+ if (rule.mode === "act") {+ // 后台推送:应用的语言+ const why = clip(oneLine(report?.message || errorText(error || RUN_ERROR.noReport)), 200);+ this.deliverRule(rule, runId, "failure", tr("rules.pausedPush", { title: rule.title, count: failures, why }));+ }+ return;+ }}- if (outcome !== "failed") return;- const failures = rule.failures + 1;- if (failures < RULE_FAILS_TO_PAUSE) return void this.store.updateRule(rule.id, { failures });- this.store.updateRule(rule.id, { failures, pausedReason: "failures", nextRunAt: 0 });- log.warn("rule paused after failing in a row", { rule: rule.id, failures });+ const fresh = this.store.getRule(rule.id);+ if (fresh && fresh.kind === "check" && this.monthSpent(fresh) >= fresh.monthBudgetUsd) this.pauseForMonth(fresh);+ }++ /**+ * 本月的预算用完:暂停到下个月 1 号(主人的时区,定时器到时自动恢复),「需要你」里一行(可以再给 $3 接着跑);+ * 执行中的规则还推一句(用户在等它的结果,不能悄悄停下),一个月只推一次。+ */+ private pauseForMonth(rule: RuleRow): void {+ if (rule.pausedReason) return;+ const now = this.now();+ this.store.updateRule(rule.id, { pausedReason: "budget", nextRunAt: 0, updatedAt: now });+ const spent = this.monthSpent(rule, now);+ log.warn("rule paused: its monthly budget is used up", { rule: rule.id, spentUsd: Math.round(spent * 10_000) / 10_000, budgetUsd: rule.monthBudgetUsd });if (rule.mode === "act") {- // 后台推送:应用的语言- const why = clip(oneLine(report?.message || errorText(error || RUN_ERROR.noReport)), 200);- this.deliverRule(rule, runId, "failure", tr("rules.pausedPush", { title: rule.title, count: failures, why }));+ const p = localParts(now, this.timeZone);+ // 一个月、一个预算额只推一次(加了预算又用完会再推)+ this.pushRule(rule, `rule:${rule.id}:budget:${p.y}-${pad2(p.mo)}:${rule.monthBudgetUsd}`, "failure", tr("rules.monthPush", { title: rule.title, spent: usdText(spent) }));}+ this.ruleChanged(rule.id);+ }++ /** 新的一个月(或加了预算):因为本月预算暂停的规则,花费回到预算以内的就接着按时间表跑 */+ private resumeMonth(now: number): void {+ for (const rule of this.store.listRules()) {+ if (rule.pausedReason !== "budget" || this.monthSpent(rule, now) >= rule.monthBudgetUsd) continue;+ this.store.updateRule(rule.id, { pausedReason: "", nextRunAt: this.nextFor({ ...rule, pausedReason: "" }, now), updatedAt: now });+ log.info("rule resumed: its monthly budget has room again", { rule: rule.id });+ this.changed(rule.id);+ }+ }++ /** 给规则每月的预算加钱(「需要你」里的继续、接口):本月预算用完暂停着的接着按时间表跑 */+ addRuleBudget(id: string, addUsd = RULE_MONTH_BUDGET_USD): { rule?: RuleView; error?: string } {+ const rule = this.store.getRule(id);+ if (!rule) return { error: "rule not found" };+ const add = Number(addUsd);+ if (!Number.isFinite(add) || add <= 0 || add > 100) return { error: tr("tasks.badBudget") };+ const now = this.now();+ const spent = this.monthSpent(rule, now);+ const raised = rule.monthBudgetUsd + add;+ const budget = Math.round(Math.min(TASK_BUDGET_MAX_USD, raised > spent ? raised : spent + add) * 100) / 100;+ this.store.updateRule(id, { monthBudgetUsd: budget, updatedAt: now });+ log.info("rule monthly budget raised", { rule: id, budgetUsd: budget });+ this.resumeMonth(now);+ this.ruleChanged(id);+ return { rule: this.getRuleView(id) };}/** 那一句用主模型写(检查用的小模型只给草稿);执行时发出去。主模型不可用就用草稿 */@@ -1760,8 +2220,14 @@ export class TaskService {const run = this.store.getRun(runId);if (!run || run.delivery) return;const id = purpose === "failure" ? `rule:${rule.id}:paused:${runId}` : `rule:${rule.id}:${runId}`;+ this.store.updateRun(runId, { delivery: this.pushRule(rule, id, purpose, text) ? id : `${id}:dropped` });+ }++ /** 经出站队列送出规则的一句(id 固定,同一 id 只发一次),写进会话历史、给聊天代理留便条;会话没了返回 false */+ private pushRule(rule: RuleRow, id: string, purpose: "rule" | "reminder" | "failure", text: string): boolean {const conv = this.store.getConversation(rule.conversationId);- if (!conv) return void this.store.updateRun(runId, { delivery: `${id}:dropped` });+ if (!conv) return false;+ if (this.store.getOutbox(id)) return true;if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.delivery) {this.o.delivery.push({id,@@ -1777,9 +2243,9 @@ export class TaskService {});}this.store.addMessage(conv.id, "assistant", text);- this.store.updateRun(runId, { delivery: id });this.note(conv.id, purpose === "failure" ? `[规则「${rule.title}」暂停了,已告诉用户] ${text}` : `[规则「${rule.title}」发给了用户] ${text}`);- log.info("rule message handed over", { rule: rule.id, run: runId, purpose, channel: conv.channel });+ log.info("rule message handed over", { rule: rule.id, id, purpose, channel: conv.channel });+ return true;}/** 启动:结束了、要发却还没交出去的(交之前应用退出了)补交;只看两天之内的 */@@ -1926,6 +2392,10 @@ export class TaskService {hint: rule.kind === "check" && rule.mode === "observe" && !rule.pausedReason && observed >= RULE_HINT_AFTER,observed,failures: rule.failures,+ pausedReason: rule.pausedReason,+ monthUsd: rule.kind === "check" ? this.monthSpent(rule) : 0,+ monthBudgetUsd: rule.monthBudgetUsd,+ runBudgetUsd: rule.runBudgetUsd,folder: rule.folder,version: rule.version,createdAt: rule.createdAt,@@ -1962,22 +2432,42 @@ export class TaskService {version: r.ruleVersion,permission: permissionText(r.permission),steps: r.startedAt && r.outcome !== "skipped" ? this.activity(r.id).length : 0,+ costUsd: r.costUsd,startedAt: r.startedAt,endedAt: r.endedAt,}));}/**- * 「需要你」里规则那一份:连续失败 3 次暂停了的(红),连续失败 2 次的(黄)。原因没了(重试成功、关掉、删掉)就消失。- * 规则执行时的审批由审批中心那一份给。+ * 「需要你」里规则那一份:连续失败 3 次暂停了的(红),连续失败 2 次的(黄),本月预算用完暂停了的(黄,可以再给 $3 接着跑)。+ * 原因没了(重试成功、关掉、删掉、下个月了)就消失。规则执行时的审批由审批中心那一份给。*/ruleAttention(): AttentionItem[] {const out: AttentionItem[] = [];for (const rule of this.store.listRules()) {const paused = !!rule.pausedReason;if (!paused && (rule.mode === "off" || rule.failures < RULE_FAILS_TO_SHOW)) continue;- const last = this.store.ruleRuns(rule.id, { limit: 1, outcome: "failed" })[0];const conv = this.store.getConversation(rule.conversationId);+ if (rule.pausedReason === "budget") {+ out.push({+ id: `rule:${rule.id}`,+ kind: "rule",+ botId: rule.botId,+ botName: this.store.getBot(rule.botId)?.name ?? rule.botId,+ subject: tr("rules.subject", { title: rule.title }),+ status: tr("rules.monthPaused"),+ line: tr("rules.monthLine", { spent: usdText(this.monthSpent(rule)), add: stepText(RULE_MONTH_BUDGET_USD) }),+ since: rule.updatedAt,+ severity: "warn",+ actions: ["continue"],+ conversationId: rule.conversationId,+ channel: conv?.channel ?? "",+ ruleId: rule.id,+ });+ continue;+ }+ // 最近一次失败(超出单次预算也算)+ const last = this.store.ruleRuns(rule.id, { limit: 10 }).find((r) => r.outcome === "failed" || (r.outcome === "budget" && r.error === RUN_ERROR.runBudget));out.push({id: `rule:${rule.id}`,kind: "rule",@@ -1985,7 +2475,7 @@ export class TaskService {botName: this.store.getBot(rule.botId)?.name ?? rule.botId,subject: tr("rules.subject", { title: rule.title }),status: tr(paused ? "rules.failingPaused" : "rules.failing", { count: rule.failures }),- line: last ? clip(oneLine(last.report?.message || errorText(last.error || RUN_ERROR.noReport)), 200) : "",+ line: last ? clip(oneLine((last.outcome === "failed" && last.report?.message) || errorText(last.error || RUN_ERROR.noReport)), 200) : "",since: last?.endedAt || rule.updatedAt,severity: paused ? "err" : "warn",actions: ["retry"],diff --git a/src/web/server.ts b/src/web/server.tsindex 735367f..f23fd86 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -470,6 +470,9 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str: app.agent.approvals.answerText(item.approvalId!, String(b.text ?? ""), "web");} else if (item.kind === "delivery" && (action === "retry" || action === "dismiss")) ok = app.delivery.act(item.id, action);else if (item.kind === "rule" && action === "retry") ok = !app.tasks.resumeRule(item.ruleId!).error;+ // 加预算接着做:规则每月再给 $3,任务再给 $1+ else if (item.kind === "rule" && action === "continue") ok = !app.tasks.addRuleBudget(item.ruleId!).error;+ else if (action === "continue") ok = !(await app.tasks.addBudget(item.taskId!, undefined, "web")).error;else if (action === "retry") ok = !(await app.tasks.retry(item.taskId!)).error;else if (action === "stop") ok = await app.tasks.stopTask(item.taskId!, "web");if (!ok) throw new HttpError(409, tr("web.couldntComplete"));@@ -492,9 +495,18 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst task = seg[1] ? app.tasks.get(decodeURIComponent(seg[1])) : undefined;if (!task) throw new HttpError(404, tr("web.taskNotFound"));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 }));+ 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, costUsd: r.costUsd, queuedAt: r.queuedAt, startedAt: r.startedAt, endedAt: r.endedAt, steps: app.tasks.activity(r.id).length }));return send(res, 200, { task, runs });}+ // 加预算(3e):{addUsd},默认 $1;停在预算上的任务接着做+ if (seg.length === 3 && seg[2] === "budget" && m === "POST") {+ const b = await readJson(req);+ const r = await app.tasks.addBudget(task.id, b.addUsd === undefined ? undefined : Number(b.addUsd), "web");+ if (r.error) throw new HttpError(400, r.error);+ return send(res, 200, { task: r.task });+ }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, tr("web.runNotFound"));@@ -541,6 +553,8 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (b.instruction !== undefined) patch.instruction = String(b.instruction);if (b.message !== undefined) patch.message = String(b.message);if (b.conversationId !== undefined) patch.conversationId = String(b.conversationId);+ if (b.runBudgetUsd !== undefined) patch.runBudgetUsd = Number(b.runBudgetUsd);+ if (b.monthBudgetUsd !== undefined) patch.monthBudgetUsd = Number(b.monthBudgetUsd);if (b.mode !== undefined) {if (!["off", "observe", "act"].includes(b.mode)) throw new HttpError(400, t("rules.badMode"));patch.mode = b.mode as RuleMode;diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.tsindex e8a72bc..6523d5e 100644--- a/test/agent.integration.test.ts+++ b/test/agent.integration.test.ts@@ -439,7 +439,8 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho/*** 系统提示词加工具定义的字符数上限(DSH 自己的部分 + 我们的人设、机器人段和工具;基线 34,052 = 提示词 3,692 + 工具 30,360,其中后台任务的 task_start、task_message、task_list 约 1,460;* 3b、3c 之后 34,289;3d 加上规则的 rule_create、rule_update 后 35,649 = 提示词 3,692 + 工具 31,957(多了 1,360);上限高约 5%;- * 暂停开关 background_pause 之后 35,960 = 提示词 3,692 + 工具 32,268(多了 311),还在上限之内)。+ * 暂停开关 background_pause 之后 35,960 = 提示词 3,692 + 工具 32,268(多了 311),还在上限之内;+ * 3e 给 task_start 加上 budget_usd 之后 36,076 = 提示词 3,692 + 工具 32,384(多了 116),还在上限之内)。* 缩短了就调低;要调高,在提交说明里写清原因。电脑操作的 MCP 工具随平台变化,不计入。*/const SURFACE_BUDGET = 37_400;diff --git a/test/cost.unit.test.ts b/test/cost.unit.test.tsnew file mode 100644index 0000000..2d55ad8--- /dev/null+++ b/test/cost.unit.test.ts@@ -0,0 +1,511 @@+/**+ * 花费与预算(3e):估算(参考价 × 用量、缓存价、阶梯计费取基础档、会话和子代理的每次模型请求)、+ * 任务的预算(停在 $1:取消这一轮但不封会话,问「已用约 $1.00,再给 $1 继续?」;回编号、接口加预算、聊天里追加都能接着做,+ * 回「停止」停掉;预算用完后再来的输入先问、不交给会话;重启后补问)、规则每次 $0.10(这次以 budget 结束、算一次失败)、+ * 每月 $3(停下并暂停,下个月 1 号按主人的时区恢复,「再给 $3」接着跑)、机器人的预算 Key 剩不到 20% 时停后台工作留给聊天、+ * 任务每次运行 4 小时(等人批准的时间不算)。TaskService 对着假宿主和假时钟。+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { BUDGET_TOOL, costOf, usdText, type Rates } from "../src/tasks/cost.js";+import { estimateRates, referencePrice } from "../src/account/model-info.js";+import { TaskService, askId, type TaskHost, type TaskNotification } from "../src/tasks/service.js";+import { approvalItems } from "../src/tasks/attention.js";+import { ApprovalCenter } from "../src/agent/approvals.js";+import { DEFAULT_SETTINGS } from "../src/agent/settings.js";+import { Outbox } from "../src/core/outbox.js";+import { Delivery } from "../src/core/delivery.js";+import { Store } from "../src/store/db.js";++const TZ = "Asia/Shanghai";+/** 上海时间 "2026-11-06T08:00" → 时间戳 */+const at = (s: string) => Date.parse(`${s}${s.length === 16 ? ":00" : ""}+08:00`);+const MIN = 60_000;+const H = 3600_000;+const flush = async (n = 6) => {+ for (let i = 0; i < n; i++) await new Promise((r) => setImmediate(r));+};++describe("估算:参考价 × 用量", () => {+ it("一次模型请求:输入、输出、缓存命中、写入各按各的价;没有缓存价按输入价(宁可多估);没有价格就是 0", () => {+ const r: Rates = { input: 10, output: 40, cacheRead: 1, cacheWrite: 12.5 };+ expect(costOf({ inputTokens: 1000, outputTokens: 500, cacheReadTokens: 10_000, cacheWriteTokens: 2000 }, r)).toBeCloseTo(0.01 + 0.02 + 0.01 + 0.025, 10);+ expect(costOf({ cacheReadTokens: 1_000_000 }, { input: 2, output: 8 })).toBe(2);+ expect(costOf({ inputTokens: 1000 }, undefined)).toBe(0);+ expect(costOf({ inputTokens: -5, outputTokens: Number.NaN }, r)).toBe(0);+ expect([usdText(1), usdText(0.084), usdText(0.004), usdText(0)]).toEqual(["$1.00", "$0.08", "<$0.01", "$0.00"]);+ });++ it("单价:可用分组里最低的倍率、缓存倍率;阶梯计费取基础那一档;按次计费、没有可用分组的不给;模型选择器的参考价照旧不给阶梯计费的", () => {+ const catalog = { group_ratio: { default: 1, vip: 0.5, hidden: 0.1 }, usable_group: { default: "", vip: "" } };+ expect(estimateRates({ model_name: "m", quota_type: 0, input_price: 2, completion_ratio: 4, cache_ratio: 0.1, create_cache_ratio: 1.25, enable_groups: ["default", "vip", "hidden"] }, catalog)).toEqual({ input: 1, output: 4, cacheRead: 0.1, cacheWrite: 1.25 });+ const tiered = {+ model_name: "t",+ quota_type: 0,+ input_price: 5,+ billing_mode: "tiered_expr",+ pricing_rules: { tiers: [{ label: "base", conditions: null, unit_prices: { input: 5, output: 30, cache_read: 0.5 } }, { label: "long", conditions: [{ var: "len" }], unit_prices: { input: 10, output: 45 } }] },+ enable_groups: ["default"],+ };+ expect(estimateRates(tiered, catalog)).toEqual({ input: 5, output: 30, cacheRead: 0.5 });+ expect(referencePrice(tiered, catalog)).toBeUndefined();+ expect(estimateRates({ model_name: "v", quota_type: 1, model_price: 0.5, enable_groups: ["default"] }, catalog)).toBeUndefined();+ expect(estimateRates({ model_name: "h", quota_type: 0, input_price: 1, enable_groups: ["hidden"] }, catalog)).toBeUndefined();+ });+});++/** 假的宿主:记下交给会话的输入、取消(会话还能接着用)和停止(之后的工具调用一律拒绝) */+class FakeHost implements TaskHost {+ available = true;+ prompts: Array<{ botId: string; sessionId: string; folder: string; model: string; text: string; resume: boolean; id: string }> = [];+ stops: string[] = [];+ cancels: string[] = [];+ settingsValue = { ...DEFAULT_SETTINGS, utilityModel: "small-model" };+ 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 }) {+ const id = `msg-${++this.n}`;+ this.prompts.push({ botId, ...o, id });+ return id;+ }+ async steer() {+ return false;+ }+ async stop(_botId: string, sessionId: string) {+ this.stops.push(sessionId);+ }+ async cancel(_botId: string, sessionId: string) {+ this.cancels.push(sessionId);+ }+ async quiet() {+ return { quiet: true };+ }+}++describe("预算(假宿主、假时钟)", () => {+ let store: Store;+ let host: FakeHost;+ let outbox: Outbox;+ let delivery: Delivery;+ let approvals: ApprovalCenter;+ let svc: TaskService;+ let ws: string;+ let now: number;+ /** 机器人的 Modelflare 预算 Key(没开就是 undefined) */+ let budget: { limitUsd: number; remainUsd: number; at: number } | undefined;+ const CONV = "b:weixin:owner";+ /** 美元 / 百万 tokens:主模型输入 $10(10 万 tokens = $1),子代理用的模型更贵 */+ const RATES: Record<string, Rates> = { "main-model": { input: 10, output: 40, cacheRead: 1 }, "small-model": { input: 10, output: 40 }, "sub-model": { input: 100, output: 100 } };++ const make = (o: { cap?: number } = {}) =>+ new TaskService({+ store,+ host,+ delivery,+ approvals,+ defaultModel: () => "main-model",+ retryDelaysMs: [5, 5, 5],+ maxBackground: 4,+ now: () => now,+ timeZone: TZ,+ taskRunCapMs: o.cap,+ rates: (m) => RATES[m],+ botBudget: () => budget,+ });+ beforeEach(() => {+ now = at("2026-11-02T10:00");+ budget = undefined;+ ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-cost-unit-"));+ store = new Store(":memory:");+ store.createBot({ id: "b", name: "小蓝", weixinEnabled: true });+ store.ensureConversation("b", "weixin", "owner", "owner");+ store.addMessage(CONV, "user", "帮我后台做个季度报告 PPT");+ store.setAgentSession(CONV, "b", "chat-1");+ host = new FakeHost(ws);+ outbox = new Outbox(store, { now: () => now });+ delivery = new Delivery({ store, outbox, now: () => now, timeZone: TZ });+ approvals = new ApprovalCenter(store, { now: () => now });+ svc = make();+ svc.start();+ });+ afterEach(() => {+ svc.stop();+ store.close();+ fs.rmSync(ws, { recursive: true, force: true });+ });++ let step = 0;+ /** 会话(或它的子代理:root 是任务会话)的一次模型请求带着用量 */+ const used = (sessionId: string, usage: Record<string, number>, model = "", root = sessionId) =>+ svc.onEvent("b", root, { method: "session.event", params: { sessionId, event: { type: "assistant/message", data: { turn: 1, step: ++step, message: { role: "assistant", content: [{ type: "text", text: "…" }], ...(model ? { source: { model } } : {}) }, usage }, time: now } } });+ /** 花 usd 美元的一次请求(按主模型、小模型的输入价:10 万 tokens = $1) */+ const spend = (sessionId: string, usd: number) => used(sessionId, { inputTokens: Math.round(usd * 100_000), outputTokens: 0 });+ const ev = (sessionId: string, type: string, data: any = {}): TaskNotification => ({ method: "session.event", params: { sessionId, event: { type, data, time: now } } });+ const status = (sessionId: string, s: "running" | "idle"): TaskNotification => ({ method: "session.status", params: { sessionId, status: s } });+ /** 最近一次交给这个会话(不给就是最近的那个会话)的输入跑一轮;during 在这一轮中间花钱、报告 */+ const turn = async (sessionId: string | undefined, during?: (sid: string) => void) => {+ const p = (sessionId ? host.prompts.filter((x) => x.sessionId === sessionId) : host.prompts).at(-1)!;+ const sid = p.sessionId;+ svc.onEvent("b", sid, status(sid, "running"));+ svc.onEvent("b", sid, ev(sid, "turn/start", { turn: 1 }));+ svc.onEvent("b", sid, ev(sid, "user/message", { id: p.id, role: "user", content: [{ type: "text", text: p.text }] }));+ during?.(sid);+ svc.onEvent("b", sid, ev(sid, "turn/end", { turn: 1, reason: { kind: "completed" } }));+ svc.onEvent("b", sid, status(sid, "idle"));+ await flush();+ };+ const start = (title = "季度报告 PPT") => {+ const r = svc.create({ botId: "b", conversationId: CONV, title, brief: "做 10 页" });+ expect(r.error).toBeUndefined();+ return r.task!;+ };+ const report = (sessionId: string, state: string, message = "") => expect(svc.report({ sessionId, state, summary: "做好了", message }).error).toBeUndefined();+ const runs = (taskId: string) => store.listRuns({ taskId }).map((r) => [r.cause, r.state, r.outcome]);+ const asks = () => store.listOutbox({ limit: 100 }).filter((r) => r.id.includes(":ask:")).reverse();+ const reply = (text: string) => approvals.handleReply(CONV, text, "weixin:owner", svc.replyContext(CONV));+ /** 规则:拨钟,到点的开 run */+ const go = async (t: number) => {+ now = t;+ svc.fireDue(now);+ await flush();+ };+ const createRule = async () => {+ const r = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "看 X 价格", instruction: "每天早上看看 X 的价格,低于 200 告诉我", schedule: "daily 08:00" } });+ expect(r.error).toBeUndefined();+ return store.listRules({ botId: "b" }).at(-1)!;+ };+ const ruleRuns = (ruleId: string) => store.ruleRuns(ruleId, { limit: 100 }).reverse();++ it("估算:会话和子代理的每次模型请求按回答它的模型的价算(没说是哪个模型就按任务的),记在 run 上、加到任务上;没有价格的不算", async () => {+ const t = start();+ await flush();+ await turn(t.sessionId, (sid) => {+ // 主模型:输入 $0.01 + 输出 $0.02 + 缓存命中 $0.01+ used(sid, { inputTokens: 1000, outputTokens: 500, cacheReadTokens: 10_000 }, "main-model");+ // 子代理用的另一个模型:$0.02+ used("sub-1", { inputTokens: 100, outputTokens: 100 }, "sub-model", sid);+ // 事件里的模型没有价格:按任务的模型算 $0.01+ used(sid, { inputTokens: 1000 }, "unknown-model");+ report(sid, "done", "做好了");+ });+ const run = store.listRuns({ taskId: t.id })[0];+ expect(run.costUsd).toBeCloseTo(0.07, 10);+ expect(run.tokensIn).toBe(1000 + 10_000 + 100 + 1000);+ expect(run.tokensOut).toBe(600);+ expect(store.getTask(t.id)!.spentUsd).toBeCloseTo(0.07, 10);+ expect(svc.get(t.id)).toMatchObject({ budgetUsd: 1, stage: { key: "ready" } });+ expect(svc.get(t.id)!.spentUsd).toBeCloseTo(0.07, 10);+ // 没有价格(外部端点、目录里没有):不估算,预算也就不起作用+ svc.stop();+ svc = new TaskService({ store, host, delivery, approvals, defaultModel: () => "no-price", now: () => now, timeZone: TZ, rates: (m) => RATES[m] });+ svc.start();+ const u = start("没有价格");+ await flush();+ await turn(u.sessionId, (sid) => {+ used(sid, { inputTokens: 5_000_000 });+ report(sid, "done", "好了");+ });+ expect(store.getTask(u.id)!.spentUsd).toBe(0);+ expect(store.listRuns({ taskId: u.id })[0]).toMatchObject({ outcome: "done", costUsd: 0, tokensIn: 5_000_000 });+ });++ it("退出演示的单元版:任务停在 $1(取消这一轮,会话不封),问「已用约 $1.00,再给 $1 继续?」;回 1 加预算,在同一个会话里接着做完", async () => {+ const t = start();+ await flush();+ await turn(t.sessionId, (sid) => {+ for (let i = 0; i < 3; i++) spend(sid, 0.25);+ expect(host.cancels).toEqual([]);+ spend(sid, 0.25);+ });+ expect(host.cancels).toEqual([t.sessionId]);+ expect(host.stops).toEqual([]);+ expect(runs(t.id)).toEqual([["launch", "ended", "budget"]]);+ expect(store.listRuns({ taskId: t.id })[0].costUsd).toBeCloseTo(1, 10);+ // 取消到达之前已经发出去的那次请求:花费照样记上+ spend(t.sessionId, 0.05);+ const run = store.listRuns({ taskId: t.id })[0];+ expect(run.costUsd).toBeCloseTo(1.05, 10);+ expect(store.getTask(t.id)!.spentUsd).toBeCloseTo(1.05, 10);+ expect(svc.activity(run.id).at(-1)).toMatchObject({ kind: "error", summary: "预算用完" });+ expect(svc.get(t.id)).toMatchObject({ stage: { key: "needs-you/budget", label: "预算用完", group: "needs" }, budgetUsd: 1 });+ // 问用户:一个不阻塞、不过期的提问,推到微信(一次),和任务的提问一个样子+ const [q] = approvals.pendingForTask(t.id);+ expect(q).toMatchObject({ kind: "question", tool: BUDGET_TOOL, blocking: false, expiresAt: 0, runId: run.id, detail: "已用约 $1.00,再给 $1 继续?" });+ expect(asks().map((r) => [r.id, r.body.text])).toEqual([[askId(q), "❓「季度报告 PPT」想问你:已用约 $1.00,再给 $1 继续?\n1. 继续\n2. 停止\n(回复编号,或引用这条消息回答)"]]);+ // 「需要你」:一行(审批中心那一份,状态是预算用完);任务那一份不重复+ expect(approvalItems(store, approvals.pendingAll())).toMatchObject([{ kind: "question", subject: "季度报告 PPT", status: "预算用完", line: "已用约 $1.00,再给 $1 继续?", taskId: t.id, actions: ["answer"] }]);+ expect(svc.attention()).toEqual([]);+ expect(svc.listText(CONV)).toContain("季度报告 PPT · 预算用完");+ // 回 1:预算加 $1,同一个会话接着做(continue run,第一条是说明)+ expect(reply("1")).toEqual({ handled: true, ack: "收到,「季度报告 PPT」继续。" });+ await flush();+ expect(store.getTask(t.id)!.budgetUsd).toBe(2);+ expect(runs(t.id)).toEqual([+ ["launch", "ended", "budget"],+ ["continue", "running", ""],+ ]);+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: t.sessionId, resume: true });+ expect(host.prompts.at(-1)!.text).toMatch(/^This task was stopped when it used its budget, and the user has now added more\. .*task_report\.$/);+ await turn(t.sessionId, (sid) => {+ spend(sid, 0.2);+ report(sid, "done", "季度报告做好了,在 report.pptx。");+ });+ expect(runs(t.id).at(-1)).toEqual(["continue", "ended", "done"]);+ expect(svc.get(t.id)!.stage.key).toBe("ready");+ expect(store.getTask(t.id)!.spentUsd).toBeCloseTo(1.25, 10);+ expect(store.listOutbox({ limit: 50 }).find((r) => r.id.includes(":result:"))!.body.text).toBe("季度报告做好了,在 report.pptx。");+ expect(approvals.pendingAll()).toEqual([]);+ });++ it("继续的其他办法:接口加预算(问的那个作废);回「停止」就停掉;聊天里转来的话连同加预算一起交给任务;写了金额就加那么多", async () => {+ const a = start("A");+ await flush();+ await turn(a.sessionId, (sid) => spend(sid, 1.05));+ const qa = approvals.pendingForTask(a.id)[0];+ expect(qa.detail).toBe("已用约 $1.05,再给 $1 继续?");+ // 接口(POST /tasks/:id/budget):加 $2+ const r = await svc.addBudget(a.id, 2, "web");+ expect(r.task).toMatchObject({ budgetUsd: 3, stage: { key: "working" } });+ expect(store.getApproval(qa.id)).toMatchObject({ status: "cancelled", decidedBy: "web" });+ expect(runs(a.id).at(-1)).toEqual(["continue", "running", ""]);+ expect(asks().find((x) => x.id === askId(qa))!.status).toBe("gone");+ expect((await svc.addBudget(a.id, 0)).error).toBe("金额不对");+ await turn(a.sessionId, (sid) => report(sid, "done", "A 好了"));++ // 回「停止」:停掉任务,回一句停了+ const b = start("B");+ await flush();+ await turn(b.sessionId, (sid) => spend(sid, 1));+ expect(asks().at(-1)!.body.text).toContain("「B」想问你:已用约 $1.00");+ expect(reply("停止")).toEqual({ handled: true, ack: "已停止后台任务「B」。" });+ await flush();+ expect(store.getTask(b.id)!.endReason).toBe("stopped");++ // 聊天代理转来的话(task_message):是对这个提问的回答,加 $1,话一起交给任务+ const c = start("C");+ await flush();+ await turn(c.sessionId, (sid) => spend(sid, 1));+ expect((await svc.message(c.id, "继续,但改成英文")).how).toBe("answered");+ await flush();+ expect(store.getTask(c.id)!.budgetUsd).toBe(2);+ expect(host.prompts.at(-1)!.text).toMatch(/^This task was stopped when it used its budget[\s\S]*\n\n\[用户追加\]\n继续,但改成英文$/);+ await turn(c.sessionId, (sid) => report(sid, "done", "C 好了"));++ // 写了金额:加那么多+ const d = start("D");+ await flush();+ await turn(d.sessionId, (sid) => spend(sid, 1));+ approvals.answerText(approvals.pendingForTask(d.id)[0].id, "再给 3 美元", "weixin:owner");+ await flush();+ expect(store.getTask(d.id)!.budgetUsd).toBe(4);+ expect(host.prompts.at(-1)!.text).not.toContain("[用户追加]");+ });++ it("预算用完以后又来的输入(重试、追加)不交给会话,先问;问的那个没了(重启前没问出去)就在启动时补问,「需要你」里任务那一份先顶上", async () => {+ const t = start();+ await flush();+ await turn(t.sessionId, (sid) => spend(sid, 1));+ const q = approvals.pendingForTask(t.id)[0];+ approvals.cancel(q.id, "test");+ // 问的那个不在了:任务那一份(继续 / 停止)+ expect(svc.attention()).toMatchObject([{ id: `task:${t.id}`, kind: "failed", status: "预算用完", line: "已用约 $1.00,再给 $1 继续?", actions: ["continue", "stop"], severity: "warn" }]);+ // 重启:补问一次+ svc.stop();+ svc = make();+ svc.start();+ expect(approvals.pendingForTask(t.id).map((r) => [r.tool, r.status])).toEqual([[BUDGET_TOOL, "pending"]]);+ expect(svc.attention()).toEqual([]);+ // 重试:不交给会话(还没加预算),这次 run 直接以 budget 结束;不再问第二遍+ const prompts = host.prompts.length;+ expect((await svc.retry(t.id)).how).toBe("resumed");+ await flush();+ expect(host.prompts).toHaveLength(prompts);+ expect(runs(t.id).at(-1)).toEqual(["retry", "ended", "budget"]);+ expect(approvals.pendingForTask(t.id)).toHaveLength(1);+ // 加了预算:那条重试的话也交过去+ await svc.addBudget(t.id);+ await flush();+ expect(host.prompts.at(-1)!.text).toContain("[用户让你再试一次]");+ expect(host.prompts.at(-1)!.text).toContain("This task was stopped when it used its budget");+ });++ it("规则每次 $0.10:超了就停下(这次以 budget 结束,算一次失败,运行记录写原因和花费);连续 3 次暂停", async () => {+ const rule = await createRule();+ for (const [i, day] of ["2026-11-03", "2026-11-04", "2026-11-05"].entries()) {+ await go(at(`${day}T08:00`));+ const sid = host.prompts.at(-1)!.sessionId;+ expect(host.prompts.at(-1)!.model).toBe("small-model");+ await turn(sid, () => {+ spend(sid, 0.06);+ expect(host.stops).not.toContain(sid);+ spend(sid, 0.06);+ });+ expect(host.stops).toContain(sid);+ expect(store.getRule(rule.id)!.failures).toBe(i + 1);+ }+ expect(svc.ruleLog(rule.id)[0]).toMatchObject({ outcome: "budget", line: "停下:超出单次预算", error: "超出单次预算" });+ expect(svc.ruleLog(rule.id)[0].costUsd).toBeCloseTo(0.12, 10);+ expect(store.getRule(rule.id)).toMatchObject({ pausedReason: "failures", nextRunAt: 0 });+ expect(svc.ruleAttention()).toMatchObject([{ status: "连续失败 3 次,已暂停", line: "超出单次预算", actions: ["retry"] }]);+ // 本月的花费:三次一共+ expect(svc.getRuleView(rule.id)!.monthUsd).toBeCloseTo(0.36, 10);+ });++ it("规则每月 $3:用完就停下并暂停(执行中的推一句,「需要你」里一行),下个月 1 号 0 点(主人的时区)自动恢复", async () => {+ const rule = await createRule();+ svc.updateRule(rule.id, { mode: "act", runBudgetUsd: 2 });+ const day = async (d: string, usd: number[]) => {+ await go(at(`${d}T08:00`));+ await turn(undefined, (sid) => {+ for (const x of usd) spend(sid, x);+ report(sid, "done");+ });+ };+ await day("2026-11-03", [1.5]);+ await day("2026-11-04", [1.0]);+ expect(store.getRule(rule.id)!.pausedReason).toBe("");+ // 第三天花到 $3.10:这一次停下(还没报告),规则暂停+ await go(at("2026-11-05T08:00"));+ const sid = host.prompts.at(-1)!.sessionId;+ spend(sid, 0.3);+ expect(host.stops).not.toContain(sid);+ spend(sid, 0.3);+ await flush();+ expect(host.stops).toContain(sid);+ expect(ruleRuns(rule.id).at(-1)).toMatchObject({ outcome: "budget", error: "month_budget" });+ expect(svc.ruleLog(rule.id)[0].line).toBe("停下:本月预算用完");+ expect(store.getRule(rule.id)).toMatchObject({ pausedReason: "budget", nextRunAt: 0, failures: 0 });+ const v = svc.getRuleView(rule.id)!;+ expect(v).toMatchObject({ state: { key: "paused", dot: "warn" }, pausedReason: "budget", monthBudgetUsd: 3 });+ expect(v.monthUsd).toBeCloseTo(3.1, 10);+ // 执行中的规则:推一句(一个月一次);「需要你」里一行,可以再给 $3+ const pushed = store.listOutbox({ limit: 50 }).filter((r) => r.id.startsWith(`rule:${rule.id}:budget:`));+ expect(pushed.map((r) => [r.id, r.purpose, r.body.text])).toEqual([[`rule:${rule.id}:budget:2026-11:3`, "failure", "⚠️ 规则「看 X 价格」本月预算用完(约 $3.10),已暂停,下月自动恢复。"]]);+ expect(svc.ruleAttention()).toEqual([+ expect.objectContaining({ id: `rule:${rule.id}`, kind: "rule", subject: "规则「看 X 价格」", status: "本月预算用完", line: "已用约 $3.10,下月自动恢复。再给 $3 继续?", severity: "warn", actions: ["continue"] }),+ ]);+ expect(svc.runRuleNow(rule.id).error).toBe("本月预算已用完(约 $3.10)");+ // 这个月里不再跑;定时器在下个月 1 号 0 点(上海)醒来+ await go(at("2026-11-06T08:00"));+ expect(ruleRuns(rule.id)).toHaveLength(3);+ expect((svc as any).nextWake()).toBe(at("2026-12-01T00:00"));+ // 上海还是 11 月 30 日 23:59(UTC 已经是 15:59):还停着+ await go(at("2026-11-30T23:59"));+ expect(store.getRule(rule.id)!.pausedReason).toBe("budget");+ // 上海 12 月 1 日 0 点(UTC 还是 11 月 30 日 16:00):恢复,按时间表跑;「需要你」里那行消失+ await go(at("2026-12-01T00:00"));+ expect(store.getRule(rule.id)).toMatchObject({ pausedReason: "", nextRunAt: at("2026-12-01T08:00") });+ expect(svc.ruleAttention()).toEqual([]);+ expect(svc.getRuleView(rule.id)!.monthUsd).toBe(0);+ await go(at("2026-12-01T08:00"));+ expect(ruleRuns(rule.id).at(-1)).toMatchObject({ state: "running", queuedAt: at("2026-12-01T08:00") });+ });++ it("「再给 $3」:本月预算用完暂停着的规则加了预算就接着按时间表跑;观察中的不推", async () => {+ const rule = await createRule();+ svc.updateRule(rule.id, { monthBudgetUsd: 0.2, runBudgetUsd: 1 });+ await go(at("2026-11-03T08:00"));+ await turn(undefined, (sid) => {+ spend(sid, 0.15);+ report(sid, "done");+ });+ // 这一次报完了才超:照常结束,之后暂停+ await go(at("2026-11-04T08:00"));+ await turn(undefined, (sid) => {+ report(sid, "done");+ spend(sid, 0.1);+ });+ expect(ruleRuns(rule.id).at(-1)).toMatchObject({ outcome: "done" });+ expect(store.getRule(rule.id)!.pausedReason).toBe("budget");+ expect(store.listOutbox({ limit: 50 }).filter((r) => r.id.startsWith("rule:"))).toEqual([]);+ expect(svc.addRuleBudget(rule.id).rule).toMatchObject({ monthBudgetUsd: 3.2, pausedReason: "", nextRunAt: at("2026-11-05T08:00"), state: { key: "observe" } });+ expect(svc.ruleAttention()).toEqual([]);+ expect(svc.updateRule(rule.id, { monthBudgetUsd: -1 }).error).toBe("金额不对");+ });++ it("机器人的预算 Key 剩不到 20%:在跑的任务停下排着(不算失败)、规则跳过、不开新任务,「需要你」里一行;预算回来就接着做", async () => {+ budget = { limitUsd: 10, remainUsd: 2.3, at: 1 };+ const rule = await createRule();+ const t = start();+ await flush();+ await turn(t.sessionId, (sid) => {+ spend(sid, 0.25);+ expect(host.cancels).toEqual([]);+ spend(sid, 0.1);+ });+ // 剩 $1.95 < $2:停下这一轮,排一个 run 等预算回来+ expect(host.cancels).toEqual([t.sessionId]);+ expect(runs(t.id)).toEqual([+ ["launch", "ended", "interrupted"],+ ["recover", "queued", ""],+ ]);+ expect(store.listRuns({ taskId: t.id })[0].error).toBe("reserve");+ expect(svc.get(t.id)!.stage.key).toBe("working/queued");+ expect(svc.attention()).toEqual([{ id: "reserve:b", kind: "budget", botId: "b", botName: "小蓝", subject: "后台工作已停", status: "", line: "机器人预算只剩约 $1.95(共 $10),留给聊天", since: now, severity: "warn", actions: ["open"] }]);+ expect(approvals.pendingAll()).toEqual([]);+ // 不开新任务(聊天代理照实说);规则到点跳过+ const r = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "start", args: { title: "又一个", brief: "" } });+ expect(r.error).toMatch(/about \$1\.95 of \$10 left\) and the rest is kept for chat/);+ expect(store.listTasks({ botId: "b" })).toHaveLength(1);+ await go(at("2026-11-03T08:00"));+ expect(svc.ruleLog(rule.id)[0]).toMatchObject({ outcome: "skipped", line: "跳过:机器人预算留给聊天" });+ expect(svc.runRuleNow(rule.id).error).toBe("机器人预算留给聊天");+ // 预算回来了(调高了预算,应用读到新的余额):排着的接着做,第一条是说明+ budget = { limitUsd: 20, remainUsd: 11.95, at: 2 };+ svc.budgetsChanged();+ await flush();+ expect(runs(t.id).at(-1)).toEqual(["recover", "running", ""]);+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: t.sessionId, resume: true });+ expect(host.prompts.at(-1)!.text).toMatch(/^The app paused this task to keep the bot's remaining budget for chat, and has now resumed it\./);+ expect(svc.attention()).toEqual([]);+ // 没开预算的机器人:从不停+ budget = undefined;+ expect(svc.reserve("b")).toBeUndefined();+ });++ it("任务每次运行最多 4 小时,等人批准的时间不算;到了取消这一轮、算失败(推一句,可以重试)", async () => {+ const t = start();+ await flush();+ const t0 = now;+ const runId = store.listRuns({ taskId: t.id })[0].id;+ now = t0 + 1 * H;+ const a = approvals.create({ kind: "approval", botId: "b", conversationId: CONV, sessionId: t.sessionId, tool: "bash", detail: "rm -rf build/", reason: "", taskId: t.id, runId, ttlMs: 12 * H });+ // 还在等批准:等着的这段到现在都不算+ now = t0 + 4 * H + 30 * MIN;+ svc.checkCaps();+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);+ now = t0 + 5 * H;+ approvals.decide(a.id, true, "weixin:owner");+ // 过了将近 8 小时,其中等了 4 小时:还差一分钟+ now = t0 + 8 * H - MIN;+ svc.checkCaps();+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);+ expect(host.cancels).toEqual([]);+ now = t0 + 8 * H;+ svc.checkCaps();+ expect(runs(t.id)).toEqual([["launch", "ended", "failed"]]);+ expect(host.cancels).toEqual([t.sessionId]);+ expect(host.stops).toEqual([]);+ expect(store.listRuns({ taskId: t.id })[0].error).toBe("运行超过 4 小时,已停下");+ expect(store.listMessages(CONV).at(-1)!.content).toBe("⚠️「季度报告 PPT」没做完:运行超过 4 小时,已停下");+ expect(svc.attention()).toMatchObject([{ id: `task:${t.id}`, kind: "failed", line: "运行超过 4 小时,已停下", actions: ["retry", "stop"] }]);+ // 重试:新的一次运行,重新计时+ await svc.retry(t.id);+ await flush();+ expect(runs(t.id).at(-1)).toEqual(["retry", "running", ""]);+ now += 3 * H;+ svc.checkCaps();+ expect(runs(t.id).at(-1)).toEqual(["retry", "running", ""]);+ });+});diff --git a/test/prompts.unit.test.ts b/test/prompts.unit.test.tsindex 82f41da..f1107d8 100644--- a/test/prompts.unit.test.ts+++ b/test/prompts.unit.test.ts@@ -23,6 +23,7 @@ import {TASK_SECTION_ORDER,placeLine,recoveryNote,+ resumeNote,segmentInput,taskBrief,RULE_NUDGE,@@ -131,6 +132,8 @@ async function parts(): Promise<Record<string, string>> {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 resume budget": resumeNote("budget", ["sleep 600"]),+ "task resume reserve": resumeNote("reserve", []),"task nudge": NUDGE,"tool task_report": runtime ? JSON.stringify((await loadPlugins()).task.tools.find((t) => t.name === "task_report") ?? "") : "","tool rule_create": tool("rule_create"),@@ -189,6 +192,10 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [["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"]],+ // —— 花费与预算(3e):用户说了上限才填;停下之后接着做时说清为什么停、被停的后台命令、先查再重复外部动作 ——+ ["task_start:用户说了花费上限才填 budget_usd,默认 $1", "tool task_start", ["budget_usd", "Only when the user names a spending limit", "Default 1"]],+ ["预算用完、用户加了预算后接着做:上一步可能没做完,先查日志再重复外部动作", "task resume budget", ["used its budget", "the user has now added more", "sleep 600", "Before repeating any outside action", ".task/journal.md", "task_report"]],+ ["为聊天留预算暂停、恢复后接着做", "task resume reserve", ["keep the bot's remaining budget for chat", "stopped: none", ".task/journal.md", "task_report"]],["没报告时提醒一次:done 带一句话、failed 带原因", "task nudge", ["task_report", "done", "failed"]],// —— 规则(3d):检查从观察开始,只在值得说时说一句;观察只看不动;执行最多可写工作区 ——["rule_create:用户原话原样;检查从观察开始只记录;提醒到点发那句;确认一句", "tool rule_create", ["verbatim", "starts in observe mode", "only recording what it would say", "kind remind", "Confirm in one sentence", "every 30m", "weekly mon,thu"]],@@ -272,6 +279,7 @@ describe.skipIf(!runtime)("提示词约定", () => {* 3a 基线 8,514(提示词 907 + 工具 7,607,其中 task_start、task_message、task_list 1,370);3b、3c 之后 8,751(工具 7,844)。* 3d 加上 rule_create(819)、rule_update(467)和 task_list 多一句「and rules」后 10,049(工具 9,142)。上限高约 5%。* 暂停开关 background_pause(280)之后 10,329(工具 9,422),还在上限之内,上限不变。+ * 3e:task_start 加上 budget_usd(116)之后 10,445(工具 9,538),还在上限之内,上限不变。* 缩短了就调低;要调高,在提交说明里写清原因。*/const BUDGET = 10_550;diff --git a/test/rules.unit.test.ts b/test/rules.unit.test.tsindex 08ffb29..0b133f3 100644--- a/test/rules.unit.test.ts+++ b/test/rules.unit.test.ts@@ -259,6 +259,10 @@ class FakeHost implements TaskHost {async stop(_botId: string, sessionId: string) {this.stops.push(sessionId);}+ cancels: string[] = [];+ async cancel(_botId: string, sessionId: string) {+ this.cancels.push(sessionId);+ }async quiet() {return { quiet: true };}diff --git a/test/tasks.integration.test.ts b/test/tasks.integration.test.tsindex 9073727..9ea2054 100644--- a/test/tasks.integration.test.ts+++ b/test/tasks.integration.test.ts@@ -5,6 +5,8 @@* 两个任务在跑时,聊天消息不排在它们后面(人的通道);收尾(后台命令)、没报告时的提醒、每种会话的工具。* 3b 退出演示:任务在微信里问「中文还是英文?」,用户回编号,任务接着做完;桌面的「需要你」列出它,回答后变空。* 另外:引用回答、中间的普通聊天不被当成回答;任务会话里的审批推到同一个微信会话(带任务名),y 编号批准后接着做。+ * 3e 退出演示:模型每次请求报的用量按(mock 的)Modelflare 价格目录估算,任务花到 $1 停下,微信和「需要你」里问+ * 「已用约 $1.00,再给 $1 继续?」,在桌面上点继续后同一个会话接着做完。*/import fs from "node:fs";import os from "node:os";@@ -26,7 +28,13 @@ async function body(req: http.IncomingMessage): Promise<any> {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 };+/** usage:这次请求报的输入 tokens(默认 10) */+type Step = { tool?: { name: string; args: any }; text?: string; hang?: boolean; usage?: number };+/**+ * mock 的 Modelflare 价格目录(AMB_MODELFLARE_ISSUER 指向 mock):mock-agent 输入 $4 / 百万 tokens,一次 62,500 tokens = $0.25;+ * 上下文 100 万,几次大请求不会触发压缩。平常的请求只有 10 个 tokens,花费可以忽略。+ */+const PRICING = { data: [{ model_name: "mock-agent", quota_type: 0, input_price: 4, completion_ratio: 1, enable_groups: ["default"], context_window: 1_000_000 }], group_ratio: { default: 1 }, usable_group: { default: "" } };describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("background tasks (real DSH, WeChat)", () => {const OWNER = "[email protected]";@@ -83,6 +91,11 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgroureturn report(`APPROVED-${tag}<<${out.includes("appr-42") ? "ran" : "not run"}>>`, 1);}if (tag.startsWith("HANG")) return { hang: true };+ // BUDGET:每一步都是一次 $0.25 的请求,一直做下去,直到宿主在 $1 停下它;加了预算之后报告做完+ if (tag.startsWith("BUDGET")) {+ if (/^This task was stopped when it used its budget/.test(user)) return report(`BUDGET-DONE-${tag}:报告写好了。`);+ return { tool: { name: "bash", args: { description: "run", command: `echo step-${done}` } }, usage: 62_500 };+ }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 } } };@@ -103,6 +116,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgroullm = 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" }] }));+ if (url === "/api/pricing") return void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(PRICING));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: "标题" };@@ -118,10 +132,13 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrousend({ 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 } });+ const prompt = step.usage ?? 10;+ send({ choices: [], usage: { prompt_tokens: prompt, completion_tokens: 5, total_tokens: prompt + 5 } });res.end("data: [DONE]\n\n");});ilink = await mockIlink();+ // 价格目录(估算花费)从 mock 读+ process.env.AMB_MODELFLARE_ISSUER = llm.url;dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-"));app = makeApp();// 主人已经扫码登录;渠道连到 mock iLink@@ -136,6 +153,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrouawait app?.stop();await llm?.close();await ilink?.close();+ delete process.env.AMB_MODELFLARE_ISSUER;fs.rmSync(dataDir, { recursive: true, force: true });});@@ -313,6 +331,52 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrouexpect((await api("/attention")).items).toEqual([]);}, 180_000);+ it("exit demo (3e): a task stops at its $1 budget and asks 「再给 $1 继续?」 on WeChat and in needs-you; continuing from the desktop finishes it in the same session", async () => {+ expect((await api("/attention")).items).toEqual([]);+ const t = await research("BUDGETQ");+ const taskCalls = () => calls.filter((c) => c.task && c.users.some((u) => u.includes("RESEARCH BUDGETQ"))).length;+ await waitFor(() => stage("BUDGETQ") === "needs-you/budget");+ // 4 次 $0.25 的请求之后停下:这一轮被取消,模型不再被调用(取消到达之前已经发出的那一次也记上)+ const n = taskCalls();+ await new Promise((r) => setTimeout(r, 2000));+ expect(taskCalls()).toBe(n);+ expect(n).toBeLessThanOrEqual(5);+ // 每次还有 5 个输出 tokens($0.00002);第 5 次请求可能在取消到达之前就回来了:那就是 $1.25+ const spent = app.store.getTask(t.id)!.spentUsd;+ expect([1, 1.25].some((v) => Math.abs(spent - v) < 0.001), `spent ${spent}`).toBe(true);+ // 微信里问一次,设计里的样子+ await waitFor(() => sentTo("❓「调研 BUDGETQ」").length === 1);+ expect(sentTo("❓「调研 BUDGETQ」")[0].text).toBe("❓「调研 BUDGETQ」想问你:已用约 $1.00,再给 $1 继续?\n1. 继续\n2. 停止\n(回复编号,或引用这条消息回答)");+ // 桌面:「需要你」一行,状态是预算用完;任务详情里有花费+ const { items } = await api("/attention");+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({ kind: "question", subject: "调研 BUDGETQ", status: "预算用完", line: "已用约 $1.00,再给 $1 继续?", taskId: t.id, actions: ["answer"] });+ expect(items[0].questions[0].options.map((o: any) => o.label)).toEqual(["继续", "停止"]);+ const d0 = await api(`/tasks/${t.id}`);+ expect(d0.task).toMatchObject({ budgetUsd: 1, stage: { key: "needs-you/budget", label: "预算用完" } });+ expect(d0.runs.map((r: any) => [r.cause, r.outcome])).toEqual([["launch", "budget"]]);+ expect(d0.runs[0].costUsd).toBeCloseTo(spent, 6);+ // 在「需要你」里点「继续」:预算加 $1,同一个会话接着做完,结果发回微信+ const r = await api(`/attention/${encodeURIComponent(items[0].id)}/answer`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ text: "1" }) });+ expect(r.ok).toBe(true);+ await waitFor(() => sentTo("BUDGET-DONE-BUDGETQ").length === 1);+ await waitFor(() => stage("BUDGETQ") === "ready");+ const d = await api(`/tasks/${t.id}`);+ expect(d.task.budgetUsd).toBe(2);+ expect(d.task.spentUsd).toBeGreaterThan(spent);+ expect(d.task.spentUsd).toBeLessThan(spent + 0.01);+ expect(d.runs.map((x: any) => [x.cause, x.outcome])).toEqual([+ ["launch", "budget"],+ ["continue", "done"],+ ]);+ const last = calls.filter((c) => c.task && c.users.some((u) => u.includes("RESEARCH BUDGETQ"))).at(-1)!;+ expect(last.users.filter((u) => /^This task was stopped when it used its budget/.test(u))).toHaveLength(1);+ expect(last.users.filter((u) => u.includes("[用户的原话]\nRESEARCH BUDGETQ"))).toHaveLength(1);+ expect((await api("/attention")).items).toEqual([]);+ await app.outbox.idle();+ expect(sentTo("❓「调研 BUDGETQ」")).toHaveLength(1);+ }, 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);diff --git a/test/tasks.unit.test.ts b/test/tasks.unit.test.tsindex efe3acd..a13b7d4 100644--- a/test/tasks.unit.test.ts+++ b/test/tasks.unit.test.ts@@ -154,6 +154,10 @@ class FakeHost implements TaskHost {async stop(_botId: string, sessionId: string) {this.stops.push(sessionId);}+ cancels: string[] = [];+ async cancel(_botId: string, sessionId: string) {+ this.cancels.push(sessionId);+ }async quiet() {return this.quiets.shift() ?? { quiet: true };}diff --git a/ui/components/rules.js b/ui/components/rules.jsindex 88487ec..ee43b96 100644--- a/ui/components/rules.js+++ b/ui/components/rules.js@@ -9,6 +9,7 @@ import { api } from "../lib/api.js";import { confirmSheet, failed, toast } from "../lib/store.js";import { channelName } from "../lib/access.js";import { t, locale } from "../lib/i18n.js";+import { hasCost, money } from "./tasks.js";const pad = (n) => String(n).padStart(2, "0");const hm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;@@ -37,10 +38,10 @@ export function fmtNext(at, now = Date.now()) {return t("time.dateTime", { date: shortDate(d), time: hm(d) });}-/** 行的第二行:观察中 · 下次 明天 08:00;正在运行;已暂停 · 连续失败 3 次(状态文字由服务端按界面语言给) */+/** 行的第二行:观察中 · 下次 明天 08:00;正在运行;已暂停 · 连续失败 3 次 / 本月预算用完(状态文字由服务端按界面语言给) */export function ruleSub(rule, now = Date.now()) {if (rule.live) return t(rule.live.state === "queued" ? "rules.queued" : "rules.running", { state: rule.state.label });- if (rule.state.key === "paused") return t("rules.paused", { count: rule.failures });+ if (rule.state.key === "paused") return rule.pausedReason === "budget" ? t("rules.pausedBudget") : t("rules.paused", { count: rule.failures });if (rule.state.key === "off" || rule.state.key === "done") return rule.state.label;return rule.nextRunAt ? t("rules.sub", { state: rule.state.label, next: fmtNext(rule.nextRunAt, now) }) : rule.state.label;}@@ -77,7 +78,7 @@ export function RuleRow({ rule, onChanged, open, onToggle }) {${open && html`<div class="row-edit rule-edit"><${RuleDetail} rule=${rule} onChanged=${onChanged} /></div>`}`;}-/** 运行记录的一行:时间 · 模式 · 一句话;点开看报告、步骤、版本和权限(不另起一块) */+/** 运行记录的一行:时间 · 模式 · 一句话 · 花了多少(有了才写);点开看报告、步骤、版本和权限(不另起一块) */function RunItem({ rule, run }) {const [open, setOpen] = useState(false);const mode = rule.kind === "remind" || !["observe", "act"].includes(run.mode) ? "" : t(`rules.mode.${run.mode}`);@@ -85,6 +86,7 @@ function RunItem({ rule, run }) {return html`<li class=${`rule-run${open ? " open" : ""}`}><button type="button" class="rule-run-head" aria-expanded=${open} onClick=${() => setOpen(!open)}><span class="at num">${fmtRunAt(run.at)}</span>${mode && html`<span class="m">${mode}</span>`}<span class="l">${run.line}</span>+ ${hasCost(run.costUsd) && html`<span class="c num">${t("tasks.costShort", { spent: money(run.costUsd) })}</span>`}<${Icon} name="chevRight" size=${12} class="chev" /></button>${open && html`<div class="rule-run-body">@@ -135,7 +137,9 @@ export function RuleDetail({ rule, runs: given, onChanged }) {: [["observe", t("rules.mode.observe")], ["act", t("rules.mode.act")], ["off", t("rules.mode.off")]];const where = rule.channel ? channelName(rule.channel) : "";const next = rule.nextRunAt && rule.state.key !== "paused" && rule.mode !== "off" ? t("rules.next", { time: fmtNext(rule.nextRunAt) }) : "";- const line = [next, where && t("rules.sendsTo", { where })].filter(Boolean).join(" · ");+ // 本月的花费:有了才写(规则详情的 下次 … · 发到 … · 本月 约 $0.41 / $3.00)+ const month = hasCost(rule.monthUsd) ? t("rules.month", { spent: money(rule.monthUsd), budget: money(rule.monthBudgetUsd) }) : "";+ const line = [next, where && t("rules.sendsTo", { where }), month].filter(Boolean).join(" · ");return html`<div class="rule-detail"><p class="rule-words selectable">${t("rules.words", { text: rule.kind === "remind" ? rule.message : rule.instruction })}</p>${line && html`<span class="hint">${line}</span>`}diff --git a/ui/components/tasks.js b/ui/components/tasks.jsindex dc2bef2..ae79b4c 100644--- a/ui/components/tasks.js+++ b/ui/components/tasks.js@@ -1,5 +1,6 @@-// 后台任务(3a):对话里请求那条消息下面的任务胶囊「后台任务 · 标题 · 进行中 ›」,点开是最新进展、每次运行折叠的处理过程和停止;-// 信息面板里一行一个任务。状态是"点 + 文字":绿 = 进行中,黄 = 等你,红 = 失败,灰 = 已完成 / 已停止。健康时不多占地方。+// 后台任务(3a):对话里请求那条消息下面的任务胶囊「后台任务 · 标题 · 进行中 ›」,点开是最新进展、花费、每次运行折叠的处理过程和停止;+// 信息面板里一行一个任务。状态是"点 + 文字":绿 = 进行中,黄 = 等你,红 = 失败,灰 = 已完成 / 已停止。健康时不多占地方:+// 花费(3e,「约 $0.08」)在有了花费之后才出现。import { useEffect, useState } from "preact/hooks";import { html, Icon, Notice } from "./ui.js";import { ActivityLine } from "./activity.js";@@ -17,6 +18,10 @@ export function stageDot(stage) {return "";}+/** 估算的花费到了一分钱才显示(之前什么都不写) */+export const hasCost = (usd) => Number(usd) >= 0.005;+export const money = (usd) => `$${Number(usd || 0).toFixed(2)}`;+/** 每次运行怎么来的(launch、followup、recover、retry、continue、answer、manual) */const cause = (c) => (has(`tasks.cause.${c}`) ? t(`tasks.cause.${c}`) : c);@@ -38,7 +43,7 @@ export async function stopTask(task) {}}-/** 任务的详情:最新进展、文件夹、每次运行(折叠的处理过程)、停止。working 时每 3 秒刷新 */+/** 任务的详情:最新进展、花费、文件夹、每次运行(折叠的处理过程)、停止。working 时每 3 秒刷新 */export function TaskDetail({ task, onChanged }) {const [d, setD] = useState(null);const [stopping, setStopping] = useState(false);@@ -65,6 +70,7 @@ export function TaskDetail({ task, onChanged }) {};return html`<div class="task-detail">${view.latest && html`<div class="task-line"><span class="t-label">${t("tasks.latest")}</span><span class="v selectable">${view.latest}</span></div>`}+ ${hasCost(view.spentUsd) && html`<div class="task-line"><span class="t-label">${t("tasks.cost")}</span><span class="v num">${t("tasks.costOf", { spent: money(view.spentUsd), budget: money(view.budgetUsd) })}</span></div>`}${view.folder && html`<div class="task-line"><span class="t-label">${t("tasks.folder")}</span><span class="v mono selectable">${view.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}@@ -88,7 +94,7 @@ export function TaskChip({ task, onChanged }) {</div>`;}-/** 信息面板里的一行:状态点 + 标题,下面一行是状态、什么时候开始的、最新进展;进行中的可以停止 */+/** 信息面板里的一行:状态点 + 标题,下面一行是状态、什么时候开始的、花了多少(有了花费才写);进行中的可以停止 */export function TaskRow({ task, onChanged, onOpen }) {const [stopping, setStopping] = useState(false);const working = task.stage.group === "working";@@ -104,7 +110,7 @@ export function TaskRow({ task, onChanged, 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 class="sub">${task.stage.label} · ${when}${hasCost(task.spentUsd) ? ` · ${t("tasks.costShort", { spent: money(task.spentUsd) })}` : ""}</div></div>${working && html`<button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? t("tasks.stopping") : t("tasks.stop")}</button>`}</div>`;diff --git a/ui/css/shell.css b/ui/css/shell.cssindex 8384792..785be23 100644--- a/ui/css/shell.css+++ b/ui/css/shell.css@@ -311,7 +311,7 @@ button.thread:active { background: var(--side-press); }text-align: left; font-size: var(--fs-xs); color: var(--fg-2); border-radius: var(--r-sm); transition: color var(--t-fast);}.rule-run-head:hover { color: var(--fg); }-.rule-run-head :is(.at, .m) { flex: none; color: var(--muted); }+.rule-run-head :is(.at, .m, .c) { flex: none; color: var(--muted); }.rule-run-head .l { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.rule-run.open .rule-run-head .l { white-space: normal; overflow-wrap: anywhere; }.rule-run-head .chev { flex: none; align-self: center; color: var(--muted); transition: transform var(--t-fast); }diff --git a/ui/design/gallery.js b/ui/design/gallery.jsindex 66e3f8e..2b4b017 100644--- a/ui/design/gallery.js+++ b/ui/design/gallery.js@@ -607,7 +607,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<${NeedsRow} count=${3} onClick=${() => {}} /><${NeedsRow} count=${2} on onClick=${() => {}} /><${NeedsRow} count=${0} /></div>`}<//>- <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你批准 / 未送达 / 失败 / 登录过期">+ <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你批准 / 预算用完(再给 $1 继续?)/ 未送达 / 失败 / 规则本月预算用完 / 登录过期 / 预算留给聊天">${() => html`<div class="list needs-list">${NEEDS.map((it) => html`<${NeedItem} item=${it} multiBot onAct=${async () => {}} />`)}</div>`}<//><//>@@ -655,10 +655,13 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场const NEEDS = [{ id: "q", kind: "question", botName: "小蓝", subject: "GPU 价格调研", status: "等你回答", line: "报告用中文还是英文?", since: Date.now() - 2 * 60_000, severity: "warn", questions: [{ id: "a", question: "报告用中文还是英文?", options: [{ label: "中文" }, { label: "英文" }] }] },{ id: "a", kind: "approval", botName: "小蓝", subject: "清理旧构建", status: "等你批准", line: "rm -rf build/", since: Date.now() - 5 * 60_000, severity: "warn" },+ { id: "bq", kind: "question", botName: "小蓝", subject: "季度报告 PPT", status: "预算用完", line: "已用约 $1.00,再给 $1 继续?", since: Date.now() - 8 * 60_000, severity: "warn", questions: [{ id: "budget", question: "已用约 $1.00,再给 $1 继续?", options: [{ label: "继续" }, { label: "停止" }] }] },{ id: "d", kind: "delivery", botName: "小蓝", subject: "1 条结果未送达微信", status: "在微信里发条消息就能收到", line: "季度报告做好了,在 tasks 文件夹里。", since: Date.now() - 20 * 60_000, severity: "warn", actions: [] },{ id: "f", kind: "failed", botName: "红魔", subject: "季度报告", status: "失败", line: "X 云的价格页要登录,我进不去", since: Date.now() - 40 * 60_000, severity: "err" },{ id: "r", kind: "rule", botName: "红魔", subject: "规则「每日 issue 巡检」", status: "连续失败 3 次,已暂停", line: "GitHub 返回 401:令牌可能过期了", since: Date.now() - 90 * 60_000, severity: "err", actions: ["retry"] },+ { id: "rb", kind: "rule", botName: "小蓝", subject: "规则「看 X 价格」", status: "本月预算用完", line: "已用约 $3.00,下月自动恢复。再给 $3 继续?", since: Date.now() - 2 * 3600_000, severity: "warn", actions: ["continue"] },{ id: "l", kind: "login", botName: "绿草", subject: "微信登录已过期", status: "", line: "", since: Date.now() - 3 * 3600_000, severity: "err" },+ { id: "rs", kind: "budget", botName: "小蓝", subject: "后台工作已停", status: "", line: "机器人预算只剩约 $1.80(共 $10),留给聊天", since: Date.now() - 4 * 3600_000, severity: "warn", actions: ["open"] },];/** 规则的样例(单人:自己的机器人小蓝):每天 8 点看 X 价格(观察了 3 次)、每周的 issue 周报、暂停了的巡检、一次性的提醒 */@@ -670,15 +673,15 @@ const at = (days, h, m = 0) => {};const rule = (o) => ({ botId: "b", kind: "check", mode: "observe", observeLeft: 0, failures: 0, hint: false, observed: 0, channel: "weixin", message: "", trigger: { kind: "schedule" }, version: 1, ...o });const RULES = [- rule({ id: "g1", title: "看 X 价格", when: "每天 08:00", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", state: { key: "observe", label: "观察中", dot: "" }, nextRunAt: at(1, 8), hint: true, observed: 3 }),+ rule({ id: "g1", title: "看 X 价格", when: "每天 08:00", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", state: { key: "observe", label: "观察中", dot: "" }, nextRunAt: at(1, 8), hint: true, observed: 3, monthUsd: 0.41, monthBudgetUsd: 3 }),rule({ id: "g2", title: "issue 周报", when: "每周一 09:00", instruction: "每周一早上把仓库上周的 issue 汇总成三句话发给我", mode: "act", state: { key: "act", label: "执行中", dot: "ok" }, nextRunAt: at(3, 9) }),rule({ id: "g3", title: "每日 issue 巡检", when: "每天 08:30", instruction: "每天看看有没有新的 issue 需要我回复", mode: "act", state: { key: "paused", label: "已暂停", dot: "err" }, failures: 3, nextRunAt: 0 }),rule({ id: "g4", title: "交房租", when: "11月3日 12:00", kind: "remind", mode: "act", message: "该交房租了。", state: { key: "remind", label: "提醒", dot: "ok" }, nextRunAt: at(2, 12) }),];const RULE_RUNS = [- { id: "x1", at: at(0, 8), mode: "observe", line: "本会发送:“X 降价了,现在 ¥199(昨天 ¥259)”", summary: "X 现在 ¥199,比昨天低 ¥60,低于 200。", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule" },- { id: "x2", at: at(-1, 8), mode: "observe", line: "本会保持安静:X 现在 ¥259", summary: "X 现在 ¥259,高于 200。", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule" },- { id: "x3", at: at(-2, 8), mode: "observe", line: "失败:页面打不开", summary: "", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule" },+ { id: "x1", at: at(0, 8), mode: "observe", line: "本会发送:“X 降价了,现在 ¥199(昨天 ¥259)”", summary: "X 现在 ¥199,比昨天低 ¥60,低于 200。", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule", costUsd: 0.03 },+ { id: "x2", at: at(-1, 8), mode: "observe", line: "本会保持安静:X 现在 ¥259", summary: "X 现在 ¥259,高于 200。", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule", costUsd: 0.02 },+ { id: "x3", at: at(-2, 8), mode: "observe", line: "失败:页面打不开", summary: "", would: "", version: 1, permission: "只读", steps: 0, cause: "schedule", costUsd: 0.01 },{ id: "x4", at: at(-5, 8), mode: "observe", line: "跳过:电脑没开", summary: "", would: "", version: 1, permission: "", steps: 0, cause: "schedule" },];diff --git a/ui/locales/en/needs.js b/ui/locales/en/needs.jsindex 7da731f..1aad449 100644--- a/ui/locales/en/needs.js+++ b/ui/locales/en/needs.js@@ -15,4 +15,6 @@ export default {send: "Send",none: "Nothing needs you right now",dismiss: "Don't show again",+ continue: "Continue",+ raiseBudget: "Change budget",};diff --git a/ui/locales/en/rules.js b/ui/locales/en/rules.jsindex ee1822c..566de29 100644--- a/ui/locales/en/rules.js+++ b/ui/locales/en/rules.js@@ -7,6 +7,8 @@ export default {running: "{state} · running",queued: "{state} · queued",paused: { one: "Paused · failed {count} time in a row", other: "Paused · failed {count} times in a row" },+ pausedBudget: "Paused · monthly budget used up",+ month: "This month about {spent} of {budget}",hint: { one: "Observed {count} time · switch to act?", other: "Observed {count} times · switch to act?" },nowActs: "“{title}” now acts",version: "Version {n}",diff --git a/ui/locales/en/tasks.js b/ui/locales/en/tasks.jsindex 08a1dce..8549388 100644--- a/ui/locales/en/tasks.js+++ b/ui/locales/en/tasks.js@@ -14,4 +14,7 @@ export default {minutes: { one: "{count} min", other: "{count} min" },paused: "Background work is paused",resume: "Resume",+ cost: "Cost",+ costOf: "About {spent} of {budget}",+ costShort: "About {spent}",};diff --git a/ui/locales/zh-CN/needs.js b/ui/locales/zh-CN/needs.jsindex 1016417..1c2a519 100644--- a/ui/locales/zh-CN/needs.js+++ b/ui/locales/zh-CN/needs.js@@ -15,4 +15,6 @@ export default {send: "发送",none: "没有需要你处理的事",dismiss: "不再提示",+ continue: "继续",+ raiseBudget: "调整预算",};diff --git a/ui/locales/zh-CN/rules.js b/ui/locales/zh-CN/rules.jsindex 2e37880..f670abe 100644--- a/ui/locales/zh-CN/rules.js+++ b/ui/locales/zh-CN/rules.js@@ -7,6 +7,8 @@ export default {running: "{state} · 正在运行",queued: "{state} · 排队中",paused: { other: "已暂停 · 连续失败 {count} 次" },+ pausedBudget: "已暂停 · 本月预算用完",+ month: "本月 约 {spent} / {budget}",hint: { other: "已观察 {count} 次 · 改为执行?" },nowActs: "「{title}」改为执行",version: "第 {n} 版",diff --git a/ui/locales/zh-CN/tasks.js b/ui/locales/zh-CN/tasks.jsindex 3271f18..25f78e5 100644--- a/ui/locales/zh-CN/tasks.js+++ b/ui/locales/zh-CN/tasks.js@@ -14,4 +14,7 @@ export default {minutes: { other: "{count} 分钟" },paused: "后台工作已暂停",resume: "恢复",+ cost: "花费",+ costOf: "约 {spent} / {budget}",+ costShort: "约 {spent}",};diff --git a/ui/main.js b/ui/main.jsindex c243994..34cc919 100644--- a/ui/main.js+++ b/ui/main.js@@ -390,7 +390,7 @@ function App() {${view === "settings" && html`<${SettingsScreen} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} onTab=${(t) => openSettings(t)} focusRow=${route.row}mf=${mf} onMfChanged=${reloadMf} onSettings=${setSettings} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}status=${status} bots=${bots} onOpenBotSettings=${openBotSettings} account=${managed ? account : null} onAccount=${setAccount} />`}- ${view === "needs" && html`<${NeedsYouScreen} multiBot=${!!bots && bots.length > 1} onChanged=${pollWorking} onOpenChat=${openChat} onRelogin=${relogin} />`}+ ${view === "needs" && html`<${NeedsYouScreen} multiBot=${!!bots && bots.length > 1} onChanged=${pollWorking} onOpenChat=${openChat} onRelogin=${relogin} onOpenBotSettings=${openBotSettings} />`}${view === "bot-settings" && routedBot && html`<${BotSettingsScreen} key=${routedBot.id} bot=${routedBot} section=${route.section}models=${models} modelsError=${modelsError} reloadModels=${reloadModels} defaultModel=${settings && settings.defaultModel}account=${managed ? account : null} onOpenSettings=${openSettings}diff --git a/ui/screens/needs-you.js b/ui/screens/needs-you.jsindex 1483cd4..a4e66f0 100644--- a/ui/screens/needs-you.js+++ b/ui/screens/needs-you.js@@ -1,5 +1,7 @@-// 需要你(3b):所有机器人里在等你的事,一行一件,操作就在行里(回答、批准、重试…);点标题那一行展开详情。+// 需要你(3b):所有机器人里在等你的事,一行一件,操作就在行里(回答、批准、重试、加预算继续…);点标题那一行展开详情。// 没事时侧栏没有这一行,直接打开这一页只有一句「没有需要你处理的事」。状态是"点 + 文字":黄 = 等你,红 = 失败 / 登录过期。+// 预算(3e):任务预算用完是一个提问(「已用约 $1.00,再给 $1 继续?」继续 / 停止);规则本月预算用完可以继续;+// 机器人的预算留给聊天、后台工作停着的,去机器人设置调整预算。import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { html, Icon, Button, Skeleton } from "../components/ui.js";import { TaskDetail } from "../components/tasks.js";@@ -28,13 +30,14 @@ function choices(item) {* 一件事:标题行(机器人 · 任务 · 状态 · 时间;只有一个机器人时不写机器人名)、第二行(问题 / 命令 / 原因)、行内操作。* onAct(action, body) 返回 Promise*/-export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin }) {+export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin, onOpenBotSettings }) {const [busy, setBusy] = useState("");const [open, setOpen] = useState(false);const [writing, setWriting] = useState(false);const [text, setText] = useState("");const input = useRef(null);const opts = item.kind === "question" ? choices(item) : null;+ const can = (a) => (item.actions || []).includes(a);useEffect(() => {if (writing) requestAnimationFrame(() => input.current?.focus());}, [writing]);@@ -67,9 +70,14 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin }) {${item.kind === "question" && !writing && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => setWriting(true)}>${t("needs.reply")}</button>`}${item.kind === "approval" && html`<${Button} variant="primary" loading=${busy === "approve"} disabled=${!!busy} onClick=${() => act("approve")}>${t("needs.approveOnce")}<//><${Button} loading=${busy === "deny"} disabled=${!!busy} onClick=${() => act("deny")}>${t("needs.deny")}<//>`}- ${item.kind === "failed" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>- <button type="button" class="text danger" disabled=${!!busy} onClick=${() => act("stop")}>${t("needs.stop")}</button>`}- ${item.kind === "rule" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`}+ ${item.kind === "failed" && (can("continue")+ ? html`<${Button} variant="primary" loading=${busy === "continue"} disabled=${!!busy} onClick=${() => act("continue")}>${t("needs.continue")}<//>`+ : html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`)}+ ${item.kind === "failed" && html`<button type="button" class="text danger" disabled=${!!busy} onClick=${() => act("stop")}>${t("needs.stop")}</button>`}+ ${item.kind === "rule" && (can("continue")+ ? html`<${Button} variant="primary" loading=${busy === "continue"} disabled=${!!busy} onClick=${() => act("continue")}>${t("needs.continue")}<//>`+ : html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`)}+ ${item.kind === "budget" && html`<${Button} onClick=${() => onOpenBotSettings?.(item.botId, "budget")}>${t("needs.raiseBudget")}<//>`}${item.kind === "delivery" && item.actions.includes("retry") && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`}${item.kind === "delivery" && item.actions.includes("dismiss") && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.dismiss")}</button>`}${item.kind === "login" && html`<${Button} onClick=${() => onRelogin?.(item.botId)}>${t("needs.relogin")}<//>`}@@ -97,7 +105,7 @@ function RuleOpen({ id }) {}/** 主区的「需要你」:每 3 秒看一次;处理掉的那件立刻消失(onChanged 让侧栏的件数也跟上) */-export function NeedsYouScreen({ multiBot, onChanged, onOpenChat, onRelogin }) {+export function NeedsYouScreen({ multiBot, onChanged, onOpenChat, onRelogin, onOpenBotSettings }) {const [items, setItems] = useState(null);const load = useCallback(() => api("/attention").then((d) => setItems(d.items || [])).catch(() => setItems((v) => v || [])), []);useEffect(() => {@@ -116,7 +124,7 @@ export function NeedsYouScreen({ multiBot, onChanged, onOpenChat, onRelogin }) {${!items && html`<div class="list needs-list"><div class="need"><${Skeleton} w="50%" /><${Skeleton} w="70%" /></div></div>`}${items && !items.length && html`<p class="set-none">${t("needs.none")}</p>`}${items && items.length > 0 && html`<div class="list needs-list">- ${items.map((it) => html`<${NeedItem} key=${it.id} item=${it} multiBot=${multiBot} onAct=${onAct(it)} onOpenChat=${onOpenChat} onRelogin=${onRelogin} />`)}+ ${items.map((it) => html`<${NeedItem} key=${it.id} item=${it} multiBot=${multiBot} onAct=${onAct(it)} onOpenChat=${onOpenChat} onRelogin=${onRelogin} onOpenBotSettings=${onOpenBotSettings} />`)}</div>`}</div></div>`;