Skip to content

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

Let a Bot's message reach a working Bot at its next step

Fei24118029d907008e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 685ad0a3..781292f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,9 +8,11 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change
- In a Bot's chat or a group chat, `@` lists the Bots you can mention first: a group's members and **Everyone**, or the other Bots. Picking one writes `@Name`.
- **Reference a chat** in the composer's **+** menu adds another Bot's chat, or a recent conversation outside the team, to your message as context.
+- A Main Bot can stop another Bot's running turn. The Bot is told why, and its reply goes back to the Main Bot.
### 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.
- 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/dev/mock-llm.mjs b/ds-bot/dev/mock-llm.mjs
index eb99cdab..27f2e0b6 100644
--- a/ds-bot/dev/mock-llm.mjs
+++ b/ds-bot/dev/mock-llm.mjs
@@ -16,7 +16,7 @@
// Commands to a Bot:
// 建群 名: A, B · 群发[回报] 名: 消息 · 改群 名 公告|管理员|模式|加|踢: 值 · 删群 名
// 看群 名 (read_group_chat) · 转告 名: 消息 (message_bot) · 搜索:查询1 | 查询2 (web_search)
-// 插话 名: 消息 (interrupt_bot) · 叫停 名: 原因 (stop_bot)
+// 插话 名: 消息 (message_bot when "now") · 排队 名: 消息 (message_bot when "queue") · 叫停 名: 原因 (stop_bot)
// 长文 N / long N (N×1000 characters) · 长任务 N [K] (N steps of K×1000, default 4)
// 查记录 词 [词…] · 查锚点 part N #序号 · 查第 N 段 (read_own_chat)
// 上下文里有 词 (searches the context except the last message) · 撑爆 (fake overflow, 400)
@@ -231,13 +231,17 @@ function decide(body) {
const userText = textOf(last?.content).trim()
// "撑爆": the provider rejects the request as past its window.
if (userText.startsWith('撑爆')) return 'overflow'
- // "长任务" keeps stepping when a Bot message splices into its turn (an
- // interrupt or a relayed note); only a fresh opener or "[Stopped by" ends it.
+ // "长任务" 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.
const longOpener = messages.findLastIndex(m => m.role === 'user' && !isResults(m) && /^长任务\s*\d+/.test(textOf(m.content)))
- if (longOpener !== -1 && /^\[(?:Interrupt|Message|Reply) from /.test(userText)) {
+ if (longOpener !== -1 && /^\[(?:Message|Reply) from /.test(userText)) {
const [, steps, size = 4] = /^长任务\s*(\d+)(?:\s+(\d+))?/.exec(textOf(messages[longOpener].content)).map(Number)
const done = messages.slice(longOpener + 1).filter(isResults).length
- if (done < steps) return [text(filler(size * 1000, `步骤${done}`)), tool('list_bots', {})]
+ if (done < steps) {
+ 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.
if (/^报错$/.test(userText) || /^(?:\[Message from [^\]]*\]\n报错\n?)+$/.test(userText)) return 'auth'
@@ -336,7 +340,8 @@ function decide(body) {
}
if ((order = /^删群\s*(\S+)$/.exec(userText))) return [tool('delete_group', { group: order[1] })]
if ((order = /^转告\s*(\S+?)\s*[::]\s*(.+)$/.exec(userText))) return [tool('message_bot', { to: order[1], message: order[2] })]
- if ((order = /^插话\s*(\S+?)\s*[::]\s*(.+)$/.exec(userText))) return [tool('interrupt_bot', { to: order[1], message: order[2] })]
+ if ((order = /^插话\s*(\S+?)\s*[::]\s*(.+)$/.exec(userText))) return [tool('message_bot', { to: order[1], message: order[2], when: 'now' })]
+ if ((order = /^排队\s*(\S+?)\s*[::]\s*(.+)$/.exec(userText))) return [tool('message_bot', { to: order[1], message: order[2], when: 'queue' })]
if ((order = /^叫停\s*(\S+?)\s*[::]\s*(.+)$/.exec(userText))) return [tool('stop_bot', { bot: order[1], reason: order[2] })]
if ((order = /^看群\s*(.+)$/.exec(userText))) return [tool('read_group_chat', { group: order[1].trim() })]
// Memory: 记住[@话题] 事实 · 团队记住 事实 · 忘掉 事实 · 回忆 [词]
diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js
index ae3945a7..0810dcf6 100644
--- a/ds-bot/src/host/constants.js
+++ b/ds-bot/src/host/constants.js
@@ -45,7 +45,7 @@ export const AGENT_SESSION_TITLE_MAX = 80
// Every tool this plugin registers for Bots. `read_browser` only exists in the
// Desktop profile, so a restriction filters this list down to registered names.
export const TEAM_TOOLS = [
- 'list_bots', 'message_bot', 'interrupt_bot', 'stop_bot', 'create_bot', 'update_bot', 'list_models',
+ 'list_bots', 'message_bot', 'stop_bot', 'create_bot', 'update_bot', 'list_models',
'create_group', 'update_group', 'delete_group', 'post_to_group', 'ask_user',
'request_secret', 'list_secrets', 'group_relay', 'read_own_chat',
'read_group_chat', 'remember', 'forget', 'recall', 'read_browser',
diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js
index 2282cfb7..e0eaa429 100644
--- a/ds-bot/src/host/delivery.js
+++ b/ds-bot/src/host/delivery.js
@@ -14,7 +14,6 @@ export function install(rt) {
const headerFor = (role, fromName, roomName, audience, note = 'new message') => {
if (role === 'reply') return `[Reply from ${fromName}]`
- if (role === 'interrupt') return `[Interrupt from ${fromName}]`
if (role === 'stopped') return `[Stopped by ${fromName}]`
if (role === 'room') return `[Group chat "${roomName}" · ${note}]`
if (role === 'report') return `[Group chat "${roomName}" · replies to your post]`
@@ -24,11 +23,11 @@ export function install(rt) {
return `[Message from ${fromName}]`
}
- // Roles recorded as team exchanges; 'interrupt' and 'stopped' count once each.
- const EXCHANGE_ROLES = new Set(['request', 'reply', 'interrupt', 'stopped'])
+ // Roles recorded as team exchanges.
+ 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, record = true }) {
+ async function deliver({ fromId, toId, sessionId, text, role, hop = 0, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false }) {
const from = rt.botOf(fromId)
const to = rt.botOf(toId)
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
@@ -47,7 +46,7 @@ export function install(rt) {
...(roomId ? { roomId } : {}),
...(audience === 'user' ? { audience } : {}),
}
- if (record && EXCHANGE_ROLES.has(role)) {
+ if (EXCHANGE_ROLES.has(role)) {
state.exchanges.push({ id: exchangeId, from: fromId, to: toId, text, role, time: Date.now(), ...(replyTo ? { replyTo } : {}), ...(audience === 'user' ? { audience } : {}) })
void rt.save()
}
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js
index a24e7cae..c2547b2d 100644
--- a/ds-bot/src/host/parts.js
+++ b/ds-bot/src/host/parts.js
@@ -593,9 +593,10 @@ export function install(rt) {
exchangeId: job.info?.exchangeId ?? randomUUID(),
handoff: true,
...(resume ? { resume: true } : {}),
+ ...(resume && job.joined?.length ? { joined: job.joined } : {}),
})
- /** @type {Map<string, {botId:string, roomId?:string, carry:any[], info?:any, resume:boolean, overflow:boolean, hard:boolean, started?:boolean, moved?:boolean, noteFailed?:boolean}>} */
+ /** @type {Map<string, {botId:string, roomId?:string, carry:any[], info?:any, joined?:any[], resume:boolean, overflow:boolean, hard:boolean, started?:boolean, moved?:boolean, noteFailed?:boolean}>} */
const switches = new Map()
// Parts that have not started a turn yet, with their handoff package's size.
const freshParts = new Map()
@@ -637,10 +638,10 @@ export function install(rt) {
// `hard`: past the hard line or the window, the part moves on even without a note
// from the model.
- function startSwitch(agent, { resume = false, carry = [], info, overflow = false, hard = overflow } = {}) {
+ function startSwitch(agent, { resume = false, carry = [], info, joined, overflow = false, hard = overflow } = {}) {
const place = placeOf(agent.id)
if (place === undefined || switches.has(agent.id) || readOnly()) return
- const job = { ...place, carry: [...carry], info, resume, overflow, hard }
+ const job = { ...place, carry: [...carry], info, joined, resume, overflow, hard }
switches.set(agent.id, job)
void runSwitch(agent, job)
.catch(error => rt.warn('ds-bot: %s did not move on to a fresh part: %s', rt.botOf(job.botId)?.name ?? agent.id, error))
@@ -654,9 +655,10 @@ export function install(rt) {
// The stopped turn goes on where it was.
const back = job.carry.splice(0)
if (resume) {
+ const carried = job.joined?.length ? { joined: job.joined } : {}
back.unshift(createUserMessage({
content: [{ type: 'text', text: 'DS Bot paused your turn for a context check. Go on with it now from where you stopped.' }],
- source: job.info ?? { kind: SOURCE_KIND, form: 'relay', role: 'resume', exchangeId: randomUUID(), senderName: 'DS Bot', hop: 0 },
+ source: job.info ? { ...job.info, ...carried } : { kind: SOURCE_KIND, form: 'relay', role: 'resume', exchangeId: randomUUID(), senderName: 'DS Bot', hop: 0, ...carried },
}))
}
await forward(job, back).catch(error => rt.warn('ds-bot: input for %s was not handed on: %s', agent.id, error))
@@ -799,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, hard: true })
+ startSwitch(agent, { resume: midTurn, carry: payload.messages, info: midTurn ? entry.info : undefined, joined: midTurn ? (entry.joined ?? []).map(joined => joined.info) : undefined, hard: true })
return { kind: 'reject' }
}, { prepend: true })
@@ -810,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, overflow: true })
+ startSwitch(agent, { resume: true, info: entry.info, joined: (entry.joined ?? []).map(joined => joined.info), overflow: true })
return undefined
}, { prepend: true })
@@ -882,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', 'interrupt', 'stopped'].includes(source.role)) {
+ } else if (source?.kind === SOURCE_KIND && source.handoff !== 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 435fe6fd..76355328 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 an asynchronous message to another Bot. 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. 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, your final text in that turn is delivered back to that Bot automatically and the user does not see it. 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 …]" 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 … · 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.',
@@ -26,7 +26,7 @@ const MAIN_RULES = [
'- When the user wants something that deserves its own ongoing specialist, call create_bot (check list_bots first to avoid duplicates). Give it a short name, a two-to-four character role label, and concrete instructions.',
'- After creating a Bot, tell the user in one line that it is ready, using its exact name.',
'- Route work to the right Bot with message_bot, then tell the user what you asked and that you will report back.',
- '- To warn another Bot off a dangerous action or redirect it in time, interrupt_bot puts your message into its running turn at the next step — an ordinary message_bot would queue behind it. If it does not listen, stop_bot ends that turn at once and tells it why; the reply comes back to you.',
+ '- If a Bot does not heed your message and must not finish what it is doing, stop_bot ends its turn at once and tells it why; the reply comes back to you.',
'- Every Bot runs on one model of its own (list_bots shows it). Pass model to create_bot or update_bot only when the user names one; list_models gives the provider/model refs.',
'- Use update_bot to rename a Bot, change its role, color, model, or instructions when the user asks.',
'- You run the group chats too. create_group makes a group (you join it as its admin unless you name another); update_group changes any group\'s name, notice, members, admin, or reply mode; post_to_group posts into any group as you, which starts a round of replies the user reads there; delete_group archives a group, only when the user asks. list_bots shows every group.',
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 43d4556d..2f703079 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -60,7 +60,7 @@ export function install(rt) {
ctx.tools.register(defineTool({
name: 'message_bot',
- description: 'Send an asynchronous message to another Bot on the team. By default 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; 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' },
@@ -69,6 +69,11 @@ export function install(rt) {
enum: ['me', 'user'],
description: '"me" (default): the reply comes back to you and the user does not see it. "user": the Bot answers the user in its own chat, where the user reads it, and nothing comes back to you. Use "user" whenever the user wants to hear from that Bot directly or asks Bots to say something in their own chats.',
},
+ 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.',
+ },
},
output,
async execute(args, exec) {
@@ -78,13 +83,20 @@ export function install(rt) {
const target = rt.findBot(args.to)
if (target === undefined) return `No Bot named ${args.to}. Team: ${Object.values(state.bots).map(bot => bot.name).join(', ')}`
if (target.id === sender.id) return 'You cannot message yourself.'
- const hop = (rt.live.get(exec.agent?.id)?.info?.hop ?? 0)
+ const turn = rt.live.get(exec.agent?.id)
+ const hop = Math.max(turn?.info?.hop ?? 0, ...(turn?.joined ?? []).map(joined => joined.info?.hop ?? 0))
if (hop >= MAX_HOPS) return 'This chain of Bot messages is already long. Stop here and report to the user instead.'
const toUser = args.reply_to === 'user'
- await rt.deliver({ fromId: sender.id, toId: target.id, text: args.message, role: 'request', hop, ...(toUser ? { audience: 'user' } : {}) })
+ 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
? `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.`
- : `Delivered to ${target.name}. Its reply will arrive later as a new message; do not wait for it.`
+ : 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.`
+ : 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.`
},
}))
@@ -99,41 +111,13 @@ export function install(rt) {
const room = rt.roomOf(rt.groupOwners.get(sessionId)?.roomId)
return room ? `group "${room.name}"` : 'its own chat'
}
- // interrupt_bot and stop_bot throw when they do nothing, so the chat shows the call
- // as failed instead of "Interrupted" or "Stopped".
+ // 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) }
- ctx.tools.register(defineTool({
- name: 'interrupt_bot',
- description: 'Main Bot only. Cut into another Bot\'s running turn with an urgent message it sees at its next step — to warn it off a dangerous action or redirect it in time, while an ordinary message_bot would still be queued. If it is not running, the message opens its next turn instead. Whatever it answers stays in its own chat and is not routed back to you; if it keeps going despite the warning, use stop_bot.',
- parameters: {
- to: { type: 'string', required: true, description: 'Exact Bot name from list_bots' },
- message: { type: 'string', required: true, description: 'Short urgent instruction, e.g. "Stop — do not run that command"' },
- },
- output,
- async execute(args, exec) {
- await rt.load()
- const sender = callerBot(exec)
- if (sender === undefined || !rt.isMain(sender.id)) refuse('Only a Main Bot can interrupt other Bots.')
- const target = rt.findBot(args.to)
- if (target === undefined) refuse(`No Bot named ${args.to}. Team: ${Object.values(state.bots).map(bot => bot.name).join(', ')}`)
- if (target.id === sender.id) refuse('You cannot interrupt yourself.')
- const text = String(args.message ?? '').trim()
- if (text === '') refuse('Write a message to send.')
- const { running, idle } = activeSessions(target.id)
- const sessions = idle ? [rt.chatOf(target.id)] : running
- for (const [index, sessionId] of sessions.entries()) {
- await rt.deliver({ fromId: sender.id, toId: target.id, sessionId, text, role: 'interrupt', steer: true, record: index === 0 })
- }
- return idle
- ? `Sent to ${target.name}; it is not running, so the message opens its next turn. What it answers stays in its own chat — nothing comes back to you.`
- : `Interrupted ${target.name} in ${running.map(whereOf).join(' and ')}: it sees your message at its next step. What it answers stays in its own chat — nothing comes back to you.`
- },
- }))
-
ctx.tools.register(defineTool({
name: 'stop_bot',
- description: 'Main Bot only. Stop another Bot\'s running turn immediately — when it must not finish a dangerous action and interrupting is not enough. Its queued messages are dropped with the turn. It is then told why in a new turn, whose reply comes back to you.',
+ description: 'Main Bot only. Stop another Bot\'s running turn immediately — when it must not finish a dangerous action and a message_bot warning is not enough. Its queued messages are dropped with the turn. It is then told why in a new turn, whose reply comes back to you.',
parameters: {
bot: { type: 'string', required: true, description: 'Exact Bot name from list_bots' },
reason: { type: 'string', description: 'Why it was stopped; it reads this afterwards' },
@@ -147,7 +131,7 @@ export function install(rt) {
if (target === undefined) refuse(`No Bot named ${args.bot}. Team: ${Object.values(state.bots).map(bot => bot.name).join(', ')}`)
if (target.id === sender.id) refuse('You cannot stop yourself.')
const { running } = activeSessions(target.id)
- if (running.length === 0) refuse(`${target.name} is not running right now, so there is nothing to stop. Use message_bot to reach it, or interrupt_bot once it is running.`)
+ if (running.length === 0) refuse(`${target.name} is not running right now, so there is nothing to stop. Use message_bot to reach it.`)
for (const sessionId of running) {
const agent = await rt.resolveAgent(sessionId)
agent.cancel({ kind: 'hook', reason: 'ds-bot/stopped' })
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index 0db9647b..7f4800f9 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -34,7 +34,7 @@ export function attachReference(queued, source, text) {
export function install(rt) {
const { ctx, state } = rt
- /** @type {Map<string, {turn?:number, pending?:any, info?:any, texts:string[]}>} */
+ /** @type {Map<string, {turn?:number, pending?:any, info?:any, texts:string[], opened?:boolean, joined?:{info:any, from:number}[]}>} */
const live = new Map()
/** @type {Map<string, {resolve:(text:string)=>void}>} member turn waiters keyed by exchange id */
const roomWaiters = new Map()
@@ -55,7 +55,7 @@ export function install(rt) {
/** @type {Record<string, string>} */
let activity = {}
const activityOf = (tool) => {
- if (/^(message_bot|interrupt_bot|stop_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(tool)) return 'sending'
+ if (/^(message_bot|stop_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(tool)) return 'sending'
if (tool === 'group_relay') return 'orbit'
if (/search|fetch|browse|browser|read|grep|glob|list/i.test(tool)) return 'searching'
return 'working'
@@ -94,6 +94,11 @@ export function install(rt) {
// package that only opens a part is acknowledged with a fixed line, also hidden.
const claimTrigger = (sessionId, entry, info) => {
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 }))
+ }
if (rt.groupOwners.has(sessionId)) return
if ((expectsReply(info) && !answersUser(info)) || info.role === 'room' || (info.role === 'handoff' && info.resume !== true)) {
markExchangeTurn(sessionId, entry.turn)
@@ -156,6 +161,8 @@ export function install(rt) {
// A turn turned away before its first step may end without a turn/end.
entry.switched = false
entry.answers = false
+ entry.opened = false
+ entry.joined = []
if (entry.pending !== undefined) {
claimTrigger(id, entry, entry.pending)
entry.pending = undefined
@@ -166,6 +173,14 @@ export function install(rt) {
// A message that shares a step with a bare handoff package is what the turn
// answers, so the turn is not a hidden acknowledgement.
const bare = info => info?.handoff === true && info.resume !== true
+ // Whether the turn was already opened by an earlier message decides what a
+ // Bot relay that lands inside it may claim: the first message of a turn
+ // still claims it as today, a later one only joins it.
+ const opened = entry.opened === true
+ if (entry.turn !== undefined && !bare(source)
+ && (source?.kind === 'user' || source?.kind === REPLY_KIND || source?.kind === 'schedule' || source?.kind === SOURCE_KIND)) {
+ entry.opened = true
+ }
if (entry.turn !== undefined && (source?.kind === 'user' || source?.kind === REPLY_KIND || source?.kind === SOURCE_KIND)) {
if (bare(source)) {
if (entry.answers) break
@@ -187,12 +202,20 @@ export function install(rt) {
})
} else if (source?.kind === SOURCE_KIND && source.role === 'kickoff' && rt.roomOf(id)) {
queueRoomMessage(id, { text: '', kickoff: true })
- } else if (source?.kind === SOURCE_KIND && source.role === 'interrupt') {
- // A steered interrupt neither claims the running turn nor queues as the
- // next one's trigger: that turn's reply still belongs to its starter.
} else if (source?.kind === SOURCE_KIND) {
- if (entry.turn !== undefined && entry.info === undefined) claimTrigger(id, entry, source)
- else entry.pending = source
+ if (entry.turn === undefined) entry.pending = source
+ else if (!opened) claimTrigger(id, entry, source)
+ 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 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.
} else if (source?.kind === 'schedule' && rt.roomOf(id)) {
// A group's scheduled task reaches the group as the user's message.
queueRoomMessage(id, { text: reminderText(textOf(event.data.content)) })
@@ -222,46 +245,57 @@ export function install(rt) {
case 'turn/end': {
setActivity(id, undefined)
const info = entry.info
- const reply = entry.texts.join('\n\n').trim()
+ const joined = entry.joined ?? []
+ const texts = entry.texts
// A turn stopped for a switch goes on in the next part, which answers instead.
const switched = entry.switched === true
entry.turn = undefined
entry.info = undefined
entry.texts = []
entry.switched = false
+ entry.joined = []
const reason = event.data?.reason
const failure = reason?.kind === 'error' && !switched ? turnFailure(reason.error) : undefined
if (failure !== undefined) noteTurnFailure(id, failure)
- if (info === undefined || switched) break
- if (info.role === 'room') {
+ 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.
+ const answer = (source, reply) => {
+ if (!expectsReply(source) || answersUser(source)) return
+ const name = rt.botOf(rt.selfOf(id))?.name ?? 'The other Bot'
+ if (failure !== undefined) {
+ // The sender was told a reply comes later; without this it would wait forever.
+ void rt.deliver({
+ fromId: rt.selfOf(id),
+ toId: source.senderSessionId,
+ text: `${name} could not answer your message: its model call failed (${failureLine(failure)}). Tell the user if it matters; do not retry right away.`,
+ role: 'reply',
+ hop: (source.hop ?? 0) + 1,
+ replyTo: source.exchangeId,
+ }).catch(error => rt.warn('ds-bot: failure notice delivery failed: %s', error))
+ } else if (reply !== '' || reason?.kind === 'aborted') {
+ // A turn stopped before it could answer still owes the sender a line,
+ // or it would wait forever for a reply that never comes.
+ void rt.deliver({
+ fromId: rt.selfOf(id),
+ toId: source.senderSessionId,
+ text: reply !== '' ? reply : `${name} was stopped before it could answer your message.`,
+ role: 'reply',
+ hop: (source.hop ?? 0) + 1,
+ replyTo: source.exchangeId,
+ }).catch(error => rt.warn('ds-bot: reply delivery failed: %s', error))
+ }
+ }
+ if (info?.role === 'room') {
const waiter = roomWaiters.get(info.exchangeId)
roomWaiters.delete(info.exchangeId)
if (failure !== undefined) waiter?.fail(failure)
- else waiter?.resolve(reason?.kind === 'aborted' ? null : reply)
- } else if (expectsReply(info) && !answersUser(info) && failure !== undefined) {
- // The sender was told a reply comes later; without this it would wait forever.
- const name = rt.botOf(rt.selfOf(id))?.name ?? 'The other Bot'
- void rt.deliver({
- fromId: rt.selfOf(id),
- toId: info.senderSessionId,
- text: `${name} could not answer your message: its model call failed (${failureLine(failure)}). Tell the user if it matters; do not retry right away.`,
- role: 'reply',
- hop: (info.hop ?? 0) + 1,
- replyTo: info.exchangeId,
- }).catch(error => rt.warn('ds-bot: failure notice delivery failed: %s', error))
- } else if (expectsReply(info) && !answersUser(info) && (reply !== '' || reason?.kind === 'aborted')) {
- // A turn stopped before it could answer still owes the sender a line,
- // or it would wait forever for a reply that never comes.
- const name = rt.botOf(rt.selfOf(id))?.name ?? 'The other Bot'
- void rt.deliver({
- fromId: rt.selfOf(id),
- toId: info.senderSessionId,
- text: reply !== '' ? reply : `${name} was stopped before it could answer your message.`,
- role: 'reply',
- hop: (info.hop ?? 0) + 1,
- replyTo: info.exchangeId,
- }).catch(error => rt.warn('ds-bot: reply delivery failed: %s', error))
+ else waiter?.resolve(reason?.kind === 'aborted' ? null : texts.join('\n\n').trim())
+ } 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())
break
}
}
diff --git a/ds-bot/test/bot-messages.test.js b/ds-bot/test/bot-messages.test.js
new file mode 100644
index 00000000..31aff935
--- /dev/null
+++ b/ds-bot/test/bot-messages.test.js
@@ -0,0 +1,377 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+import { test } from 'node:test'
+import { apply } from '../index.js'
+import { fakeContext } from './fake-ctx.js'
+import { install as installTurns } from '../src/host/turns.js'
+import { install as installParts } from '../src/host/parts.js'
+import { SOURCE_KIND } from '../src/host/constants.js'
+
+// A two-Bot team, optionally with b in a group Session 'gb' of room 'Ops'.
+function team({ group = false } = {}) {
+ return {
+ version: 1,
+ mainBotIds: ['a'],
+ bots: {
+ a: { id: 'a', name: 'Chief', role: 'Boss', sessionId: 'a', createdAt: 1 },
+ b: { id: 'b', name: 'Writer', role: 'Write', sessionId: 'b', createdAt: 2 },
+ },
+ rooms: group ? { r1: { id: 'r1', name: 'Ops', members: ['a', 'b'], mode: 'admin', admin: 'a', named: true, sessions: { b: 'gb' } } } : {},
+ agents: {},
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+ prefs: {},
+ revision: 0,
+ }
+}
+
+// Services for a full apply(): resolveAgent returns a per-Session agent that
+// records followup/steer/inject/cancel calls.
+async function start(seed) {
+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-messages-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(seed))
+ const ctx = fakeContext()
+ const agents = new Map()
+ const agentOf = (sessionId) => {
+ if (!agents.has(sessionId)) {
+ const calls = []
+ agents.set(sessionId, {
+ session: { id: sessionId, requestHeader: () => undefined },
+ id: sessionId,
+ calls,
+ status: 'idle',
+ followup(message) { calls.push(['followup', message]) },
+ steer(message) { calls.push(['steer', message]) },
+ inject(message) { calls.push(['inject', message]) },
+ cancel(cause) { calls.push(['cancel', cause]) },
+ async whenIdle() {},
+ async runMaintenance(fn) { return fn(AbortSignal.timeout(60_000)) },
+ inbox: { nextStep: [], nextTurn: [], remove() {} },
+ })
+ }
+ return agents.get(sessionId)
+ }
+ Object.assign(ctx, {
+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },
+ workspaceRegistry: {
+ get: () => undefined,
+ resolveByPath: async () => undefined,
+ create: async path => ({ id: 'w1', path }),
+ archiveSession: async () => {},
+ },
+ sessionController: {
+ create: async () => ({ sessionId: 's1' }),
+ resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }),
+ selectModel: async () => {},
+ page: async () => ({ records: [], hasMore: false }),
+ },
+ sessionTitle: { rename: async () => {} },
+ sessions: { flush: async () => {} },
+ })
+ let route
+ const register = ctx.connection.fetch.register
+ ctx.connection.fetch.register = (options) => {
+ route = options
+ return register(options)
+ }
+ apply(ctx, { home })
+ let seq = 0
+ const emit = (id, type, data) => {
+ for (const listener of ctx.listeners.get('session/event') ?? []) {
+ if (listener.length >= 2) listener({ id }, { type, seq: ++seq, data })
+ }
+ }
+ // Runs every registered waterfall listener; `next` settles the chain.
+ const fire = (name, payload) => Promise.all((ctx.listeners.get(name) ?? []).map(listener => listener(payload, () => Promise.resolve(undefined))))
+ const tool = (name, args, sessionId) => ctx.registeredTools.get(name).execute(args, { agent: { id: sessionId } })
+ const call = async (endpoint, payload) => (await route.fetch(new Request('http://localhost/api/bot', {
+ method: 'POST', body: JSON.stringify({ endpoint, payload }),
+ }))).json()
+ const exchanges = async () => (await call('exchange', { a: 'a', b: 'b' })).value ?? []
+ const stop = () => {
+ ctx.dispose()
+ rmSync(home, { recursive: true, force: true })
+ }
+ // Loading once fills the Session-owner indexes turns.js filters events by.
+ await tool('list_bots', {}, 'a')
+ return { ctx, agents, agentOf, emit, fire, tool, call, exchanges, home, stop }
+}
+
+const textOf = content => content.map(block => block.text ?? '').join('\n')
+
+test('message_bot steers by default; on an idle Bot it opens the next turn', async (t) => {
+ const { agents, emit, tool, stop } = await start(team())
+ t.after(stop)
+
+ // Idle: the message goes to the Bot's own chat and starts its next turn.
+ const idle = await tool('message_bot', { to: 'Writer', message: 'how are you' }, 'a')
+ assert.equal(idle, 'Delivered to Writer. Its reply will arrive later as a new message; do not wait for it.')
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer'])
+ assert.match(textOf(agents.get('b').calls[0][1].content), /^\[Message from Chief\]/)
+ assert.equal(agents.get('b').calls[0][1].source.role, 'request')
+
+ // 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.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer', 'steer'])
+})
+
+test('message_bot when "queue" waits for the current work, and reply_to "user" always queues', async (t) => {
+ const { agents, emit, tool, stop } = await start(team())
+ t.after(stop)
+
+ emit('b', 'turn/start', { turn: 1 })
+ const queued = await tool('message_bot', { to: 'Writer', message: 'later', when: 'queue' }, 'a')
+ assert.equal(queued, 'Queued for Writer: it reads your message after its current work. Its reply will arrive later as a new message; do not wait for it.')
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['followup'])
+
+ const toUser = await tool('message_bot', { to: 'Writer', message: 'tell them', reply_to: 'user', when: 'now' }, 'a')
+ assert.equal(toUser, 'Delivered to Writer. It will answer the user in its own chat; nothing comes back to you, so point the user to Writer\'s chat instead of relaying.')
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['followup', 'followup'])
+ assert.equal(agents.get('b').calls[1][1].source.audience, 'user')
+})
+
+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)
+
+ const out = await tool('message_bot', { to: 'Chief', message: 'heads up' }, 'b')
+ assert.equal(out, 'Delivered to Chief. Its reply will arrive later as a new message; do not wait for it.')
+ assert.deepEqual(agents.get('a').calls.map(([kind]) => kind), ['steer'])
+ assert.equal(agents.get('a').calls[0][1].source.senderSessionId, 'b')
+})
+
+test('stop_bot cancels the running turns and tells the Bot why in a new turn', async (t) => {
+ const { agents, emit, tool, stop } = await start(team({ group: true }))
+ t.after(stop)
+
+ await assert.rejects(tool('stop_bot', { bot: 'Writer' }, 'a'), /not running/)
+ assert.deepEqual(agents.get('b')?.calls ?? [], [])
+
+ emit('b', 'turn/start', { turn: 1 })
+ emit('gb', 'turn/start', { turn: 1 })
+ const out = await tool('stop_bot', { bot: 'Writer', reason: 'that command deletes data' }, 'a')
+ assert.match(out, /Stopped Writer in its own chat and group "Ops"/)
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['cancel', 'followup'])
+ assert.deepEqual(agents.get('b').calls[0][1], { kind: 'hook', reason: 'ds-bot/stopped' })
+ assert.deepEqual(agents.get('gb').calls.map(([kind]) => kind), ['cancel'])
+ const notice = agents.get('b').calls[1][1]
+ assert.match(textOf(notice.content), /^\[Stopped by Chief\]\nthat command deletes data$/)
+ assert.equal(notice.source.role, 'stopped')
+})
+
+test('stop_bot belongs to a Main Bot', async (t) => {
+ const { tool, stop } = await start(team())
+ t.after(stop)
+
+ await assert.rejects(tool('stop_bot', { bot: 'Writer' }, 'b'), { message: 'Only a Main Bot can stop other Bots.' })
+ await assert.rejects(tool('stop_bot', { bot: 'Chief' }, 'a'), { message: 'You cannot stop yourself.' })
+ await assert.rejects(tool('stop_bot', { bot: 'Writer' }, 'a'), { message: 'Writer is not running right now, so there is nothing to stop. Use message_bot to reach it.' })
+})
+
+function turnsHost() {
+ let listener
+ const delivered = []
+ const rt = {
+ ctx: { on: (name, fn) => { if (name === 'session/event') listener = fn } },
+ state: { exchangeTurns: {}, questions: {} },
+ bots: { a: { id: 'a', name: 'Chief' }, b: { id: 'b', name: 'Writer' } },
+ isBotSession: () => true,
+ roomOf: () => undefined,
+ groupOwners: new Map(),
+ chatOwners: new Map(),
+ botOf: id => rt.bots[id],
+ selfOf: id => id,
+ save: async () => {},
+ deliver: async (args) => { delivered.push(args) },
+ noteFailure() {},
+ warn() {},
+ switchJobs: () => [],
+ dropKickoff() {},
+ }
+ installTurns(rt)
+ let seq = 0
+ const emit = (id, type, data) => listener({ id }, { type, seq: ++seq, data })
+ return { rt, emit, delivered }
+}
+
+const replySource = (role, extra = {}) => ({ kind: SOURCE_KIND, role, senderSessionId: 'a', senderName: 'Chief', exchangeId: 'x1', hop: 0, ...extra })
+const textBlock = (content) => [{ type: 'text', text: content }]
+const assistantText = text => ({ message: { content: textBlock(text) } })
+
+test('a stopped notice routes the acknowledgement back like a request', () => {
+ const { rt, emit, delivered } = turnsHost()
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('[Stopped by Chief]\nwhy'), source: replySource('stopped', { exchangeId: 's1' }) })
+ assert.deepEqual(rt.state.exchangeTurns.b, [1])
+ emit('b', 'assistant/message', assistantText('understood'))
+ 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, 's1')
+ assert.equal(delivered[0].text, 'understood')
+})
+
+test('a request that joins a user-started turn answers with the text that follows it', () => {
+ 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', '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(rt.state.exchangeTurns, {})
+})
+
+test('a request that joins a Bot-triggered turn gets only the after-text, the trigger 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' }) })
+ 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: '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']])
+})
+
+test('a joined request aborted without after-text still answers its sender', () => {
+ 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', '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')
+ assert.equal(delivered[0].replyTo, 'e1')
+ assert.match(delivered[0].text, /was stopped before it could answer/)
+})
+
+test('a joined request gets the failure notice when the model call fails', () => {
+ 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', 'turn/end', { turn: 1, reason: { kind: 'error', error: { code: 'SERVER', message: 'upstream busy', status: 503 } } })
+ assert.equal(delivered.length, 1)
+ assert.equal(delivered[0].replyTo, 'e1')
+ assert.match(delivered[0].text, /^Writer could not answer your message: its model call failed \(SERVER 503: upstream busy\)/)
+})
+
+test('a joined request never claims the next turn', () => {
+ 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', 'user/message', { content: textBlock('[Message from Chief]\nmore'), source: replySource('request', { exchangeId: 'e1' }) })
+ emit('b', 'assistant/message', assistantText('answer'))
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+ emit('b', 'turn/start', { turn: 2 })
+ 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(rt.state.exchangeTurns, {})
+})
+
+test('a schedule-started turn stays visible when a request joins', () => {
+ const { rt, emit, delivered } = turnsHost()
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('routine'), source: { kind: 'schedule' } })
+ emit('b', 'assistant/message', assistantText('before'))
+ 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(rt.state.exchangeTurns, {})
+})
+
+test('a duplicate exchangeId joins no second reply', () => {
+ const { emit, delivered } = turnsHost()
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\ntask'), source: replySource('request', { exchangeId: 'e0' }) })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\ntask'), source: replySource('request', { exchangeId: 'e0' }) })
+ emit('b', 'assistant/message', assistantText('answer'))
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+ assert.equal(delivered.length, 1)
+ assert.equal(delivered[0].replyTo, 'e0')
+})
+
+test('a joined request crosses a part switch and is answered in the new part', async (t) => {
+ const { agents, agentOf, emit, fire, stop } = await start(team())
+ t.after(stop)
+
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\ntask'), source: replySource('request', { exchangeId: 'e0' }) })
+ emit('b', 'assistant/message', assistantText('half'))
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmore'), source: replySource('request', { exchangeId: 'e1' }) })
+ // The model call hits the window: the turn stops and the part moves on.
+ await fire('agent/request-error', { failure: { code: 'CONTEXT_WINDOW_EXCEEDED' }, signal: AbortSignal.timeout(60_000), agent: agentOf('b') })
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'error', error: { code: 'CONTEXT_WINDOW_EXCEEDED' } } })
+ // Neither the trigger nor the joined request answers from the old part.
+ for (let count = 0; count < 200 && agents.get('s1')?.calls.find(([, message]) => message.source?.handoff === true) === undefined; count += 1) await delay(5)
+ 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'])
+
+ // The resumed turn routes the trigger's and the joined request's replies.
+ 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 replies = (agents.get('a')?.calls ?? []).filter(([, message]) => message.source?.role === 'reply')
+ assert.deepEqual(replies.map(([, message]) => message.source.replyTo), ['e0', 'e1'])
+ assert.equal(textOf(replies[0][1].content), '[Reply from Writer]\ndone')
+ assert.equal(textOf(replies[1][1].content), '[Reply from Writer]\ndone')
+})
+
+test('the caller hop is the highest of the turn\'s trigger and joined requests', async (t) => {
+ const { agents, emit, tool, stop } = await start(team())
+ t.after(stop)
+
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\ntask'), source: replySource('request', { exchangeId: 'e0', hop: 1 }) })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmore'), source: replySource('request', { exchangeId: 'e1', hop: 4 }) })
+ await tool('message_bot', { to: 'Chief', message: 'onward' }, 'b')
+ assert.equal(agents.get('a').calls[0][1].source.hop, 4)
+})
+
+test('an earlier part keeps the request its Bot answered', async () => {
+ const writer = { id: 'b', name: 'Writer', createdAt: 1, sessionId: 'b2', segments: [{ sessionId: 'b1', endedAt: 2 }] }
+ const events = [
+ { type: 'user/message', seq: 1, time: 10, data: { turn: 1, content: [{ type: 'text', text: '[Message from Chief]\nDo not delete that' }], source: replySource('request') } },
+ { type: 'assistant/message', seq: 2, time: 11, data: { turn: 1, message: { content: [{ type: 'text', text: 'Understood, I stopped.' }] } } },
+ ]
+ const rt = {
+ ctx: { on() {}, effect() {}, get() {}, sessionController: { page: async () => ({ records: events.map(event => ({ event })), hasMore: false }) } },
+ config: {},
+ state: { exchangeTurns: {} },
+ chatOwners: new Map([['b2', 'b']]),
+ pastOwners: new Map([['b1', { botId: 'b' }]]),
+ botOf: id => (id === 'b' ? writer : undefined),
+ roomOf: () => undefined,
+ chatOf: () => 'b2',
+ resolveAgent: async id => ({ session: { id, seq: 3 } }),
+ }
+ installParts(rt)
+ const { items } = await rt.earlierPage('b2')
+ assert.deepEqual(items.map(item => [item.kind, item.role ?? item.text]), [['event', 'request'], ['bot', 'Understood, I stopped.']])
+ assert.equal(items[0].botId, 'a')
+})
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index bcd2c120..754bf635 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -42,7 +42,6 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {
'prompt bot-identity 640',
'tool list_bots',
'tool message_bot',
- 'tool interrupt_bot',
'tool stop_bot',
'tool create_bot',
'tool update_bot',
diff --git a/ds-bot/test/interrupt.test.js b/ds-bot/test/interrupt.test.js
deleted file mode 100644
index 9dc1e8bb..00000000
--- a/ds-bot/test/interrupt.test.js
+++ /dev/null
@@ -1,261 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { test } from 'node:test'
-import { apply } from '../index.js'
-import { fakeContext } from './fake-ctx.js'
-import { install as installTurns } from '../src/host/turns.js'
-import { install as installParts } from '../src/host/parts.js'
-import { SOURCE_KIND } from '../src/host/constants.js'
-
-// A two-Bot team, optionally with b in a group Session 'gb' of room 'Ops'.
-function team({ group = false } = {}) {
- return {
- version: 1,
- mainBotIds: ['a'],
- bots: {
- a: { id: 'a', name: 'Chief', role: 'Boss', sessionId: 'a', createdAt: 1 },
- b: { id: 'b', name: 'Writer', role: 'Write', sessionId: 'b', createdAt: 2 },
- },
- rooms: group ? { r1: { id: 'r1', name: 'Ops', members: ['a', 'b'], mode: 'admin', admin: 'a', named: true, sessions: { b: 'gb' } } } : {},
- agents: {},
- exchanges: [],
- exchangeTurns: {},
- questions: {},
- prefs: {},
- revision: 0,
- }
-}
-
-// Services for a full apply(): resolveAgent returns a per-Session agent that
-// records followup/steer/inject/cancel calls.
-async function start(seed) {
- const home = mkdtempSync(join(tmpdir(), 'ds-bot-interrupt-'))
- writeFileSync(join(home, 'state.json'), JSON.stringify(seed))
- const ctx = fakeContext()
- const agents = new Map()
- const agentOf = (sessionId) => {
- if (!agents.has(sessionId)) {
- const calls = []
- agents.set(sessionId, {
- session: { id: sessionId },
- calls,
- status: 'idle',
- followup(message) { calls.push(['followup', message]) },
- steer(message) { calls.push(['steer', message]) },
- inject(message) { calls.push(['inject', message]) },
- cancel(cause) { calls.push(['cancel', cause]) },
- })
- }
- return agents.get(sessionId)
- }
- Object.assign(ctx, {
- llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },
- workspaceRegistry: {
- get: () => undefined,
- resolveByPath: async () => undefined,
- create: async path => ({ id: 'w1', path }),
- archiveSession: async () => {},
- },
- sessionController: {
- create: async () => ({ sessionId: 's1' }),
- resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }),
- selectModel: async () => {},
- },
- sessionTitle: { rename: async () => {} },
- sessions: { flush: async () => {} },
- })
- let route
- const register = ctx.connection.fetch.register
- ctx.connection.fetch.register = (options) => {
- route = options
- return register(options)
- }
- apply(ctx, { home })
- let seq = 0
- const emit = (id, type, data) => {
- for (const listener of ctx.listeners.get('session/event') ?? []) {
- if (listener.length >= 2) listener({ id }, { type, seq: ++seq, data })
- }
- }
- const tool = (name, args, sessionId) => ctx.registeredTools.get(name).execute(args, { agent: { id: sessionId } })
- const call = async (endpoint, payload) => (await route.fetch(new Request('http://localhost/api/bot', {
- method: 'POST', body: JSON.stringify({ endpoint, payload }),
- }))).json()
- const exchanges = async () => (await call('exchange', { a: 'a', b: 'b' })).value ?? []
- const stop = () => {
- ctx.dispose()
- rmSync(home, { recursive: true, force: true })
- }
- // Loading once fills the Session-owner indexes turns.js filters events by.
- await tool('list_bots', {}, 'a')
- return { ctx, agents, agentOf, emit, tool, call, exchanges, home, stop }
-}
-
-const textOf = content => content.map(block => block.text ?? '').join('\n')
-
-test('interrupt_bot steers into the Bot\'s running turn; on an idle Bot it opens the next turn', async (t) => {
- const { agents, emit, tool, stop } = await start(team())
- t.after(stop)
-
- // Idle: the interrupt goes to the Bot's own chat and starts its next turn.
- const idle = await tool('interrupt_bot', { to: 'Writer', message: 'Stop — do not run that' }, 'a')
- assert.match(idle, /not running/)
- assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer'])
- assert.match(textOf(agents.get('b').calls[0][1].content), /^\[Interrupt from Chief\]/)
- assert.equal(agents.get('b').calls[0][1].source.role, 'interrupt')
-
- // Running: the interrupt cuts into that turn instead of queuing.
- emit('b', 'turn/start', { turn: 1 })
- const busy = await tool('interrupt_bot', { to: 'Writer', message: 'Really, stop' }, 'a')
- assert.match(busy, /Interrupted Writer/)
- assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer', 'steer'])
-})
-
-test('interrupt_bot steers every Session the Bot is running in, recording one exchange', async (t) => {
- const { agents, emit, tool, exchanges, stop } = await start(team({ group: true }))
- t.after(stop)
-
- emit('b', 'turn/start', { turn: 1 })
- emit('gb', 'turn/start', { turn: 1 })
- const out = await tool('interrupt_bot', { to: 'Writer', message: 'Hands off' }, 'a')
- assert.match(out, /its own chat/)
- assert.match(out, /group "Ops"/)
- assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer'])
- assert.deepEqual(agents.get('gb').calls.map(([kind]) => kind), ['steer'])
- const logged = await exchanges()
- assert.equal(logged.filter(entry => entry.role === 'interrupt').length, 1)
-})
-
-test('interrupt_bot and stop_bot belong to a Main Bot', async (t) => {
- const { agents, tool, stop } = await start(team())
- t.after(stop)
-
- // A refusal fails the call, so the chat does not show it as done.
- await assert.rejects(tool('interrupt_bot', { to: 'Writer', message: 'x' }, 'b'), { message: 'Only a Main Bot can interrupt other Bots.' })
- await assert.rejects(tool('stop_bot', { bot: 'Writer' }, 'b'), { message: 'Only a Main Bot can stop other Bots.' })
- await assert.rejects(tool('interrupt_bot', { to: 'Chief', message: 'x' }, 'a'), { message: 'You cannot interrupt yourself.' })
- await assert.rejects(tool('stop_bot', { bot: 'Chief' }, 'a'), { message: 'You cannot stop yourself.' })
- await assert.rejects(tool('interrupt_bot', { to: 'Nobody', message: 'x' }, 'a'), /No Bot named Nobody/)
- await assert.rejects(tool('interrupt_bot', { to: 'Writer', message: ' ' }, 'a'), { message: 'Write a message to send.' })
- assert.deepEqual(agents.get('b')?.calls ?? [], [])
-})
-
-test('stop_bot cancels the running turns and tells the Bot why in a new turn', async (t) => {
- const { agents, emit, tool, stop } = await start(team({ group: true }))
- t.after(stop)
-
- await assert.rejects(tool('stop_bot', { bot: 'Writer' }, 'a'), /not running/)
- assert.deepEqual(agents.get('b')?.calls ?? [], [])
-
- emit('b', 'turn/start', { turn: 1 })
- emit('gb', 'turn/start', { turn: 1 })
- const out = await tool('stop_bot', { bot: 'Writer', reason: 'that command deletes data' }, 'a')
- assert.match(out, /Stopped Writer in its own chat and group "Ops"/)
- assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['cancel', 'followup'])
- assert.deepEqual(agents.get('b').calls[0][1], { kind: 'hook', reason: 'ds-bot/stopped' })
- assert.deepEqual(agents.get('gb').calls.map(([kind]) => kind), ['cancel'])
- const notice = agents.get('b').calls[1][1]
- assert.match(textOf(notice.content), /^\[Stopped by Chief\]\nthat command deletes data$/)
- assert.equal(notice.source.role, 'stopped')
-})
-
-function turnsHost() {
- let listener
- const delivered = []
- const rt = {
- ctx: { on: (name, fn) => { if (name === 'session/event') listener = fn } },
- state: { exchangeTurns: {}, questions: {} },
- bots: { a: { id: 'a', name: 'Chief' }, b: { id: 'b', name: 'Writer' } },
- isBotSession: () => true,
- roomOf: () => undefined,
- groupOwners: new Map(),
- chatOwners: new Map(),
- botOf: id => rt.bots[id],
- selfOf: id => id,
- save: async () => {},
- deliver: async (args) => { delivered.push(args) },
- noteFailure() {},
- warn() {},
- switchJobs: () => [],
- dropKickoff() {},
- }
- installTurns(rt)
- let seq = 0
- const emit = (id, type, data) => listener({ id }, { type, seq: ++seq, data })
- return { rt, emit, delivered }
-}
-
-const replySource = (role, extra = {}) => ({ kind: SOURCE_KIND, role, senderSessionId: 'a', senderName: 'Chief', exchangeId: 'x1', hop: 0, ...extra })
-
-test('a steered interrupt never claims the running turn or steals the next one', () => {
- const { emit, delivered } = turnsHost()
- // The running turn answers a request; an interrupt cuts in mid-turn.
- emit('b', 'turn/start', { turn: 1 })
- emit('b', 'user/message', { content: [{ type: 'text', text: 'hi' }], source: replySource('request') })
- emit('b', 'user/message', { content: [{ type: 'text', text: 'stop' }], source: replySource('interrupt', { exchangeId: 'i1' }) })
- emit('b', 'assistant/message', { message: { content: [{ type: 'text', text: 'done' }] } })
- emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
- // The turn's reply routes to the request, not to the interrupt.
- assert.equal(delivered.length, 1)
- assert.equal(delivered[0].replyTo, 'x1')
- assert.equal(delivered[0].role, 'reply')
-
- // An interrupt left behind must not claim the next turn either.
- emit('b', 'turn/start', { turn: 2 })
- emit('b', 'user/message', { content: [{ type: 'text', text: 'q' }], source: replySource('request', { exchangeId: 'x2' }) })
- emit('b', 'assistant/message', { message: { content: [{ type: 'text', text: 'ok' }] } })
- emit('b', 'turn/end', { turn: 2, reason: { kind: 'completed' } })
- assert.equal(delivered.length, 2)
- assert.equal(delivered[1].replyTo, 'x2')
-})
-
-test('a turn stopped before answering still closes the exchange for the sender', () => {
- const { emit, delivered } = turnsHost()
- emit('b', 'turn/start', { turn: 1 })
- emit('b', 'user/message', { content: [{ type: 'text', text: 'hi' }], source: replySource('request') })
- 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')
- assert.equal(delivered[0].role, 'reply')
- assert.equal(delivered[0].replyTo, 'x1')
- assert.match(delivered[0].text, /was stopped before it could answer/)
-})
-
-test('a stopped notice routes the acknowledgement back like a request', () => {
- const { rt, emit, delivered } = turnsHost()
- emit('b', 'turn/start', { turn: 1 })
- emit('b', 'user/message', { content: [{ type: 'text', text: 'why' }], source: replySource('stopped', { exchangeId: 's1' }) })
- assert.deepEqual(rt.state.exchangeTurns.b, [1])
- emit('b', 'assistant/message', { message: { content: [{ type: 'text', text: 'understood' }] } })
- 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, 's1')
- assert.equal(delivered[0].text, 'understood')
-})
-
-test('an earlier part keeps the interrupt that its Bot answered', async () => {
- const writer = { id: 'b', name: 'Writer', createdAt: 1, sessionId: 'b2', segments: [{ sessionId: 'b1', endedAt: 2 }] }
- const events = [
- { type: 'user/message', seq: 1, time: 10, data: { turn: 1, content: [{ type: 'text', text: '[Interrupt from Chief]\nDo not delete that' }], source: replySource('interrupt') } },
- { type: 'assistant/message', seq: 2, time: 11, data: { turn: 1, message: { content: [{ type: 'text', text: 'Understood, I stopped.' }] } } },
- ]
- const rt = {
- ctx: { on() {}, effect() {}, get() {}, sessionController: { page: async () => ({ records: events.map(event => ({ event })), hasMore: false }) } },
- config: {},
- state: { exchangeTurns: {} },
- chatOwners: new Map([['b2', 'b']]),
- pastOwners: new Map([['b1', { botId: 'b' }]]),
- botOf: id => (id === 'b' ? writer : undefined),
- roomOf: () => undefined,
- chatOf: () => 'b2',
- resolveAgent: async id => ({ session: { id, seq: 3 } }),
- }
- installParts(rt)
- const { items } = await rt.earlierPage('b2')
- assert.deepEqual(items.map(item => [item.kind, item.role ?? item.text]), [['event', 'interrupt'], ['bot', 'Understood, I stopped.']])
- assert.equal(items[0].botId, 'a')
-})