Skip to content

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

Merge origin/master (P2: allowlist + outbox) into feat/p1-live-control

Marla735bbbc5a61d
diff --cc docs/development.md
index 9cb832d,c2d5c9b..95cd440
--- a/docs/development.md
+++ b/docs/development.md
@@@ -96,12 -96,9 +96,12 @@@ docker exec amb cat /data/ui-token
- 设置 → Modelflare:账户、余额与充值、余额提醒、用量、通知、邀请;连接状态(只显示 Key 尾号);未登录时可更换密钥或断开(机器人与会话保留,断开后回到首次连接页);默认模型、刷新模型列表。
- 对话中输入框右侧的模型按钮可为当前会话切换模型(也可设为机器人默认);`/model`、`/reset`、`/new`、`/status`、`/stop`、`/help` 照常可用。
- 处理过程:代理回合的每一步(模型请求及用时与 tokens、工具调用及参数与输出、重试、子代理)折叠在回复上方的"用时"一行里,点开查看;微信 / 飞书会话在信息面板 → 最近会话里看,正在处理的那一轮实时显示并可中止。
-- 卡住的消息:`/stop`(任何渠道)或信息面板里的「中止」立即结束正在处理的回合;代理 10 分钟没有任何进展(模型不回、工具不动、只在重试;等你批准或回答不算)会自动中止,单回合最长 30 分钟(`AMB_AGENT_IDLE_TIMEOUT_MS`、`AMB_AGENT_TURN_TIMEOUT_MS` 可调)。DSH 没有中断单个回合的接口,中止时会重启该机器人的代理进程。前一条还在处理时发来的新消息会先收到一句提示;`/status` 显示它走到了哪一步、多久没有进展。网页对话里切到别的机器人或刷新窗口不会打断正在处理的消息,回来时接着显示(你的消息、到目前为止的回复和处理过程);停止按钮在排队、代理启动中、等你批准时也能用,纯对话也一样。
+- 卡住的消息:`/stop`(任何渠道)或信息面板里的「中止」立即结束正在处理的回合;代理 10 分钟没有任何进展(模型不回、工具不动、只在重试;等你批准或回答不算)会自动中止,单回合最长 30 分钟(`AMB_AGENT_IDLE_TIMEOUT_MS`、`AMB_AGENT_TURN_TIMEOUT_MS` 可调)。中止只停这个会话的回合(经代理进程里的 amb-control 插件取消它),同一机器人的其它会话照常进行;10 秒内没停下(`AMB_STOP_GRACE_MS`)才重启代理进程。`/status` 显示它走到了哪一步、多久没有进展。网页对话里切到别的机器人或刷新窗口不会打断正在处理的消息,回来时接着显示(你的消息、到目前为止的回复和处理过程);停止按钮在排队、代理启动中、等你批准时也能用,纯对话也一样。
- - 插话:代理正在处理时又发来的消息(文字连同图片 / 文件)直接并入这一轮,模型在下一步就看到,回复一起给(先回一句"收到");代理还没接手或正在收尾时照常排队,命令(`/model`、`/reset`…)也排队。网页对话在回复进行中同样可以接着发。
- - 长命令转后台:命令跑过 30 秒(Windows PowerShell 60 秒)就转成后台任务、不再卡住这一轮,代理先回复"还在跑";命令结束时代理被唤醒、拿到结果,回复作为一条新消息发到同一个会话(网页对话实时显示,飞书回复你最近的那条消息,微信占一条回复配额),处理过程里能看到后台命令的步骤,`/status`、中止、看门狗都认这一轮。
++- 插话:代理正在处理时又发来的消息(文字连同图片 / 文件)直接并入这一轮,模型在下一步就看到,回复一起给(先回一句"收到",经出站队列发、10 分钟没发出去就不再发);插话同样先过准入(不在允许名单里的人发的消息不会并入);代理还没接手或正在收尾时照常排队,命令(`/model`、`/reset`…)也排队。网页对话在回复进行中同样可以接着发。
++- 长命令转后台:命令跑过 30 秒(Windows PowerShell 60 秒)就转成后台任务、不再卡住这一轮,代理先回复"还在跑";命令结束时代理被唤醒、拿到结果,回复作为一条新消息发到同一个会话(网页对话实时显示;微信、飞书和普通回复一样经出站队列发送:id 由代理会话和回合号推出、只发一次,微信发送时才查 24 小时窗口和配额,飞书回复你最近的那条消息,这条消息的 id 存在库里),处理过程里能看到后台命令的步骤,`/status`、中止、看门狗都认这一轮。
+- 每个会话用自己的模型:同一个代理进程里各会话各走各的模型和接口(每种接口一个 provider,上下文窗口、最大输出按模型),换模型不重启代理进程;补丁里没列出的模型在运行中补上。
- 重启后的提醒:应用退出或崩溃时还没处理完的消息(每个会话在数据库里留一个处理中的标记,处理完就删),下次启动时在原会话里说一次「上次的消息「…」因为应用重启没有处理完,请重新发送」,不会自动重发。网页对话记进会话历史;微信用存下的 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。
+- 代理的对话接口:代理按 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`。
- API Key 只保存在内置网关的隔离配置中,不经过命令行参数、不写日志,前端只拿到尾号。
- 开发/测试:设置 `AMB_MAGPIE_BASE_URL` 可直接使用一个 OpenAI 兼容端点(不启动内置网关,界面视为已连接,账户功能不可用);`AMB_MODELFLARE_BASE_URL` 可把 Modelflare 基址指向本地 mock,`AMB_MODELFLARE_ISSUER` 把登录与账户接口指向本地 mock。
diff --cc docs/development_en.md
index dd028a5,1fac7bf..46e4acb
--- a/docs/development_en.md
+++ b/docs/development_en.md
@@@ -96,12 -96,9 +96,12 @@@ Inside the container the console listen
- Settings → Modelflare: account, balance and top-up, balance reminder, usage, notifications, invites; connection status (only the key's last characters are shown); when not signed in you can replace the key or disconnect (bots and sessions are kept; disconnecting returns to the first-connection screen); default model, refresh model list.
- The model button to the right of the composer switches the model for the current session (or sets it as the bot default); `/model`, `/reset`, `/new`, `/status`, `/stop` and `/help` all work.
- Activity: every step of an agent turn (model requests with timing and tokens, tool calls with arguments and output, retries, sub-agents) is folded into the "time" line above the reply; click to expand. For WeChat / Feishu sessions, see info panel → Recent sessions, where the turn in progress is shown live and can be aborted.
-- Stuck messages: `/stop` (any channel) or "Abort" in the info panel ends the current turn immediately. A turn with no progress for 10 minutes (no model reply, no tool activity, only retries; waiting for your approval or answer does not count) is aborted automatically, and a single turn is capped at 30 minutes (`AMB_AGENT_IDLE_TIMEOUT_MS`, `AMB_AGENT_TURN_TIMEOUT_MS`). DSH has no API to interrupt a single turn, so aborting restarts that bot's agent process. A new message that arrives while the previous one is still being handled gets a short notice first; `/status` shows which step it reached and how long since the last progress. In the web chat, switching to another bot or reloading the window does not interrupt a message in progress; when you return it picks up where it was (your message, the reply so far and the activity). The stop button also works while queued, while the agent is starting and while waiting for approval, and for plain chat too.
+- Stuck messages: `/stop` (any channel) or "Abort" in the info panel ends the current turn immediately. A turn with no progress for 10 minutes (no model reply, no tool activity, only retries; waiting for your approval or answer does not count) is aborted automatically, and a single turn is capped at 30 minutes (`AMB_AGENT_IDLE_TIMEOUT_MS`, `AMB_AGENT_TURN_TIMEOUT_MS`). Aborting stops only that conversation's turn (the amb-control plugin inside the agent process cancels it); the bot's other conversations keep running. Only if it has not stopped within 10 seconds (`AMB_STOP_GRACE_MS`) is the agent process restarted. `/status` shows which step it reached and how long since the last progress. In the web chat, switching to another bot or reloading the window does not interrupt a message in progress; when you return it picks up where it was (your message, the reply so far and the activity). The stop button also works while queued, while the agent is starting and while waiting for approval, and for plain chat too.
- - 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). 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, as a reply to your latest message on Feishu, using one WeChat reply from the quota). The activity shows the background command's steps, and `/status`, abort and the watchdog treat that turn like any other.
++- 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.
- 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 when the agent process starts (shown as `api` in the agent status under Troubleshooting); `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, the agent redoes it on Chat automatically and the user still gets a reply; if it already called tools, the error is reported and the next turn uses 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`.
- The API key is stored only in the gateway's isolated configuration — never on a command line, never in logs — and the front end only receives its last characters.
- Development / testing: `AMB_MAGPIE_BASE_URL` points the app at any OpenAI-compatible endpoint (the gateway is not started, the UI treats itself as connected, and account features are unavailable); `AMB_MODELFLARE_BASE_URL` points the Modelflare base URL at a local mock, and `AMB_MODELFLARE_ISSUER` points sign-in and account APIs at a local mock.
diff --cc src/agent/host.ts
index f710f4a,68bdb0f..48bab93
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@@ -470,78 -358,6 +470,80 @@@ export function callDetail(name: string
return s === "{}" ? "" : s.slice(0, 300);
}
+/** 一个进行中的回合(插话、中止用) */
+interface HostTurn {
+ sessionId: string;
+ /** 这一轮的模型(插话带的图片只给能看图的模型) */
+ model: string;
+ /** 代理收下了这条消息(收到第一条会话事件):此后插话、中止才落得到这一轮上 */
+ accepted: Promise<void>;
+ /** run 已经结束(代理空闲了),正在收尾 */
+ finishing: boolean;
+ stopping: boolean;
+ /** 跟踪的是代理自己醒来的一轮(不是宿主发的消息) */
+ wake?: boolean;
+ /** 宿主发起的这一轮已经空闲过一次:之后再忙起来就是代理自己醒了 */
+ idleSeen?: boolean;
+}
+
+/** 一轮的结果 */
+export interface TurnResult {
+ text: string;
+ sessionId: string;
+ files: string[];
+ usage: TurnUsage;
+}
+
+/** 代理自己醒来的一轮:先缓存通知,有人跟踪时交给它;代理空闲时结束 */
+class Wake {
+ buffer: SdkNotification[] = [];
+ listener: ((n: SdkNotification) => void) | undefined;
+ ended = false;
+ /** 已经有人在跟踪 */
+ taken = false;
+ readonly done: Promise<void>;
+ private settle!: (err?: Error) => void;
+ constructor(
+ readonly conversationId: string,
+ readonly sessionId: string,
++ /** 这一轮的回合号(会话上一轮 + 1) */
++ readonly turn: number,
+ ) {
+ this.done = new Promise<void>((resolve, reject) => (this.settle = (err) => (err ? reject(err) : resolve())));
+ this.done.catch(() => undefined);
+ }
+ push(n: SdkNotification): void {
+ if (this.listener) this.listener(n);
+ else if (this.buffer.length < 5000) this.buffer.push(n);
+ }
+ attach(fn: (n: SdkNotification) => void): void {
+ this.listener = fn;
+ for (const n of this.buffer.splice(0)) fn(n);
+ }
+ end(err?: Error): void {
+ if (this.ended) return;
+ this.ended = true;
+ this.settle(err);
+ }
+}
+
+/** 中止信号的原因(manager 用 TurnStopped 中止;别的原因按用户中止算) */
+function stopReason(sig: AbortSignal): TurnStopped {
+ return sig.reason instanceof TurnStopped ? sig.reason : new TurnStopped("user", 0);
+}
+
+/** 一条 assistant/message 是不是完整的回答(不带工具调用、没被打断):是就返回它的文字 */
+export function answerText(data: any): string {
+ if (data?.interrupted) return "";
+ const content: any[] = Array.isArray(data?.message?.content) ? data.message.content : [];
+ if (content.some((b) => b?.type === "tool-call")) return "";
+ return content
+ .filter((b) => b?.type === "text")
+ .map((b) => String(b.text ?? ""))
+ .join("")
+ .trim();
+}
+
/**
* 每个 bot 一个 DSH 子进程(懒启动):DSH_HOME = <data>/dsh/<botId>,工作区 = <data>/workspaces/<botId>,
* workspace-write 沙箱;模型请求经本地 bridge 代理到 magpie(子进程拿不到真实密钥)。
@@@ -551,29 -367,14 +553,31 @@@ export class AgentHost
state: HostState = "stopped";
lastError = "";
restarts = 0;
+ /** 最近一轮用的模型(子进程启动时是启动用的模型) */
model = "";
- /** 当前子进程跟模型说话用的接口 */
+ /** 最近一轮跟模型说话用的接口 */
api: AgentApi | "" = "";
- /** 当前子进程因为回退才走 Chat Completions:回退记录(状态里显示原因) */
+ /** 最近一轮因为回退才走 Chat Completions:回退记录(状态里显示原因) */
fallback: ApiFallback | undefined;
private ownFallbacks: ApiFallbacks | undefined;
- /** 当前子进程补丁里写的上下文窗口与最大输出 */
- private limits: { window: number; maxTokens: number } | undefined;
+ /** 宿主 → 子进程的指令通道(amb-control 插件) */
+ readonly control = new ControlChannel();
+ /** 模型 → 路线(当前子进程内有效,换进程时重新查模型资料) */
+ private routes = new Map<string, Promise<ModelRoute>>();
+ /** 用过的模型:重新拉起子进程时都写进补丁 */
+ private known = new Set<string>();
+ /** 当前子进程已经能用的 provider/model(补丁里的,加上运行中补上的) */
+ private childRoutes = new Map<string, ModelRoute>();
+ /** 当前子进程启动时的默认路线(会话没选模型时用它) */
+ private initRoute: ModelRoute | undefined;
+ /** 会话 → 进行中的回合(插话、中止用) */
+ private turns = new Map<string, HostTurn>();
+ /** DSH session → 代理自己醒来的一轮 */
+ private wakes = new Map<string, Wake>();
+ /** 正在把消息交给代理的会话(还没登记成回合) */
+ private claimed = new Set<string>();
++ /** DSH session → 最近的回合号 */
++ private lastTurn = new Map<string, number>();
private harness: SdkHarness | undefined;
private starting: Promise<SdkHarness> | undefined;
private opened = new Set<string>();
@@@ -1380,174 -1126,9 +1384,183 @@@ exec "$REAL" "$@
}
throw e;
} finally {
- clearTimeout(timer);
- unlisten();
+ turn.finishing = true;
offRejection();
+ if (this.turns.get(input.conversationId) === turn) this.turns.delete(input.conversationId);
+ this.active--;
+ }
+ }
+
+ /**
+ * 一轮的事件处理:工具调用(审批提示用)、交付文件、用量、模型的完整回答、出错原因,再转给观察者(活动记录、看门狗)。
+ * accept:第一条本会话事件到达时调用(代理收下了消息)。
+ */
+ private tracker(sessionId: string, route: ModelRoute, observer: TurnObserver | undefined, accept?: () => void) {
+ const st = {
+ toolCalls: 0,
+ presented: [] as string[],
+ /** 这一轮里模型的每个完整回答(不带工具调用的回复):插进来的消息让回合多答了一次时,几次回答都交给用户 */
+ answers: [] as string[],
+ usage: { tokens: 0, window: route.limits.window, maxTokens: route.limits.maxTokens } as TurnUsage,
+ turnError: undefined as string | undefined,
+ };
+ const onNotification = (n: SdkNotification) => {
+ if (process.env.AMB_DSH_TRACE) fs.appendFileSync(process.env.AMB_DSH_TRACE, JSON.stringify(n).slice(0, 2000) + "\n");
+ if (n.method === "subagent.started" || n.method === "subagent.finished") return observer?.onEvent?.(n.method.replace(".", "/"), n.params, Date.now());
+ if (n.method !== "session.event") return;
+ // 子代理会话的事件(只送来本会话和它的子代理的通知):不进本回合的用量和步骤,只说明子代理还在干活
+ if (n.params?.sessionId !== sessionId) return observer?.onEvent?.("subagent/event", { sessionId: n.params?.sessionId, event: n.params?.event }, Number(n.params?.event?.time) || Date.now());
+ // 第一条通知就是代理收下这条消息的回执:此后才能插话、中止
+ accept?.();
+ const ev = n.params.event;
+ const data = ev?.data ?? {};
+ if (ev?.type === "tool/call") {
+ st.toolCalls++;
+ this.calls.set(String(data.callId), { name: String(data.name), args: String(data.arguments ?? ""), at: Date.now() });
+ if (this.calls.size > 500) this.calls.delete(this.calls.keys().next().value!);
+ if (data.name === "present") st.presented.push(...presentPaths(String(data.arguments ?? "")));
+ observer?.onProgress?.(`🔧 ${summarizeCall(String(data.name), String(data.arguments ?? "")).split(this.workspace + "/").join("")}`);
+ }
+ if (ev?.type === "tool/result") {
+ // Windows:PowerShell 本身拉不起来(被杀毒软件删了、被策略拦了…)时退回下一个,不让代理一直用一个起不来的 shell(其他平台上探测器不管)
+ const msg = data?.message ?? {};
+ const call = this.calls.get(String(msg.toolCallId ?? ""));
+ if (call && /^(pwsh|powershell)$/i.test(call.name)) pwshProbe.observeToolResult(this.pwshPath, contentText(msg.content));
+ }
+ if (ev?.type === "request/context" && Number(data?.contextWindow) > 0) st.usage.window = Number(data.contextWindow);
+ if (ev?.type === "assistant/message") {
+ if (data?.usage) {
+ const u = data.usage;
+ const t = Number(u.totalTokens) || (Number(u.inputTokens) || 0) + (Number(u.outputTokens) || 0);
+ if (t > 0) st.usage.tokens = t;
+ }
+ const answer = answerText(data);
+ if (answer) st.answers.push(answer);
+ }
+ if (ev?.type === "turn/end" && data?.reason?.kind === "error") st.turnError = String(data.reason.error?.message ?? "unknown error");
+ observer?.onEvent?.(String(ev?.type), data, Number(ev?.time) || Date.now());
+ };
+ return { st, onNotification };
+ }
+
+ /**
+ * 等一轮结束;中止(/stop、看门狗、单回合上限)时只中止这个会话(agent.cancel),宽限期内没停下才重启子进程。
+ * 中止了就抛 TurnStopped(restarted 说明有没有重启)。
+ */
+ private async awaitTurn<T>(turn: HostTurn, run: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
+ // 宽限期内没停下、子进程被关掉时,run 随后以"runtime closed"失败,已经没人等它
+ run.catch(() => undefined);
+ const timeoutMs = this.o.turnTimeoutMs ?? 30 * 60_000;
+ let stopping: Promise<TurnStopped> | undefined;
+ let wake!: () => void;
+ const stopRequested = new Promise<void>((r) => (wake = r));
+ const stop = (why: TurnStopped) => {
+ if (stopping) return;
+ turn.stopping = true;
+ stopping = this.stopSession(turn, why, run);
+ wake();
+ };
+ const timer = setTimeout(() => stop(new TurnStopped("timeout", timeoutMs)), timeoutMs);
+ const onAbort = () => stop(stopReason(signal!));
+ if (signal?.aborted) onAbort();
+ else signal?.addEventListener("abort", onAbort, { once: true });
+ try {
+ const first = await Promise.race([run.then((r) => ({ r }), (e: unknown) => ({ e })), stopRequested.then(() => undefined)]);
+ turn.finishing = true;
+ if (stopping) throw await stopping;
+ if (!first) throw new Error("agent turn ended without a result");
+ if ("e" in first) throw first.e;
+ return first.r;
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", onAbort);
+ }
+ }
+
+ /**
+ * 所有通知都先经过这里(同步,按到达顺序):认出代理自己醒来的一轮(后台命令结束时 DSH 唤醒空闲的代理),
+ * 把这一轮的事件交给跟踪它的人。宿主发起的一轮在它第一次空闲之前不算。
+ */
+ private tap(n: SdkNotification): void {
+ for (const w of this.wakes.values()) if (!w.ended && this.relates(n, w.sessionId)) w.push(n);
++ // 每个会话最近的回合号(代理自己醒来的那一轮是下一个)
++ const ev = n.method === "session.event" ? n.params?.event : undefined;
++ if ((ev?.type === "turn/start" || ev?.type === "turn/end") && Number(ev.data?.turn) > 0) this.lastTurn.set(String(n.params.sessionId), Number(ev.data.turn));
+ if (n.method !== "session.status") return;
+ const sid = String(n.params?.sessionId ?? "");
+ const own = [...this.turns.values()].find((t) => t.sessionId === sid && !t.wake);
+ if (n.params?.status === "idle") {
+ if (own) own.idleSeen = true;
+ this.wakes.get(sid)?.end();
+ return;
+ }
+ if (n.params?.status !== "running" || (own && !own.idleSeen)) return;
+ const prev = this.wakes.get(sid);
+ if (prev && !prev.ended) return;
+ const conv = this.o.store.conversationForSession(sid);
+ // 只跟踪会话自己的 DSH session(不是子代理、不是归档了的旧段)
+ if (!conv || this.o.store.getAgentSession(conv) !== sid || this.claimed.has(conv)) return;
- const w = new Wake(conv, sid);
++ const w = new Wake(conv, sid, (this.lastTurn.get(sid) ?? 0) + 1);
+ this.wakes.set(sid, w);
+ log.info("agent woke up on its own (a background job ended); following that turn", { bot: this.o.botId, conversationId: conv });
+ // 没人接(没有渠道能回复):结束一分钟后丢掉
+ void w.done.then(
+ () => setTimeout(() => !w.taken && this.wakes.get(sid) === w && this.wakes.delete(sid), 60_000).unref?.(),
+ () => undefined,
+ );
+ try {
+ this.o.onWake?.(conv, sid);
+ } catch (e) {
+ log.warn("wake handler failed", { message: (e as Error).message });
+ }
+ }
+
+ /** 通知属于这个会话或它的子代理 */
+ private relates(n: SdkNotification, root: string): boolean {
+ const c = this.harness?.client;
+ const under = (id: string) => id === root || (typeof c?.isDescendantOf === "function" && !!c.isDescendantOf(id, root));
+ if (n.method === "subagent.started" || n.method === "subagent.finished") return under(String(n.params?.parentSessionId ?? "")) || n.params?.childSessionId === root;
+ return under(String(n.params?.sessionId ?? ""));
+ }
+
+ /** 这个会话的代理自己醒着(后台命令结束后被唤醒) */
+ woke(conversationId: string): boolean {
- return [...this.wakes.values()].some((w) => w.conversationId === conversationId && !w.taken);
++ return !!this.wakeId(conversationId);
++ }
++
++ /** 代理自己醒来、还没人跟着的那一轮的确定标识(DSH session + 回合号):出站消息的 id 由它推出,同一轮的回复只发一次 */
++ wakeId(conversationId: string): string | undefined {
++ const w = [...this.wakes.values()].find((x) => x.conversationId === conversationId && !x.taken);
++ return w ? `${w.sessionId}:t${w.turn}` : undefined;
+ }
+
+ /**
+ * 跟踪代理自己醒来的一轮(见 tap):和普通回合一样记步骤、算用量、收交付文件,能插话、能中止,
+ * 结束时返回模型的回复,由运行时发到会话里。
+ */
+ async followTurn(input: { conversationId: string; model: string; observer?: TurnObserver; signal?: AbortSignal }): Promise<TurnResult> {
+ const w = [...this.wakes.values()].find((x) => x.conversationId === input.conversationId && !x.taken);
+ if (!w) throw new Error("no wake-up turn to follow");
+ w.taken = true;
+ const route = await this.routeFor(input.model);
+ this.active++;
+ const turn: HostTurn = { sessionId: w.sessionId, model: input.model, accepted: Promise.resolve(), finishing: false, stopping: false, wake: true };
+ this.turns.set(input.conversationId, turn);
+ const tr = this.tracker(w.sessionId, route, input.observer);
+ try {
+ input.observer?.onStart?.();
+ w.attach(tr.onNotification);
+ await this.awaitTurn(turn, w.done, input.signal);
+ const { turnError, answers, presented, usage } = tr.st;
+ if (!answers.length && turnError) throw new Error(turnError);
+ return { text: answers.join("\n\n"), sessionId: w.sessionId, files: deliverables(this.workspace, presented), usage };
+ } catch (e) {
+ if (e instanceof TurnStopped) log.warn("agent wake-up turn stopped", { bot: this.o.botId, reason: e.reason, restarted: e.restarted });
+ throw e;
+ } finally {
+ turn.finishing = true;
+ 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--;
}
}
diff --cc src/app.ts
index e1a7ff4,2cb2770..e0cbb8d
--- a/src/app.ts
+++ b/src/app.ts
@@@ -589,10 -618,7 +618,10 @@@ export class App
this.channels.set(botId, ch);
if (bot.feishuAppId && bot.feishuAppSecret && !ch.feishu) {
const transport = this.opts.feishuTransport?.(bot) ?? new LarkTransport(bot.feishuAppId, bot.feishuAppSecret);
- ch.feishu = new FeishuChannel(bot.id, transport, this.runtime, this.queue, this.config.feishu.throttleMs);
- // 代理自己醒来的一轮(后台命令结束):回复到这个会话最近收到的那条消息
- const throttleMs = this.config.feishu.throttleMs;
- this.runtime.registerReplier(bot.id, "feishu", (_conv, last) => (last?.replyHandle?.messageId ? { out: new FeishuReply(transport, last.replyHandle.messageId, throttleMs) } : undefined));
+ ch.feishu = new FeishuChannel(bot.id, transport, this.runtime, this.queue, this.config.feishu.throttleMs, this.outbox);
++ // 代理自己醒来的一轮(后台命令结束):经出站队列回复到这个会话最近收到的那条消息
++ const fs = ch.feishu;
++ this.runtime.registerReplier(bot.id, "feishu", (conv, handle, key) => (handle?.messageId ? { out: fs.followUp(conv.peerId, handle.messageId, key) } : undefined));
ch.feishuError = undefined;
ch.feishu.start().catch((e) => {
ch.feishuError = (e as Error).message;
@@@ -605,13 -631,9 +634,12 @@@
fetchImpl: this.opts.weixinFetch,
cdnBaseUrl: this.config.weixin.cdnBaseUrl,
pollTimeoutMs: this.opts.weixinPollTimeoutMs,
+ outbox: this.outbox,
});
ch.weixin.onExpired = () => this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在信息面板的「渠道」里重新扫码`);
+ const wx = ch.weixin;
- this.runtime.registerReplier(bot.id, "weixin", (conv) => {
- const out = wx.replyTo(conv.peerId);
- return out ? { out } : undefined;
- });
++ // 代理自己醒来的一轮:经出站队列发给这个微信用户(发送时才查 24 小时窗口和配额)
++ this.runtime.registerReplier(bot.id, "weixin", (conv, _handle, key) => ({ out: wx.followUp(conv.peerId, key) }));
ch.weixin.start();
}
}
diff --cc src/channels/feishu/card.ts
index f3a30c4,0c06d67..30ea861
--- a/src/channels/feishu/card.ts
+++ b/src/channels/feishu/card.ts
@@@ -39,29 -138,33 +138,34 @@@ export class FeishuReply implements Rep
case "stream.finish":
return this.finish(op.text);
case "text":
- return this.sendText(op.text);
- return this.post("text", { text: op.text }, this.ids.of("text", op.text));
++ // ack("收到,这条会并入…")过一会儿就没意义了,发不出去不必一直等
++ return this.post("text", { text: op.text }, this.ids.of(op.ack ? "ack" : "text", op.text), op.ack ? 10 * 60_000 : undefined);
case "file":
await this.inflight;
- if (this.transport.replyFile) {
- try {
- await this.transport.replyFile(this.replyTo, op.path);
- return;
- } catch (e) {
- log.warn("feishu file upload failed", { name: op.name, message: (e as Error).message.slice(0, 200) });
- }
- }
- return this.sendText(`⚠️ 文件「${op.name}」发送失败,可在工作区中查看。`);
- case "interactive":
- if (op.buttons?.length && this.transport.replyActionCard) {
- try {
- const title = op.kind === "approval" ? `需批准(${op.code ?? ""})` : "需要你的回答";
- await this.transport.replyActionCard(this.replyTo, actionCardSpec(title, op.prompt, op.buttons));
- return;
- } catch (e) {
- log.warn("action card failed, sending text", { message: (e as Error).message });
- }
- }
- return this.sendText(op.requestId ? op.prompt : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") : ""}`);
+ return this.post("file", { path: op.path, name: op.name }, this.ids.of("file", op.path));
+ case "interactive": {
+ const text = op.requestId ? op.prompt : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") : ""}`;
+ const title = op.kind === "approval" ? `需批准(${op.code ?? ""})` : "需要你的回答";
+ const card = op.buttons?.length ? actionCardSpec(title, op.prompt, op.buttons) : undefined;
+ // 审批/提问十分钟后过期,发不出去就不必再等
+ return this.post(card ? "card" : "text", { text, ...(card ? { card } : {}) }, this.ids.of("prompt", op.requestId ?? text), 10 * 60_000);
+ }
+ }
+ }
+
+ /** 交给出站队列(先落库再发,等第一次发送结束);没有队列就直接发 */
+ private async post(kind: OutboxKind, body: OutboxBody, role: string, ttlMs?: number): Promise<void> {
+ if (this.out) {
+ const { outbox, botId, chatId, key } = this.out;
+ await outbox.send({ id: `fs:${botId}:${key}:${role}`, botId, channel: "feishu", peerId: chatId, kind, body, replyTo: this.replyTo, ttlMs: ttlMs ?? this.out.ttlMs });
+ return;
+ }
+ const row = { id: crypto.randomUUID(), kind, body, replyTo: this.replyTo, progress: 0, attempts: 0 } as OutboxRow;
+ try {
+ await deliverFeishu(this.transport, row, () => {}, false);
+ } catch (e) {
+ if (!(e instanceof Gone)) throw e;
+ log.warn("feishu reply dropped", { reason: e.message });
}
}
diff --cc src/channels/feishu/channel.ts
index 8b1e30e,292885b..93b586f
--- a/src/channels/feishu/channel.ts
+++ b/src/channels/feishu/channel.ts
@@@ -1,4 -1,4 +1,4 @@@
--import type { ChannelCapabilities, ChannelStatus, InboundEvent, Part } from "../../core/types.js";
++import type { ChannelCapabilities, ChannelStatus, InboundEvent, Part, ReplySession } from "../../core/types.js";
import { Dedup, KeyedQueue } from "../../core/queue.js";
import type { BotRuntime } from "../../core/runtime.js";
import type { FeishuMessageEvent, FeishuTransport } from "./transport.js";
@@@ -116,14 -135,19 +135,27 @@@ export class FeishuChannel
void p.finally(() => this.pending.delete(p));
}
++ /**
++ * 主动发到一个飞书会话的回复(代理自己醒来的一轮:后台命令结束):回复用户最近的那条消息(replyTo 存在会话的 KV 里,重启也在),
++ * 和普通回复一样经出站队列,id 由 key 推出。
++ */
++ followUp(chatId: string, replyTo: string, key: string): ReplySession {
++ return new FeishuReply(this.transport, replyTo, this.throttleMs, { outbox: this.outbox, botId: this.botId, chatId, key });
++ }
++
async idle(): Promise<void> {
while (this.pending.size) await Promise.all([...this.pending]);
+ await this.outbox.idle();
}
- /** 主动提醒:发到一个已有的单聊会话;传输层不支持时返回 false */
- async notify(chatId: string, text: string): Promise<boolean> {
+ /**
+ * 主动发一条通知到单聊会话(余额提醒、使用请求、批准结果):进出站队列,id 不给时同样的内容一分钟内只发一次。
+ * 传输层不支持主动发消息时返回 false。
+ */
+ notify(chatId: string, text: string, id?: string): boolean {
if (!this.transport.sendText) return false;
- await this.transport.sendText(chatId, text);
+ const key = id ?? `notice:${this.botId}:feishu:${stableId(`${chatId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`;
+ void this.outbox.send({ id: key, botId: this.botId, channel: "feishu", peerId: chatId, kind: "notice", body: { text } });
return true;
}
}
diff --cc src/channels/weixin/channel.ts
index 396ab90,41f1f31..14ea4e1
--- a/src/channels/weixin/channel.ts
+++ b/src/channels/weixin/channel.ts
@@@ -103,29 -180,14 +180,15 @@@ export class WeixinReply implements Rep
case "stream.start":
case "stream.update":
return;
- case "stream.finish":
+ case "stream.finish": {
+ const role = this.ids.final();
+ return this.enqueue(() => this.post("text", { text: op.text }, role));
+ }
case "text":
- return this.enqueue(() => this.send(op.text));
- return this.enqueue(() => this.post("text", { text: op.text }, this.ids.of("text", op.text)));
++ // ack("收到,这条会并入…")过一会儿就没意义了,发不出去不必一直等
++ return this.enqueue(() => this.post("text", { text: op.text }, this.ids.of(op.ack ? "ack" : "text", op.text), op.ack ? SHORT_TTL_MS : undefined));
case "file":
- return this.enqueue(async () => {
- if (this.quota.remaining(this.userId) <= 0) {
- this.log.warn("weixin quota exhausted, file dropped", { userId: this.userId });
- return;
- }
- try {
- // 上传失败不占配额;发送串行,先查后扣不会超发
- await this.client.sendMedia(this.userId, op.path, this.contextToken);
- this.quota.tryConsume(this.userId);
- this.sent.push(`[文件] ${op.name}`);
- } catch (e) {
- this.log.warn("weixin media send failed", { name: op.name, message: (e as Error).message.slice(0, 200) });
- if (this.quota.tryConsume(this.userId)) {
- const t = `⚠️ 文件「${op.name}」发送失败,可在工作区中查看。`;
- await this.client.sendText(this.userId, t, this.contextToken);
- this.sent.push(t);
- }
- }
- });
+ return this.enqueue(() => this.post("file", { path: op.path, name: op.name }, this.ids.of("file", op.path)));
case "interactive": {
const text = op.requestId
? op.prompt // 代理请求:提示里已含编号/回复方式
@@@ -225,28 -303,28 +304,37 @@@ export class WeixinChannel
}
/**
- * 主动提醒:发给扫码登录的那个微信用户。需要他最近发过消息(有 context_token),
- * 并占用同一份回复配额;没有可用配额时放弃,返回 false。
+ * 主动给某人发一条通知(使用请求、批准结果、余额提醒):要他最近 24 小时内发过消息、还有配额,否则返回 false。
+ * 进出站队列(同一 id 只发一次),占用他的回复配额。
*/
- async notifyOwner(text: string): Promise<boolean> {
- return this.notify(this.store.getWeixinAccount(this.botId)?.ownerUserId ?? "", text);
+ tell(userId: string, text: string, id: string): boolean {
+ if (!this.client || !this.quota.open(userId) || this.quota.remaining(userId) <= 0) return false;
+ void this.outbox.send({ id, botId: this.botId, channel: "weixin", peerId: userId, kind: "notice", body: { text, raw: true } });
+ return true;
}
- /** 主动发给某个微信用户(如重启后的提醒):同样要有他最近的 context_token、占用同一份回复配额;发不出去返回 false */
+ /** 主动发给某个微信用户(余额提醒、重启后的提醒):同 tell;同样的内容一分钟内只发一次 */
async notify(userId: string, text: string): Promise<boolean> {
- const peer = userId ? this.store.getWeixinPeer(this.botId, userId) : undefined;
- if (!this.client || !peer?.contextToken || !this.quota.tryConsume(userId)) return false;
- await this.client.sendText(userId, text, peer.contextToken);
- return true;
+ return !!userId && this.tell(userId, text, `notice:${this.botId}:weixin:${stableId(`${userId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`);
}
- /** 主动发到一个微信会话(代理自己醒来的一轮):用这个用户最近的 context_token,占同一份回复配额;登录不在时没有 */
- replyTo(userId: string): ReplySession | undefined {
- const token = this.store.getWeixinPeer(this.botId, userId)?.contextToken;
- return this.client && token ? new WeixinReply(this.client, userId, token, this.quota) : undefined;
+ /** 主动提醒:发给扫码登录的那个微信用户 */
+ async notifyOwner(text: string): Promise<boolean> {
+ return this.notify(this.store.getWeixinAccount(this.botId)?.ownerUserId ?? "", text);
+ }
+
++ /**
++ * 主动发到一个微信会话的回复(代理自己醒来的一轮:后台命令结束):和普通回复一样经出站队列,id 由 key 推出;
++ * 会话凭证、24 小时窗口和配额在发送时才查(deliverWeixin),发不出去在界面里看得到。
++ */
++ followUp(userId: string, key: string): ReplySession {
++ const token = this.store.getWeixinPeer(this.botId, userId)?.contextToken ?? "";
++ return new WeixinReply(this.client!, userId, token, this.quota, { outbox: this.outbox, botId: this.botId, key });
+ }
+
async stop(): Promise<void> {
+ this.unregister?.();
+ this.unregister = undefined;
this.abort?.abort();
await this.loop?.catch(() => {});
this.loop = undefined;
diff --cc src/core/runtime.ts
index 9f06149,16a6b71..f23dcb0
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@@ -15,7 -14,8 +15,8 @@@ import { segmentInput, type ChatPlace
import { clearInflight, markInflight, takeNotice } from "./recovery.js";
import { pwshProbe, pwshStatusLine } from "../agent/pwsh.js";
import { isBotProviderModel } from "../modelflare.js";
-import type { ApprovalRow } from "../store/db.js";
+import type { ApprovalRow, Conversation } from "../store/db.js";
+ import type { AccessControl } from "./access.js";
const log = logger("runtime");
@@@ -126,15 -124,6 +129,20 @@@ interface Inflight
/** 回合还没交给代理(或纯对话还没出字)就被停止时的回复 */
export const stoppedText = (ms: number) => `已中止(处理了 ${fmtSecs(ms)})。`;
+/** 新消息并进了正在进行的代理回合:先回这一句,回复在那一轮结束时一起给 */
+export const STEER_ACK = "收到,这条会并入正在进行的处理,稍后一起回复。";
+
+/**
+ * 不是回复某条消息、而是主动发到会话里(代理自己醒来的一轮:后台命令结束):渠道给出这个会话的出站会话。
- * last 是这个会话最近收到的一条消息(回复句柄);done 在这一轮结束时调用。没有办法发时返回 undefined。
++ * 微信、飞书的回复会话经出站队列发(和普通回复同一条路:落库、按会话排队、重试、发送时才查微信的窗口和配额)。
++ * handle 是这个会话最近收到的那条消息的回复句柄(存在 KV 里,重启也在);key 决定出站消息的 id(同一轮的回复只发一次);
++ * done 在这一轮结束时调用。没有办法发时返回 undefined。
+ */
- export type Replier = (conv: Conversation, last: InboundEvent | undefined) => { out: ReplySession; done?: () => void } | undefined;
++export type Replier = (conv: Conversation, handle: Record<string, string> | undefined, key: string) => { out: ReplySession; done?: () => void } | undefined;
++
++/** 会话最近收到的那条消息的回复句柄(飞书回复要它) */
++const REPLY_TO = "reply-to:";
+
/** 渠道无关的对话运行时:命令处理、上下文拼装、流式调用模型、持久化。 */
export class BotRuntime {
private modelCache: { at: number; list: string[] } | undefined;
@@@ -142,22 -131,7 +150,20 @@@
private inflight = new Map<string, Set<Inflight>>();
/** 应用正在退出:正在处理的消息算被打断,不再回复也不改用纯对话 */
private closing = false;
- constructor(private opts: RuntimeOptions) {}
+ /** 会话 → 之前所有消息都处理完的时刻(同一会话的消息按到达顺序处理;并进进行中回合的不必等) */
+ private tails = new Map<string, Promise<void>>();
- /** 会话 → 最近收到的一条消息(只留回复句柄):主动发消息时回复到它 */
- private lastInbound = new Map<string, InboundEvent>();
+ /** "<botId>:<渠道>" → 主动发消息的出站会话 */
+ private repliers = new Map<string, Replier>();
+ constructor(private opts: RuntimeOptions) {
+ // 代理自己醒来开了一轮(后台命令结束):跟着它,把回复发到会话里
+ if (opts.agent) opts.agent.onWake = (botId, convId) => void this.wake(botId, convId).catch((e) => log.warn("wake-up turn failed", { message: (e as Error).message }));
+ }
+
+ /** 渠道登记怎么主动往它的会话里发消息(代理自己醒来的一轮用);botId 为 "*" 时对所有机器人有效 */
+ registerReplier(botId: string, channel: ChannelId, fn: Replier | undefined): void {
+ if (fn) this.repliers.set(`${botId}:${channel}`, fn);
+ else this.repliers.delete(`${botId}:${channel}`);
+ }
/** 应用退出前调用(App.stop):之后失败的回合留下重启标记,由下次启动告诉用户 */
shutdown(): void {
@@@ -215,8 -194,9 +226,9 @@@
const link = () => t.abort.abort();
if (opts.signal?.aborted) link();
else opts.signal?.addEventListener("abort", link, { once: true });
- this.lastInbound.set(conv.id, { ...ev, parts: [] });
- const set = this.inflight.get(conv.id) ?? new Set<Inflight>();
- this.inflight.set(conv.id, set);
- set.add(t);
++ // 回复句柄存下来(代理自己醒来的一轮要回复到它;重启也在)
++ if (Object.keys(ev.replyHandle).length) store.setKV(REPLY_TO + conv.id, JSON.stringify(ev.replyHandle));
+ const done = this.enter(conv.id, t);
// 重启标记:应用退出或崩溃时还没处理完的,下次启动告诉用户
const text = eventText(ev);
if (text) markInflight(store, conv.id, text);
@@@ -269,21 -227,9 +281,23 @@@
if (!text) return;
const images = inboundImages(ev);
// 上次重启时没处理完、当时又没能告诉用户的:先说一声
- const notice = takeNotice(store, conv.id);
+ const notice = takeNotice(store, convId);
if (notice) await out.apply({ type: "text", text: notice }).catch((e) => log.warn("restart notice failed", { message: (e as Error).message.slice(0, 200) }));
+ // 前面还有消息在处理:代理回合进行中就把这条并进去(模型下一步看到,回复一起给),否则排在它们后面。
+ // 命令(/model、/reset…)不并入,等前面的处理完
+ if (prior) {
+ if (agent?.available && !signal.aborted && !text.startsWith("/") && (await this.steer(agent, bot.id, convId, text, images, out, t))) {
+ await prior;
++ // 应用正在退出、它并进的那一轮没做完:重启标记留着(下次启动告诉用户)
++ if (this.closing) t.interrupted = true;
+ return;
+ }
+ await prior;
+ }
+ // 前面的消息可能换了模型(/model)
+ const conv = { id: convId, model: store.getConversation(convId)?.model ?? "" };
+
// 排队时就被停止了:不再处理(命令也不执行),留一句"已中止"
if (signal.aborted) {
const msg = stoppedText(Date.now() - t.since);
@@@ -413,8 -363,9 +432,9 @@@
// Windows:代理执行命令用的 PowerShell;没有 7 时建议安装
const ps = a?.available ? pwshStatusLine(pwshProbe.snapshot()) : "";
const turn = a?.turnsInProgress.get(convId);
- const busy = turn ? [busyLine(turn.since, turn.lastProgress, turn.activity.steps)] : [];
+ const busy = turn ? [busyLine(turn.since, turn.lastProgress, turn.activity.steps, !!a?.canSteer(convId))] : [];
- return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
+ const who = this.opts.access ? [this.opts.access.policyLine(botId)] : [];
+ return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...who, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
}
/** 卡片按钮回调:批准/拒绝/选择选项。 */
@@@ -577,85 -519,6 +597,107 @@@
}
}
+ /**
+ * 把新消息并入这个会话正在进行的代理回合:成功就存下用户消息(排在上一条后面)、让出渠道队列、回一句收到。
+ * 回合没在跑、正在收尾或中止、指令通道不通时返回 false,消息照常排队。图片只交给能看图的模型(由宿主判断)。
+ */
+ private async steer(agent: AgentManager, botId: string, convId: string, text: string, images: TurnImage[], out: ReplySession, t: Inflight): Promise<boolean> {
+ if (!agent.canSteer(convId)) return false;
+ const ok = await agent.steer(botId, convId, { text, ...(images.length ? { images } : {}) }).catch((e: Error) => {
+ log.warn("steer failed", { message: e.message.slice(0, 200) });
+ return false;
+ });
+ if (!ok) return false;
+ log.info("message steered into the running turn", { bot: botId, conversationId: convId });
+ this.opts.store.addMessage(convId, "user", text);
+ t.userStored = true;
+ t.release?.();
- await out.apply({ type: "text", text: STEER_ACK });
++ await out.apply({ type: "text", text: STEER_ACK, ack: true });
+ return true;
+ }
+
+ /**
+ * 代理自己醒来的一轮(后台命令结束,DSH 唤醒了空闲的代理):像普通回合一样登记(/status、/stop、看门狗、插话都认它),
+ * 经渠道主动发到会话里(网页对话进 live 登记;飞书回复最近一条消息;微信占一条回复配额),回复与步骤存进历史。
+ */
+ async wake(botId: string, convId: string): Promise<void> {
+ const { store } = this.opts;
+ const agent = this.opts.agent;
+ const conv = store.getConversation(convId);
+ const bot = store.getBot(botId);
+ // 那一轮已经有人跟着、或者随代理进程一起没了:不发任何东西
- if (this.closing || !agent?.available || !conv || !bot || !agent.host(botId).woke(convId)) return;
- const r = (this.repliers.get(`${botId}:${conv.channel}`) ?? this.repliers.get(`*:${conv.channel}`))?.(conv, this.lastInbound.get(convId));
++ const wakeId = agent?.available ? agent.host(botId).wakeId(convId) : undefined;
++ if (this.closing || !agent || !conv || !bot || !wakeId) return;
++ let handle: Record<string, string> | undefined;
++ try {
++ handle = JSON.parse(store.getKV(REPLY_TO + convId) || "null") ?? undefined;
++ } catch {
++ handle = undefined;
++ }
++ const r = (this.repliers.get(`${botId}:${conv.channel}`) ?? this.repliers.get(`*:${conv.channel}`))?.(conv, handle, `wake:${wakeId}`);
+ if (!r) log.warn("no way to reply in this conversation; the wake-up reply is only kept in its history", { bot: botId, conversationId: convId, channel: conv.channel });
+ const out: ReplySession = r?.out ?? { apply: async () => undefined };
+ const t: Inflight = { botId, since: Date.now(), abort: new AbortController(), userStored: true };
+ const done = this.enter(convId, t);
++ // 重启标记:这一轮没做完应用就退出或崩溃了,下次启动告诉用户(说的是让命令跑起来的那条消息)
++ const asked = store.listMessages(convId, 20).filter((m) => m.role === "user").at(-1)?.content;
++ markInflight(store, convId, asked || "后台命令的结果");
+ const steps = new Map<string, ActivityStep>();
+ const unbind = agent.approvals.bindSink(convId, async (row) => void (await out.apply(interactiveOp(row))));
+ const halt = () => agent.stopTurn(convId);
+ t.abort.signal.addEventListener("abort", halt, { once: true });
+ try {
+ const model = conv.model || bot.defaultModel || this.opts.defaultModel();
+ const routed = model && this.opts.route ? this.opts.route(botId, model) : model;
+ await out.apply({ type: "typing", on: true });
+ await out.apply({ type: "stream.start" });
+ let res: Awaited<ReturnType<AgentManager["followTurn"]>>;
+ try {
+ res = await agent.followTurn(botId, {
+ conversationId: convId,
+ model: routed,
+ onStep: (step) => {
+ steps.set(step.id, step);
+ void out.apply({ type: "activity", step });
+ },
+ });
+ } catch (e) {
++ // 应用正在退出时代理进程被关掉:不回复,重启标记留着
++ if (this.closing) {
++ t.interrupted = true;
++ return;
++ }
+ const msg = turnFailedText(e as Error, [...steps.values()]);
+ store.addMessage(convId, "assistant", msg, [...steps.values()]);
+ await out.apply({ type: "stream.finish", text: msg });
+ return;
+ }
+ const finalText = res.text.trim() || "(后台任务已结束,没有文字回复)";
+ store.addMessage(convId, "assistant", finalText, [...steps.values()]);
+ await out.apply({ type: "stream.finish", text: finalText });
+ for (const f of res.files ?? []) {
+ try {
+ await out.apply({ type: "file", path: f, name: path.basename(f) });
+ } catch (e) {
+ log.warn("deliver file failed", { name: path.basename(f), message: (e as Error).message.slice(0, 200) });
+ }
+ }
+ } finally {
+ t.abort.signal.removeEventListener("abort", halt);
+ unbind();
+ await out.apply({ type: "typing", on: false }).catch(() => undefined);
+ done.leave();
++ if (!this.inflight.get(convId)?.size && !t.interrupted) {
++ try {
++ clearInflight(store, convId);
++ } catch {
++ /* 退出时数据库可能已经关了 */
++ }
++ }
+ r?.done?.();
+ }
+ }
+
/** 返回 null 表示不是已知命令,按普通消息处理。 */
private async command(text: string, convId: string, convModel: string, botModel: string, botId: string): Promise<string | null> {
const [cmd, ...rest] = text.trim().split(/\s+/);
diff --cc src/core/types.ts
index c09c425,c09c425..12babfa
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@@ -45,7 -45,7 +45,8 @@@ export type OutboundOp
| { type: "stream.start" }
| { type: "stream.update"; text: string }
| { type: "stream.finish"; text: string }
-- | { type: "text"; text: string }
++ /** ack:一句确认("收到,这条会并入正在进行的处理…"),没有自己的回复;渠道给它短的有效期 */
++ | { type: "text"; text: string; ack?: boolean }
/** 代理回合的一步(新增或更新,按 id):只有网页对话显示,其它渠道忽略 */
| { type: "activity"; step: ActivityStep }
/** 代理交付的本地文件(present):微信走 CDN 媒体消息,飞书上传文件/图片,网页列出文件名 */
diff --cc src/web/live.ts
index 1ea1ae0,1ba63da..bb18746
--- a/src/web/live.ts
+++ b/src/web/live.ts
@@@ -59,7 -53,6 +58,7 @@@ export class LiveTurn implements ReplyS
async apply(op: OutboundOp): Promise<void> {
if (this.done) return;
- if (op.type === "text" && op.text === STEER_ACK) this.steered = true;
++ if (op.type === "text" && op.ack) this.steered = true;
if (op.type === "stream.update" || op.type === "stream.finish" || op.type === "text") this.text = op.text;
else if (op.type === "activity") this.steps.set(op.step.id, op.step);
else if (op.type === "file") this.files.push(op.name);
diff --cc test/agent.integration.test.ts
index ef17d4b,a9acb3f..ae2e87d
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@@ -6,11 -6,10 +6,11 @@@ import module from "node:module"
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { App } from "../src/app.js";
import { loadConfig } from "../src/config.js";
-import { RETRY_NOTE, locateDshRuntime } from "../src/agent/host.js";
+import { RETRY_NOTE, SHELL_LIMITS, locateDshRuntime } from "../src/agent/host.js";
import { CHAT_RULES, MEMORY_GUIDE, botIdentity } from "../src/agent/prompts/index.js";
+import { STEER_ACK } from "../src/core/runtime.js";
import { findAppRoot } from "../src/magpie/supervisor.js";
--import { listen } from "./helpers.js";
++import { listen, mockIlink } from "./helpers.js";
/**
* 真实 DSH 子进程 + 脚本化的模型(会发出工具调用),Chat Completions、Responses、Anthropic Messages 三种接口都能答。
@@@ -1121,190 -1093,4 +1123,298 @@@ describe.skipIf(!runtime || !hasBwrap |
await sc.settled();
}
}, 300_000);
+
+ // —— 实时控制:插话、按会话中止、同一进程里各会话各用各的模型、长命令转后台 ——
+ /** 一个微信会话发一条消息,不等它结束:返回 { done(回复文字), conv } */
+ const startOn = (user: string, model: string, text: string, images: Buffer[] = []) => {
+ const conv = app.store.ensureConversation("default", "weixin", user, user, "dm");
++ app.access.allow("default", "weixin", user, "test");
+ app.store.setConversationModel(conv.id, model);
+ const ops: any[] = [];
+ const parts = [{ type: "text" as const, text }, ...images.map((data) => ({ type: "image" as const, data, mime: "image/png" }))];
+ const done = app.runtime
+ .handle({ id: `${user}-${rnd()}`, channel: "weixin", botId: "default", conversation: { kind: "dm", id: user }, sender: { id: user }, parts, replyHandle: {}, receivedAt: Date.now() }, { apply: async (op) => void ops.push(op) })
+ .then(() => ops.findLast((o) => o.type === "stream.finish" || o.type === "text")?.text as string);
+ return { done, conv: conv.id, ops };
+ };
+ const toolRunning = async (conv: string) => ((await api(`/conversations/${encodeURIComponent(conv)}/turn`)) as any).turn?.steps?.some((s: any) => s.kind === "tool" && s.status === "running");
+
+ it("a message sent while a turn runs is steered into it: one reply, history in order, the web live registry consistent, no restart", async () => {
+ expect((await chat("/reset")).reply).toMatch(/已清空/);
+ expect((await chat("hello before steering")).reply).toBe("好的");
+ const host = app.agent.host("default");
+ const pid = host.pid;
+ const conv = (await console_()).conversationId;
+ const first = chat("STEERME please");
+ await waitFor(() => toolRunning(conv));
+ const before = calls.length;
+ const second = chat("STEERTEXT extra-xyz");
+ // 网页的 live 登记里两条都在:第二条并进了第一条,没有自己的回复
+ let d: any;
+ await waitFor(async () => (d = await api("/bots/default/chat")).live?.length === 2 && d.live[1].steered);
+ expect(d.live.map((t: any) => [t.userText, t.steered])).toEqual([
+ ["STEERME please", false],
+ ["STEERTEXT extra-xyz", true],
+ ]);
+ expect((await first).reply).toBe("SAW<<STEERTEXT extra-xyz>>");
+ expect((await second).reply).toBe(STEER_ACK);
+ // 第二条没有单独开一轮:之后的模型请求都带着第一条(同一轮里的下一步)
+ expect(calls.slice(before).every((c) => JSON.stringify(c.body).includes("STEERME please"))).toBe(true);
+ const after = await console_();
+ expect(after.messages.slice(-3).map((m: any) => [m.role, m.content])).toEqual([
+ ["user", "STEERME please"],
+ ["user", "STEERTEXT extra-xyz"],
+ ["assistant", "SAW<<STEERTEXT extra-xyz>>"],
+ ]);
+ expect(after.messages.filter((m: any) => m.content === "STEERTEXT extra-xyz")).toHaveLength(1);
+ expect(((await api("/bots/default/chat")) as any).live).toEqual([]);
+ const a = await api(`/conversations/${encodeURIComponent(conv)}/messages/${after.messages.at(-1).id}/activity`);
+ expect(a.steps.some((s: any) => s.kind === "steer" && s.summary === "STEERTEXT extra-xyz")).toBe(true);
+ expect(host.pid).toBe(pid);
+ }, 120_000);
+
+ it("an image sent while a turn runs reaches the agent with the steered message", async () => {
+ if (!app.agent.host("default").imageInput) return; // Linux 上的 Electron:只给路径
+ const a = startOn("steer-img", "gpt-5-mock", "STEERME with a picture");
+ await waitFor(() => toolRunning(a.conv));
+ const b = startOn("steer-img", "gpt-5-mock", "LOOKSTEER", [png]);
+ expect(await a.done).toMatch(/^SAWIMG<<data:image\/(png|jpeg|webp);base64\|path>>$/);
+ expect(await b.done).toBe(STEER_ACK);
+ const hist = app.store.listMessages(a.conv).map((m) => [m.role, m.content.replace(/inbox\/\S+\.png/, "inbox/X.png")]);
+ expect(hist.slice(-3)).toEqual([
+ ["user", "STEERME with a picture"],
+ ["user", "LOOKSTEER\n[图片 inbox/X.png]"],
+ ["assistant", expect.stringMatching(/^SAWIMG<</)],
+ ]);
+ }, 120_000);
+
+ it("/stop cancels only that conversation's turn: another conversation of the same bot keeps running, no restart", async () => {
+ const host = app.agent.host("default");
+ const pid = host.pid;
+ const restarts = host.restarts;
+ const b = startOn("stop-b", "mock-agent", "SLOWOK b");
+ const a = startOn("stop-a", "mock-agent", "HANG stop-a");
+ await waitFor(() => toolRunning(b.conv));
+ await waitFor(async () => ((await api(`/conversations/${encodeURIComponent(a.conv)}/turn`)) as any).turn?.steps?.length > 0);
+ expect(app.runtime.stop(a.conv)).toBe(true);
+ expect(await a.done).toMatch(/^已中止(处理了 \d+ 秒)。可以继续发消息。$/);
+ expect(await b.done).toContain("slow-done");
+ expect(host.pid).toBe(pid);
+ expect(host.restarts).toBe(restarts);
+ expect(host.state).toBe("running");
+ }, 120_000);
+
+ it("each conversation runs on its own model in one agent process: a switch, even to a model the patch did not list, needs no restart", async () => {
+ catalog["gpt-6-mock"] = ["openai", "openai-response", "openai-response-compact"];
+ catalog["claude-switch-mock"] = ["anthropic", "openai"];
+ const host = app.agent.host("default");
+ expect(host.state).toBe("running");
+ const pid = host.pid;
+ expect((host.status() as any).models).not.toContain("claude-switch-mock");
+ const from = calls.length;
+ // 会话 X 在 gpt-6-mock(Responses)上跑一条几秒的命令;同时会话 Y 用一个新模型(Anthropic Messages)
+ const x = startOn("switch-x", "gpt-6-mock", "SLOWOK on responses");
+ await waitFor(() => toolRunning(x.conv));
+ const y = await turnOn("switch-y", "claude-switch-mock", "QUICKSORT on a new model");
+ expect(y.reply).toContain("[1, 2, 3, 5, 7, 9]");
+ expect(await x.done).toContain("slow-done");
+ expect(callsFor("claude-switch-mock", from).map((c) => c.api)).toEqual(callsFor("claude-switch-mock", from).map(() => "messages"));
+ expect(callsFor("claude-switch-mock", from).length).toBeGreaterThan(0);
+ expect(callsFor("gpt-6-mock", from).filter((c) => c.body.tools).every((c) => c.api === "responses")).toBe(true);
+ // 每个请求都是它所在会话的模型
+ for (const c of calls.slice(from).filter((c) => c.body.tools)) {
+ const body = JSON.stringify(c.body);
+ if (body.includes("SLOWOK on responses")) expect(c.model).toBe("gpt-6-mock");
+ if (body.includes("QUICKSORT on a new model")) expect(c.model).toBe("claude-switch-mock");
+ }
+ // 会话 Y 再换回 gpt-6-mock:同一个会话、同一个进程
+ const again = calls.length;
+ expect((await turnOn("switch-y", "gpt-6-mock", "QUICKSORT after switching back")).reply).toContain("[1, 2, 3, 5, 7, 9]");
+ expect(callsFor("gpt-6-mock", again).filter((c) => c.body.tools).every((c) => c.api === "responses")).toBe(true);
+ expect(callsFor("claude-switch-mock", again)).toEqual([]);
+ expect(host.pid).toBe(pid);
+ expect((host.status() as any).models).toEqual(expect.arrayContaining(["gpt-6-mock", "claude-switch-mock"]));
+ }, 180_000);
+
+ it("tool processes never see the bridge token or the control channel id (DSH scrubs *TOKEN*/*KEY* from their environment)", async () => {
+ const r = await chat("TOKENS check");
+ expect(r.reply).toContain("token=none control=none key=none");
+ expect(r.reply).not.toContain(app.agent.bridge.token);
+ expect(r.reply).not.toContain(app.agent.host("default").control.id);
+ }, 120_000);
+
+ it("a long command moves to the background; the turn replies at once; when it ends the agent wakes and the follow-up reaches the chat", async () => {
+ const host = app.agent.host("default");
+ const saved = { ...SHELL_LIMITS };
+ // 测试里把转后台的阈值调到 1.5 秒(真实是 30 秒),重启代理进程让补丁生效
+ Object.assign(SHELL_LIMITS, { bashMs: 1500, bashMaxMs: 3000 });
+ try {
+ await host.restart();
+ expect((await chat("/reset")).reply).toMatch(/已清空/);
+ const conv = (await console_()).conversationId;
+ const t0 = Date.now();
+ const r = await chat("BGJOB now");
+ expect(r.reply).toMatch(/^STILL-RUNNING<<\[still running after 1500ms; moved to background job bash-\S+\]/);
+ // 没有等命令跑完(它要 4 秒):这一轮的回复里还没有它的输出
+ expect(r.reply).not.toContain("bg-finished-42");
+ expect(Date.now() - t0).toBeLessThan(30_000);
+ const first = await console_();
+ const steps1 = (await api(`/conversations/${encodeURIComponent(conv)}/messages/${first.messages.at(-1).id}/activity`)).steps;
+ expect(steps1.find((s: any) => s.kind === "job")).toMatchObject({ title: "后台命令", status: "ok", summary: expect.stringContaining("(回复时仍在后台运行)") });
+ // 命令结束:代理被唤醒,宿主像普通回合一样跟着这一轮:网页 live 里有一条(没有用户消息),/status 和信息面板都认它
+ let live: any;
+ await waitFor(async () => !!(live = ((await api("/bots/default/chat")) as any).live.find((t: any) => t.userText === "")), 30_000);
+ expect(live.steered).toBe(false);
+ await waitFor(async () => !!((await api(`/conversations/${encodeURIComponent(conv)}/turn`)) as any).turn);
+ expect((await chat("/status")).reply).toMatch(/本会话上一条消息还在处理/);
+ expect((await api("/agent")).busy).toEqual(["default"]);
+ // 回复存进历史、发到会话里
+ let d: any;
+ await waitFor(async () => /BGDONE/.test((d = await console_()).messages.at(-1)?.content ?? ""), 60_000);
+ const reply = d.messages.at(-1);
+ expect(reply.role).toBe("assistant");
+ expect(reply.content).toContain("bg-finished-42");
+ expect(reply.content).toContain("wake-step");
+ expect(d.messages.slice(-3).map((m: any) => m.role)).toEqual(["user", "assistant", "assistant"]);
+ const steps2 = (await api(`/conversations/${encodeURIComponent(conv)}/messages/${reply.id}/activity`)).steps;
+ expect(steps2.map((s: any) => s.kind)).toEqual(expect.arrayContaining(["job", "model", "tool"]));
+ await waitFor(async () => ((await api("/bots/default/chat")) as any).live.length === 0);
+ expect(((await api(`/conversations/${encodeURIComponent(conv)}/turn`)) as any).turn).toBeNull();
+ } finally {
+ Object.assign(SHELL_LIMITS, saved);
+ await host.restart();
+ }
+ }, 180_000);
+
+ it("a wake-up turn can be stopped like any other; nothing restarts", async () => {
+ const host = app.agent.host("default");
+ const saved = { ...SHELL_LIMITS };
+ Object.assign(SHELL_LIMITS, { bashMs: 1500, bashMaxMs: 3000 });
+ try {
+ await host.restart();
+ expect((await chat("/reset")).reply).toMatch(/已清空/);
+ const conv = (await console_()).conversationId;
+ expect((await chat("BGJOB again")).reply).toMatch(/^STILL-RUNNING/);
+ const pid = host.pid;
+ await waitFor(async () => !!((await api(`/conversations/${encodeURIComponent(conv)}/turn`)) as any).turn, 30_000);
+ expect((await chat("/stop")).reply).toMatch(/^正在中止上一条消息/);
+ let d: any;
+ await waitFor(async () => /^已中止/.test((d = await console_()).messages.at(-1)?.content ?? ""), 30_000);
+ expect(d.messages.at(-1).content).toMatch(/^已中止(处理了 \d+ 秒)。可以继续发消息。$/);
+ expect(host.pid).toBe(pid);
+ // 同一个会话、同一个代理进程照常接着用
+ expect((await chat("QUICKSORT after stopping the wake-up turn")).reply).toContain("[1, 2, 3, 5, 7, 9]");
+ expect(host.pid).toBe(pid);
+ } finally {
+ Object.assign(SHELL_LIMITS, saved);
+ await host.restart();
+ }
+ }, 180_000);
++
++ // —— 微信端到端(真实 DSH + mock iLink):插话的"收到"、后台命令结束后的回复都经出站队列发到微信,各只发一次 ——
++ describe("on WeChat (mock iLink)", () => {
++ const OWNER = "[email protected]";
++ const FRIEND = "[email protected]";
++ let ilink: Awaited<ReturnType<typeof mockIlink>>;
++ const sentTo = (user: string, text: string) => ilink.state.sent.filter((s) => s.to === user && s.text.includes(text));
++ const outboxRows = (user: string) => app.store.listOutbox({ botId: "default", limit: 500 }).filter((r) => r.peerId === user).reverse();
++
++ beforeAll(async () => {
++ ilink = await mockIlink();
++ // 已经扫码登录:扫码的是 OWNER;渠道连到 mock iLink
++ app.store.saveWeixinAccount({ botId: "default", botToken: "tok", ilinkBotId: "[email protected]", baseUrl: ilink.url, ownerUserId: OWNER });
++ await app.restartBot("default");
++ });
++ afterAll(async () => {
++ await app.channels.get("default")?.weixin?.stop();
++ await ilink?.close();
++ });
++
++ it("a long command is backgrounded; when it ends the follow-up reply reaches WeChat exactly once, through the outbox", async () => {
++ const host = app.agent.host("default");
++ const saved = { ...SHELL_LIMITS };
++ Object.assign(SHELL_LIMITS, { bashMs: 1500, bashMaxMs: 3000 });
++ try {
++ await host.restart();
++ const conv = `default:weixin:${OWNER}`;
++ app.store.setConversationModel(conv, "");
++ ilink.push(OWNER, "BGJOB on wechat");
++ // 这一轮先回"还在跑"
++ await waitFor(() => sentTo(OWNER, "STILL-RUNNING").length === 1, 60_000);
++ expect(sentTo(OWNER, "bg-finished-42")).toHaveLength(0);
++ // 命令结束:代理醒来,回复作为一条新消息发到微信
++ await waitFor(() => sentTo(OWNER, "BGDONE").length === 1, 60_000);
++ const done = sentTo(OWNER, "BGDONE")[0];
++ expect(done.text).toContain("bg-finished-42");
++ expect(done.text).toContain("wake-step");
++ // 经出站队列:id 由 DSH 会话和回合号推出(wx:<机器人>:wake:<会话>:t<回合>:final),状态 sent
++ const rows = outboxRows(OWNER);
++ const wake = rows.filter((r) => /^wx:default:wake:[^:]+:t\d+:final$/.test(r.id));
++ expect(wake).toHaveLength(1);
++ expect(wake[0]).toMatchObject({ status: "sent", kind: "text", channel: "weixin" });
++ expect(wake[0].body.text).toContain("BGDONE");
++ expect(wake[0].id).toBe(`wx:default:wake:${app.store.getAgentSession(conv)}:t2:final`);
++ // 先是这一轮的回复,再是后台命令结束后的那条(按会话顺序)
++ expect(rows.map((r) => r.body.text?.split("<<")[0])).toEqual(["STILL-RUNNING", "BGDONE"]);
++ // 再等一会儿:没有重发,平台的 client_id 都不一样
++ await new Promise((r) => setTimeout(r, 2000));
++ await app.outbox.idle();
++ expect(sentTo(OWNER, "BGDONE")).toHaveLength(1);
++ expect(new Set(ilink.state.clientIds).size).toBe(ilink.state.clientIds.length);
++ // 历史:用户消息、这一轮的回复、后台命令结束后的回复;没有正在进行的回合,重启标记清掉了
++ const hist = app.store.listMessages(conv).map((m) => [m.role, m.content.split("<<")[0]]);
++ expect(hist.slice(-3)).toEqual([
++ ["user", "BGJOB on wechat"],
++ ["assistant", "STILL-RUNNING"],
++ ["assistant", "BGDONE"],
++ ]);
++ await waitFor(() => !app.agent.turnsInProgress.has(conv));
++ expect(app.store.getKV(`inflight:${conv}`)).toBeFalsy();
++ } finally {
++ Object.assign(SHELL_LIMITS, saved);
++ await host.restart();
++ }
++ }, 180_000);
++
++ it("a message sent while the turn runs is steered: the 收到 ack and the one reply go through the outbox, once each", async () => {
++ const conv = `default:weixin:${OWNER}`;
++ const before = ilink.state.sent.length;
++ ilink.push(OWNER, "STEERME on wechat");
++ await waitFor(() => toolRunning(conv), 60_000);
++ ilink.push(OWNER, "STEERTEXT from wechat");
++ await waitFor(() => sentTo(OWNER, "SAW<<STEERTEXT from wechat>>").length === 1, 60_000);
++ await app.outbox.idle();
++ const mine = ilink.state.sent.slice(before).filter((s) => s.to === OWNER).map((s) => s.text);
++ expect(mine).toEqual([STEER_ACK, "SAW<<STEERTEXT from wechat>>"]);
++ // ack 的出站记录:短有效期、只发一次
++ const ack = outboxRows(OWNER).filter((r) => r.body.text === STEER_ACK);
++ expect(ack).toHaveLength(1);
++ expect(ack[0].status).toBe("sent");
++ expect(ack[0].expiresAt - ack[0].createdAt).toBeLessThanOrEqual(10 * 60_000);
++ expect(app.store.listMessages(conv).slice(-3).map((m) => [m.role, m.content])).toEqual([
++ ["user", "STEERME on wechat"],
++ ["user", "STEERTEXT from wechat"],
++ ["assistant", "SAW<<STEERTEXT from wechat>>"],
++ ]);
++ await waitFor(() => !app.agent.turnsInProgress.has(conv));
++ expect(app.store.getKV(`inflight:${conv}`)).toBeFalsy();
++ }, 120_000);
++
++ it("a steer never bypasses the allowlist: removed while its turn runs, the next message is refused, not steered", async () => {
++ const entry = app.access.allow("default", "weixin", FRIEND, "test");
++ const conv = `default:weixin:${FRIEND}`;
++ ilink.push(FRIEND, "STEERME from a friend");
++ await waitFor(() => toolRunning(conv), 60_000);
++ // 主人在回合进行中把他移出允许名单
++ app.access.remove(entry.id);
++ ilink.push(FRIEND, "STEERTEXT should not get in");
++ await waitFor(() => sentTo(FRIEND, "NOSTEER").length === 1, 60_000);
++ await app.outbox.idle();
++ expect(sentTo(FRIEND, "SAW<<")).toHaveLength(0);
++ expect(sentTo(FRIEND, STEER_ACK)).toHaveLength(0);
++ expect(app.store.listMessages(conv).map((m) => m.content)).not.toContain("STEERTEXT should not get in");
++ // 模型从没见过这条
++ expect(calls.some((c) => JSON.stringify(c.body).includes("STEERTEXT should not get in"))).toBe(false);
++ }, 120_000);
++ });
});
diff --cc test/live-control.unit.test.ts
index 74123ab,0000000..b09dc0c
mode 100644,000000..100644
--- a/test/live-control.unit.test.ts
+++ b/test/live-control.unit.test.ts
@@@ -1,265 -1,0 +1,383 @@@
+/** 实时控制的零件:渠道队列让位、宿主 → 代理进程的指令通道(经 bridge)、后台命令与插话在活动记录里的样子、只算完整回答。 */
+import os from "node:os";
+import { afterEach, describe, expect, it } from "vitest";
+import { KeyedQueue } from "../src/core/queue.js";
+import { AgentBridge } from "../src/agent/bridge.js";
+import { ControlChannel } from "../src/agent/control.js";
+import { ActivityLog, describeStep, promotedJob } from "../src/agent/activity.js";
+import { answerText } from "../src/agent/host.js";
+import { BotRuntime, STEER_ACK } from "../src/core/runtime.js";
+import { Store } from "../src/store/db.js";
+import { DEFAULT_SETTINGS } from "../src/agent/settings.js";
+import type { AgentManager } from "../src/agent/manager.js";
+import type { InboundEvent, OutboundOp } from "../src/core/types.js";
+import { until } from "./helpers.js";
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+describe("KeyedQueue: a task can give up its slot early", () => {
+ it("the next task of the same key starts once the first releases; run() still resolves when the task ends", async () => {
+ const q = new KeyedQueue();
+ const log: string[] = [];
+ let finishFirst!: () => void;
+ const first = q.run("k", async () => {
+ log.push("a+");
+ const release = KeyedQueue.releaser();
+ await sleep(10);
+ release?.();
+ await new Promise<void>((r) => (finishFirst = r));
+ log.push("a-");
+ });
+ const second = q.run("k", async () => void log.push("b"));
+ await second;
+ expect(log).toEqual(["a+", "b"]);
+ let firstDone = false;
+ void first.then(() => (firstDone = true));
+ await sleep(5);
+ expect(firstDone).toBe(false);
+ finishFirst();
+ await first;
+ expect(log).toEqual(["a+", "b", "a-"]);
+ });
+
+ it("outside a queued task there is nothing to release", () => {
+ expect(KeyedQueue.releaser()).toBeUndefined();
+ });
+});
+
+describe("control channel (host → amb-control plugin over the bridge)", () => {
+ let bridge: AgentBridge | undefined;
+ afterEach(async () => {
+ await bridge?.stop();
+ bridge = undefined;
+ });
+ const setup = async () => {
+ const ch = new ControlChannel();
+ bridge = new AgentBridge({ upstream: () => ({ baseUrl: "", apiKey: "" }), ask: async () => ({ id: "" }), wait: async () => ({}), cancel: async () => {}, control: { poll: (b, s) => ch.poll(b, s), result: (b) => ch.result(b) } });
+ await bridge.start();
+ const post = async (p: string, body: unknown, token = bridge!.token) =>
+ fetch(bridge!.url + p, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) });
+ return { ch, post };
+ };
+
+ it("a command reaches the waiting poll, its result comes back; nothing in either carries the bridge token", async () => {
+ const { ch, post } = await setup();
+ const id = ch.reset();
+ expect(ch.connected).toBe(false);
+ const polling = post("/dsh/control/poll", { botId: "b", controlId: id });
+ await sleep(50);
+ expect(ch.connected).toBe(true);
+ const sent = ch.send("steer", { sessionId: "s1", text: "hi" }, 5000);
+ const got = (await (await polling).json()) as any;
+ expect(got.commands).toEqual([{ sessionId: "s1", text: "hi", id: expect.any(String), op: "steer" }]);
+ expect(JSON.stringify(got)).not.toContain(bridge!.token);
+ expect((await post("/dsh/control/result", { botId: "b", controlId: id, id: got.commands[0].id, ok: true, result: { accepted: true } })).status).toBe(200);
+ expect(await sent).toEqual({ accepted: true });
+ });
+
+ it("queued commands wait for the next poll; a failed command rejects with the plugin's error", async () => {
+ const { ch, post } = await setup();
+ const id = ch.reset();
+ const sent = ch.send("providers", {}, 5000);
+ const got = (await (await post("/dsh/control/poll", { botId: "b", controlId: id })).json()) as any;
+ expect(got.commands.map((c: any) => c.op)).toEqual(["providers"]);
+ const failed = expect(sent).rejects.toThrow("llm-pi-ai entry not found");
+ await post("/dsh/control/result", { botId: "b", controlId: id, id: got.commands[0].id, ok: false, error: "llm-pi-ai entry not found" });
+ await failed;
+ });
+
+ it("a restarted child gets a new id: the old one's poll is told to stop, its pending commands fail at once", async () => {
+ const { ch, post } = await setup();
+ const old = ch.reset();
+ const sent = ch.send("cancel", { sessionId: "s" }, 60_000);
+ const fresh = ch.reset();
+ await expect(sent).rejects.toThrow("代理进程已重启");
+ expect(fresh).not.toBe(old);
+ expect(await (await post("/dsh/control/poll", { botId: "b", controlId: old })).json()).toEqual({ stop: true });
+ // 子进程退出:通道关闭,发不出去
+ ch.close();
+ await expect(ch.send("ping", {}, 1000)).rejects.toThrow("代理进程没有运行");
+ });
+
+ it("no answer within the timeout: the command fails and is not delivered later", async () => {
+ const { ch, post } = await setup();
+ const id = ch.reset();
+ await expect(ch.send("ping", {}, 30)).rejects.toThrow("代理进程没有响应(ping)");
+ const r = post("/dsh/control/poll", { botId: "b", controlId: id });
+ await sleep(50);
+ ch.close();
+ expect(((await (await r).json()) as any).commands).toEqual([]);
+ });
+
+ it("requests without the bridge token are refused", async () => {
+ const { ch, post } = await setup();
+ const id = ch.reset();
+ expect((await post("/dsh/control/poll", { botId: "b", controlId: id }, "wrong")).status).toBe(401);
+ });
+});
+
+describe("activity: background commands and steered messages", () => {
+ const T0 = 1_800_000_000_000;
+ const promoted = (id: string) => ({ message: { toolCallId: "c1", content: [{ type: "text", text: `[still running after 30000ms; moved to background job ${id}]\nThe command keeps running in the background.` }], isError: false } });
+
+ it("a command moved to the background gets its own step; it ends during the turn (job/settled) or is noted as still running", () => {
+ expect(promotedJob(promoted("bash-1"))).toBe("bash-1");
+ expect(promotedJob({ message: { content: [{ type: "text", text: "started background job bash-2" }] } })).toBeUndefined();
+ const log = new ActivityLog();
+ log.apply("tool/call", { callId: "c1", name: "bash", arguments: '{"command":"npm test"}' }, T0);
+ log.apply("tool/result", promoted("bash-1"), T0 + 30_000);
+ expect(log.steps.map((s) => [s.kind, s.title, s.status])).toEqual([
+ ["tool", "bash", "ok"],
+ ["job", "后台命令", "running"],
+ ]);
+ expect(describeStep(log.last!)).toBe("后台命令在运行:npm test");
+ log.apply("job/settled", { jobId: "bash-1", status: "completed", detail: "exit code: 1", finishedAt: T0 + 50_000 }, T0 + 50_000);
+ expect(log.last).toMatchObject({ kind: "job", status: "error", ms: 20_000, output: "exit code: 1" });
+
+ const still = new ActivityLog();
+ still.apply("tool/call", { callId: "c1", name: "bash", arguments: '{"command":"make"}' }, T0);
+ still.apply("tool/result", promoted("bash-3"), T0 + 30_000);
+ still.finish(T0 + 31_000);
+ expect(still.last).toMatchObject({ kind: "job", status: "ok", summary: "make (回复时仍在后台运行)" });
+ });
+
+ it("the wake-up turn shows the job's end from DSH's notice; a steered message is a step of its own", () => {
+ const log = new ActivityLog();
+ log.apply("user/message", { role: "user", content: [{ type: "text", text: "background job bash-9 (bash: make) finished [status: completed, exit code: 0]. Read its output with job_output." }], source: { kind: "tool-jobs", form: "notice", summary: "bash make [status: completed]" } }, T0);
+ expect(log.last).toMatchObject({ id: "j:bash-9", kind: "job", title: "后台命令结束", summary: "bash make [status: completed]", status: "ok" });
+ log.apply("user/message", { role: "user", content: [{ type: "text", text: "hi" }], source: { kind: "user" } }, T0 + 1);
+ expect(log.steps).toHaveLength(1);
+ log.apply("steer", { text: "also check the README" }, T0 + 2);
+ expect(log.last).toMatchObject({ kind: "steer", title: "追加消息", summary: "also check the README", status: "ok" });
+ expect(describeStep(log.last!)).toBe("收到追加消息:also check the README");
+ });
+});
+
+describe("the reply of a turn", () => {
+ it("only complete answers count: no tool calls, not interrupted", () => {
+ const msg = (content: unknown[], extra = {}) => ({ message: { role: "assistant", content }, ...extra });
+ expect(answerText(msg([{ type: "text", text: " done " }]))).toBe("done");
+ expect(answerText(msg([{ type: "text", text: "let me look" }, { type: "tool-call", id: "c", name: "bash", arguments: "{}" }]))).toBe("");
+ expect(answerText(msg([{ type: "text", text: "half" }], { interrupted: true }))).toBe("");
+ expect(answerText(msg([{ type: "reasoning", text: "hmm" }]))).toBe("");
+ });
+});
+
+describe("runtime: a message sent while an agent turn runs", () => {
+ const ev = (text: string): InboundEvent => ({ id: Math.random().toString(36), channel: "web", botId: "b1", conversation: { kind: "dm", id: "console" }, sender: { id: "owner" }, parts: [{ type: "text", text }], replyHandle: {}, receivedAt: Date.now() });
+ function setup(steerable: boolean) {
+ const store = new Store(":memory:");
+ store.createBot({ id: "b1", name: "测试" });
+ const turns = new Map<string, any>();
+ const steered: string[] = [];
+ const finishers: Array<(v: unknown) => void> = [];
+ let runs = 0;
+ const agent = {
+ available: true,
+ host: () => ({ state: "running", workspace: os.tmpdir(), diagnostics: () => ({}) }),
+ approvals: { bindSink: () => () => {}, handleReply: () => ({ handled: false }), pending: () => [] },
+ turnsInProgress: turns,
+ settings: () => ({ ...DEFAULT_SETTINGS, memory: { ...DEFAULT_SETTINGS.memory, enabled: false } }),
+ memoryPrefix: () => "",
+ takeSeed: () => "",
+ canSteer: (conv: string) => steerable && turns.has(conv),
+ steer: async (_bot: string, _conv: string, m: { text: string }) => (steered.push(m.text), true),
+ runTurn: (_bot: string, input: any) => {
+ runs++;
+ turns.set(input.conversationId, { since: Date.now(), lastProgress: Date.now(), activity: { steps: [] } });
+ input.observer?.onStart?.();
+ return new Promise((r) => finishers.push(r)).finally(() => turns.delete(input.conversationId));
+ },
+ stopTurn: () => false,
+ } as unknown as AgentManager;
+ const models = { listModels: async () => ["m1"], streamChat: async () => "纯对话" };
+ const rt = new BotRuntime({ store, models: models as any, defaultModel: () => "m1", contextMessages: 20, contextChars: 20_000, agent });
+ const q = new KeyedQueue();
+ const send = (text: string) => {
+ const ops: OutboundOp[] = [];
+ const done = q.run("web:b1:console", () => rt.handle(ev(text), { apply: async (op) => void ops.push(op) }));
+ return { ops, done, texts: () => ops.filter((o): o is Extract<OutboundOp, { text: string }> => "text" in o).map((o) => o.text) };
+ };
+ const history = () => store.listMessages("b1:web:console").map((m) => [m.role, m.content]);
+ return { rt, send, steered, finishers, runs: () => runs, history };
+ }
+ const reply = { text: "一起回答", sessionId: "S", files: [], usage: { tokens: 1, window: 10, maxTokens: 1 } };
+
+ it("is steered into it: the channel queue gives way once the agent took the first, one reply, history in order", async () => {
+ const s = setup(true);
+ const a = s.send("第一条");
+ await until(() => s.finishers.length === 1);
+ const b = s.send("补充一句");
+ await until(() => b.texts().length > 0);
+ expect(b.texts()).toEqual([STEER_ACK]);
+ expect(s.steered).toEqual(["补充一句"]);
+ // 第二条等第一条的回合结束才算处理完(网页 live 登记里它一直在)
+ let bDone = false;
+ void b.done.then(() => (bDone = true));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(bDone).toBe(false);
+ s.finishers[0](reply);
+ await a.done;
+ await b.done;
+ expect(s.runs()).toBe(1);
+ expect(a.texts().at(-1)).toBe("一起回答");
+ expect(s.history()).toEqual([
+ ["user", "第一条"],
+ ["user", "补充一句"],
+ ["assistant", "一起回答"],
+ ]);
+ });
+
+ it("can't be steered (turn finishing, channel down): it waits and runs as its own turn afterwards", async () => {
+ const s = setup(false);
+ const a = s.send("第一条");
+ await until(() => s.finishers.length === 1);
+ const b = s.send("第二条");
+ await new Promise((r) => setTimeout(r, 30));
+ expect(s.runs()).toBe(1);
+ s.finishers[0](reply);
+ await a.done;
+ await until(() => s.finishers.length === 2);
+ s.finishers[1]({ ...reply, text: "第二个回答" });
+ await b.done;
+ expect(s.steered).toEqual([]);
+ expect(s.history()).toEqual([
+ ["user", "第一条"],
+ ["assistant", "一起回答"],
+ ["user", "第二条"],
+ ["assistant", "第二个回答"],
+ ]);
+ });
+
+ it("commands never steer: /model waits for the running turn", async () => {
+ const s = setup(true);
+ const a = s.send("第一条");
+ await until(() => s.finishers.length === 1);
+ const b = s.send("/help");
+ await new Promise((r) => setTimeout(r, 30));
+ expect(b.texts()).toEqual([]);
+ s.finishers[0](reply);
+ await a.done;
+ await b.done;
+ expect(b.texts()[0]).toMatch(/^可用命令/);
+ expect(s.steered).toEqual([]);
+ });
+});
++
++describe("runtime: restart markers and wake-up replies", () => {
++ const CONV = "b1:weixin:u1";
++ const ev = (text: string, id = Math.random().toString(36)): InboundEvent => ({ id, channel: "weixin", botId: "b1", conversation: { kind: "dm", id: "u1" }, sender: { id: "u1" }, parts: [{ type: "text", text }], replyHandle: { contextToken: "ctx-1" }, receivedAt: Date.now() });
++ const reply = { text: "回答", sessionId: "S", files: [], usage: { tokens: 1, window: 10, maxTokens: 1 } };
++ function setup() {
++ const store = new Store(":memory:");
++ store.createBot({ id: "b1", name: "测试" });
++ const turns = new Map<string, any>();
++ const pending: Array<{ resolve: (v: unknown) => void; reject: (e: Error) => void }> = [];
++ let wakeId: string | undefined;
++ let follow: { resolve: (v: unknown) => void; reject: (e: Error) => void } | undefined;
++ const agent = {
++ available: true,
++ host: () => ({ state: "running", workspace: os.tmpdir(), diagnostics: () => ({}), wakeId: () => wakeId }),
++ approvals: { bindSink: () => () => {}, handleReply: () => ({ handled: false }), pending: () => [] },
++ turnsInProgress: turns,
++ settings: () => ({ ...DEFAULT_SETTINGS, memory: { ...DEFAULT_SETTINGS.memory, enabled: false } }),
++ memoryPrefix: () => "",
++ takeSeed: () => "",
++ canSteer: (conv: string) => turns.has(conv),
++ steer: async () => true,
++ runTurn: (_bot: string, input: any) => {
++ turns.set(input.conversationId, { since: Date.now(), lastProgress: Date.now(), activity: { steps: [] } });
++ input.observer?.onStart?.();
++ return new Promise((resolve, reject) => pending.push({ resolve, reject })).finally(() => turns.delete(input.conversationId));
++ },
++ followTurn: () => {
++ const t = wakeId;
++ wakeId = undefined;
++ return new Promise((resolve, reject) => (follow = { resolve, reject })).then((v) => (void t, v));
++ },
++ stopTurn: () => false,
++ } as unknown as AgentManager & { onWake?: (b: string, c: string) => void };
++ const models = { listModels: async () => ["m1"], streamChat: async () => "纯对话" };
++ const rt = new BotRuntime({ store, models: models as any, defaultModel: () => "m1", contextMessages: 20, contextChars: 20_000, agent });
++ const q = new KeyedQueue();
++ const send = (text: string) => q.run("weixin:b1:u1", () => rt.handle(ev(text), { apply: async () => undefined }));
++ const marker = () => store.getKV(`inflight:${CONV}`);
++ return { store, rt, agent, send, pending, marker, wake: (id: string) => (wakeId = id), follow: () => follow };
++ }
++
++ it("a steered message keeps the conversation's restart marker until the turn it joined is done", async () => {
++ const s = setup();
++ const a = s.send("第一条");
++ await until(() => s.pending.length === 1);
++ const b = s.send("补充一句");
++ await new Promise((r) => setTimeout(r, 20));
++ expect(JSON.parse(s.marker()!).preview).toBe("第一条");
++ s.pending[0].resolve(reply);
++ await Promise.all([a, b]);
++ expect(s.marker()).toBeFalsy();
++ });
++
++ it("the app shuts down while the joined turn runs: the marker stays for the next start, also after the steered message finished", async () => {
++ const s = setup();
++ const a = s.send("第一条");
++ await until(() => s.pending.length === 1);
++ const b = s.send("补充一句");
++ await new Promise((r) => setTimeout(r, 20));
++ s.rt.shutdown();
++ s.pending[0].reject(new Error("DeepSeek Harness runtime closed"));
++ await Promise.all([a, b]);
++ expect(JSON.parse(s.marker()!).preview).toBe("第一条");
++ });
++
++ it("a wake-up turn: its reply goes to the conversation's replier under a key fixed by the DSH session and turn; the marker is set while it runs", async () => {
++ const s = setup();
++ await (async () => {
++ const a = s.send("BGJOB please");
++ await until(() => s.pending.length === 1);
++ s.pending[0].resolve({ ...reply, text: "还在跑" });
++ await a;
++ })();
++ expect(s.marker()).toBeFalsy();
++ const ops: OutboundOp[] = [];
++ const seen: Array<{ handle: unknown; key: string }> = [];
++ let ended = 0;
++ s.rt.registerReplier("b1", "weixin", (_conv, handle, key) => (seen.push({ handle, key }), { out: { apply: async (op) => void ops.push(op) }, done: () => void ended++ }));
++ s.wake("S:t2");
++ const w = s.rt.wake("b1", CONV);
++ await until(() => !!s.follow());
++ // 回复句柄来自 KV(重启也在),出站 id 的 key 由会话与回合号推出
++ expect(seen).toEqual([{ handle: { contextToken: "ctx-1" }, key: "wake:S:t2" }]);
++ expect(JSON.parse(s.marker()!).preview).toBe("BGJOB please");
++ s.follow()!.resolve({ ...reply, text: "后台命令跑完了" });
++ await w;
++ expect(ops.filter((o) => o.type === "stream.finish").map((o: any) => o.text)).toEqual(["后台命令跑完了"]);
++ expect(ended).toBe(1);
++ expect(s.marker()).toBeFalsy();
++ expect(s.store.listMessages(CONV).map((m) => [m.role, m.content])).toEqual([
++ ["user", "BGJOB please"],
++ ["assistant", "还在跑"],
++ ["assistant", "后台命令跑完了"],
++ ]);
++ // 没有醒着的一轮(已经有人跟着、或者随代理进程没了):什么也不发
++ await s.rt.wake("b1", CONV);
++ expect(seen).toHaveLength(1);
++ });
++
++ it("the app shuts down during a wake-up turn: no reply, the marker stays", async () => {
++ const s = setup();
++ const a = s.send("BGJOB please");
++ await until(() => s.pending.length === 1);
++ s.pending[0].resolve(reply);
++ await a;
++ const ops: OutboundOp[] = [];
++ s.rt.registerReplier("b1", "weixin", () => ({ out: { apply: async (op) => void ops.push(op) } }));
++ s.wake("S:t2");
++ const w = s.rt.wake("b1", CONV);
++ await until(() => !!s.follow());
++ s.rt.shutdown();
++ s.follow()!.reject(new Error("代理进程已退出"));
++ await w;
++ expect(ops.some((o) => o.type === "stream.finish")).toBe(false);
++ expect(JSON.parse(s.marker()!).preview).toBe("BGJOB please");
++ });
++});