A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
feat(group): batch fan-in barrier, promise retry, idle loop guard and subagent stop
Fei2411f77c92e3eccc
diff --git a/docs/plans/2026-10-07-group-chat.md b/docs/plans/2026-10-07-group-chat.mdindex 10ed2b4f..a1f8d3f6 100644--- a/docs/plans/2026-10-07-group-chat.md+++ b/docs/plans/2026-10-07-group-chat.md@@ -26,8 +26,8 @@- 一轮进行中用户发的话立刻写进群,交给它该叫的人(管理员模式下是管理员),不排在正在回答的成员后面。- 一个成员同一时间只回答一个叫它的消息;前一个回答完(或转去后台干活)才开始下一个。- 全员轮流的普通消息(不带 `@`)仍按顺序:上一个人发完(或跳过)下一个人才开始,每个人看到本轮之前所有人的发言和自己的位置。-- 回复里 `@` 了别人,被点的人接着说(接力)。接力次数、每人每轮、每轮总数都没有上限;用户的消息一定有人回应。要停下群里的工作,用户在群详情里点「全部停止」或逐个停。-- 每个成员可以跳过(`[PASS]`),不必每轮都说话。+- 回复里 `@` 了别人,被点的人接着说(接力)。有实质进展(调了工具、产出新内容)的接力不设次数上限;只有 Bot 之间连续 6 轮 0 工具调用且只是重复或客套确认时,才会暂停并在群里提示,等用户发言后继续。要主动停下群里的工作,用户在群详情里点「全部停止」或逐个停。+- 每个成员可以跳过(`[PASS]`),不必每轮都说话。被点名干活的成员如果只回复「收到 / 现在去查」却没调任何工具就结束回合,宿主会自动把这句作为进度发到群里并在同一调用上续推一次,让它真正调用工具把活做完(#469)。### 提及@@ -46,14 +46,16 @@### 干活中的进度和迟到的回复- 成员在群里接到需要干活的任务时,第一次调用工具后 15 秒仍在干活,本轮就继续往下走,不再等它。-- 干活过程中,它说的第一句话和带 `@` 的话立刻发到群里;间隔不到 30 秒的几句合并成一条发。最后的结果由派活的 Bot(管理员或叫它的成员)接话。+- 干活过程中,它说的第一句话和带 `@` 的话立刻发到群里;间隔不到 30 秒的几句合并成一条发。轮次进行中进来的 Bot 群帖、进度和完成消息直接并入当前轮次处理,不再额外塞进群 Session 的待发队列(#663)。+- 派活按批次收回:不管被点名的成员是在 15 秒内干完还是 15 秒后干完,也不管回复里有没有手写 `@派活人`,只要调了工具干完活(或明确提出需要管理员拍板),都算作该批次的子项完成;同一条消息并行点名多个人时,各自完成的话立刻发到群里,等这一批全部落地后再统一唤醒派活的 Bot 一次(#619)。- 本轮结束后才完成的回复照样发进群,它叫的人照样接着说。- 回答超时只在成员的会话完全没有动静时计时(4 分钟)。没及时回应、需要审批的成员各在群里留一行淡色事件,让用户知道发生了什么。### 审批与状态- 群里成员的审批请求(例如提权)由 DS Bot 接到群里:输入框上方的状态胶囊列出正在忙的成员,等审批的排在前面;点开群详情可以「允许一次」或「拒绝」。需要审批的成员立刻让出发言。-- 有成员在本群干活(含等审批)时,群详情的成员列表标题旁有一个「全部停止」按钮:一次停掉本群正在跑的一轮和每个成员在本群的工作,被停下的成员各在群里留一行「已叫停」;它们在私聊和别的群里的活照常。DSH 自己的停止只停这一轮,轮次放手后还在干活的成员停不到;群详情里仍可以逐个停。+- 成员在群里派出的 DSH 子代理(`subagent`)运行期间,即使成员自己的回合先结束,该成员在群里仍保持忙碌状态并计入派活批次;群详情里的「全部停止」和单成员「停止」会一并中断子代理并忽略其后续结算通知(#701)。+- 有成员在本群干活(含等审批、跑子代理)时,群详情的成员列表标题旁有一个「全部停止」按钮:一次停掉本群正在跑的一轮和每个成员在本群的工作,被停下的成员各在群里留一行「已叫停」;它们在私聊和别的群里的活照常。DSH 自己的停止只停这一轮,轮次放手后还在干活的成员停不到;群详情里仍可以逐个停。- 群的工作文件夹和统一权限是群级设置,见 [角色与权限](2026-10-07-roles-and-permissions.md)。### 群的设置@@ -95,3 +97,4 @@- 2026-10-29:群的停止按钮一次停掉本群的一轮和所有成员在本群的工作,放在群详情的成员列表标题旁,不放在状态胶囊旁(#592,PR #616)。- 2026-10-30:去掉 Bot 之间接力的上限、群设置里的这一项和「继续」按钮;以前停在上限的叫人在群的下一轮接着跑(#655)。- 2026-10-30:同一条消息点到的成员同时开工,`@` 一发出来就生效,一轮中用户的话和 Bot 的帖马上交给该叫的人;只有全员轮流的普通消息还按顺序(#726)。+- 2026-10-31:派活按批次收回并等同一批全部落地后统一叫醒派活 Bot(#619);只回「收到/开工」未调工具的回合自动续推一次(#469);连续 6 轮 0 工具重复或客套空转自动暂停;运行中已吸收的群帖不再塞进群 Session 待发队列(#663);群成员派出的 DSH 子代理并入群忙碌状态与停止控制(#701)。diff --git a/ds-bot/client.js b/ds-bot/client.jsindex 255db8d8..57d20937 100644--- a/ds-bot/client.js+++ b/ds-bot/client.js@@ -4332,7 +4332,7 @@ var HANDOFF_CSS = `.bt-handoff .bt-q-foot{flex-wrap:wrap}`;-// node_modules/deep-view/src/react/ui.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/react/ui.jsvar import_react7 = require("react");var FallbackMarkdown = ({ text }) => (0, import_react7.createElement)("span", null, String(text ?? ""));var ViewUi = (0, import_react7.createContext)({ t: (key) => key, Markdown: FallbackMarkdown });@@ -4399,7 +4399,7 @@ function useOptionKeys2(count, onPick, ownRef) {return count > 0 && listening <= 1;}-// node_modules/deep-view/src/core/formula.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/core/formula.jsvar FUNCTIONS = {min: { args: [1, Infinity], run: (...values) => Math.min(...values.map(num)) },max: { args: [1, Infinity], run: (...values) => Math.max(...values.map(num)) },@@ -4680,7 +4680,7 @@ function evaluate(tree, lookup) {}}-// node_modules/deep-view/src/core/views.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/core/views.jsvar LAYOUT = ["stack", "row"];var DISPLAY = ["text", "metric", "table", "chart", "progress", "callout", "sources", "html"];var INPUT_TYPES = ["slider", "choice", "toggle", "number"];@@ -5300,7 +5300,7 @@ function validateForm(node, values) {return { fields };}-// node_modules/deep-view/src/react/chart.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/react/chart.jsvar import_react8 = require("react");var PALETTE = ["var(--dv-accent)", "var(--dv-ink-tangerine)", "var(--dv-ink-green)", "var(--dv-ink-violet)", "var(--dv-ink-sky)", "var(--dv-ink-rose)", "var(--dv-ink-yellow)", "var(--dv-ink-cyan)", "var(--dv-ink-magenta)"];var colorAt = (index) => PALETTE[index % PALETTE.length];@@ -5739,7 +5739,7 @@ var CHART_CSS = `@media (prefers-reduced-motion:reduce){.dv-chart-mark,.dv-chart-dot{transition:none}.dv-chart-tip{animation:none}}`;-// node_modules/deep-view/src/react/frame.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/react/frame.jsvar import_react9 = require("react");var THEME_VARS = [["--view-ink", "--bt-ink", "--dv-ink"],@@ -5821,7 +5821,7 @@ var HTML_CSS = `.dv-view-frame-stopped{margin:0;font-size:13px;line-height:18px;color:var(--dv-ink-2)}`;-// node_modules/deep-view/src/react/card.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/react/card.jsvar import_react10 = require("react");var mdLabels = (ui2) => ({ code: { copyLabel: ui2.t("Copy"), copiedLabel: ui2.t("Copied") }, footnotes: ui2.t("Footnotes") });var TONES2 = ["good", "warn", "bad"];@@ -6490,7 +6490,7 @@ ${CHART_CSS}${HTML_CSS}`;-// node_modules/deep-view/src/react/styles.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/react/styles.jsvar THEME_CSS = `body{--dv-ink:var(--dsw-alias-label-primary);@@ -6587,10 +6587,10 @@ button.dv-q-opt:active{background:var(--dv-active)}@media (prefers-reduced-motion:reduce){.dv-q,.dv-view-bare,.dv-q-submit,.dv-menu,.dv-q-check{animation:none}}`;-// node_modules/deep-view/src/react/index.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/react/index.jsvar DEEP_VIEW_CSS = THEME_CSS + QUESTION_CSS + WIDGET_CSS;-// node_modules/deep-view/src/core/reply.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/deep-view/src/core/reply.jsvar REPLY_KIND = "user-question-reply";function viewCardText(args) {let card = args;diff --git a/ds-bot/office.js b/ds-bot/office.jsindex ada743e1..a4aab41b 100644--- a/ds-bot/office.js+++ b/ds-bot/office.js@@ -34,9 +34,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__gemod));-// node_modules/@xmldom/xmldom/lib/conventions.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/conventions.jsvar require_conventions = __commonJS({- "node_modules/@xmldom/xmldom/lib/conventions.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/conventions.js"(exports) {"use strict";function find(list, predicate, ac) {if (ac === void 0) {@@ -243,9 +243,9 @@ var require_conventions = __commonJS({}});-// node_modules/@xmldom/xmldom/lib/errors.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/errors.jsvar require_errors = __commonJS({- "node_modules/@xmldom/xmldom/lib/errors.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/errors.js"(exports) {"use strict";var conventions = require_conventions();function extendError(constructor, writableName) {@@ -402,9 +402,9 @@ var require_errors = __commonJS({}});-// node_modules/@xmldom/xmldom/lib/grammar.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/grammar.jsvar require_grammar = __commonJS({- "node_modules/@xmldom/xmldom/lib/grammar.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/grammar.js"(exports) {"use strict";function detectUnicodeSupport(RegExpImpl) {try {@@ -609,9 +609,9 @@ var require_grammar = __commonJS({}});-// node_modules/@xmldom/xmldom/lib/dom.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/dom.jsvar require_dom = __commonJS({- "node_modules/@xmldom/xmldom/lib/dom.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/dom.js"(exports) {"use strict";var conventions = require_conventions();var find = conventions.find;@@ -3276,9 +3276,9 @@ var require_dom = __commonJS({}});-// node_modules/@xmldom/xmldom/lib/entities.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/entities.jsvar require_entities = __commonJS({- "node_modules/@xmldom/xmldom/lib/entities.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/entities.js"(exports) {"use strict";var freeze = require_conventions().freeze;exports.XML_ENTITIES = freeze({@@ -5419,9 +5419,9 @@ var require_entities = __commonJS({}});-// node_modules/@xmldom/xmldom/lib/sax.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/sax.jsvar require_sax = __commonJS({- "node_modules/@xmldom/xmldom/lib/sax.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/sax.js"(exports) {"use strict";var conventions = require_conventions();var g = require_grammar();@@ -6201,9 +6201,9 @@ var require_sax = __commonJS({}});-// node_modules/@xmldom/xmldom/lib/dom-parser.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/dom-parser.jsvar require_dom_parser = __commonJS({- "node_modules/@xmldom/xmldom/lib/dom-parser.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/dom-parser.js"(exports) {"use strict";var conventions = require_conventions();var dom = require_dom();@@ -6469,9 +6469,9 @@ var require_dom_parser = __commonJS({}});-// node_modules/@xmldom/xmldom/lib/index.js+// ../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/index.jsvar require_lib = __commonJS({- "node_modules/@xmldom/xmldom/lib/index.js"(exports) {+ "../../../DS Bot/DeepSeek-Bot/ds-bot/node_modules/@xmldom/xmldom/lib/index.js"(exports) {"use strict";var conventions = require_conventions();exports.assign = conventions.assign;diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.jsindex 25d00f01..73f1bbb6 100644--- a/ds-bot/src/host/constants.js+++ b/ds-bot/src/host/constants.js@@ -72,6 +72,9 @@ export const TEAM_TOOLS = [// A member still at work this long after its first tool call lets the round go on; it// posts its reply when the work is done.export const ROOM_WORK_GRACE_MS = 15_000+// Consecutive Bot-to-Bot relays with no tool call and only repetitive or ack text+// before the round parks the remaining calls and asks the user before continuing.+export const ROOM_IDLE_RELAY_LIMIT = 6export const OWN_CHAT_LINE_MAX = 400// The message an anchor points at is shown whole (up to this), so a long draft takesdiff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 2cf4cebd..ab8364d8 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -22,7 +22,7 @@ import { readFile, rm } from 'node:fs/promises'import { join } from 'node:path'import { createUserMessage } from '@deepseek-ai/dsh-llm'import { defineTool } from '@deepseek-ai/dsh-tools'-import { GROUP_LINE_READ, ROOM_REPLY_TIMEOUT_MS, ROOM_STEP_GAP_MS, ROOM_WORK_GRACE_MS, SOURCE_KIND, TEAM_TOOLS, TEXT_KEPT } from './constants.js'+import { GROUP_LINE_READ, ROOM_IDLE_RELAY_LIMIT, ROOM_REPLY_TIMEOUT_MS, ROOM_STEP_GAP_MS, ROOM_WORK_GRACE_MS, SOURCE_KIND, TEAM_TOOLS, TEXT_KEPT } from './constants.js'import { escapeRegExp, headOf, splitRef, textOf } from './text.js'import { mentionSpans, speakerOf } from '../shared/mentions.js'import { GROUP_REF, output } from './tools.js'@@ -33,6 +33,26 @@ const ROOM_FIRST_LOOK = 12const ROOM_DELTA_MAX = 24const ROOM_EARLIER_MAX = 8+// A reply that hands back an unresolved decision to the admin or caller without @Name (#619).+const NEEDS_CALLER_DECISION = /需要.*(?:决定|拍板|确认|指示|裁决|定夺)|请.*(?:管理员|负责人|组长|拍板|决定|指示|确认)|等.*(?:管理员|负责人|决定|拍板|指示)|\b(?:need|needs|waiting\s+for|requires)\s+(?:the\s+)?(?:admin|lead|leader|chief|you)\s+to\s+(?:decide|confirm|choose|approve|pick)\b/i+const needsCallerDecision = text => typeof text === 'string' && NEEDS_CALLER_DECISION.test(text)++// Short ack/thanks/closing phrases with no new content, used by the 0-tool idle loop guard.+const IDLE_ACK_BODY = /^(?:(?:收到|好的|好|明白|明白了|了解|了解了|没问题|谢谢|多谢|感谢|辛苦了|辛苦|不客气|不用谢|完毕|完成|好嘞|行|ok|okay|got\s+it|understood|noted|thanks|thank\s+you|you\s+are\s+welcome|you're\s+welcome|welcome|np|no\s+problem|roger|ack|done|all\s+good|sounds\s+good)(?:[\s,,、。.!!~~::]+|$))+$/i+const normalizeRelayBody = (text, everyone) => {+ let out = String(text ?? '')+ for (const bot of everyone) {+ out = out.replace(new RegExp(`@${escapeRegExp(bot.name)}\\b`, 'gi'), '')+ out = out.replaceAll(`@${bot.name}`, '')+ }+ return out.replace(/@(?:all|everyone|所有人|全体)/gi, '').replace(/[\s,,、。.!!??;;::'"“”‘’()()[\]【】~~-]+/g, ' ').trim().toLowerCase()+}+const isIdleRelayText = (text, everyone, priorBodies) => {+ const norm = normalizeRelayBody(text, everyone)+ if (norm === '' || (norm.length <= 45 && IDLE_ACK_BODY.test(norm))) return true+ return priorBodies.some(prev => prev !== '' && (prev === norm || (prev.length >= 8 && norm.length >= 8 && (prev.includes(norm) || norm.includes(prev)))))+}+// Logs written before rooms were versioned get sequence numbers in place.const ensureRoomLog = (room) => {if (typeof room.seq !== 'number') {@@ -93,7 +113,7 @@ export const referenceNote = references => (references?.length? `Conversations the user referenced in this round:\n\n${references.map(reference => reference.text).join('\n\n')}`: '')-const ROOM_REPLY = 'Reply with your message for the group, no name prefix: in a discussion, one or two short messages. When you are asked to do something, do it now with your tools. The group does not wait for you and sees what you write while you work: say what you will do, write again only when something matters, and end with the result, never a promise to do it later. Reply [PASS] to stay silent when you have nothing new to add or the message is for someone else.'+const ROOM_REPLY = 'Reply with your message for the group, no name prefix: in a discussion, one or two short messages. When you are asked to do something, call your first tool in the same step as your opening note — if you stop without a tool call, your turn ends and no work runs. The group does not wait for you and sees what you write while you work: say what you will do, write again only when something matters, and end with the result, never a promise to do it later. Reply [PASS] to stay silent when you have nothing new to add or the message is for someone else.'const ROOM_CALLS = 'Writing "@Name" calls that member at once, to answer or to do what you ask, as soon as your message is posted: call members before you start on your own part. Members called in one message start together and do not see each other\'s replies until they post, so when one needs another\'s result, call the first and ask it to call the next. When a member finishes work you gave it, you answer its result. To only mention a member, write its name without "@".'const slotLabel = (slot, self) => {@@ -279,11 +299,18 @@ export function install(rt) {return lines}- // Members whose turn in this group is running, and since when.+ // Members whose turn or DSH subagent in this group is running, and since when.const workingIn = room => room.members.flatMap((id) => {- const entry = rt.live.get(room.sessions?.[id])+ const sessionId = room.sessions?.[id]+ const entry = rt.live.get(sessionId)const bot = rt.botOf(id)- return entry?.turn !== undefined && bot !== undefined ? [{ bot, since: entry.since ?? Date.now() }] : []+ if (bot === undefined) return []+ if (entry?.turn !== undefined) return [{ bot, since: entry.since ?? Date.now() }]+ if (sessionId !== undefined && rt.hasSubagents?.(sessionId)) {+ const subSince = rt.roomWorkView?.()?.[room.id]?.find(item => item.botId === id)?.since+ return [{ bot, since: subSince ?? Date.now() }]+ }+ return []})// How many group lines a member has not been shown yet, counted the same way a// round counts the lines it carries over (unseenLines), so the number a speaker@@ -293,6 +320,72 @@ export function install(rt) {const unreadCount = (room, botId) => unseenLines(room, botId).lengthconst minutesSince = at => Math.max(1, Math.round((Date.now() - at) / 60000))+ // Active Bot-to-Bot call batches in groups: when Bot `by` calls one or more members+ // together (`@B @C`), the batch tracks which callees are still working so:+ // 1) a callee that finishes tool work within the round (< 15s) without writing `@by`+ // still hands the result back to `by` (#619), and+ // 2) when multiple callees work in parallel, `by` is woken once when the last callee+ // in the batch finishes rather than woken piecemeal on every early reply.+ const roomBatches = new Map()+ const memberBatch = new Map()+ const batchKeyOf = (roomId, botId) => `${roomId}:${botId}`++ const activeInRoom = (room, botId) => {+ const sessionId = room.sessions?.[botId]+ if (sessionId !== undefined && (rt.live.get(sessionId)?.turn !== undefined || rt.hasSubagents?.(sessionId) === true)) return true+ return [...rt.roomProgress.values()].some(round => round.roomId === room.id+ && round.slots.some(slot => slot.id === botId && (slot.status === 'waiting' || slot.status === 'speaking')))+ }++ const registerBatch = (roomId, by, callees) => {+ if (by === undefined || callees.length === 0) return undefined+ const batch = {+ key: randomUUID(),+ roomId,+ by,+ pending: new Set(callees.map(peer => peer.id)),+ done: [],+ worked: false,+ answered: false,+ }+ roomBatches.set(batch.key, batch)+ for (const peer of callees) {+ const mKey = batchKeyOf(roomId, peer.id)+ const prev = memberBatch.get(mKey)+ if (prev !== undefined) {+ prev.pending.delete(peer.id)+ if (prev.pending.size === 0) roomBatches.delete(prev.key)+ }+ memberBatch.set(mKey, batch)+ }+ return batch.key+ }++ const markBatchWorked = (roomId, botId) => {+ const batch = memberBatch.get(batchKeyOf(roomId, botId))+ if (batch !== undefined) batch.worked = true+ }++ const pruneBatchPending = (room, batch) => {+ for (const otherId of batch.pending) {+ if (!room.members.includes(otherId) || !activeInRoom(room, otherId)) {+ batch.pending.delete(otherId)+ if (memberBatch.get(batchKeyOf(room.id, otherId)) === batch) memberBatch.delete(batchKeyOf(room.id, otherId))+ }+ }+ }++ const dropMemberFromBatch = (room, botId) => {+ const mKey = batchKeyOf(room.id, botId)+ const batch = memberBatch.get(mKey)+ if (batch === undefined) return undefined+ memberBatch.delete(mKey)+ batch.pending.delete(botId)+ pruneBatchPending(room, batch)+ if (batch.pending.size === 0) roomBatches.delete(batch.key)+ return batch+ }+// A member's message in the round: in the log, for the members after it, and in the// round's replies, for the user.const postInRound = (room, round, member, text, duration) => {@@ -309,7 +402,7 @@ export function install(rt) {// called it, which answers what the turn posts after the round moved on. What the// member writes before its last step is posted at once and collected in `said`, and// `heard` takes each such line once it is posted.- async function roomTurn(room, member, sessionId, { text, files }, note, signal, round, by, said = [], heard = () => {}) {+ async function roomTurn(room, member, sessionId, { text, files }, note, signal, round, by, said = [], heard = () => {}, onWork = () => {}) {if (signal.aborted) return nullconst startedAt = Date.now()const exchangeId = randomUUID()@@ -320,7 +413,7 @@ export function install(rt) {// delivery lands: a delivery that failed leaves the member where it was.const seenAt = room.seq// Checked before the delivery, which may start the turn at once.- const busy = rt.live.get(sessionId)?.turn !== undefined+ const busy = rt.live.get(sessionId)?.turn !== undefined || rt.hasSubagents?.(sessionId) === trueconst done = new Promise((resolve) => {let timerlet grace@@ -334,7 +427,10 @@ export function install(rt) {clearTimeout(timer)timer = setTimeout(() => finish({ missed: true }), ROOM_REPLY_TIMEOUT_MS)}- const work = () => { grace ??= setTimeout(() => finish({ working: true }), ROOM_WORK_GRACE_MS) }+ const work = () => {+ onWork()+ grace ??= setTimeout(() => finish({ working: true }), ROOM_WORK_GRACE_MS)+ }const say = (raw) => {const step = stripOwnName(member.name, raw)if (isPass(step)) return@@ -367,7 +463,7 @@ export function install(rt) {}const reply = await done// A turn that ended leaves nothing for a stop to cancel.- if (typeof reply === 'string' || reply?.failure !== undefined) started.splice(started.indexOf(turn), 1)+ if ((typeof reply === 'string' || reply?.failure !== undefined) && !rt.hasSubagents?.(sessionId)) started.splice(started.indexOf(turn), 1)if (reply === null || typeof reply === 'object') return replyreturn stripOwnName(member.name, String(reply ?? '').trim())}@@ -390,6 +486,8 @@ export function install(rt) {const QUICK_TOOLS = new Set(TEAM_TOOLS)rt.workRoomTurn = (sessionId, tool) => {if (QUICK_TOOLS.has(tool)) return+ const owner = rt.groupOwners.get(sessionId)+ if (owner !== undefined) markBatchWorked(owner.roomId, owner.botId)for (const waiter of waitersOf(sessionId)) waiter.work()}// The group Session's inbox changed: a running round looks for the user's messages@@ -409,6 +507,7 @@ export function install(rt) {function callIn(round, callees, note, by, { ordered = false } = {}) {if (callees.length === 0) returnround.batches = (round.batches ?? 0) + 1+ const batchKey = registerBatch(round.roomId, by, callees)let lastfor (const peer of callees) {const waiting = round.slots.findIndex(slot => slot.id === peer.id && slot.status === 'waiting')@@ -417,6 +516,7 @@ export function install(rt) {if (moves && waiting !== -1) round.slots.splice(waiting, 1)slot.note = noteslot.batch = round.batches+ if (batchKey !== undefined) slot.batchKey = batchKeyif (by === undefined) delete slot.byelse slot.by = byif (!moves) slot.ordered = false@@ -441,16 +541,20 @@ export function install(rt) {}// LEGACY: groups used to park Bot calls past a relay limit until the user went on.- // Calls still parked from then run in the group's next round, with its opening- // speakers; one already waiting in the round is not called twice.+ // Calls still parked from then (or by the idle ping-pong guard) run in the group's+ // next round, with its opening speakers; one already waiting in the round is not+ // called twice.const releaseParked = (room, round) => {const parked = room.paused ?? []delete room.pausedfor (const entry of parked) {if (round.slots.some(slot => slot.id === entry.id && slot.status === 'waiting')) continue+ const peer = rt.botOf(entry.id)+ const batchKey = peer && entry.by !== undefined ? registerBatch(room.id, entry.by, [peer]) : undefinedround.batches = (round.batches ?? 0) + 1round.slots.push({id: entry.id, name: entry.name, status: 'waiting', batch: round.batches,+ ...(batchKey !== undefined ? { batchKey } : {}),...(entry.note !== undefined ? { note: entry.note } : {}),...(entry.by !== undefined ? { by: entry.by } : {}),})@@ -482,6 +586,7 @@ export function install(rt) {if (round.kickoff) returnconst lines = waitingLines(agent).filter(line => agent.inbox.remove(line.id))if (lines.length === 0) return+ round.idleRelays = 0const members = room.members.map(rt.botOf).filter(Boolean)for (const line of lines) {appendRoom(room, { who: 'User', text: line.text })@@ -497,7 +602,10 @@ export function install(rt) {// The members a member's message calls: those it names with @, or everyone when the// admin writes "@all" (only the admin, so a member cannot set off a storm). A turn// calls each member once, however many of its lines name it.- function callFrom(room, round, member, text, called) {+ // When Bots bounce 0-tool repetitive or ack-only messages back and forth for+ // ROOM_IDLE_RELAY_LIMIT consecutive turns, the next call is parked in `room.paused`+ // with a notice until the user writes.+ function callFrom(room, round, member, text, called, { worked = false, byBot = false } = {}) {const everyone = room.members.map(rt.botOf).filter(Boolean)const others = everyone.filter(other => other.id !== member.id)const { all, found: named } = mentionsIn(text, everyone)@@ -505,6 +613,33 @@ export function install(rt) {const callees = (rt.isAdminOf(room, member.id) && all ? [...found, ...others.filter(other => !found.includes(other))] : found).filter(peer => !called.has(peer.id))for (const peer of callees) called.add(peer.id)+ if (callees.length === 0) return+ if (worked) {+ round.idleRelays = 0+ } else if (byBot) {+ const history = round.botBodies?.get(member.id) ?? []+ if (isIdleRelayText(text, everyone, history)) round.idleRelays = (round.idleRelays ?? 0) + 1+ else round.idleRelays = 0+ const norm = normalizeRelayBody(text, everyone)+ if (norm !== '') (round.botBodies ??= new Map()).set(member.id, [...history, norm])+ if ((round.idleRelays ?? 0) >= ROOM_IDLE_RELAY_LIMIT) {+ const parked = room.paused ?? []+ for (const peer of callees) {+ if (!parked.some(entry => entry.id === peer.id)) {+ parked.push({ id: peer.id, name: peer.name, note: `${member.name} mentioned you`, by: member.id })+ }+ }+ room.paused = parked+ const names = callees.map(peer => peer.name)+ appendRoom(room, { who: 'DS Bot', kind: 'notice', reason: 'paused', limit: ROOM_IDLE_RELAY_LIMIT, names })+ round.replies.push({ kind: 'paused', count: ROOM_IDLE_RELAY_LIMIT, limit: ROOM_IDLE_RELAY_LIMIT, names, time: Date.now() })+ void rt.save().catch(() => {})+ return+ }+ } else {+ const norm = normalizeRelayBody(text, everyone)+ if (norm !== '') (round.botBodies ??= new Map()).set(member.id, [...(round.botBodies?.get(member.id) ?? []), norm])+ }callIn(round, callees, `${member.name} mentioned you`, member.id)}@@ -555,6 +690,7 @@ export function install(rt) {// Settings may change mid-round, for example when the admin removes someone.if (member === undefined || !room.members.includes(slot.id)) {slot.status = 'left'+ dropMemberFromBatch(room, slot.id)return}slot.status = 'speaking'@@ -564,12 +700,14 @@ export function install(rt) {} catch (error) {rt.warn('ds-bot: group Session for %s in %s failed: %s', member.name, room.name, error)slot.status = 'failed'+ dropMemberFromBatch(room, member.id)round.failed.push(member.name)round.replies.push({ kind: 'failed', botId: member.id, name: member.name, color: member.color, code: 'SESSION', text: String(error?.message ?? error).slice(0, 300), time: Date.now() })return}if (session === undefined) {slot.status = 'left'+ dropMemberFromBatch(room, member.id)return}await loadGroupLines(room)@@ -579,8 +717,20 @@ export function install(rt) {const said = []const called = new Set()const startedAt = Date.now()- const reply = await roomTurn(room, member, session.id, { text, files: prompt.files }, slot.note ?? 'your turn', signal, round, slot.by, said, line => callFrom(room, round, member, line, called))+ let worked = false+ const onWork = () => {+ worked = true+ slot.worked = true+ round.idleRelays = 0+ markBatchWorked(room.id, member.id)+ }+ const reply = await roomTurn(+ room, member, session.id, { text, files: prompt.files }, slot.note ?? 'your turn', signal, round, slot.by, said,+ line => callFrom(room, round, member, line, called, { worked, byBot: slot.by !== undefined }),+ onWork,+ )const final = typeof reply === 'string' && !isPass(reply) ? reply : undefined+ const subRunning = rt.hasSubagents?.(session.id) === trueif (reply?.failure !== undefined) {// Not a pass: the user sees why the member is silent, and the round goes on.slot.status = 'failed'@@ -593,12 +743,21 @@ export function install(rt) {round.replies.push({ kind: 'approval', botId: member.id, name: member.name, color: member.color, time: Date.now() })} else if (reply?.working) {slot.status = 'working'+ markBatchWorked(room.id, member.id)+ round.replies.push({ kind: 'working', botId: member.id, name: member.name, color: member.color, time: Date.now() })+ } else if (subRunning) {+ if (final !== undefined) {+ postInRound(room, round, member, final, Date.now() - startedAt)+ callFrom(room, round, member, final, called, { worked: true, byBot: slot.by !== undefined })+ }+ slot.status = 'working'+ markBatchWorked(room.id, member.id)round.replies.push({ kind: 'working', botId: member.id, name: member.name, color: member.color, time: Date.now() })} else if (final !== undefined || (typeof reply === 'string' && said.length > 0)) {slot.status = 'posted'if (final !== undefined) {postInRound(room, round, member, final, Date.now() - startedAt)- callFrom(room, round, member, final, called)+ callFrom(room, round, member, final, called, { worked, byBot: slot.by !== undefined })}} else {slot.status = typeof reply === 'string' ? 'passed' : 'missed'@@ -611,6 +770,31 @@ export function install(rt) {appendRoom(room, { who: 'DS Bot', kind: 'notice', reason: 'missed', names: [member.name], minutes: Math.round(ROOM_REPLY_TIMEOUT_MS / 60000) })}}+ // Settle the member's place in its call batch when its work did not continue in the background.+ if (slot.status !== 'working') {+ const batch = (slot.batchKey ? roomBatches.get(slot.batchKey) : undefined) ?? memberBatch.get(batchKeyOf(room.id, member.id))+ if (batch !== undefined) {+ if (slot.status === 'posted') {+ batch.done.push(member.name)+ if (called.size > 0) batch.answered = true+ if (worked || needsCallerDecision(final)) batch.worked = true+ }+ dropMemberFromBatch(room, member.id)+ if (batch.pending.size === 0 && batch.done.length > 0 && batch.worked && !batch.answered && !signal.aborted) {+ const caller = rt.botOf(batch.by)+ if (caller !== undefined && room.members.includes(caller.id)+ && !round.slots.some(other => other.id === caller.id && (other.status === 'waiting' || other.status === 'speaking'))) {+ callIn(round, [caller], `${batch.done.join(' and ')} finished the work you asked for`, undefined)+ }+ }+ } else if (slot.status === 'posted' && called.size === 0 && needsCallerDecision(final) && room.mode === 'admin' && room.admin && room.admin !== member.id) {+ const admin = rt.botOf(room.admin)+ if (admin !== undefined && room.members.includes(admin.id)+ && !round.slots.some(other => other.id === admin.id && (other.status === 'waiting' || other.status === 'speaking'))) {+ callIn(round, [admin], `${member.name} finished the work and needs your decision`, undefined)+ }+ }+ }}ctx.tools.register(defineTool({@@ -656,6 +840,8 @@ export function install(rt) {// A member a Bot's post calls by name works for that Bot.const named = opener.botId === undefined ? [] : mentionsIn(opener.text ?? '', room.members.map(rt.botOf).filter(Boolean)).foundconst { speakers, ordered } = openingCall(room, opener)+ const calledByOpener = speakers.filter(member => named.includes(member))+ const openingBatchKey = opener.botId !== undefined && calledByOpener.length > 0 ? registerBatch(room.id, opener.botId, calledByOpener) : undefined// The admin alone with the user's message: when it passes, the round ends with// nothing said, and the group says so once.const admin = room.members.map(rt.botOf).filter(Boolean).find(bot => rt.isAdminOf(room, bot.id))@@ -671,7 +857,7 @@ export function install(rt) {id: member.id, name: member.name, status: 'waiting', batch: 1,...(ordered ? { ordered: true } : {}),...(opener.kickoff ? { note: 'the group was just created' } : {}),- ...(named.includes(member) ? { by: opener.botId } : {}),+ ...(named.includes(member) ? { by: opener.botId, ...(openingBatchKey ? { batchKey: openingBatchKey } : {}) } : {}),...(opener.done ? { note: `${opener.name ?? 'a member'} finished the work you asked for` } : {}),})),batches: 1,@@ -831,7 +1017,13 @@ export function install(rt) {const { all, found: named } = mentionsIn(opener.text, everyone, opener.references)const found = named.filter(bot => bot.id !== opener.botId)if (opener.progress) return at(found)- if (opener.late) return at(found.length > 0 ? found : members.filter(bot => bot.id === opener.askedBy))+ if (opener.late) {+ if (found.length > 0) return at(found)+ const asked = members.filter(bot => bot.id === opener.askedBy)+ if (asked.length > 0) return at(asked)+ if (needsCallerDecision(opener.text) && room.mode === 'admin' && admin) return at([admin])+ return at([])+ }if (opener.member) return at(found)if (found.length > 0 && !all) return at(found)if (!all && room.mode === 'admin' && admin) return at([admin])@@ -845,7 +1037,8 @@ export function install(rt) {// wants the replies (`reportBack`) gets those of the members it called when the// round ends.function callPost(room, round, sender, text, extra) {- if (extra.failed !== undefined || extra.resumed || extra.stopped) return false+ if (extra.failed !== undefined && !extra.askedBy) return false+ if (extra.resumed || extra.stopped) return falseconst post = { ...extra, botId: sender.id, name: sender.name, text }const { speakers, ordered } = openingCall(room, post)if (speakers.length === 0) return false@@ -864,12 +1057,9 @@ export function install(rt) {// A Bot's message into the group's own Session, which relays it as a new round.// While a round runs, the post goes into the group's log and that round's replies at// once, and the members it calls start in that round, so it is not held back until- // the round ends; the relay it still opens does not write it again (source `logged`)- // nor call them again (source `called`).+ // the round ends and never sits in the group Session's QueueDock (#663).async function postToRoom(room, sender, text, extra = {}, files = []) {- const running = [...rt.roomProgress.values()].find(round => round.roomId === room.id)- let logged- let called = false+ const running = [...rt.roomProgress.values()].find(round => round.roomId === room.id && round.nudge !== undefined)if (running !== undefined) {ensureRoomLog(room)if (extra.failed !== undefined) {@@ -877,25 +1067,23 @@ export function install(rt) {const { code, status, message } = extra.failedrunning.failed.push(sender.name)running.replies.push({ kind: 'failed', botId: sender.id, name: sender.name, color: sender.color, code, ...(status ? { status } : {}), text: message, time: Date.now() })- logged = true} else if (extra.resumed === true || extra.stopped === true || extra.done === true) {const kind = extra.done === true ? 'done' : extra.stopped === true ? 'stopped' : extra.again === true ? 'cut' : 'resumed'appendRoom(room, { who: sender.name, botId: sender.id, kind, text: '' })running.replies.push({ kind, botId: sender.id, name: sender.name, color: sender.color, time: Date.now() })- logged = room.seq} else {const line = [text, ...files.map(fileLine)].filter(Boolean).join('\n')appendRoom(room, { who: sender.name, botId: sender.id, text: line, ...(files.length > 0 ? { files } : {}) })running.replies.push({ botId: sender.id, name: sender.name, color: sender.color, text: line, time: Date.now() })- logged = room.seq}- called = callPost(room, running, sender, text, extra)+ callPost(room, running, sender, text, extra)await rt.save()+ return}const agent = await rt.resolveAgent(room.id)agent.followup(createUserMessage({content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }, ...files.map(attachment => ({ type: 'file', attachment }))],- source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, ...extra, ...(logged !== undefined ? { logged } : {}), ...(called ? { called: true } : {}) },+ source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, ...extra },}))await ctx.sessions.flush(agent.session)}@@ -903,18 +1091,48 @@ export function install(rt) {// A member the round moved on from (it went on working, went quiet or waited for an// approval) posts what its turn ended with. The member that asked for it and anyone- // it names answer. Work whose result already went out as a step line (`shown`) and- // that ends with nothing more to say still tells the member that asked for it,- // which answers the result: where the result sits in the turn decides nothing.+ // it names answer. When multiple members were called in one batch, each result posts+ // as soon as it is ready, and the caller is woken once when the last member in the+ // batch finishes.async function lateRoomReply(sessionId, info, reply, { shown = false } = {}) {const owner = rt.groupOwners.get(sessionId)const room = rt.roomOf(owner?.roomId ?? info.roomId)const member = rt.botOf(owner?.botId)if (room === undefined || member === undefined || !room.members.includes(member.id)) returnconst text = stripOwnName(member.name, reply)- const done = isPass(text) && shown && info.askedBy !== undefined+ // While a DSH subagent of this member is still running, the member's work is not+ // finished yet: post any non-empty text as a progress line and keep its batch open.+ if (rt.hasSubagents?.(sessionId) === true) {+ if (!isPass(text)) {+ const calls = callsIn(room, member, text)+ await postToRoom(room, member, text, { progress: true, ...(!calls ? { quiet: true } : {}) })+ .catch(error => rt.warn('ds-bot: subagent progress from %s failed: %s', member.name, error))+ }+ return+ }+ const currentBatch = memberBatch.get(batchKeyOf(room.id, member.id))+ const batch = currentBatch !== undefined && (info.role !== 'room' || info.askedBy === currentBatch.by) ? currentBatch : undefined+ const askedBy = info.role === 'room' ? info.askedBy : (info.askedBy ?? batch?.by)+ const named = mentionsIn(text, room.members.map(rt.botOf).filter(Boolean)).found.filter(bot => bot.id !== member.id)+ let waitingPeers = false+ let batchDoneBefore = false+ if (batch !== undefined) {+ if (named.length > 0) batch.answered = true+ if (!isPass(text) || shown) batch.done.push(member.name)+ dropMemberFromBatch(room, member.id)+ waitingPeers = batch.pending.size > 0+ batchDoneBefore = !waitingPeers && batch.done.length > 0 && !batch.answered+ }+ if (waitingPeers && named.length === 0) {+ if (!isPass(text)) {+ await postToRoom(room, member, text, { late: true, quiet: true })+ .catch(error => rt.warn('ds-bot: late group reply from %s failed: %s', member.name, error))+ }+ return+ }+ const done = isPass(text) && (shown || batchDoneBefore) && askedBy !== undefinedif (isPass(text) && !done) return- await postToRoom(room, member, done ? '' : text, { late: true, ...(done ? { done: true } : {}), ...(info.askedBy ? { askedBy: info.askedBy } : {}) })+ await postToRoom(room, member, done ? '' : text, { late: true, ...(done ? { done: true } : {}), ...(askedBy ? { askedBy } : {}) }).catch(error => rt.warn('ds-bot: late group reply from %s failed: %s', member.name, error))}rt.lateRoomReply = lateRoomReply@@ -926,6 +1144,10 @@ export function install(rt) {return room !== undefined && member !== undefined && room.members.includes(member.id) ? { room, member } : undefined}const callsIn = (room, member, text) => mentionsIn(text, room.members.map(rt.botOf).filter(Boolean)).found.some(bot => bot.id !== member.id)+ rt.callsRoomMember = (sessionId, info, raw) => {+ const { room, member } = memberIn(sessionId, info) ?? {}+ return room !== undefined && member !== undefined && callsIn(room, member, stripOwnName(member.name, raw ?? ''))+ }// What a member says while it works, into the group. While the member holds its place// in a round, it joins that round. Later, it joins whatever round runs in the group, or@@ -984,16 +1206,23 @@ export function install(rt) {}rt.withRoomSteps = (lines, reply) => (lines === '' ? reply : isPass(reply) ? lines : `${lines}\n\n${reply}`)- // The user stops a member's work in this group from the group's details. Messages- // still waiting for that member here go with it.+ // The user stops a member's work in this group from the group's details, including+ // any running DSH subagents it spawned (#701). Messages still waiting for that+ // member here go with it.async function stopMemberWork(roomId, botId) {await rt.load()const room = rt.roomOf(roomId)const member = rt.botOf(botId)const sessionId = rt.own(room?.sessions, botId)- if (room === undefined || member === undefined || sessionId === undefined || rt.live.get(sessionId)?.turn === undefined) return false- const agent = await rt.resolveAgent(sessionId)- agent.cancel({ kind: 'user' })+ const turnRunning = sessionId !== undefined && rt.live.get(sessionId)?.turn !== undefined+ const subRunning = sessionId !== undefined && rt.hasSubagents?.(sessionId) === true+ if (room === undefined || member === undefined || sessionId === undefined || (!turnRunning && !subRunning)) return false+ dropMemberFromBatch(room, botId)+ await rt.stopSubagents?.(sessionId)+ if (turnRunning) {+ const agent = await rt.resolveAgent(sessionId)+ agent.cancel({ kind: 'user' })+ }await postToRoom(room, member, '', { quiet: true, stopped: true })return true}@@ -1016,15 +1245,20 @@ export function install(rt) {rt.stopRoomWork = stopRoomWork// The round said such a member posts when done; a failed model call is how it ended.- // Nobody answers it.+ // Nobody answers it unless other members of its batch already finished and waited on+ // the barrier for this member.async function lateRoomFailure(sessionId, info, failure) {const owner = rt.groupOwners.get(sessionId)const room = rt.roomOf(owner?.roomId ?? info.roomId)const member = rt.botOf(owner?.botId)if (room === undefined || member === undefined || !room.members.includes(member.id)) return+ const batch = dropMemberFromBatch(room, member.id)+ const wakeCaller = batch !== undefined && batch.pending.size === 0 && batch.done.length > 0 && !batch.answered ? batch.by : undefinedconst { code, status, message } = failureawait postToRoom(room, member, `Could not finish: its model call failed (${failureLine(failure)}).`, {- late: true, quiet: true, failed: { code, ...(status ? { status } : {}), message },+ late: true,+ ...(wakeCaller ? { askedBy: wakeCaller } : { quiet: true }),+ failed: { code, ...(status ? { status } : {}), message },}).catch(error => rt.warn('ds-bot: late group failure from %s failed: %s', member.name, error))}rt.lateRoomFailure = lateRoomFailurediff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex 82a0264c..a4c375ec 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -64,13 +64,19 @@ export const stripWrittenCalls = text => textconst PROGRAM_TOOL = 'run_code'const RETRY_TEXT = 'Your last reply wrote a tool call as plain text (<tool_call>…), so it did not run and nothing happened. Call the tool through the tool interface now, then reply as you meant to.'+const RETRY_PROMISE_TEXT = 'Your last reply said you would start working, but you ended the turn without calling any tool, so nothing ran. Call the tools you need and complete the task now, or state your final answer if no tool is needed.'++// A reply that only promises to start investigating/checking/running tools now without+// actually calling a tool or handing off with @Name (#469).+const PROMISED_WORK = /(?:^(?:收到|好的|明白|好|行|没问题|了解)[,,、。.!!:\s]*(?:我(?:现在|这就|先|马上|立刻|去|来)?(?:开始|着手|去|来|准备)?(?:排查|检查|调查|查看|看看|搜索|搜一下|分析|处理|执行|运行|跑一下|修改|修复|实现|编写|整理|验证|测试|读一下|翻一下)|(?:现在|马上|立刻)?(?:开始|着手)(?:执行|处理|排查|检查|调查|干活|开工)|开工(?:[。!!,,\s]|$))|^(?:开工(?:[。!!,,\s]|$)|我(?:现在|这就|先|马上|立刻)(?:开始|着手|去)(?:排查|检查|调查|查看|搜索|分析|处理|执行|运行|修改|修复|实现|编写|整理|验证|测试))|\b(?:(?:i\s+will|i'll|let\s+me|going\s+to)\s+(?:start|begin|check|look\s+into|investigate|search|run|inspect|read|fix|implement|work\s+on)\b|(?:starting|beginning)\s+(?:the\s+)?(?:investigation|check|search|work|execution|analysis)\b|^on\s+it[,.\s!]+(?:i'll|i\s+will|let\s+me|starting|checking)\b))/i+export const promisesWork = text => typeof text === 'string' && text.trim().length <= 240 && PROMISED_WORK.test(text.trim())export function install(rt) {const { ctx, state } = rt// The retry goes where the turn's trigger came from: a group round's waiter or a// Bot's request keeps its exchange; anything else is a nudge in the Bot's own chat.- const retryWrittenCall = (id, info) => {+ const retryTurn = (id, info, note, text) => {const keeps = info !== undefined && (info.role === 'room' || expectsReply(info))return rt.deliver({...(keeps && info.senderSessionId ? { fromId: info.senderSessionId } : {}),@@ -83,11 +89,13 @@ export function install(rt) {...(keeps && info.audience ? { audience: info.audience } : {}),...(keeps && info.askedBy ? { askedBy: info.askedBy } : {}),...(keeps && info.senderRoomId ? { fromRoomId: info.senderRoomId } : {}),- note: 'your tool call did not run',+ note,retried: true,- text: RETRY_TEXT,+ text,})}+ const retryWrittenCall = (id, info) => retryTurn(id, info, 'your tool call did not run', RETRY_TEXT)+ const retryPromisedWork = (id, info) => retryTurn(id, info, 'you stopped before calling any tool', RETRY_PROMISE_TEXT)/** @type {Map<string, {turn?:number, pending?:any, pendingText?:string, info?:any, texts:string[], opened?:boolean, joined?:{info:any, from:number}[]}>} */const live = new Map()@@ -100,14 +108,100 @@ export function install(rt) {const queueRoomMessage = (roomId, item) => roomInbox.set(roomId, [...(roomInbox.get(roomId) ?? []), item])// Member turns of a group round the user stopped: what they end with stays out of the group.const stoppedRoomTurns = new Set()+ // Running DSH subagents spawned by each Bot Session: parentSessionId → Map<childId, {childId, label?, since}>.+ /** @type {Map<string, Map<string, {childId:string, label?:string, since:number}>>} */+ const subagentsByParent = new Map()+ /** @type {Map<string, string>} childId → parentSessionId */+ const subagentParent = new Map()+ // Subagent child IDs and parent Sessions whose subagents were stopped by the user;+ // late settlement notices from these stopped children must not wake the parent (#701).+ const stoppedSubagents = new Set()+ const stoppedSubagentParents = new Set()++ const STOPPED_KEPT = 200+ const rememberStopped = (set, value) => {+ set.add(value)+ if (set.size > STOPPED_KEPT) set.delete(set.values().next().value)+ }++ const subagentLabelFromCall = (entry) => {+ const call = [...(entry?.calls?.values() ?? [])].findLast(item => item.name === 'subagent')+ if (call === undefined) return undefined+ try {+ const args = JSON.parse(call.args || '{}')+ const raw = [args.description, args.label, args.prompt, args.task].find(value => typeof value === 'string' && value.trim() !== '')+ return raw?.replace(/\s+/g, ' ').trim().slice(0, 120)+ } catch {+ return undefined+ }+ }++ const noteSubagentStart = (parentId, childId, label, since = Date.now()) => {+ if (typeof parentId !== 'string' || parentId === '' || typeof childId !== 'string' || childId === '') return+ if (stoppedSubagents.has(childId) || (!rt.isBotSession(parentId) && !rt.roomOf(parentId))) return+ subagentParent.set(childId, parentId)+ let map = subagentsByParent.get(parentId)+ if (map === undefined) subagentsByParent.set(parentId, map = new Map())+ const existing = map.get(childId)+ map.set(childId, {+ childId,+ label: label || existing?.label || subagentLabelFromCall(live.get(parentId)),+ since: existing?.since ?? since,+ })+ if (rt.groupOwners.has(parentId)) rt.workRoomTurn?.(parentId, 'subagent')+ }++ const noteSubagentEnd = (childId) => {+ if (typeof childId !== 'string' || childId === '') return+ const parentId = subagentParent.get(childId)+ if (parentId === undefined) return+ const map = subagentsByParent.get(parentId)+ map?.delete(childId)+ if (map !== undefined && map.size === 0) subagentsByParent.delete(parentId)+ }++ const hasSubagents = id => (subagentsByParent.get(id)?.size ?? 0) > 0++ const subagentDoingOf = (id) => {+ const active = [...(subagentsByParent.get(id)?.values() ?? [])].at(-1)+ if (active === undefined) return undefined+ return { since: active.since, tool: 'subagent', ...(active.label ? { note: active.label.slice(0, 120) } : {}) }+ }++ async function stopSubagents(sessionId) {+ const map = subagentsByParent.get(sessionId)+ const childIds = [...(map?.keys() ?? [])]+ for (const agent of ctx.get?.('agents')?.list?.() ?? []) {+ if (agent?.session?.header?.parentSession === sessionId && typeof agent.id === 'string' && !childIds.includes(agent.id)) {+ childIds.push(agent.id)+ }+ }+ if (childIds.length === 0) return false+ subagentsByParent.delete(sessionId)+ stoppedSubagentParents.add(sessionId)+ for (const childId of childIds) {+ rememberStopped(stoppedSubagents, childId)+ await Promise.resolve(ctx.subagents?.interrupt?.(childId, { kind: 'user', parentSessionId: sessionId })).catch(() => {})+ const childAgent = ctx.get?.('agents')?.get?.(childId)+ if (childAgent !== undefined) {+ try { childAgent.cancel?.({ kind: 'user' }) } catch {}+ }+ }+ const parent = await rt.resolveAgent(sessionId).catch(() => undefined)+ for (const message of [...(parent?.inbox?.nextStep ?? []), ...(parent?.inbox?.nextTurn ?? [])]) {+ if (message?.source?.kind === 'subagent-settled' || stoppedSubagents.has(message?.source?.senderSessionId)) {+ parent.inbox.remove(message.id)+ }+ }+ return true+ }// A stopped round stops the member work it started: the turn that answers it, or the// delivery still waiting for the member's Session. An earlier turn there keeps going.// An exchange whose turn already ended stays in the set, so it is bounded.- const STOPPED_KEPT = 200async function stopRoomTurn(sessionId, exchangeId) {- stoppedRoomTurns.add(exchangeId)- if (stoppedRoomTurns.size > STOPPED_KEPT) stoppedRoomTurns.delete(stoppedRoomTurns.values().next().value)+ rememberStopped(stoppedRoomTurns, exchangeId)+ await stopSubagents(sessionId)const agent = await rt.resolveAgent(sessionId).catch(() => undefined)if (agent === undefined) returnconst entry = live.get(sessionId)@@ -191,7 +285,7 @@ export function install(rt) {// turn's end, which shows the rest as the turn's reply.const showSteps = (id, entry, upTo) => {const info = entry.info- if (!speaksInGroup(id, info) || (info?.role === 'room' && stoppedRoomTurns.has(info.exchangeId))) return+ if (entry.suppressedSubagent || !speaksInGroup(id, info) || (info?.role === 'room' && stoppedRoomTurns.has(info.exchangeId))) returnfor (; entry.shown < upTo; entry.shown += 1) {const text = stripWrittenCalls(entry.texts[entry.shown])if (text !== '') void rt.roomStepText?.(id, info, text, entry.shown === 0)?.catch(error => rt.warn('ds-bot: step text from %s not posted: %s', id, error))@@ -212,6 +306,7 @@ export function install(rt) {const text = `${rt.botOf(botId)?.name ?? 'The other Bot'} was deleted before it could answer your message.`const waiting = new Map()for (const id of sessionIds) {+ await stopSubagents(id)const entry = live.get(id)const held = [entry?.info, entry?.pending, ...(entry?.joined ?? []).map(joined => joined.info)]if (entry?.turn !== undefined) {@@ -255,6 +350,12 @@ export function install(rt) {const owner = rt.groupOwners.get(id)if (owner !== undefined) merged[owner.botId] ??= value}+ for (const [id, map] of subagentsByParent) {+ if (map.size === 0) continue+ const owner = rt.groupOwners.get(id)+ const botId = owner?.botId ?? rt.chatOwners.get(id)+ if (botId !== undefined) merged[botId] ??= 'working'+ }// A Bot writing its handoff note is thinking.for (const job of rt.switchJobs()) {if (job.roomId === undefined) merged[job.botId] = 'thinking'@@ -295,6 +396,14 @@ export function install(rt) {if (botId === undefined || (owner !== undefined && bots[botId] !== undefined)) continuebots[botId] = { since: entry.since, ...doingOf(entry), ...(owner ? { roomId: owner.roomId } : {}) }}+ for (const [id] of subagentsByParent) {+ const sub = subagentDoingOf(id)+ if (sub === undefined) continue+ const owner = rt.groupOwners.get(id)+ const botId = owner?.botId ?? rt.chatOwners.get(id)+ if (botId === undefined || bots[botId] !== undefined) continue+ bots[botId] = { ...sub, ...(owner ? { roomId: owner.roomId } : {}) }+ }for (const job of rt.switchJobs()) {// `folder` marks the switch the chat must name: the working folder changed.const work = { since: job.since, switching: true, ...(job.folder === true ? { folder: true } : {}), ...(job.roomId ? { roomId: job.roomId } : {}) }@@ -329,6 +438,11 @@ export function install(rt) {const owner = rt.groupOwners.get(id)if (entry.turn !== undefined && owner !== undefined) add(owner.roomId, owner.botId, { since: entry.since, ...doingOf(entry) })}+ for (const [id] of subagentsByParent) {+ const owner = rt.groupOwners.get(id)+ const sub = owner !== undefined ? subagentDoingOf(id) : undefined+ if (sub !== undefined) add(owner.roomId, owner.botId, sub)+ }for (const job of rt.switchJobs()) {if (job.roomId !== undefined) add(job.roomId, job.botId, { since: job.since, switching: true, ...(job.folder === true ? { folder: true } : {}) })}@@ -364,6 +478,18 @@ export function install(rt) {})}+ ctx.on?.('subagent/start', (info) => {+ const childId = info?.id+ if (typeof childId !== 'string' || childId === '' || stoppedSubagents.has(childId)) return+ const parentId = subagentParent.get(childId)+ ?? ctx.get?.('agents')?.get?.(childId)?.session?.header?.parentSession+ ?? [...live.entries()].find(([, entry]) => [...(entry.calls?.values() ?? [])].some(call => call.name === 'subagent'))?.[0]+ if (parentId !== undefined) noteSubagentStart(parentId, childId, undefined)+ })+ ctx.on?.('subagent/end', (info) => {+ noteSubagentEnd(info?.id)+ })+ctx.on('session/event', (session, event) => {const id = session?.idif (id === undefined) return@@ -375,16 +501,26 @@ export function install(rt) {const entry = liveOf(id)if (rt.groupOwners.has(id)) rt.touchRoomTurn?.(id)switch (event.type) {+ case 'subagent/catalog': {+ const childId = event.data?.childId+ const label = typeof event.data?.label === 'string' ? event.data.label.trim() : undefined+ noteSubagentStart(id, childId, label, event.time ?? Date.now())+ break+ }case 'tool/call': {const name = String(event.data?.name ?? '')startCall(id, entry, event.data?.callId, name, String(event.data?.arguments ?? ''))// A program is as quick as the tools it runs, so its sub-calls decide.- if (rt.groupOwners.has(id) && name !== PROGRAM_TOOL) rt.workRoomTurn?.(id, name)+ if (name !== PROGRAM_TOOL) {+ entry.toolCount = (entry.toolCount ?? 0) + 1+ if (rt.groupOwners.has(id)) rt.workRoomTurn?.(id, name)+ }break}case 'tool/ptc-dispatch-start': {const name = String(event.data?.name ?? '')startCall(id, entry, event.data?.subCallId, name, JSON.stringify(event.data?.arguments ?? {}))+ entry.toolCount = (entry.toolCount ?? 0) + 1if (rt.groupOwners.has(id)) rt.workRoomTurn?.(id, name)break}@@ -402,6 +538,8 @@ export function install(rt) {entry.shown = 0entry.step = undefinedentry.info = undefined+ entry.toolCount = 0+ entry.suppressedSubagent = false// A turn turned away before its first step may end without a turn/end.entry.switched = falseentry.answers = false@@ -427,6 +565,7 @@ export function install(rt) {entry.answers = carry.answersentry.joined = carry.joinedentry.later = carry.later+ entry.toolCount = carry.toolCount ?? 0entry.opened = trueentry.carried = trueif (carry.info !== undefined) claimTrigger(id, entry, carry.info)@@ -442,6 +581,16 @@ export function install(rt) {breakcase 'user/message': {const source = event.data?.source+ if (source?.kind === 'subagent-settled' || source?.kind === 'agent-message') {+ if (typeof source.senderSessionId === 'string') noteSubagentEnd(source.senderSessionId)+ if (stoppedSubagentParents.has(id) || (typeof source.senderSessionId === 'string' && stoppedSubagents.has(source.senderSessionId))) {+ entry.suppressedSubagent = true+ void rt.resolveAgent(id).then(agent => agent?.cancel({ kind: 'hook', reason: 'ds-bot/stopped' })).catch(() => {})+ break+ }+ } else if (source?.kind === 'user' || source?.kind === SOURCE_KIND) {+ stoppedSubagentParents.delete(id)+ }// A result that came back counts as taken once a turn reads it.if (source?.kind === SOURCE_KIND && source.work !== undefined && source.replyTo !== undefined) rt.takenWork?.(source.work, source.replyTo)// A message that shares a step with a bare handoff package is what the turn@@ -546,6 +695,13 @@ export function install(rt) {case 'agent/inbox/spliced':// A message the user sends to a group while its round runs joins that round.if (rt.roomOf(id)) rt.nudgeRoom?.(id)+ if (stoppedSubagentParents.has(id)) {+ for (const inserted of event.data?.inserted ?? []) {+ if (inserted?.source?.kind === 'subagent-settled' || stoppedSubagents.has(inserted?.source?.senderSessionId)) {+ void rt.resolveAgent(id).then(agent => agent?.inbox?.remove(inserted.id)).catch(() => {})+ }+ }+ }// A message the user steered into the running turn is fresh input, like// a send that never queued.if (event.data?.target === 'next-step' && entry.turn !== undefined@@ -576,7 +732,7 @@ export function install(rt) {const steerCut = cut !== undefined && event.data?.reason?.kind === 'aborted'&& event.data.reason.reason?.kind === 'hook' && event.data.reason.reason.reason === STEER_CUTif (steerCut) {- entry.carry = { info: entry.info, joined: entry.joined ?? [], later: entry.later ?? [], texts: entry.texts.slice(0, cut.texts), shown: entry.shown, answers: entry.answers }+ entry.carry = { info: entry.info, joined: entry.joined ?? [], later: entry.later ?? [], texts: entry.texts.slice(0, cut.texts), shown: entry.shown, answers: entry.answers, toolCount: entry.toolCount ?? 0 }}const info = entry.infoconst joined = entry.joined ?? []@@ -584,6 +740,8 @@ export function install(rt) {const texts = entry.texts.slice(entry.shown)const shown = entry.shown > 0const { lastText, lastCalled } = entry+ const toolCount = entry.toolCount ?? 0+ const suppressedSubagent = entry.suppressedSubagent === true// A turn stopped for a switch goes on in the next part, which answers instead.const switched = entry.switched === trueentry.turn = undefined@@ -591,6 +749,8 @@ export function install(rt) {entry.texts = []entry.shown = 0entry.step = undefined+ entry.toolCount = 0+ entry.suppressedSubagent = falseentry.switched = falseentry.joined = []entry.since = undefined@@ -601,7 +761,7 @@ export function install(rt) {entry.lastCalled = undefinedconst later = entry.later ?? []entry.later = []- if (steerCut) break+ if (steerCut || suppressedSubagent) breakfor (const result of later) {void rt.deliver({fromId: result.info.senderSessionId,@@ -625,8 +785,20 @@ export function install(rt) {// round or sender gets the real answer; a second time, the text goes on without// the call.const wroteCall = failure === undefined && reason?.kind === 'completed' && lastCalled !== true && writesToolCall(lastText)- const retry = wroteCall && info?.retried !== true && !(info?.role === 'room' && stoppedRoomTurns.has(info.exchangeId))- if (retry) void retryWrittenCall(id, info).catch(error => rt.warn('ds-bot: asking %s to run its written tool call failed: %s', id, error))+ const promisedOnly = !wroteCall && failure === undefined && reason?.kind === 'completed'+ && toolCount === 0 && lastCalled !== true && info?.role === 'room'+ && promisesWork(lastText) && !rt.callsRoomMember?.(id, info, lastText)+ const retry = (wroteCall || promisedOnly) && info?.retried !== true && !(info?.role === 'room' && stoppedRoomTurns.has(info.exchangeId))+ if (retry) {+ if (promisedOnly) {+ const opening = stripWrittenCalls(lastText ?? '')+ if (opening !== '') void rt.roomStepText?.(id, info, opening, !shown)?.catch(() => {})+ roomWaiters.get(info.exchangeId)?.touch()+ void retryPromisedWork(id, info).catch(error => rt.warn('ds-bot: asking %s to run its promised work failed: %s', id, error))+ } else {+ void retryWrittenCall(id, info).catch(error => rt.warn('ds-bot: asking %s to run its written tool call failed: %s', id, error))+ }+ }const replyText = () => {const reply = (wroteCall ? texts.map(stripWrittenCalls) : texts).join('\n\n').trim()return wroteCall && reply === '' ? 'Tried to run a tool but wrote the call as text, so it did not run.' : reply@@ -716,5 +888,5 @@ export function install(rt) {if (entry?.turn !== undefined) entry.cut = { texts: entry.texts.length }}- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, releaseBot, markSteerCut })+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, releaseBot, markSteerCut, hasSubagents, stopSubagents })}diff --git a/ds-bot/test/group-work.test.js b/ds-bot/test/group-work.test.jsindex 4a393f48..3d1c19c4 100644--- a/ds-bot/test/group-work.test.js+++ b/ds-bot/test/group-work.test.js@@ -486,14 +486,12 @@ const busyRound = async (t, room, services) => {return { host, first }}-test('a post during a running round is in the log at once, once, and calls its members in that round', async (t) => {+test('a post during a running round is in the log at once, calls its members in that round, and queues no extra relay post (#663)', async (t) => {const { host, first } = await busyRound(t)await host.tool('post_to_group', { group: 'Ops', message: '@Tester 看一下文档' }, 'a')const logged = logLines(host).at(-1)assert.deepEqual([logged.who, logged.botId, logged.text], ['Chief', 'a', '@Tester 看一下文档'])- const post = host.takePost()- assert.equal(post.source.logged, logged.seq)- assert.equal(post.source.called, true)+ assert.deepEqual(host.agentOf('r1').calls, [], 'absorbed into the running round without polluting the room Session queue')// The Tester starts in the running round at once, while the Writer still works.await settle(() => host.agentOf('gc').calls.length === 1)@@ -504,11 +502,6 @@ test('a post during a running round is in the log at once, once, and calls its mawait settle(() => first() !== undefined)assert.ok(first().replies.some(reply => reply.botId === 'a' && reply.text === '@Tester 看一下文档'))assert.ok(first().replies.some(reply => reply.botId === 'c' && reply.text === '看过了。'))-- // The relay the post still opens calls nobody again and writes the line nowhere.- const second = host.round('c2', post)- await settle(() => second() !== undefined)- assert.deepEqual(second().replies, [])assert.equal(host.agentOf('gc').calls.length, 1)assert.equal(logLines(host).filter(line => line.text === '@Tester 看一下文档').length, 1)})@@ -516,8 +509,7 @@ test('a post during a running round is in the log at once, once, and calls its mtest('a post during a running round with report_back gets the replies of the members it called', async (t) => {const { host, first } = await busyRound(t)await host.tool('post_to_group', { group: 'Ops', message: '@Tester 看一下文档', report_back: true }, 'a')- const post = host.takePost()- assert.equal(typeof post.source.logged, 'number')+ assert.deepEqual(host.agentOf('r1').calls, [])await settle(() => host.agentOf('gc').calls.length === 1)host.begin('gc')host.finish('gc', '看过了。')@@ -527,12 +519,6 @@ test('a post during a running round with report_back gets the replies of the memconst report = host.agentOf('a').calls[0]assert.match(text(report), /Tester: 看过了。/)assert.doesNotMatch(text(report), /看一下文档|Writer/)-- // The relay the post opens reports nothing again.- const second = host.round('c2', post)- await settle(() => second() !== undefined)- await new Promise(resolve => setImmediate(resolve))- assert.equal(host.agentOf('a').calls.length, 1)})test('a late reply during a running round is logged at once, called in that round and not repeated', async (t) => {@@ -553,12 +539,8 @@ test('a late reply during a running round is logged at once, called in that rounhost.begin('ga')host.emit('gb', 'tool/result', { callId: 'k1' })host.finish('gb', '整理好了,在 docs/ 下。')- await settle(() => host.agentOf('r1').calls.length === 1)- const post = host.takePost()- assert.equal(post.source.late, true)- assert.equal(typeof post.source.logged, 'number')- assert.ok(logLines(host).some(line => line.who === 'Writer' && line.text === '整理好了,在 docs/ 下。'))- assert.equal(post.source.called, true)+ await settle(() => logLines(host).some(line => line.who === 'Writer' && line.text === '整理好了,在 docs/ 下。'))+ assert.deepEqual(host.agentOf('r1').calls, [])// The Chief, which asked for it, answers the result in this round once its own turn ends.host.finish('ga', '确认过了。')await settle(() => host.agentOf('ga').calls.length === 3)@@ -566,11 +548,6 @@ test('a late reply during a running round is logged at once, called in that rounhost.finish('ga', '[PASS]')await settle(() => second() !== undefined)assert.ok(second().replies.some(reply => reply.botId === 'b' && reply.text === '整理好了,在 docs/ 下。'))-- // The relay it opens calls nobody again, and writes the line nowhere again.- const third = host.round('c3', post)- await settle(() => third() !== undefined)- assert.deepEqual(third().replies, [])assert.equal(host.agentOf('ga').calls.length, 3)assert.equal(logLines(host).filter(line => line.text === '整理好了,在 docs/ 下。').length, 1)})@@ -586,19 +563,13 @@ test('a member stopped during a running round is logged at once and not repeatedassert.deepEqual([stopped.ok, stopped.value], [true, true])const last = logLines(host).at(-1)assert.deepEqual([last.who, last.botId, last.kind], ['Writer', 'b', 'stopped'])- const post = host.takePost()- assert.equal(post.source.stopped, true)- assert.equal(typeof post.source.logged, 'number')+ assert.deepEqual(host.agentOf('r1').calls, [])host.emit('gb', 'turn/end', { turn: 1, reason: { kind: 'aborted' } })await settle(() => host.agentOf('gc').calls.length === 1)host.begin('gc')host.finish('gc', '在整理了。')await settle(() => first() !== undefined)assert.ok(first().replies.some(reply => reply.kind === 'stopped' && reply.botId === 'b'))-- // The relay the stopped post opens writes no second event line.- const second = host.round('c2', post)- await settle(() => second() !== undefined)assert.equal(logLines(host).filter(line => line.kind === 'stopped').length, 1)})@@ -612,17 +583,13 @@ test('a Main Bot outside the group posts into its running round, and a long postassert.deepEqual([line.who, line.botId], ['Chief', 'a'])assert.equal(line.files?.length, 1)assert.match(line.text, /\[File "Post from Chief\.txt"/)- const post = host.takePost()- assert.equal(typeof post.source.logged, 'number')+ assert.deepEqual(host.agentOf('r1').calls, [])// The admin answers the post in the running round, once its own turn there ends.host.finish('gb', '整理好了。')await settle(() => host.agentOf('gb').calls.length === 2)host.begin('gb')host.finish('gb', '收到,看一下。')await settle(() => first() !== undefined)- const second = host.round('c2', post)- await settle(() => second() !== undefined)- assert.deepEqual(second().replies, [])assert.equal(logLines(host).filter(entry => entry.files?.length === 1).length, 1)})@@ -728,13 +695,9 @@ test('a member post during a running round is logged at once and calls nobody neconst during = logLines(host)const logged = during.at(-1)assert.deepEqual([logged.who, logged.botId, logged.text], ['Writer', 'b', '群里的进展'])- const post = host.takePost()- assert.equal(post.source.logged, logged.seq)+ assert.deepEqual(host.agentOf('r1').calls, [])host.finish('gb', '整理好了。')await settle(() => first() !== undefined)-- const second = host.round('c2', post)- await settle(() => second() !== undefined)assert.equal(logLines(host).filter(line => line.text === '群里的进展').length, 1)assert.deepEqual(host.agentOf('ga').calls, [])assert.deepEqual(host.agentOf('gc').calls, [])@@ -1100,3 +1063,187 @@ test('deleting a working Bot clears its activity and tells the Bots waiting forhost.emit('b', 'turn/end', { turn: 1, reason: { kind: 'aborted' } })assert.equal((await host.call('state', {})).value.activity.b, undefined)})++// #619: a member that finishes tool work inside the 15s grace without writing @Caller+// still hands the result back to the Bot that asked for it.+test('in-round tool work that finishes before the grace without @Caller still wakes the caller (#619)', async (t) => {+ const host = await start(t)+ const first = host.round('c1', host.say('排查一下构建报错'))+ await settle(() => host.agentOf('ga').calls.length === 1)+ host.begin('ga')+ host.finish('ga', '@Writer 去读一下构建日志')++ await settle(() => host.agentOf('gb').calls.length === 1)+ host.begin('gb')+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'read', arguments: JSON.stringify({ file_path: 'build.log' }) })+ host.emit('gb', 'tool/result', { callId: 'k1' })+ // Finishes inside the round (< 15s) and forgets to write @Chief.+ host.finish('gb', '查清楚了,是缺少环境变量 FOO,需要决定用哪个默认值。')++ await settle(() => host.agentOf('ga').calls.length === 2)+ const follow = host.begin('ga')+ assert.match(text(follow), /Writer finished the work you asked for/)+ assert.match(text(follow), /Writer: 查清楚了,是缺少环境变量 FOO/)+ host.finish('ga', '默认设成 bar。')+ await settle(() => first() !== undefined)+ assert.deepEqual(first().replies.map(reply => [reply.name, reply.text]), [+ ['Chief', '@Writer 去读一下构建日志'],+ ['Writer', '查清楚了,是缺少环境变量 FOO,需要决定用哪个默认值。'],+ ['Chief', '默认设成 bar。'],+ ])+})++// Parallel fan-in barrier: when Chief calls @Writer @Tester in one message and both go+// past the 15s grace, Writer's early result posts at once without waking Chief, and+// Tester's final result wakes Chief once with both results.+test('parallel batch barrier posts each late reply at once and wakes the caller once when all finish', async (t) => {+ t.mock.timers.enable({ apis: ['setTimeout'] })+ const host = await start(t)+ const first = host.round('c1', host.say('全面检查一下'))+ await settle(() => host.agentOf('ga').calls.length === 1)+ host.begin('ga')+ host.finish('ga', '@Writer @Tester 分别检查文档和测试')++ await settle(() => host.agentOf('gb').calls.length === 1 && host.agentOf('gc').calls.length === 1)+ host.begin('gb')+ host.begin('gc')+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'read', arguments: '{}' })+ host.emit('gc', 'tool/call', { callId: 'k2', name: 'pwsh', arguments: '{}' })+ t.mock.timers.tick(ROOM_WORK_GRACE_MS)+ await settle(() => first() !== undefined)+ assert.deepEqual(kinds(first()), [['message', 'Chief'], ['working', 'Writer'], ['working', 'Tester']])++ // Writer finishes first while Tester is still working: its reply posts with quiet=true.+ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.finish('gb', '文档检查完毕,没有断链。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const earlyPost = host.takePost()+ assert.equal(earlyPost.source.late, true)+ assert.equal(earlyPost.source.quiet, true, 'does not wake Chief while Tester is still working')+ const second = host.round('c2', earlyPost)+ await settle(() => second() !== undefined)+ assert.equal(host.agentOf('ga').calls.length, 1, 'Chief was not woken prematurely')++ // Tester finishes second: now the batch barrier releases and wakes Chief once.+ host.emit('gc', 'tool/result', { callId: 'k2' })+ host.finish('gc', '测试全部通过。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const finalPost = host.takePost()+ assert.equal(finalPost.source.late, true)+ assert.equal(finalPost.source.quiet, undefined)+ assert.equal(finalPost.source.askedBy, 'a')+ const third = host.round('c3', finalPost)+ await settle(() => host.agentOf('ga').calls.length === 2)+ const synth = host.begin('ga')+ assert.match(text(synth), /Writer: 文档检查完毕,没有断链。/)+ assert.match(text(synth), /Tester: 测试全部通过。/)+ host.finish('ga', '文档和测试都通过了。')+ await settle(() => third() !== undefined)+})++// #469: a member that replies only "收到,我现在开始排查" without calling any tool gets+// one automatic continuation turn on the same exchange so the work actually runs.+test('a member that only promises to start working without calling a tool gets one continuation turn (#469)', async (t) => {+ const host = await start(t)+ const first = host.round('c1', host.say('@Writer 排查一下构建失败的原因'))+ await settle(() => host.agentOf('gb').calls.length === 1)+ const initial = host.begin('gb')+ // Ends the turn with a verbal promise only and 0 tool calls.+ host.finish('gb', '收到,我现在开始排查构建日志。')++ // The host automatically nudges gb once on the same exchangeId.+ await settle(() => host.agentOf('gb').calls.length === 2)+ const retryMsg = host.begin('gb')+ assert.equal(retryMsg.source.exchangeId, initial.source.exchangeId)+ assert.equal(retryMsg.source.retried, true)+ assert.match(text(retryMsg), /stopped before calling any tool/)++ // In the continuation turn the member calls its tool and gives the real answer.+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'read', arguments: JSON.stringify({ file_path: 'build.log' }) })+ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.finish('gb', '排查完毕:原因是端口冲突。')+ await settle(() => first() !== undefined)+ assert.deepEqual(first().replies.map(reply => [reply.name, reply.text]), [+ ['Writer', '收到,我现在开始排查构建日志。'],+ ['Writer', '排查完毕:原因是端口冲突。'],+ ])+})++// Progress-based loop guard: consecutive 0-tool ack/repetitive relays pause after 6+// turns and park the next call in room.paused, whereas tool calls reset the counter.+test('consecutive 0-tool ack ping-pong relays pause after 6 turns and resume when the user writes', async (t) => {+ const host = await start(t)+ const first = host.round('c1', host.say('@Chief 开始'))+ await settle(() => host.agentOf('ga').calls.length === 1)+ host.begin('ga')+ host.finish('ga', '@Writer 收到,辛苦了')++ for (let step = 1; step <= 6; step += 1) {+ const isWriter = step % 2 === 1+ const sessionId = isWriter ? 'gb' : 'ga'+ const target = isWriter ? '@Chief' : '@Writer'+ const count = isWriter ? Math.ceil(step / 2) : Math.floor(step / 2) + 1+ await settle(() => host.agentOf(sessionId).calls.length === count)+ host.begin(sessionId)+ host.finish(sessionId, `${target} 收到,谢谢!`)+ }+ await settle(() => first() !== undefined)+ const pausedReplies = first().replies.filter(reply => reply.kind === 'paused')+ assert.equal(pausedReplies.length, 1)+ assert.deepEqual(pausedReplies[0].names, ['Writer'])+ const saved = JSON.parse(readFileSync(join(host.home, 'state.json'), 'utf8')).rooms.r1+ assert.equal(saved.paused?.length, 1)+ assert.equal(saved.paused[0].id, 'b')+})++// #701: when a group member spawns a DSH subagent and ends its own turn, the member+// stays marked as working in the group, and stopping the group interrupts the subagent+// and suppresses its late settlement notice.+test('a group member with a running DSH subagent stays working and stop-room-work interrupts the subagent (#701)', async (t) => {+ const host = await start(t)+ const interrupted = []+ host.ctx.subagents = {+ interrupt: async (childId, opts) => { interrupted.push({ childId, opts }) },+ }+ const first = host.round('c1', host.say('@Writer 派子代理跑长任务'))+ await settle(() => host.agentOf('gb').calls.length === 1)+ host.begin('gb')+ host.emit('gb', 'tool/call', { callId: 's1', name: 'subagent', arguments: JSON.stringify({ description: 'Run long benchmark' }) })+ host.emit('gb', 'subagent/catalog', { childId: 'sub-1', label: 'Run long benchmark', mode: 'continuable' })+ host.emit('gb', 'tool/result', { callId: 's1' })+ host.finish('gb', '子代理已派出,正在后台运行。')++ await settle(() => first() !== undefined)+ assert.deepEqual(kinds(first()), [['message', 'Writer'], ['working', 'Writer']])++ // Even though gb's own turn ended, Writer still shows as working on its subagent in r1.+ const stateDuring = (await host.call('state', {})).value+ assert.equal(stateDuring.activity.b, 'working')+ assert.deepEqual(stateDuring.work.rooms.r1, [{ botId: 'b', since: stateDuring.work.rooms.r1[0].since, tool: 'subagent', note: 'Run long benchmark' }])++ // User clicks "Stop all" in the group: it interrupts sub-1 and logs Writer as stopped.+ const stopped = await host.call('stop-room-work', { roomId: 'r1' })+ assert.deepEqual([stopped.ok, stopped.value], [true, true])+ assert.equal(interrupted.length, 1)+ assert.equal(interrupted[0].childId, 'sub-1')+ assert.equal(interrupted[0].opts.parentSessionId, 'gb')+ assert.deepEqual((await host.call('state', {})).value.work.rooms.r1, undefined)++ // Clear the stopped event post from r1's inbox.+ await settle(() => host.agentOf('r1').calls.length === 1)+ const stopPost = host.takePost()+ assert.equal(stopPost.source.stopped, true)++ // Later, when the interrupted subagent emits its settlement notice to gb, gb is+ // cancelled and suppressed so it does not speak in the group again.+ host.emit('gb', 'turn/start', { turn: 2 })+ host.emit('gb', 'user/message', {+ content: [{ type: 'text', text: 'Subagent sub-1 settled' }],+ source: { kind: 'subagent-settled', form: 'notice', senderSessionId: 'sub-1' },+ })+ host.emit('gb', 'assistant/message', { message: { content: [{ type: 'text', text: '子代理被中断了。' }] } })+ host.emit('gb', 'turn/end', { turn: 2, reason: { kind: 'completed' } })+ await settle(() => true)+ assert.deepEqual(host.agentOf('r1').calls, [], 'suppressed settlement notice does not post to the group')+})+diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.jsindex d5ec81e1..58741014 100644--- a/ds-bot/test/install.test.js+++ b/ds-bot/test/install.test.js@@ -39,6 +39,8 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {'on llm/adapters-updated','on credentials/reference-updated','on settings/document-updated',+ 'on subagent/start',+ 'on subagent/end','on session/event','on session/event','on tools/execute',