🤖 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
Agent: replace the idle DSH child after 100 task and rule sessions
Marla5c0721aec7c8
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.mdindex 227649f..2e3f771 100644--- a/docs/design/background-tasks-and-proactive.md+++ b/docs/design/background-tasks-and-proactive.md@@ -672,6 +672,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);| Rule edited during a run | The run finishes under its recorded version; the next run uses the new version || Two hosts open the same data dir | On desktop, Electron's `requestSingleInstanceLock()` already prevents it. The headless CLI and Docker build need a data-dir lock before the Scheduler starts (a small addition in 3d) || Prompt injection from a web page during a task or rule | Permission caps (observe is read-only; act is capped at workspace), approvals go to needs-you, and denied acting tools. We can't fully prevent network side effects from shell tools, and the UI says so |+| The DSH child's memory grows with sessions the SDK can't close (one per rule run) | About 0.25–0.45 MB per finished session (measured). After more than 100 task and rule sessions the child is replaced as soon as it is fully idle: no chat turn, run, pending approval, compaction or background job. Nothing is interrupted or recovered || Disk growth (task folders, DSH session JSONL) | Retention: archive done tasks after 30 days, and offer to delete their folders and sessions; sizes are shown in the task detail (Q9) |## 12. Testing strategydiff --git a/docs/development.md b/docs/development.mdindex 6fa2367..a4dd72f 100644--- a/docs/development.md+++ b/docs/development.md@@ -106,6 +106,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令- 插话:代理正在处理时又发来的消息(文字连同图片 / 文件)直接并入这一轮,模型在下一步就看到,回复一起给(先回一句"收到",经出站队列发、10 分钟没发出去就不再发);插话同样先过准入(不在允许名单里的人发的消息不会并入);代理还没接手或正在收尾时照常排队,命令(`/model`、`/reset`…)也排队。网页对话在回复进行中同样可以接着发。- 长命令转后台:命令跑过 30 秒(Windows PowerShell 60 秒)就转成后台任务、不再卡住这一轮,代理先回复"还在跑";命令结束时代理被唤醒、拿到结果,回复作为一条新消息发到同一个会话(网页对话实时显示;微信、飞书和普通回复一样经出站队列发送:id 由代理会话和回合号推出、只发一次,微信发送时才查 24 小时窗口和配额,飞书回复你最近的那条消息,这条消息的 id 存在库里),处理过程里能看到后台命令的步骤,`/status`、中止、看门狗都认这一轮。- 每个会话用自己的模型:同一个代理进程里各会话各走各的模型和接口(每种接口一个 provider,上下文窗口、最大输出按模型),换模型不重启代理进程;补丁里没列出的模型在运行中补上。+- 换新的代理进程:DSH 的 SDK 关不掉会话,后台任务和每次规则运行的会话都留在代理进程里,直到它重启(实测一个跑完、空闲的会话多占约 0.25–0.45 MB)。一个代理进程开过 100 个以上这样的会话后,等它完全空闲(没有聊天回合、没有在跑或收尾的任务和规则、没有等批准的、没有在压缩的会话、进程里没有后台命令)就在后台换一个新的;会话照常接着用,不中断任何东西,用户看不到。故障排查的代理状态里有 `taskSessions` 和 `recycles`;`AMB_DSH_RECYCLE_SESSIONS` 可改门槛。- 重启后的提醒:应用退出或崩溃时还没处理完的消息(每个会话在数据库里留一个处理中的标记,处理完就删),下次启动时在原会话里说一次「上次的消息「…」因为应用重启没有处理完,请重新发送」,不会自动重发。网页对话记进会话历史;微信用存下的 context_token 发送、占用同一份回复配额,超过 24 小时窗口或配额用完时等你在那个会话里发下一条消息时先说;飞书发到原单聊。- 代理的对话接口:代理按 Modelflare 公开目录里该模型支持的接口选——有 Responses API 的(GPT-5.4 及以后、Grok 4.5 及以后、DeepSeek V4、GLM-5、Kimi K3 等)走 `/v1/responses`(推理模型默认推理强度 medium,加密推理随历史回放);没有 Responses、有 Anthropic Messages 的(Claude)走 `/v1/messages`;其余模型、拿不到目录时(离线、中国大陆线路)以及外部端点走 Chat Completions。接口按模型在代理进程里第一次用到它时选定(故障排查的代理状态里显示最近一轮的 `api` 和进程里的模型);`AMB_AGENT_API=chat` 强制全部走 Chat Completions(排查用)。纯对话(非代理)仍走 Chat Completions。安全网:某个模型在 Responses / Messages 上的请求被上游拒绝(HTTP 400/404/405/415/422 或“不支持的参数 / 接口”,限流、余额、权限、上游故障、上下文过长不算)时,这个模型 24 小时内改走 Chat Completions(记在数据目录的 `dsh/api-fallback.json`,日志有警告,代理状态显示 `openai-completions (fallback: 原因)`);这一轮如果还没调用过工具,这个会话换到 Chat 上自动重做一遍(不重启代理进程),用户照常收到回复,已经调用过工具的则照常报错、下一轮起走 Chat。- 内置网关:magpie 以 `--gateway` 模式运行,使用本程序数据目录内独立的 HOME/配置目录;**不读取**你电脑上已有的 Claude/Codex 等订阅凭据,**不改写**任何 agent 配置,关闭自动更新与账户发现。它只供本进程内部调用,界面不再反代它的页面或 `/v1`。diff --git a/docs/development_en.md b/docs/development_en.mdindex 20a8330..a73b8ed 100644--- a/docs/development_en.md+++ b/docs/development_en.md@@ -106,6 +106,7 @@ Inside the container the console listens on 0.0.0.0, so token access is enforced- Steering: a message (text, images, files) sent while the agent is working joins the current turn; the model sees it at its next step and one reply covers both (you get a short "received" first, sent through the outbox and dropped if it cannot go out within 10 minutes). Steered messages pass the same admission check as any other: a message from someone not on the allowlist never joins a turn. Before the agent has taken the previous message, or while the turn is finishing, it queues as before, and so do commands (`/model`, `/reset`…). In the web chat you can keep typing while a reply is in progress.- Long commands move to the background: a command still running after 30 seconds (60 for PowerShell on Windows) becomes a background job instead of blocking the turn, and the agent replies that it is still running. When it ends the agent is woken with the result and its reply arrives as a new message in the same conversation (live in the web chat; on WeChat and Feishu it goes through the outbox like any reply: its id is derived from the agent session and turn so it is sent once, WeChat's 24-hour window and quota are checked at send time, and on Feishu it replies to your latest message, whose id is kept in the database). The activity shows the background command's steps, and `/status`, abort and the watchdog treat that turn like any other.- Each conversation uses its own model: inside one agent process every conversation runs on its own model and API (one provider per API, context window and max output per model). Switching models does not restart the agent process; a model the launch patch did not list is added at runtime.+- Replacing the agent process: the DSH SDK cannot close a session, so every background task's session and every rule run's session stays in the agent process until it restarts (measured: about 0.25–0.45 MB per finished, idle session). Once a process has opened more than 100 of them, it is replaced in the background as soon as it is fully idle: no chat turn, no task or rule run running or settling, no pending approval, no compaction, no background job in the process. Sessions carry on as before, nothing is interrupted and the user sees nothing. The troubleshooting agent status shows `taskSessions` and `recycles`; `AMB_DSH_RECYCLE_SESSIONS` changes the threshold.- Notice after a restart: a message still being handled when the app quit or crashed (each conversation keeps an in-progress marker in the database, removed when the message is done) is reported once in its conversation at the next start — "上次的消息「…」因为应用重启没有处理完,请重新发送" (the last message was not finished because the app restarted; please send it again). Nothing is resent automatically. The web chat gets it in its history; WeChat uses the stored context_token and the same reply quota, and when the 24-hour window or the quota has run out it is said before the reply to your next message in that conversation; Feishu sends it to the original chat.- Agent API: the agent picks the API from what the Modelflare public catalog says the model supports — models with the Responses API (GPT-5.4 and later, Grok 4.5 and later, DeepSeek V4, GLM-5, Kimi K3 and others) use `/v1/responses` (reasoning models default to medium effort; encrypted reasoning is replayed with history); models without Responses but with Anthropic Messages (Claude) use `/v1/messages`; all other models, the case where the catalog is unavailable (offline, the mainland China route) and external endpoints use Chat Completions. The API is chosen per model the first time the agent process uses it (the agent status under Troubleshooting shows the last turn's `api` and the models in the process); `AMB_AGENT_API=chat` forces Chat Completions everywhere (for troubleshooting). Plain chat (non-agent) still uses Chat Completions. Safety net: when the upstream rejects a model's Responses / Messages request (HTTP 400/404/405/415/422 or "unsupported parameter / endpoint"; rate limits, balance, permissions, upstream outages and context overflows do not count), that model switches to Chat Completions for 24 hours (recorded in `dsh/api-fallback.json` in the data directory, with a warning in the log, and the agent status shows `openai-completions (fallback: reason)`). If the turn has not called any tool yet, that conversation redoes it on Chat automatically (without restarting the agent process) and the user still gets a reply; if it already called tools, the error is reported and the next turn uses Chat.- Built-in gateway: magpie runs in `--gateway` mode with its own HOME / config directory inside the app's data directory. It **does not read** existing Claude / Codex subscription credentials on your computer, **does not rewrite** any agent configuration, and has auto-update and account discovery turned off. It is only called from inside the app process; the console no longer proxies its pages or `/v1`.diff --git a/dsh-runtime/plugins/amb-control.mjs b/dsh-runtime/plugins/amb-control.mjsindex 1c3b81a..54b9e26 100644--- a/dsh-runtime/plugins/amb-control.mjs+++ b/dsh-runtime/plugins/amb-control.mjs@@ -13,6 +13,8 @@// model sees it at its next step); refused when the agent is idle// cancel {sessionId} cancel just this session's turn (agent.cancel), its subagents// and the shell jobs the turn started+// idle {} how many agents are busy (not idle, or input queued) and how many+// shell jobs run: the host recycles the child only when both are 0//// Ops this plugin does not know go to the handlers other plugins put on globalThis[Symbol.for('amb.control.handlers')]// (amb-tasks: task-quiet, task-stop), so there is one command channel per child.@@ -232,6 +234,21 @@ export function apply(ctx) {if (delivered.size > 1000) delivered.delete(delivered.values().next().value)return { accepted: true }},+ // the host recycles an idle child (the SDK cannot close a session, so each one stays until the child+ // restarts): is anything still going on in it? Agents that are not idle or have queued input, and+ // running shell jobs, whoever owns them.+ async idle() {+ const list = agents()?.list?.() ?? []+ const registry = jobs()+ const running = new Set()+ for (const a of list) {+ try {+ for (const j of registry?.list?.(String(a.id)) ?? []) if (live(j.status)) running.add(String(j.id))+ } catch {}+ }+ const busy = list.filter((a) => a.status !== 'idle' || pendingIds(a).size > 0).length+ return { agents: list.length, busy, jobs: running.size }+ },async cancel({ sessionId }) {const agent = agents()?.get(String(sessionId))if (!agent) return { running: false }diff --git a/src/agent/host.ts b/src/agent/host.tsindex 04a0973..02cb758 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -176,6 +176,13 @@ export class ResumeFailed extends Error {}/** 设置变了、后台任务又一直在跑:最多等这么久就重启代理进程(任务随后恢复) */export const TASK_RESTART_WAIT_MS = 10 * 60_000;+/**+ * SDK 关不掉会话:每个任务、规则会话都留在子进程里,直到它重启。实测(真实 DSH + mock 模型,一次运行两三次模型请求)+ * 一个跑完、空闲的会话让子进程多占约 0.25–0.45 MB(新进程约 160 MB)。开过这么多个之后,完全空闲时换一个新的子进程:+ * 多出来的最多约 40 MB;最勤的规则(每 15 分钟,一天 96 次)大约一天换一次。AMB_DSH_RECYCLE_SESSIONS 可改。+ */+export const RECYCLE_AFTER_SESSIONS = 100;+/** 换接口重做时交给模型的话(上一条用户消息已经在会话里) */export const RETRY_NOTE = "[系统提示]\n上一条用户消息因模型接口不兼容没有处理,现已换用其它接口。请直接处理上面那条用户消息。";@@ -203,6 +210,8 @@ export interface AgentHostOptions {onWake?: (conversationId: string, sessionId: string) => void;/** 后台任务会话(task-*)和它们子代理的通知:root 是任务会话 id(任务服务据此记步骤、判断这一轮结束) */onTaskEvent?: (root: string, n: SdkNotification) => void;+ /** 宿主这边也空闲(没有在跑或收尾的任务、规则 run,没有等批准的,没有在压缩的会话):开过的会话多了可以换新的子进程 */+ idle?: () => boolean;}export type HostState = "stopped" | "starting" | "running" | "backoff" | "error";@@ -241,7 +250,8 @@ export type HostEvent =| { type: "spawned"; pid: number | undefined }| { type: "initialized"; pid: number | undefined; ms: number }| { type: "failed"; message: string }- | { type: "exit"; pid: number | undefined; code: number | null; signal: string | null };+ /** recycled:空闲时为了放掉开过的会话换的(上面没有在跑的东西,不用恢复) */+ | { type: "exit"; pid: number | undefined; code: number | null; signal: string | null; recycled?: boolean };/** 拿不到 Modelflare 的模型资料时的兜底(上下文窗口、最大输出) */const MODEL_LIMITS: Array<[RegExp, number, number]> = [@@ -620,6 +630,12 @@ export class AgentHost {private taskBusy = new Set<string>();/** 设置变了、等着重启的起点(0 = 没在等) */private staleSince = 0;+ /** 正在问子进程空不空(换新的子进程之前) */+ private recycling = false;+ /** 空闲时换掉的那个子进程(它的退出不用恢复什么) */+ private recycledPid: number | undefined;+ /** 空闲时换过几次子进程(不算重启:用户看不到) */+ recycles = 0;constructor(private o: AgentHostOptions) {}@@ -667,8 +683,10 @@ export class AgentHost {child.once?.("exit", (code: number | null, signal: string | null) => {lines.flush();this.lastExit = { pid, code, signal, at: Date.now() };- log.info("dsh process exited", { bot: this.o.botId, pid, code, signal });- this.emit({ type: "exit", pid, code, signal });+ const recycled = pid !== undefined && pid === this.recycledPid;+ if (recycled) this.recycledPid = undefined;+ log.info("dsh process exited", { bot: this.o.botId, pid, code, signal, ...(recycled ? { recycled } : {}) });+ this.emit({ type: "exit", pid, code, signal, ...(recycled ? { recycled } : {}) });});}@@ -1046,16 +1064,61 @@ exec "$REAL" "$@"/*** 设置或 PowerShell 变了(比如内置 PowerShell 7 刚装好、或者坏了退回)而且空闲:在后台重启子进程,* 下一条消息不用再等启动。正在跑的回合不打断,等下一条消息时由 ensure() 换。+ * 开过的任务、规则会话多了(RECYCLE_AFTER_SESSIONS)也走这里换一个新的,但只在完全空闲时(见 fullyIdle),从不等着打断谁:+ * 没有要恢复的,用户看不到。回合、任务和规则的 run 结束时都来看一次。*/async restartIfStale(): Promise<void> {- if (!this.harness || this.starting || this.active > 0 || this.entering > 0 || this.stopped || this.sig === this.settingsSig() || !this.tasksAllowRestart()) return;+ if (!this.harness || this.starting || this.active > 0 || this.entering > 0 || this.stopped) return;+ if (this.sig !== this.settingsSig()) {+ if (!this.tasksAllowRestart()) return;+ log.info("bot settings or PowerShell changed while idle, restarting dsh in the background", { bot: this.o.botId });+ } else if (this.worn && !this.recycling) {+ this.recycling = true;+ let idle = false;+ try {+ idle = await this.fullyIdle();+ } finally {+ this.recycling = false;+ }+ if (!idle) return;+ log.info("dsh holds many finished task and rule sessions; replacing it while idle", { bot: this.o.botId, sessions: this.taskSessions.size, pid: this.pid });+ this.recycledPid = this.pid;+ this.recycles++;+ } else return;const model = this.model;- log.info("bot settings or PowerShell changed while idle, restarting dsh in the background", { bot: this.o.botId });await this.closeHarness();this.state = "stopped";await this.ensure(model).catch(() => undefined);}+ /** 这个子进程开过的任务、规则会话(含 resume 的)比 RECYCLE_AFTER_SESSIONS 多 */+ private get worn(): boolean {+ const env = Number(process.env.AMB_DSH_RECYCLE_SESSIONS);+ return this.taskSessions.size > (env > 0 ? env : RECYCLE_AFTER_SESSIONS);+ }++ /**+ * 能不能悄悄换掉子进程:这边没有聊天回合(含正在进入的、代理自己醒来的)、没有任务会话在跑一轮,宿主那边也空闲(o.idle:+ * 没有在跑或收尾的 run、没有等批准的、没有在压缩的会话),子进程里每个代理都空着、没有排着的输入、没有在跑的后台命令。+ * 问子进程要一来一回,回来之后再看一遍这边。+ */+ private async fullyIdle(): Promise<boolean> {+ const here = () =>+ !!this.harness &&+ !this.starting &&+ !this.stopped &&+ this.active === 0 &&+ this.entering === 0 &&+ this.turns.size === 0 &&+ this.claimed.size === 0 &&+ this.wakes.size === 0 &&+ this.taskBusy.size === 0 &&+ (this.o.idle?.() ?? true);+ if (!here() || !this.control.connected) return false;+ const r = await this.control.send<{ busy?: number; jobs?: number }>("idle", {}, 5_000).catch(() => undefined);+ return r?.busy === 0 && r?.jobs === 0 && here();+ }+/** 本机上一次成功启动的耗时;没有记录 = 第一次启动(冷启动:杀毒软件逐个扫描运行时文件,可能要几分钟) */private get initRecordFile(): string {return path.join(this.o.dataDir, "dsh", ".init.json");@@ -1680,6 +1743,7 @@ exec "$REAL" "$@"if (this.wakes.get(w.sessionId) === w) this.wakes.delete(w.sessionId);if (this.turns.get(input.conversationId) === turn) this.turns.delete(input.conversationId);this.active--;+ if (this.active === 0) void this.restartIfStale();}}@@ -1772,6 +1836,9 @@ exec "$REAL" "$@"retryInMs: this.state === "error" ? Math.max(0, this.retryAfter - Date.now()) : undefined,startedAt: this.startedAt || undefined,lastExit: this.lastExit,+ // 这个子进程开过的任务、规则会话,和空闲时换过几次(见 RECYCLE_AFTER_SESSIONS)+ taskSessions: this.taskSessions.size,+ recycles: this.recycles,nextStartInMs: this.state === "backoff" ? Math.max(0, this.nextStartAt - Date.now()) : undefined,stderrTail: this.stderrTail.slice(-50),};diff --git a/src/agent/manager.ts b/src/agent/manager.tsindex 0d723b1..82787f0 100644--- a/src/agent/manager.ts+++ b/src/agent/manager.ts@@ -237,18 +237,31 @@ export class AgentManager {apiFallbacks: this.apiFallbacks,onWake: (conv) => this.onWake?.(botId, conv),onTaskEvent: (root, n) => this.tasks?.onEvent(botId, root, n),+ idle: () => this.idle(botId),});- // 代理进程退出(中止宽限期内没停下、设置变化、崩溃、重启、停止):进程里的压缩跟着没了,不再等它;跑着的后台任务记为中断、排恢复+ // 代理进程退出(中止宽限期内没停下、设置变化、崩溃、重启、停止):进程里的压缩跟着没了,不再等它;跑着的后台任务记为中断、排恢复。+ // 空闲时换掉的(recycled)上面什么都没在跑:之后才开始的 run 已经在用新的进程,不能当成被打断h.on((e) => {if (e.type !== "exit") return;this.endCompaction((c) => c.botId === botId);- this.tasks?.onChildExit(botId);+ if (!e.recycled) this.tasks?.onChildExit(botId);});this.hosts.set(botId, h);}return h;}+ /**+ * 换代理进程之前宿主这边的检查(聊天回合由代理宿主自己看):没有在跑或收尾的任务、规则 run,没有等批准的(阻塞的),+ * 没有在等管家判定或原地压缩的会话+ */+ private idle(botId: string): boolean {+ if (this.tasks?.busy(botId)) return false;+ if (this.approvals.pendingAll().some((a) => a.botId === botId && a.blocking)) return false;+ if ([...this.compactDone.values()].some((c) => c.botId === botId)) return false;+ return ![...this.gates.keys()].some((conv) => this.o.store.getConversation(conv)?.botId === botId);+ }+/** PowerShell 等启动参数变了:空闲的代理进程在后台换用新的(正在跑回合的等下一条消息) */async refreshIdle(): Promise<void> {await Promise.all([...this.hosts.values()].map((h) => h.restartIfStale().catch(() => undefined)));@@ -914,6 +927,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)),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/tasks/service.ts b/src/tasks/service.tsindex 9867208..a12df56 100644--- a/src/tasks/service.ts+++ b/src/tasks/service.ts@@ -102,6 +102,8 @@ export interface TaskHost {stop(botId: string, sessionId: string): Promise<void>;/** 会话空闲时还有没有后台命令、子代理在跑;有就由插件在它们结束、会话再次空闲时报 task-settled */quiet(botId: string, sessionId: string): Promise<{ quiet: boolean; jobs?: string[] }>;+ /** 这个机器人的一个 run 结束了:代理进程完全空闲、开过的会话又多了,就换一个新的(host.ts restartIfStale) */+ runEnded?(botId: string): void;}/** DSH 的一条通知(SDK 的 session.event / session.status / subagent.*) */@@ -788,6 +790,7 @@ export class TaskService {log.info("background task run ended", { task: l.taskId, run: l.runId, outcome, ...(error ? { error } : {}) });this.changed(l.taskId);this.pump();+ this.o.host.runEnded?.(l.botId);}private forget(l: Live): void {@@ -1137,6 +1140,11 @@ export class TaskService {return parseSteps(this.store.getRun(runId)?.activity);}+ /** 这个机器人有没有在跑、收尾中的 run(任务的或规则的):有就不换代理进程 */+ busy(botId: string): boolean {+ return [...this.live.values()].some((l) => l.botId === botId) || this.store.listRuns({ botId, states: ["running", "settling"], limit: 1 }).length > 0;+ }+/** 每个机器人正在进行的任务数(侧栏"正在工作") */background(): Record<string, number> {const out: Record<string, number> = {};@@ -1585,6 +1593,7 @@ export class TaskService {log.info("rule run ended", { rule: l.ruleId, run: l.runId, mode: l.mode, outcome, ...(error ? { error } : {}) });this.changed(l.ruleId);this.pump();+ this.o.host.runEnded?.(l.botId);}/**diff --git a/test/agent-manager.unit.test.ts b/test/agent-manager.unit.test.tsindex b1edb21..426cb6f 100644--- a/test/agent-manager.unit.test.ts+++ b/test/agent-manager.unit.test.ts@@ -6,7 +6,7 @@ import path from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Store } from "../src/store/db.js";import { AgentManager } from "../src/agent/manager.js";-import { TurnStopped, type TurnInput } from "../src/agent/host.js";+import { RECYCLE_AFTER_SESSIONS, TurnStopped, type TurnInput } from "../src/agent/host.js";import type { MediaModel, MediaService } from "../src/agent/media.js";import { STEWARD_SYSTEM } from "../src/agent/steward.js";@@ -295,3 +295,91 @@ describe("idle watchdog: long tool calls are work, a silent turn is still stoppe}});});++describe("recycling the agent process: only after more than RECYCLE_AFTER_SESSIONS task and rule sessions, and only when nothing at all is going on", () => {+ it("each thing that is still going on holds it; the recycled child's exit recovers nothing, any other exit still does", async () => {+ const store = new Store(":memory:");+ store.createBot({ id: "b", name: "b" });+ const mgr = new AgentManager({ store, dataDir: dir, runtimeDir: "/rt", upstream: () => ({ baseUrl: "", apiKey: "" }), enabled: true });+ let runs = false;+ const exits: string[] = [];+ mgr.tasks = { busy: () => runs, onChildExit: (bot: string) => void exits.push(bot) } as any;+ const host = mgr.host("b") as any;+ const closed: string[] = [];+ const children: EventEmitter[] = [];+ const fakeHarness = (id: string, pid: number) => {+ const child = Object.assign(new EventEmitter(), { pid });+ children.push(child);+ host.watchChild(child);+ return { id, close: async () => void closed.push(id), client: { child } };+ };+ let spawned = 0;+ host.spawn = async () => {+ spawned++;+ return (host.harness = fakeHarness(`new${spawned}`, 200 + spawned));+ };+ Object.assign(host, { harness: fakeHarness("old", 101), model: "m", state: "running" });+ host.sig = host.settingsSig();+ let reply: { busy: number; jobs: number } | Error = { busy: 0, jobs: 0 };+ let connected = true;+ const asked: string[] = [];+ host.control = {+ get connected() {+ return connected;+ },+ send: async (op: string) => {+ asked.push(op);+ if (reply instanceof Error) throw reply;+ return reply;+ },+ close() {},+ reset() {},+ };+ const tryIt = async () => {+ await host.restartIfStale();+ return closed.length;+ };+ for (let i = 0; i < RECYCLE_AFTER_SESSIONS; i++) host.taskSessions.add(`rule-r-${i}`);+ // 不多于门槛:不问、不换+ expect(await tryIt()).toBe(0);+ expect(asked).toEqual([]);+ host.taskSessions.add("task-t_1");+ // 子进程里还有事:有代理没空着(或有排着的输入)、有后台命令在跑、问不到+ for (const r of [{ busy: 1, jobs: 0 }, { busy: 0, jobs: 1 }, new Error("timeout")]) {+ reply = r;+ expect(await tryIt()).toBe(0);+ }+ reply = { busy: 0, jobs: 0 };+ // 宿主这边还有事:任务或规则的 run 在跑或收尾、有等批准的、有会话在原地压缩、有聊天回合、有任务会话在跑一轮、指令通道不通+ runs = true;+ expect(await tryIt()).toBe(0);+ runs = false;+ const a = mgr.approvals.create({ kind: "approval", botId: "b", conversationId: "b:web:console", sessionId: "s", tool: "bash", detail: "rm -rf x", reason: "" });+ expect(await tryIt()).toBe(0);+ mgr.approvals.cancel(a.id);+ (mgr as any).compactDone.set("S1", { botId: "b", conv: "b:web:console", resolve: () => undefined });+ expect(await tryIt()).toBe(0);+ (mgr as any).compactDone.clear();+ for (const k of ["active", "entering"]) {+ host[k] = 1;+ expect(await tryIt()).toBe(0);+ host[k] = 0;+ }+ host.taskBusy.add("task-t_1");+ expect(await tryIt()).toBe(0);+ host.taskBusy.clear();+ connected = false;+ expect(await tryIt()).toBe(0);+ connected = true;+ expect(exits).toEqual([]);+ // 全都空着:换一个新的子进程,重新计数;不算重启+ expect(await tryIt()).toBe(1);+ expect([closed, spawned, host.recycles, host.restarts, host.taskSessions.size, host.harness.id]).toEqual([["old"], 1, 1, 0, 0, "new1"]);+ // 换掉的那个退出:它上面什么都没在跑,不恢复(之后才开始的 run 已经在用新进程);别的退出照旧恢复+ children[0].emit("exit", 0, null);+ expect(exits).toEqual([]);+ children[1].emit("exit", null, "SIGKILL");+ expect(exits).toEqual(["b"]);+ store.close();+ });+});diff --git a/test/dsh-recycle.integration.test.ts b/test/dsh-recycle.integration.test.tsnew file mode 100644index 0000000..c11683a--- /dev/null+++ b/test/dsh-recycle.integration.test.ts@@ -0,0 +1,152 @@+/**+ * 空闲时换掉开过很多会话的代理进程(SDK 关不掉会话,每次规则运行都开一个新的):真实 DSH 子进程 + 脚本化的模型 + mock iLink。+ * 这里把门槛调成 3 个会话。开过的会话多了、完全空闲时换一个新的子进程:规则的运行都正常结束(没有被打断、没有重跑),+ * 不发任何消息,聊天照常;聊天会话还有后台命令在跑时不换,命令结束、醒来的那一轮回复发出去之后才换。+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import http from "node:http";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { App } from "../src/app.js";+import { loadConfig } from "../src/config.js";+import { locateDshRuntime } from "../src/agent/host.js";+import { findAppRoot } from "../src/magpie/supervisor.js";+import { listen, mockIlink } from "./helpers.js";++const runtime = locateDshRuntime(findAppRoot());+const hasBwrap = fs.existsSync("/usr/bin/bwrap");++async function body(req: http.IncomingMessage): Promise<any> {+ const chunks: Buffer[] = [];+ for await (const c of req) chunks.push(c as Buffer);+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");+}+const textOf = (c: any): string => (typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => (typeof p === "string" ? p : (p?.text ?? ""))).join("") : "");+type Step = { tool?: { name: string; args: any }; text?: string };++describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("recycling the idle agent process (real DSH)", () => {+ const OWNER = "[email protected]";+ const CONV = `default:weixin:${OWNER}`;+ let app: App;+ let dataDir: string;+ let llm: Awaited<ReturnType<typeof listen>>;+ let ilink: Awaited<ReturnType<typeof mockIlink>>;+ const env = process.env.AMB_DSH_RECYCLE_SESSIONS;++ /** 规则会话:报一句「没什么要说的」就结束;聊天:PING → PONG,JOB → 放一个后台命令,醒来时说 JOB-DONE */+ function plan(messages: any[], tools: string[]): Step {+ let last = -1;+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user" && !/^Current runtime context/.test(textOf(messages[i].content))) { last = i; break; }+ const user = textOf(messages[last]?.content);+ const done = messages.slice(last + 1).filter((m) => m.role === "tool").length;+ if (tools.includes("task_report")) return done ? { text: "已报告" } : { tool: { name: "task_report", args: { state: "done", summary: "X 还是 ¥259" } } };+ if (/background job/.test(user)) return { text: "JOB-DONE" };+ if (/JOB/.test(user)) return done ? { text: "JOB-STARTED" } : { tool: { name: "bash", args: { description: "run", command: "sleep 8 && echo job-done", run_in_background: true } } };+ const p = /PING (\w+)/.exec(user);+ return { text: p ? `PONG-${p[1]}` : "好的" };+ }++ beforeAll(async () => {+ process.env.AMB_DSH_RECYCLE_SESSIONS = "3";+ llm = await listen(async (req, res) => {+ const url = req.url?.split("?")[0] ?? "";+ if (url.endsWith("/models")) return void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ object: "list", data: [{ id: "mock-agent", object: "model" }] }));+ const b = await body(req);+ const tools = (b.tools ?? []).map((t: any) => t.function?.name ?? t.name);+ const step: Step = b.tools ? plan(b.messages ?? [], tools) : { text: "标题" };+ if (!b.stream) return void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ choices: [{ message: { role: "assistant", content: step.text ?? "" }, finish_reason: "stop" }] }));+ res.writeHead(200, { "content-type": "text/event-stream" });+ const send = (o: any) => res.write(`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", model: b.model, ...o })}\n\n`);+ if (step.tool) {+ send({ choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_" + Math.random().toString(36).slice(2, 8), type: "function", function: { name: step.tool.name, arguments: JSON.stringify(step.tool.args) } }] } }] });+ send({ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] });+ } else {+ send({ choices: [{ index: 0, delta: { role: "assistant", content: step.text } }] });+ send({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] });+ }+ send({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } });+ res.end("data: [DONE]\n\n");+ });+ ilink = await mockIlink();+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-recycle-"));+ app = new App(loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: ilink.url, AMB_DEFAULT_MODEL: "mock-agent", AMB_AGENT_PREWARM: "0" } }), {+ printQrToTerminal: false,+ weixinPollTimeoutMs: 1000,+ deliveryLimits: { dailyCap: { weixin: 1000 }, coalesceMs: 0 },+ });+ app.store.createBot({ id: "default", name: "小蓝", weixinEnabled: true, settings: { avatar: "blue", quietHours: { enabled: false, from: "22:00", to: "08:00" } } as any });+ app.store.saveWeixinAccount({ botId: "default", botToken: "tok", ilinkBotId: "[email protected]", baseUrl: ilink.url, ownerUserId: OWNER });+ await app.start();+ }, 60_000);++ afterAll(async () => {+ if (env === undefined) delete process.env.AMB_DSH_RECYCLE_SESSIONS;+ else process.env.AMB_DSH_RECYCLE_SESSIONS = env;+ await app?.stop();+ await llm?.close();+ await ilink?.close();+ fs.rmSync(dataDir, { recursive: true, force: true });+ });++ const waitFor = async (fn: () => boolean | Promise<boolean>, ms = 60_000) => {+ for (const end = Date.now() + ms; Date.now() < end; await new Promise((r) => setTimeout(r, 100))) if (await fn()) return;+ throw new Error("waitFor: timeout");+ };+ const sentTo = (text = "") => ilink.state.sent.filter((s) => s.to === OWNER && s.text.startsWith(text));+ const host = () => app.agent.host("default");+ let ruleId = "";+ /** 立即运行一次规则,等它跑完 */+ const runOnce = async () => {+ const before = app.store.ruleRuns(ruleId, { limit: 100 }).length;+ expect(app.tasks.runRuleNow(ruleId)).toEqual({});+ await waitFor(() => {+ const runs = app.store.ruleRuns(ruleId, { limit: 100 });+ return runs.length > before && runs[0].state === "ended";+ });+ };+ /** 等一会儿:要换的话这时已经换了 */+ const settle = () => new Promise((r) => setTimeout(r, 1500));++ it("after more than 3 rule sessions the idle child is replaced: every run ends done, nothing is sent, chat carries on", async () => {+ ilink.push(OWNER, "PING first");+ await waitFor(() => sentTo("PONG-first").length === 1);+ ruleId = app.tasks.createRule({ botId: "default", conversationId: CONV, title: "看 X 价格", instruction: "看看 X 的价格", schedule: { kind: "once", at: Date.now() + 7 * 86400_000, tz: "UTC" } }).rule!.id;+ const pid = host().pid;+ for (let i = 0; i < 3; i++) await runOnce();+ await settle();+ // 3 个还不到门槛+ expect([host().pid, host().recycles]).toEqual([pid, 0]);+ await runOnce();+ await waitFor(() => host().recycles === 1 && host().state === "running" && host().pid !== pid);+ expect(host().restarts).toBe(0);+ // 看不出来:每次运行都正常结束,没有被打断、重跑或跳过的;什么都没发给用户+ expect(app.store.ruleRuns(ruleId, { limit: 100 }).map((r) => [r.cause, r.outcome])).toEqual(Array(4).fill(["manual", "done"]));+ expect(sentTo()).toHaveLength(1);+ // 聊天照常(在新的进程里接着原来的会话),没有任何重启说明+ ilink.push(OWNER, "PING after");+ await waitFor(() => sentTo("PONG-after").length === 1);+ expect(sentTo().map((s) => s.text)).toEqual(["PONG-first", "PONG-after"]);+ // 新进程里重新计数+ await runOnce();+ await settle();+ expect(host().recycles).toBe(1);+ expect(host().diagnostics()).toMatchObject({ taskSessions: 1, recycles: 1 });+ }, 120_000);++ it("a chat's background job holds it: no recycle while the job runs; after the job's wake-up reply it goes", async () => {+ const pid = host().pid;+ ilink.push(OWNER, "JOB");+ await waitFor(() => sentTo("JOB-STARTED").length === 1);+ // 门槛早过了(新进程里第 2–5 个会话),但聊天会话的后台命令还在跑+ for (let i = 0; i < 4; i++) await runOnce();+ await settle();+ expect([host().pid, host().recycles]).toEqual([pid, 1]);+ // 命令结束:代理醒来、回复发出去,之后才换+ await waitFor(() => sentTo("JOB-DONE").length === 1, 30_000);+ await waitFor(() => host().recycles === 2 && host().state === "running" && host().pid !== pid);+ expect(host().restarts).toBe(0);+ expect(app.store.ruleRuns(ruleId, { limit: 100 }).every((r) => r.outcome === "done")).toBe(true);+ expect(sentTo().map((s) => s.text)).toEqual(["PONG-first", "PONG-after", "JOB-STARTED", "JOB-DONE"]);+ }, 120_000);+});diff --git a/test/tasks.unit.test.ts b/test/tasks.unit.test.tsindex 5739830..878fd32 100644--- a/test/tasks.unit.test.ts+++ b/test/tasks.unit.test.ts@@ -814,6 +814,21 @@ describe("TaskService(假宿主)", () => {expect(svc.get(t.id)!.stage.key).toBe("needs-you/approval");});+ it("run 结束时告诉宿主(代理进程完全空闲、开过的会话多了就换新的);在跑、收尾中的 run 算忙", async () => {+ const ended: string[] = [];+ (host as TaskHost).runEnded = (botId) => void ended.push(botId);+ expect(svc.busy("b")).toBe(false);+ const t = start();+ await flush();+ expect(svc.busy("b")).toBe(true);+ host.quiets.push({ quiet: false, jobs: ["j1"] });+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));+ expect(store.listRuns({ taskId: t.id })[0].state).toBe("settling");+ expect([svc.busy("b"), ended]).toEqual([true, []]);+ svc.settled({ sessionId: t.sessionId });+ expect([svc.busy("b"), svc.busy("other"), ended]).toEqual([false, false, ["b"]]);+ });+it("每个机器人最多 10 个进行中的任务", async () => {host.settingsValue = normalizeSettings({ taskSlots: 8 });for (let i = 0; i < 10; i++) start(`T${i}`);