Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Answer a joined Bot message in its own turn after the work

Fei2411513ba5b952e7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5473a268..ce5e0dcf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change
### Changed
-- When a Bot messages another Bot that is working, the message reaches it at its next step instead of waiting until its current work is done, and the reply still comes back. A Bot can still queue a separate task behind the current work.
+- When a Bot messages another Bot that is working, the message reaches it at its next step instead of waiting until its current work is done. It answers once that work is done, and the reply comes back. A Bot can still queue a separate task behind the current work.
- Bots give a brief progress message when starting a multi-step task in their own chat with the user, and at meaningful milestones on long tasks.
- Every Bot can change its own name, role, color, model and instructions; only a Main Bot changes other Bots.
- Updating a copy installed from GitHub uses the repository's current address.
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 1c8ebe1a..ee2af03e 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -1415,7 +1415,7 @@ function toolArgs(root) {
var RELAY_ROLES = /* @__PURE__ */ new Set(["request", "reply", "stopped"]);
var isRelayContext = (data) => {
const source = data?.source;
- if (source === null || typeof source !== "object" || source.kind !== "bot" || source.handoff === true) return false;
+ if (source === null || typeof source !== "object" || source.kind !== "bot" || source.handoff === true || source.deferred === true) return false;
return RELAY_ROLES.has(source.role) && typeof source.senderSessionId === "string";
};
var stepShows = (step) => (step?.blocks ?? []).some((block) => {
@@ -3948,7 +3948,8 @@ function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnClock, us
const data = node.data;
const source = data.source !== null && typeof data.source === "object" ? data.source : {};
const selfId = roster.byId[sessionId]?.id ?? sessionId;
- const relayed = source.kind === "bot" && source.handoff !== true && (source.role === "request" || source.role === "reply" || source.role === "stopped") && typeof source.senderSessionId === "string";
+ const deferred = source.kind === "bot" && source.deferred === true;
+ const relayed = source.kind === "bot" && source.handoff !== true && !deferred && (source.role === "request" || source.role === "reply" || source.role === "stopped") && typeof source.senderSessionId === "string";
const turn = node.location?.turn?.turn ?? data.turn;
(0, import_react6.useLayoutEffect)(() => {
if (relayed) actions.noteTurnPeer(sessionId, turn, source.senderSessionId);
@@ -3974,7 +3975,7 @@ function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnClock, us
if (source.kind === "bot") {
if (source.handoff === true) return roster.roomsById[sessionId] ? null : (0, import_react6.createElement)(EarlierParts, { sessionId, roster, actions });
if (source.role === "kickoff" || source.role === "room") return null;
- if (source.role === "secret") return null;
+ if (source.role === "secret" || deferred) return null;
if (source.role === "post") {
const room2 = roster.roomsById[sessionId];
const poster = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t("a Bot"), color: "gray" };
diff --git a/ds-bot/dev/mock-llm.mjs b/ds-bot/dev/mock-llm.mjs
index d3586216..3f59dc93 100644
--- a/ds-bot/dev/mock-llm.mjs
+++ b/ds-bot/dev/mock-llm.mjs
@@ -235,7 +235,7 @@ function decide(body) {
if (userText.startsWith('撑爆')) return 'overflow'
// "长任务" keeps stepping when a Bot message splices into its turn (a relayed
// note); only a fresh opener or "[Stopped by" ends it. A spliced "[Message
- // from X]" also gets a one-line acknowledgement, as its joined reply's text.
+ // from X]" is taken into account there; it is answered in a turn of its own.
const longOpener = messages.findLastIndex(m => m.role === 'user' && !isResults(m) && /^长任务\s*\d+/.test(textOf(m.content).trimStart()))
if (longOpener !== -1 && /^\[(?:Message|Reply) from /.test(userText)) {
const task = /^长任务\s*(\d+)(?:\s+(\d+))?/.exec(textOf(messages[longOpener].content).trimStart())
@@ -243,8 +243,8 @@ function decide(body) {
const size = Number(task[2] ?? 4)
const done = messages.slice(longOpener + 1).filter(isResults).length
if (done < steps) {
- const joined = /^\[Message from ([^\]]+)\]/.exec(userText)?.[1]
- return [text(`${joined ? `${joined} 插进来的话收到了,继续干活。\n` : ''}${filler(size * 1000, `步骤${done}`)}`), tool('list_bots', {})]
+ const joined = /^\[Message from ([^\]·]+?)(?: · [^\]]*)?\]/.exec(userText)?.[1]
+ return [text(`${joined ? `(已按 ${joined} 的话调整)\n` : ''}${filler(size * 1000, `步骤${done}`)}`), tool('list_bots', {})]
}
}
// "报错": the provider rejects the key, in the user's chat or in a message from a Bot.
@@ -371,7 +371,7 @@ function decide(body) {
const asked = userText.split('\n').slice(1).join(' ').trim().replace(/[。.!!??]+$/u, '')
return [text(`${match[1]} 转来一句话:「${asked}」。我先说打算:把手头已有的材料理一遍,列出还缺什么,再和你确认先后顺序;你确认之前我不会动手。`)]
}
- if ((match = /^\[Message from ([^\]]+)\]/.exec(userText))) {
+ if ((match = /^\[Message from ([^\]·]+?)(?: · [^\]]*)?\]/.exec(userText))) {
return [text(`给 ${match[1]} 的回复:\n- 先做:把现有材料理一遍\n- 需要用户提供:目标和截止时间(尚未聊过)\n- 节奏:确认后每天同步一次`)]
}
if ((match = /^\[Reply from ([^\]]+)\]\n.* could not answer your message: its model call failed \(([^)]+)\)/.exec(userText))) {
diff --git a/ds-bot/src/client/cells.js b/ds-bot/src/client/cells.js
index 789f778b..77c04abc 100644
--- a/ds-bot/src/client/cells.js
+++ b/ds-bot/src/client/cells.js
@@ -285,7 +285,10 @@ export function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnCl
// Team state (exchanges) is keyed by the Bot id; Session state by the part shown.
const selfId = roster.byId[sessionId]?.id ?? sessionId
// A resumed handoff keeps the relayed message's source, but it opens a part, not a run.
- const relayed = source.kind === 'bot' && source.handoff !== true && (source.role === 'request' || source.role === 'reply' || source.role === 'stopped') && typeof source.senderSessionId === 'string'
+ // A deferred request was already shown where the Bot read it mid-turn; the turn
+ // that answers it adds no second line.
+ const deferred = source.kind === 'bot' && source.deferred === true
+ const relayed = source.kind === 'bot' && source.handoff !== true && !deferred && (source.role === 'request' || source.role === 'reply' || source.role === 'stopped') && typeof source.senderSessionId === 'string'
const turn = node.location?.turn?.turn ?? data.turn
// Noted before paint so a folded line never flashes in before its run's first line.
useLayoutEffect(() => {
@@ -320,7 +323,7 @@ export function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnCl
// Group turns belong to the group chat; the member's own chat stays one-to-one.
if (source.role === 'kickoff' || source.role === 'room') return null
// The secret card itself shows what the user did; the note to the Bot stays out.
- if (source.role === 'secret') return null
+ if (source.role === 'secret' || deferred) return null
if (source.role === 'post') {
const room = roster.roomsById[sessionId]
const poster = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t('a Bot'), color: 'gray' }
diff --git a/ds-bot/src/client/text.js b/ds-bot/src/client/text.js
index 9ab52280..66d5c07c 100644
--- a/ds-bot/src/client/text.js
+++ b/ds-bot/src/client/text.js
@@ -127,11 +127,12 @@ export function toolArgs(root) {
// A relay context is a Bot-to-Bot request, reply or stop notice injected into the
// model's history. ds-bot's own package sources (kickoff, room, secret, handoff
-// parts) are not events in the chat.
+// parts) are not events in the chat, nor is a deferred request handed back after
+// its line was already shown.
const RELAY_ROLES = new Set(['request', 'reply', 'stopped'])
export const isRelayContext = (data) => {
const source = data?.source
- if (source === null || typeof source !== 'object' || source.kind !== 'bot' || source.handoff === true) return false
+ if (source === null || typeof source !== 'object' || source.kind !== 'bot' || source.handoff === true || source.deferred === true) return false
return RELAY_ROLES.has(source.role) && typeof source.senderSessionId === 'string'
}
diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js
index e0eaa429..11ba757e 100644
--- a/ds-bot/src/host/delivery.js
+++ b/ds-bot/src/host/delivery.js
@@ -12,7 +12,8 @@ export function install(rt) {
return resolved.agent
}
- const headerFor = (role, fromName, roomName, audience, note = 'new message') => {
+ const headerFor = (role, fromName, roomName, audience, note = 'new message', deferred = false) => {
+ if (deferred) return `[Message from ${fromName} · you read it during your last task; answer it now]`
if (role === 'reply') return `[Reply from ${fromName}]`
if (role === 'stopped') return `[Stopped by ${fromName}]`
if (role === 'room') return `[Group chat "${roomName}" · ${note}]`
@@ -27,7 +28,9 @@ export function install(rt) {
const EXCHANGE_ROLES = new Set(['request', 'reply', 'stopped'])
// `sessionId` defaults to the recipient's own chat; group turns name its group Session.
- async function deliver({ fromId, toId, sessionId, text, role, hop = 0, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false }) {
+ // `deferred`: a request the Bot already read mid-turn, handed back to answer in a
+ // turn of its own; its exchange was recorded when it first arrived.
+ async function deliver({ fromId, toId, sessionId, text, role, hop = 0, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false }) {
const from = rt.botOf(fromId)
const to = rt.botOf(toId)
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
@@ -45,8 +48,9 @@ export function install(rt) {
...(replyTo ? { replyTo } : {}),
...(roomId ? { roomId } : {}),
...(audience === 'user' ? { audience } : {}),
+ ...(deferred ? { deferred: true } : {}),
}
- if (EXCHANGE_ROLES.has(role)) {
+ if (EXCHANGE_ROLES.has(role) && !deferred) {
state.exchanges.push({ id: exchangeId, from: fromId, to: toId, text, role, time: Date.now(), ...(replyTo ? { replyTo } : {}), ...(audience === 'user' ? { audience } : {}) })
void rt.save()
}
@@ -54,7 +58,7 @@ export function install(rt) {
// A steered message cuts into a running turn at its next step; a follow-up
// queues for the next turn (see turns.js for how each is routed).
const message = createUserMessage({
- content: [{ type: 'text', text: `${headerFor(role, fromName, room?.name, audience, note)}\n${text}` }],
+ content: [{ type: 'text', text: `${headerFor(role, fromName, room?.name, audience, note, deferred)}\n${text}` }],
source,
})
if (steer) agent.steer(message)
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js
index c2547b2d..a2c434ab 100644
--- a/ds-bot/src/host/parts.js
+++ b/ds-bot/src/host/parts.js
@@ -801,7 +801,7 @@ export function install(rt) {
// `messages` left the inbox for this step, so the switch carries them along.
const entry = rt.liveOf(agent.id)
entry.switched = true
- startSwitch(agent, { resume: midTurn, carry: payload.messages, info: midTurn ? entry.info : undefined, joined: midTurn ? (entry.joined ?? []).map(joined => joined.info) : undefined, hard: true })
+ startSwitch(agent, { resume: midTurn, carry: payload.messages, info: midTurn ? entry.info : undefined, joined: midTurn ? [...(entry.joined ?? [])] : undefined, hard: true })
return { kind: 'reject' }
}, { prepend: true })
@@ -812,7 +812,7 @@ export function install(rt) {
if (!rt.isBotSession(agent.id) || switches.has(agent.id) || readOnly()) return next()
const entry = rt.liveOf(agent.id)
entry.switched = true
- startSwitch(agent, { resume: true, info: entry.info, joined: (entry.joined ?? []).map(joined => joined.info), overflow: true })
+ startSwitch(agent, { resume: true, info: entry.info, joined: [...(entry.joined ?? [])], overflow: true })
return undefined
}, { prepend: true })
@@ -884,7 +884,7 @@ export function install(rt) {
} else if (source?.kind === REPLY_KIND) {
const reply = readReply(textOf(event.data.content))
if (reply !== undefined) items.push({ kind: 'answer', questions: reply.questions, answers: reply.answers, time: event.time })
- } else if (source?.kind === SOURCE_KIND && source.handoff !== true && ['request', 'reply', 'report', 'stopped'].includes(source.role)) {
+ } else if (source?.kind === SOURCE_KIND && source.handoff !== true && source.deferred !== true && ['request', 'reply', 'report', 'stopped'].includes(source.role)) {
items.push({ kind: 'event', role: source.role, botId: source.senderSessionId ?? null, name: source.senderName ?? null, roomId: source.roomId ?? null, time: event.time })
}
}
diff --git a/ds-bot/src/host/prompt.js b/ds-bot/src/host/prompt.js
index a0581b06..41637ad9 100644
--- a/ds-bot/src/host/prompt.js
+++ b/ds-bot/src/host/prompt.js
@@ -5,9 +5,9 @@ const TEAM_RULES = [
'## How your Bot team works',
'- Every Bot is its own long-lived conversation with the user, with its own memory and computer.',
'- The team changes over time. Call list_bots whenever you need to know who exists; do not rely on memory.',
- '- message_bot sends a message to another Bot. If it is working, it reads your message at its next step, so you can also use message_bot to warn it off a mistake or redirect it in time. Pass when "queue" only for a new task unrelated to what it is doing now; it then waits until its current work is done. Its reply arrives later as a new "[Reply from …]" message. Never wait, poll, or resend.',
+ '- message_bot sends a message to another Bot. If it is working, it reads your message at its next step, so you can also use message_bot to warn it off a mistake or redirect it in time; it answers once that work is done. Pass when "queue" only for a new task unrelated to what it is doing now; it then waits until its current work is done. Its reply arrives later as a new "[Reply from …]" message. Never wait, poll, or resend.',
'- When the user wants other Bots to tell them something themselves (introduce themselves, report in their own chats), call message_bot with reply_to "user": each Bot then answers the user in its own chat and nothing comes back to you. Do not relay those answers yourself.',
- '- When a "[Message from …]" arrives, what you write after it in that turn is delivered back to that Bot automatically; when the message opened the turn, the user does not see that turn. If it arrives while you are working on something else, take it into account and answer it in the same turn, together with that work. Answer it directly and briefly, as a list of facts. Never invent facts: say "not discussed yet" when you do not know. If the message brings a request or a decision meant for the user, handle it in the same turn too — do the work, or ask the user with ask_user.',
+ '- When a "[Message from …]" opens a turn, your final text in that turn is delivered back to that Bot automatically and the user does not see it. If one arrives while you are working on something else, take it into account in that work but do not answer it there: once the work is done, it comes back to you in a turn of its own to answer. Answer it directly and briefly, as a list of facts. Never invent facts: say "not discussed yet" when you do not know. If the message brings a request or a decision meant for the user, handle it in the same turn too — do the work, or ask the user with ask_user.',
'- When a "[Message from … · the user sees your reply here]" arrives, your reply is shown to the user in your own chat and is not sent back. Talk to the user directly, as yourself.',
'- When a "[Reply from …]" arrives, tell the user the outcome if it matters to them.',
'- Chat like a teammate texting: short sentences, often two or three short messages instead of one long one, no headings. When the user asks for a deliverable (a plan, schedule, draft, or list), write it out in full in the chat; never claim you gave something you did not write. Mention other Bots by their exact name.',
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 2f703079..ade3c930 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -58,9 +58,21 @@ export function install(rt) {
},
}))
+ // Sessions a Bot is running in right now: its own chat plus each group Session
+ // with a live turn. An idle Bot reports just its own chat.
+ const activeSessions = (botId) => {
+ const running = [...new Set([rt.chatOf(botId), ...rt.groupSessionsOf(botId)])]
+ .filter(sessionId => rt.live.get(sessionId)?.turn !== undefined)
+ return { running, idle: running.length === 0 }
+ }
+ const whereOf = (sessionId) => {
+ const room = rt.roomOf(rt.groupOwners.get(sessionId)?.roomId)
+ return room ? `group "${room.name}"` : 'its own chat'
+ }
+
ctx.tools.register(defineTool({
name: 'message_bot',
- description: 'Send a message to another Bot on the team. If that Bot is working, it reads your message at its next step and can change course; if it is idle, it starts on it right away. Its reply arrives later as a new message to you; with reply_to "user" it answers the user in its own chat instead.',
+ description: 'Send a message to another Bot on the team. If that Bot is working, it reads your message at its next step and can change course, then answers once that work is done; if it is idle, it starts on it right away. Its reply arrives later as a new message to you; with reply_to "user" it answers the user in its own chat instead.',
parameters: {
to: { type: 'string', required: true, description: 'Exact Bot name from list_bots' },
message: { type: 'string', required: true, description: 'Self-contained message; the other Bot cannot see this conversation' },
@@ -72,7 +84,7 @@ export function install(rt) {
when: {
type: 'string',
enum: ['now', 'queue'],
- description: '"now" (default): a working Bot reads your message at its next step, between its current actions; use it for questions, information it needs, corrections and warnings. "queue": it reads your message only after its current work is done, as a separate task; use it only for a new task unrelated to what it is doing now. With reply_to "user" the message always queues.',
+ description: '"now" (default): a working Bot reads your message at its next step, between its current actions, and answers once its current work is done; use it for questions, information it needs, corrections and warnings. "queue": it reads your message only after its current work is done, as a separate task; use it only for a new task unrelated to what it is doing now. With reply_to "user" the message always queues.',
},
},
output,
@@ -90,27 +102,21 @@ export function install(rt) {
const working = rt.live.get(rt.chatOf(target.id))?.turn !== undefined
const steer = args.when !== 'queue' && !toUser
await rt.deliver({ fromId: sender.id, toId: target.id, text: args.message, role: 'request', hop, steer, ...(toUser ? { audience: 'user' } : {}) })
- return toUser
+ const sent = toUser
? `Delivered to ${target.name}. It will answer the user in its own chat; nothing comes back to you, so point the user to ${target.name}'s chat instead of relaying.`
: working && steer
- ? `Delivered to ${target.name} while it is working: it reads your message at its next step. Its reply will arrive later as a new message; do not wait for it.`
+ ? `Delivered to ${target.name} while it is working: it reads your message at its next step and answers once that work is done. Its reply will arrive later as a new message; do not wait for it.`
: working
? `Queued for ${target.name}: it reads your message after its current work. Its reply will arrive later as a new message; do not wait for it.`
: `Delivered to ${target.name}. Its reply will arrive later as a new message; do not wait for it.`
+ // Messages reach a Bot's own chat only; work in a group goes on without them.
+ const groups = activeSessions(target.id).running.filter(sessionId => sessionId !== rt.chatOf(target.id))
+ if (groups.length === 0) return sent
+ const stop = rt.isMain(sender.id) ? ' If it must not go on there, use stop_bot.' : ''
+ return `${sent} ${target.name} is also working in ${groups.map(whereOf).join(' and ')}; your message does not reach that work.${stop}`
},
}))
- // Sessions a Bot is running in right now: its own chat plus each group Session
- // with a live turn. An idle Bot reports just its own chat.
- const activeSessions = (botId) => {
- const running = [...new Set([rt.chatOf(botId), ...rt.groupSessionsOf(botId)])]
- .filter(sessionId => rt.live.get(sessionId)?.turn !== undefined)
- return { running, idle: running.length === 0 }
- }
- const whereOf = (sessionId) => {
- const room = rt.roomOf(rt.groupOwners.get(sessionId)?.roomId)
- return room ? `group "${room.name}"` : 'its own chat'
- }
// stop_bot throws when it does nothing, so the chat shows the call as failed
// instead of "Stopped".
const refuse = (message) => { throw new Error(message) }
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index 7f4800f9..66a2850e 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -96,8 +96,7 @@ export function install(rt) {
entry.info = info
// A turn that was stopped for a part switch brings its joined requests along.
if (Array.isArray(info.joined) && info.joined.length > 0) {
- entry.joined = info.joined.filter(item => item !== undefined && item !== null)
- .map(item => ({ info: item, from: 0 }))
+ entry.joined = info.joined.filter(item => item?.info !== undefined && item.info !== null)
}
if (rt.groupOwners.has(sessionId)) return
if ((expectsReply(info) && !answersUser(info)) || info.role === 'room' || (info.role === 'handoff' && info.resume !== true)) {
@@ -208,11 +207,12 @@ export function install(rt) {
else if (expectsReply(source) && !answersUser(source)
&& source.exchangeId !== entry.info?.exchangeId
&& !(entry.joined ?? []).some(joined => joined.info.exchangeId === source.exchangeId)) {
- // A request that lands inside a running turn is answered by the text
- // that follows it, routed back at turn/end. A failed-switch resume
- // message re-sends the trigger's own source; the same exchangeId must
- // not join twice.
- entry.joined = [...(entry.joined ?? []), { info: source, from: entry.texts.length }]
+ // A request that lands inside a running turn steers that work but is
+ // answered in a hidden turn of its own once the work is done, so the
+ // sender never gets the turn's text. A failed-switch resume message
+ // re-sends the trigger's own source; the same exchangeId must not join twice.
+ const text = textOf(event.data.content).replace(/^\[[^\]\n]*\]\n?/, '')
+ entry.joined = [...(entry.joined ?? []), { info: source, text }]
}
// A mid-turn relay that owes no reply only informs the turn: it neither
// claims the running turn nor queues as the next one's trigger.
@@ -259,8 +259,7 @@ export function install(rt) {
if (failure !== undefined) noteTurnFailure(id, failure)
if (switched) break
// Whoever the turn answers gets the same three-way rule: a failure notice,
- // the turn's text (or a stopped-before-answer line), or nothing. A joined
- // request is answered by only the text that follows where it landed.
+ // the turn's text (or a stopped-before-answer line), or nothing.
const answer = (source, reply) => {
if (!expectsReply(source) || answersUser(source)) return
const name = rt.botOf(rt.selfOf(id))?.name ?? 'The other Bot'
@@ -295,7 +294,24 @@ export function install(rt) {
} else if (info !== undefined) {
answer(info, texts.join('\n\n').trim())
}
- for (const request of joined) answer(request.info, texts.slice(request.from).join('\n\n').trim())
+ for (const request of joined) {
+ // A failed or stopped turn closes the request like any other; a finished
+ // one hands it back to the Bot to answer next.
+ if (failure !== undefined || reason?.kind === 'aborted') {
+ answer(request.info, '')
+ continue
+ }
+ void rt.deliver({
+ fromId: request.info.senderSessionId,
+ toId: rt.selfOf(id),
+ sessionId: id,
+ text: request.text,
+ role: 'request',
+ hop: request.info.hop ?? 0,
+ exchangeId: request.info.exchangeId,
+ deferred: true,
+ }).catch(error => rt.warn('ds-bot: deferred request delivery failed: %s', error))
+ }
break
}
}
diff --git a/ds-bot/test/bot-messages.test.js b/ds-bot/test/bot-messages.test.js
index 31aff935..259bd02d 100644
--- a/ds-bot/test/bot-messages.test.js
+++ b/ds-bot/test/bot-messages.test.js
@@ -117,7 +117,7 @@ test('message_bot steers by default; on an idle Bot it opens the next turn', asy
// Running: the message cuts into that turn instead of queuing.
emit('b', 'turn/start', { turn: 1 })
const busy = await tool('message_bot', { to: 'Writer', message: 'watch out' }, 'a')
- assert.equal(busy, 'Delivered to Writer while it is working: it reads your message at its next step. Its reply will arrive later as a new message; do not wait for it.')
+ assert.equal(busy, 'Delivered to Writer while it is working: it reads your message at its next step and answers once that work is done. Its reply will arrive later as a new message; do not wait for it.')
assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer', 'steer'])
})
@@ -136,6 +136,57 @@ test('message_bot when "queue" waits for the current work, and reply_to "user" a
assert.equal(agents.get('b').calls[1][1].source.audience, 'user')
})
+test('a Bot busy in a group gets the message in its own chat, and the sender is told', async (t) => {
+ const seed = team({ group: true })
+ seed.rooms.r1.sessions.a = 'ga'
+ const { agents, emit, tool, stop } = await start(seed)
+ t.after(stop)
+
+ emit('gb', 'turn/start', { turn: 1 })
+ const out = await tool('message_bot', { to: 'Writer', message: 'status?' }, 'a')
+ assert.equal(out, 'Delivered to Writer. Its reply will arrive later as a new message; do not wait for it. Writer is also working in group "Ops"; your message does not reach that work. If it must not go on there, use stop_bot.')
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer'])
+ assert.equal(agents.get('gb'), undefined)
+
+ // A non-Main sender gets no stop_bot hint.
+ emit('ga', 'turn/start', { turn: 1 })
+ const back = await tool('message_bot', { to: 'Chief', message: 'done' }, 'b')
+ assert.equal(back, 'Delivered to Chief. Its reply will arrive later as a new message; do not wait for it. Chief is also working in group "Ops"; your message does not reach that work.')
+})
+
+test('a request steered into a running turn is recorded once and answered in a turn of its own', async (t) => {
+ const { agents, emit, tool, exchanges, stop } = await start(team())
+ t.after(stop)
+
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('write the letter'), source: { kind: 'user' } })
+ await tool('message_bot', { to: 'Writer', message: 'which year is the data?' }, 'a')
+ const steered = agents.get('b').calls[0][1]
+ emit('b', 'user/message', { content: steered.content, source: steered.source })
+ emit('b', 'assistant/message', assistantText('the letter, for the user'))
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+ for (let count = 0; count < 200 && agents.get('b').calls.length < 2; count += 1) await delay(5)
+
+ // Nothing from the user's turn goes to Chief; the request comes back to Writer.
+ assert.equal(agents.get('a')?.calls.length ?? 0, 0)
+ const [kind, again] = agents.get('b').calls[1]
+ assert.equal(kind, 'followup')
+ assert.equal(textOf(again.content), '[Message from Chief · you read it during your last task; answer it now]\nwhich year is the data?')
+ assert.equal(again.source.deferred, true)
+ assert.equal(again.source.exchangeId, steered.source.exchangeId)
+ assert.deepEqual((await exchanges()).map(entry => entry.role), ['request'])
+
+ emit('b', 'turn/start', { turn: 2 })
+ emit('b', 'user/message', { content: again.content, source: again.source })
+ emit('b', 'assistant/message', assistantText('2025'))
+ emit('b', 'turn/end', { turn: 2, reason: { kind: 'completed' } })
+ for (let count = 0; count < 200 && (agents.get('a')?.calls ?? []).length < 1; count += 1) await delay(5)
+ const reply = agents.get('a').calls[0][1]
+ assert.equal(textOf(reply.content), '[Reply from Writer]\n2025')
+ assert.equal(reply.source.replyTo, steered.source.exchangeId)
+ assert.deepEqual((await exchanges()).map(entry => entry.role), ['request', 'reply'])
+})
+
test('a non-Main Bot can steer a message to a Main Bot', async (t) => {
const { agents, tool, stop } = await start(team())
t.after(stop)
@@ -218,23 +269,30 @@ test('a stopped notice routes the acknowledgement back like a request', () => {
assert.equal(delivered[0].text, 'understood')
})
-test('a request that joins a user-started turn answers with the text that follows it', () => {
+// What the turn hands back for a joined request: the request itself, to answer next.
+const deferredOf = job => [job.fromId, job.toId, job.sessionId, job.role, job.exchangeId, job.hop, job.deferred, job.text]
+
+test('a request that joins a user-started turn is handed back, not answered with the turn\'s text', () => {
const { rt, emit, delivered } = turnsHost()
emit('b', 'turn/start', { turn: 1 })
emit('b', 'user/message', { content: textBlock('write the letter'), source: { kind: 'user' } })
emit('b', 'assistant/message', assistantText('first half'))
- emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmake it shorter'), source: replySource('request', { exchangeId: 'e1' }) })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmake it shorter'), source: replySource('request', { exchangeId: 'e1', hop: 2 }) })
emit('b', 'assistant/message', assistantText('second half'))
emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
- assert.equal(delivered.length, 1)
- assert.equal(delivered[0].toId, 'a')
- assert.equal(delivered[0].role, 'reply')
- assert.equal(delivered[0].replyTo, 'e1')
- assert.equal(delivered[0].text, 'second half')
+ assert.deepEqual(delivered.map(deferredOf), [['a', 'b', 'b', 'request', 'e1', 2, true, 'make it shorter']])
assert.deepEqual(rt.state.exchangeTurns, {})
+
+ // The handed-back request opens a hidden turn whose text is the reply.
+ emit('b', 'turn/start', { turn: 2 })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief · you read it during your last task; answer it now]\nmake it shorter'), source: replySource('request', { exchangeId: 'e1', hop: 2, deferred: true }) })
+ emit('b', 'assistant/message', assistantText('done, it is shorter'))
+ emit('b', 'turn/end', { turn: 2, reason: { kind: 'completed' } })
+ assert.deepEqual(delivered.slice(1).map(job => [job.toId, job.role, job.replyTo, job.hop, job.text]), [['a', 'reply', 'e1', 3, 'done, it is shorter']])
+ assert.deepEqual(rt.state.exchangeTurns, { b: [2] })
})
-test('a request that joins a Bot-triggered turn gets only the after-text, the trigger the whole turn', () => {
+test('a request that joins a Bot-triggered turn is handed back; the trigger gets the whole turn', () => {
const { rt, emit, delivered } = turnsHost()
emit('b', 'turn/start', { turn: 1 })
emit('b', 'user/message', { content: textBlock('[Message from Chief]\ntask'), source: replySource('request', { exchangeId: 'e0' }) })
@@ -243,15 +301,16 @@ test('a request that joins a Bot-triggered turn gets only the after-text, the tr
emit('b', 'assistant/message', assistantText('second half'))
emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
assert.deepEqual(rt.state.exchangeTurns.b, [1])
- assert.deepEqual(delivered.map(job => [job.replyTo, job.text]), [['e0', 'first half\n\nsecond half'], ['e1', 'second half']])
+ assert.deepEqual(delivered.map(job => [job.role, job.replyTo ?? job.exchangeId, job.text]), [['reply', 'e0', 'first half\n\nsecond half'], ['request', 'e1', 'more']])
})
-test('a joined request aborted without after-text still answers its sender', () => {
+test('a joined request in a stopped turn tells its sender, and is not handed back', () => {
const { emit, delivered } = turnsHost()
emit('b', 'turn/start', { turn: 1 })
emit('b', 'user/message', { content: textBlock('write the letter'), source: { kind: 'user' } })
emit('b', 'assistant/message', assistantText('first half'))
emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmore'), source: replySource('request', { exchangeId: 'e1' }) })
+ emit('b', 'assistant/message', assistantText('second half'))
emit('b', 'turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'hook', reason: 'ds-bot/stopped' } } })
assert.equal(delivered.length, 1)
assert.equal(delivered[0].toId, 'a')
@@ -282,8 +341,7 @@ test('a joined request never claims the next turn', () => {
emit('b', 'user/message', { content: textBlock('next task'), source: { kind: 'user' } })
emit('b', 'assistant/message', assistantText('for the user'))
emit('b', 'turn/end', { turn: 2, reason: { kind: 'completed' } })
- assert.equal(delivered.length, 1)
- assert.equal(delivered[0].replyTo, 'e1')
+ assert.deepEqual(delivered.map(job => [job.role, job.exchangeId, job.deferred]), [['request', 'e1', true]])
assert.deepEqual(rt.state.exchangeTurns, {})
})
@@ -295,9 +353,7 @@ test('a schedule-started turn stays visible when a request joins', () => {
emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmore'), source: replySource('request', { exchangeId: 'e1' }) })
emit('b', 'assistant/message', assistantText('after'))
emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
- assert.equal(delivered.length, 1)
- assert.equal(delivered[0].replyTo, 'e1')
- assert.equal(delivered[0].text, 'after')
+ assert.deepEqual(delivered.map(job => [job.role, job.exchangeId, job.text]), [['request', 'e1', 'more']])
assert.deepEqual(rt.state.exchangeTurns, {})
})
@@ -312,7 +368,7 @@ test('a duplicate exchangeId joins no second reply', () => {
assert.equal(delivered[0].replyTo, 'e0')
})
-test('a joined request crosses a part switch and is answered in the new part', async (t) => {
+test('a joined request crosses a part switch and is handed back in the new part', async (t) => {
const { agents, agentOf, emit, fire, stop } = await start(team())
t.after(stop)
@@ -328,18 +384,21 @@ test('a joined request crosses a part switch and is answered in the new part', a
const handoff = agents.get('s1').calls.find(([, message]) => message.source?.handoff === true)[1]
assert.equal((agents.get('a')?.calls ?? []).filter(([, message]) => message.source?.role === 'reply').length, 0)
assert.equal(handoff.source.exchangeId, 'e0')
- assert.deepEqual(handoff.source.joined.map(info => info.exchangeId), ['e1'])
+ assert.deepEqual(handoff.source.joined.map(item => [item.info.exchangeId, item.text]), [['e1', 'more']])
- // The resumed turn routes the trigger's and the joined request's replies.
+ // The resumed turn answers its trigger and hands the joined request back there.
emit('s1', 'turn/start', { turn: 1 })
emit('s1', 'user/message', { content: textBlock('[Handoff]\npackage'), source: handoff.source })
emit('s1', 'assistant/message', assistantText('done'))
emit('s1', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
- for (let count = 0; count < 200 && (agents.get('a')?.calls ?? []).length < 2; count += 1) await delay(5)
+ const handedBack = () => agents.get('s1').calls.find(([, message]) => message.source?.deferred === true)
+ for (let count = 0; count < 200 && ((agents.get('a')?.calls ?? []).length < 1 || handedBack() === undefined); count += 1) await delay(5)
const replies = (agents.get('a')?.calls ?? []).filter(([, message]) => message.source?.role === 'reply')
- assert.deepEqual(replies.map(([, message]) => message.source.replyTo), ['e0', 'e1'])
+ assert.deepEqual(replies.map(([, message]) => message.source.replyTo), ['e0'])
assert.equal(textOf(replies[0][1].content), '[Reply from Writer]\ndone')
- assert.equal(textOf(replies[1][1].content), '[Reply from Writer]\ndone')
+ assert.equal(handedBack()[0], 'followup')
+ assert.equal(handedBack()[1].source.exchangeId, 'e1')
+ assert.equal(textOf(handedBack()[1].content), '[Message from Chief · you read it during your last task; answer it now]\nmore')
})
test('the caller hop is the highest of the turn\'s trigger and joined requests', async (t) => {
diff --git a/ds-bot/test/mock-llm.test.js b/ds-bot/test/mock-llm.test.js
index 8637b3a8..063fb5f7 100644
--- a/ds-bot/test/mock-llm.test.js
+++ b/ds-bot/test/mock-llm.test.js
@@ -61,10 +61,13 @@ test('长任务 writes text on every step when the step size is left out', async
assert.equal(out.text.length, 4000) // a tool result continues the task
fold(messages, out)
- // A spliced Bot message mid-task hits the other parse of the same command.
+ // A spliced Bot message mid-task hits the other parse of the same command, and its
+ // note comes before the step's text.
messages.push({ role: 'user', content: '[Message from HelperBot] 进度如何?' })
out = await call(url, messages)
- assert.equal(out.text.length, 4000)
+ const ack = '(已按 HelperBot 的话调整)\n'
+ assert.ok(out.text.startsWith(ack), out.text.slice(0, 40))
+ assert.equal(out.text.length - ack.length, 4000)
fold(messages, out)
out = await call(url, messages)
diff --git a/ds-bot/test/tool-node.test.js b/ds-bot/test/tool-node.test.js
index 02ad1add..1ab8e3b1 100644
--- a/ds-bot/test/tool-node.test.js
+++ b/ds-bot/test/tool-node.test.js
@@ -103,7 +103,8 @@ test('non-relay context and ds-bot package sources are ignored', () => {
relay(22, 'request', { senderSessionId: undefined }),
{ time: 24, source: { kind: 'agent-instructions' } },
{ time: 26, source: null },
+ relay(27, 'request', { deferred: true }),
relay(28, 'request'),
]
- assert.deepEqual(relaysBefore(contexts, steps, steps[1]), [contexts[7]])
+ assert.deepEqual(relaysBefore(contexts, steps, steps[1]), [contexts[8]])
})