Skip to content

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

Let a Main Bot interrupt and stop a running Bot

lulu feizhufcfbd88b293f
diff --git a/.gitignore b/.gitignore
index 4b165251..07e2f8cc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,4 @@ node_modules/
.dsh-test*/
.dsh-home/
/shots/
+.playwright-mcp/
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 52c84b7f..cf9382a0 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -417,6 +417,7 @@ var ZH = {
"Replies from": "群聊回复:",
"Reply from": "收到回复:",
"Message from": "收到消息:",
+ "Stopped by": "叫停者:",
"{count} messages with": "{count} 条消息,来自",
"Routine started": "例行任务开始",
Update: "更新",
@@ -443,6 +444,10 @@ var ZH = {
"Checking the keys": "查看密钥",
"Asking {name}": "询问 {name}",
"Asking another Bot": "询问其他 Bot",
+ "Interrupting {name}": "给 {name} 插话",
+ "Interrupting another Bot": "给其他 Bot 插话",
+ "Stopping {name}": "叫停 {name}",
+ "Stopping another Bot": "叫停其他 Bot",
"Creating {name}": "创建 {name}",
"Updating {name}": "更新 {name}",
"Checking the team": "查看团队",
@@ -453,6 +458,10 @@ var ZH = {
"{name} is typing…": "{name} 正在输入…",
"Couldn't message {name}": "没能给 {name} 发消息",
Messaged: "已发消息给",
+ "Couldn't interrupt {name}": "没能给 {name} 插话",
+ Interrupted: "已插话",
+ "Couldn't stop {name}": "没能叫停 {name}",
+ Stopped: "已叫停",
Created: "已创建",
Updated: "已更新",
"Created group": "已创建群聊",
@@ -2664,7 +2673,7 @@ function installCompiledStyles(text, tag) {
var import_react2 = require("react");
var STATES = ["idle", "thinking", "searching", "working", "sending", "orbit", "alert", "done"];
var botState = (running, activity, alert) => running ? STATES.includes(activity) ? activity : "working" : alert ? "alert" : "idle";
-var toolState = (name) => /^(message_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(name) ? "sending" : /search|fetch|browse|read|grep|glob|list|recall/i.test(name) ? "searching" : "working";
+var toolState = (name) => /^(message_bot|interrupt_bot|stop_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(name) ? "sending" : /search|fetch|browse|read|grep|glob|list|recall/i.test(name) ? "searching" : "working";
function useGaze(ref, enabled) {
(0, import_react2.useEffect)(() => {
if (!enabled) return void 0;
@@ -3870,7 +3879,7 @@ 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") && typeof source.senderSessionId === "string";
+ const relayed = source.kind === "bot" && source.handoff !== true && (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);
@@ -3919,7 +3928,7 @@ function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnClock, us
if (!bots.some((bot) => bot.id === peer.id)) bots.push(peer);
}
return (0, import_react6.createElement)(EventLine, {
- prefix: count > 1 ? t("{count} messages with", { count }) : t("Message from"),
+ prefix: source.role === "stopped" ? t("Stopped by") : count > 1 ? t("{count} messages with", { count }) : t("Message from"),
bots,
onOpen: (bot) => actions.openExchange(selfId, bot.id)
});
@@ -4041,6 +4050,14 @@ function toolActivity(name, arg, findBot) {
const target = findBot(arg("to"));
return { label: target ? t("Asking {name}", { name: target.name }) : t("Asking another Bot"), state: "sending" };
}
+ case "interrupt_bot": {
+ const target = findBot(arg("to"));
+ return { label: target ? t("Interrupting {name}", { name: target.name }) : t("Interrupting another Bot"), state: "sending" };
+ }
+ case "stop_bot": {
+ const target = findBot(arg("bot"));
+ return { label: target ? t("Stopping {name}", { name: target.name }) : t("Stopping another Bot"), state: "sending" };
+ }
case "create_bot":
return { label: t("Creating {name}", { name: arg("name") ?? t("a Bot") }), state: "sending" };
case "update_bot": {
@@ -4158,6 +4175,16 @@ function ToolCell({ node, sessionId, useRoster, useUi, actions }) {
if (done && root.isError) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Couldn't message {name}", { name: target.name }));
return (0, import_react6.createElement)(EventLine, { prefix: t("Messaged"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id) });
}
+ case "interrupt_bot": {
+ const target = findBot(arg("to")) ?? { name: arg("to") ?? "…", color: "gray" };
+ if (done && root.isError) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Couldn't interrupt {name}", { name: target.name }));
+ return (0, import_react6.createElement)(EventLine, { prefix: t("Interrupted"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(roster.byId[sessionId]?.id ?? sessionId, bot.id) });
+ }
+ case "stop_bot": {
+ const target = findBot(arg("bot")) ?? { name: arg("bot") ?? "…", color: "gray" };
+ if (done && root.isError) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Couldn't stop {name}", { name: target.name }));
+ return (0, import_react6.createElement)(EventLine, { prefix: t("Stopped"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(roster.byId[sessionId]?.id ?? sessionId, bot.id) });
+ }
case "create_bot": {
const created = findBot(arg("name"));
if (!done || created === void 0) return null;
diff --git a/ds-bot/dev/mock-llm.mjs b/ds-bot/dev/mock-llm.mjs
index 63454b7d..eb99cdab 100644
--- a/ds-bot/dev/mock-llm.mjs
+++ b/ds-bot/dev/mock-llm.mjs
@@ -16,6 +16,7 @@
// Commands to a Bot:
// 建群 名: A, B · 群发[回报] 名: 消息 · 改群 名 公告|管理员|模式|加|踢: 值 · 删群 名
// 看群 名 (read_group_chat) · 转告 名: 消息 (message_bot) · 搜索:查询1 | 查询2 (web_search)
+// 插话 名: 消息 (interrupt_bot) · 叫停 名: 原因 (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)
@@ -230,6 +231,14 @@ 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.
+ 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)) {
+ 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', {})]
+ }
// "报错": 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'
const lastCall = [...messages].reverse().find(m => m.role === 'assistant' && Array.isArray(m.content) && m.content.some(b => b.type === 'tool_use'))
@@ -327,6 +336,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('stop_bot', { bot: order[1], reason: order[2] })]
if ((order = /^看群\s*(.+)$/.exec(userText))) return [tool('read_group_chat', { group: order[1].trim() })]
// Memory: 记住[@话题] 事实 · 团队记住 事实 · 忘掉 事实 · 回忆 [词]
if ((order = /^(团队)?记住(?:@(\S+))?\s*[::]?\s*(.+)$/.exec(userText)) && tools.has('remember')) {
diff --git a/ds-bot/src/client/cells.js b/ds-bot/src/client/cells.js
index aa809c2a..f3415cf4 100644
--- a/ds-bot/src/client/cells.js
+++ b/ds-bot/src/client/cells.js
@@ -262,7 +262,7 @@ 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') && typeof source.senderSessionId === 'string'
+ const relayed = source.kind === 'bot' && source.handoff !== true && (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(() => {
@@ -321,7 +321,7 @@ export function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnCl
if (!bots.some(bot => bot.id === peer.id)) bots.push(peer)
}
return h(EventLine, {
- prefix: count > 1 ? t('{count} messages with', { count }) : t('Message from'),
+ prefix: source.role === 'stopped' ? t('Stopped by') : count > 1 ? t('{count} messages with', { count }) : t('Message from'),
bots,
onOpen: bot => actions.openExchange(selfId, bot.id),
})
@@ -452,6 +452,14 @@ function toolActivity(name, arg, findBot) {
const target = findBot(arg('to'))
return { label: target ? t('Asking {name}', { name: target.name }) : t('Asking another Bot'), state: 'sending' }
}
+ case 'interrupt_bot': {
+ const target = findBot(arg('to'))
+ return { label: target ? t('Interrupting {name}', { name: target.name }) : t('Interrupting another Bot'), state: 'sending' }
+ }
+ case 'stop_bot': {
+ const target = findBot(arg('bot'))
+ return { label: target ? t('Stopping {name}', { name: target.name }) : t('Stopping another Bot'), state: 'sending' }
+ }
case 'create_bot': return { label: t('Creating {name}', { name: arg('name') ?? t('a Bot') }), state: 'sending' }
case 'update_bot': {
const target = findBot(arg('name')) ?? findBot(arg('bot'))
@@ -546,6 +554,16 @@ export function ToolCell({ node, sessionId, useRoster, useUi, actions }) {
if (done && root.isError) return h('div', { className: 'bt-event' }, t("Couldn't message {name}", { name: target.name }))
return h(EventLine, { prefix: t('Messaged'), bots: [target], onOpen: bot => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id) })
}
+ case 'interrupt_bot': {
+ const target = findBot(arg('to')) ?? { name: arg('to') ?? '…', color: 'gray' }
+ if (done && root.isError) return h('div', { className: 'bt-event' }, t("Couldn't interrupt {name}", { name: target.name }))
+ return h(EventLine, { prefix: t('Interrupted'), bots: [target], onOpen: bot => bot.id && actions.openExchange(roster.byId[sessionId]?.id ?? sessionId, bot.id) })
+ }
+ case 'stop_bot': {
+ const target = findBot(arg('bot')) ?? { name: arg('bot') ?? '…', color: 'gray' }
+ if (done && root.isError) return h('div', { className: 'bt-event' }, t("Couldn't stop {name}", { name: target.name }))
+ return h(EventLine, { prefix: t('Stopped'), bots: [target], onOpen: bot => bot.id && actions.openExchange(roster.byId[sessionId]?.id ?? sessionId, bot.id) })
+ }
case 'create_bot': {
const created = findBot(arg('name'))
if (!done || created === undefined) return null
diff --git a/ds-bot/src/client/i18n.js b/ds-bot/src/client/i18n.js
index a12a9390..edf3121d 100644
--- a/ds-bot/src/client/i18n.js
+++ b/ds-bot/src/client/i18n.js
@@ -371,6 +371,7 @@ const ZH = {
'Replies from': '群聊回复:',
'Reply from': '收到回复:',
'Message from': '收到消息:',
+ 'Stopped by': '叫停者:',
'{count} messages with': '{count} 条消息,来自',
'Routine started': '例行任务开始',
Update: '更新',
@@ -397,6 +398,10 @@ const ZH = {
'Checking the keys': '查看密钥',
'Asking {name}': '询问 {name}',
'Asking another Bot': '询问其他 Bot',
+ 'Interrupting {name}': '给 {name} 插话',
+ 'Interrupting another Bot': '给其他 Bot 插话',
+ 'Stopping {name}': '叫停 {name}',
+ 'Stopping another Bot': '叫停其他 Bot',
'Creating {name}': '创建 {name}',
'Updating {name}': '更新 {name}',
'Checking the team': '查看团队',
@@ -407,6 +412,10 @@ const ZH = {
'{name} is typing…': '{name} 正在输入…',
"Couldn't message {name}": '没能给 {name} 发消息',
Messaged: '已发消息给',
+ "Couldn't interrupt {name}": '没能给 {name} 插话',
+ Interrupted: '已插话',
+ "Couldn't stop {name}": '没能叫停 {name}',
+ Stopped: '已叫停',
Created: '已创建',
Updated: '已更新',
'Created group': '已创建群聊',
diff --git a/ds-bot/src/client/mark.js b/ds-bot/src/client/mark.js
index 849a6cf3..02fc7e39 100644
--- a/ds-bot/src/client/mark.js
+++ b/ds-bot/src/client/mark.js
@@ -11,7 +11,7 @@ export { colorOf, lookOf } from './characters.js'
// motion. Uploaded images only bob or hop, since they have no parts to move.
const STATES = ['idle', 'thinking', 'searching', 'working', 'sending', 'orbit', 'alert', 'done']
export const botState = (running, activity, alert) => (running ? (STATES.includes(activity) ? activity : 'working') : alert ? 'alert' : 'idle')
-export const toolState = name => (/^(message_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(name) ? 'sending'
+export const toolState = name => (/^(message_bot|interrupt_bot|stop_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(name) ? 'sending'
: /search|fetch|browse|read|grep|glob|list|recall/i.test(name) ? 'searching' : 'working')
// Eyes follow the pointer on large marks.
diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js
index 7ac2150f..2fe4bf8c 100644
--- a/ds-bot/src/host/constants.js
+++ b/ds-bot/src/host/constants.js
@@ -42,7 +42,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', 'create_bot', 'update_bot', 'list_models',
+ 'list_bots', 'message_bot', 'interrupt_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 3d76760f..2282cfb7 100644
--- a/ds-bot/src/host/delivery.js
+++ b/ds-bot/src/host/delivery.js
@@ -14,6 +14,8 @@ 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]`
if (role === 'kickoff') return '[Bot team setup]'
@@ -22,8 +24,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'])
+
// `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() }) {
+ async function deliver({ fromId, toId, sessionId, text, role, hop = 0, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, record = true }) {
const from = rt.botOf(fromId)
const to = rt.botOf(toId)
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
@@ -42,15 +47,19 @@ export function install(rt) {
...(roomId ? { roomId } : {}),
...(audience === 'user' ? { audience } : {}),
}
- if (role === 'request' || role === 'reply') {
+ if (record && 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()
}
const agent = await resolveAgent(sessionId ?? rt.chatOf(toId))
- agent.followup(createUserMessage({
+ // 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}` }],
source,
- }))
+ })
+ if (steer) agent.steer(message)
+ else agent.followup(message)
await ctx.sessions.flush(agent.session)
return exchangeId
}
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js
index 182ced6f..28e90e51 100644
--- a/ds-bot/src/host/parts.js
+++ b/ds-bot/src/host/parts.js
@@ -864,7 +864,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'].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 aa4b6f34..e5149c43 100644
--- a/ds-bot/src/host/prompt.js
+++ b/ds-bot/src/host/prompt.js
@@ -25,6 +25,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.',
'- 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 732a049b..d41c5c29 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -88,6 +88,73 @@ 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: '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)) return 'Only a Main Bot can interrupt other Bots.'
+ 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 interrupt yourself.'
+ const text = String(args.message ?? '').trim()
+ if (text === '') return '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.',
+ 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' },
+ },
+ output,
+ async execute(args, exec) {
+ await rt.load()
+ const sender = callerBot(exec)
+ if (sender === undefined || !rt.isMain(sender.id)) return 'Only a Main Bot can stop other Bots.'
+ const target = rt.findBot(args.bot)
+ if (target === undefined) return `No Bot named ${args.bot}. Team: ${Object.values(state.bots).map(bot => bot.name).join(', ')}`
+ if (target.id === sender.id) return 'You cannot stop yourself.'
+ const { running } = activeSessions(target.id)
+ if (running.length === 0) return `${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.`
+ for (const sessionId of running) {
+ const agent = await rt.resolveAgent(sessionId)
+ agent.cancel({ kind: 'hook', reason: 'ds-bot/stopped' })
+ }
+ const why = String(args.reason ?? '').trim() || 'Stop what you are doing; the previous turn was ended on purpose. Acknowledge briefly.'
+ await rt.deliver({ fromId: sender.id, toId: target.id, text: why, role: 'stopped' })
+ return `Stopped ${target.name} in ${running.map(whereOf).join(' and ')}. It is told why in a new turn, whose reply comes back to you.`
+ },
+ }))
+
ctx.tools.register(defineTool({
name: 'create_bot',
description: 'Main Bot only. Create a new Bot on the user\'s team. It appears in the sidebar and greets the user.',
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index ad2ed353..9d50009a 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -45,7 +45,7 @@ export function install(rt) {
/** @type {Record<string, string>} */
let activity = {}
const activityOf = (tool) => {
- if (/^(message_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(tool)) return 'sending'
+ 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 (tool === 'group_relay') return 'orbit'
if (/search|fetch|browse|browser|read|grep|glob|list/i.test(tool)) return 'searching'
return 'working'
@@ -76,13 +76,16 @@ export function install(rt) {
// A request whose audience is the user is answered in the recipient's own chat: that
// turn stays visible there and its reply is not routed back to the sender.
const answersUser = info => info.role === 'request' && info.audience === 'user'
+ // Roles whose turn owes the sender a reply: a 'stopped' notice asks the Bot to
+ // acknowledge, exactly like a request.
+ const expectsReply = info => info.role === 'request' || info.role === 'stopped'
// A group Session is hidden as a whole, so its turns need no marking. A handoff
// package that only opens a part is acknowledged with a fixed line, also hidden.
const claimTrigger = (sessionId, entry, info) => {
entry.info = info
if (rt.groupOwners.has(sessionId)) return
- if ((info.role === 'request' && !answersUser(info)) || info.role === 'room' || (info.role === 'handoff' && info.resume !== true)) {
+ if ((expectsReply(info) && !answersUser(info)) || info.role === 'room' || (info.role === 'handoff' && info.resume !== true)) {
markExchangeTurn(sessionId, entry.turn)
}
}
@@ -174,6 +177,9 @@ 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
@@ -220,7 +226,7 @@ export function install(rt) {
roomWaiters.delete(info.exchangeId)
if (failure !== undefined) waiter?.fail(failure)
else waiter?.resolve(reason?.kind === 'aborted' ? null : reply)
- } else if (info.role === 'request' && !answersUser(info) && failure !== undefined) {
+ } 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({
@@ -231,11 +237,14 @@ export function install(rt) {
hop: (info.hop ?? 0) + 1,
replyTo: info.exchangeId,
}).catch(error => rt.warn('ds-bot: failure notice delivery failed: %s', error))
- } else if (info.role === 'request' && !answersUser(info) && reply !== '') {
+ } 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,
+ text: reply !== '' ? reply : `${name} was stopped before it could answer your message.`,
role: 'reply',
hop: (info.hop ?? 0) + 1,
replyTo: info.exchangeId,
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index 528cd09e..bcd2c120 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -42,6 +42,8 @@ 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',
'tool list_models',
diff --git a/ds-bot/test/interrupt.test.js b/ds-bot/test/interrupt.test.js
new file mode 100644
index 00000000..ba5de442
--- /dev/null
+++ b/ds-bot/test/interrupt.test.js
@@ -0,0 +1,233 @@
+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 { 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)
+
+ assert.equal(await tool('interrupt_bot', { to: 'Writer', message: 'x' }, 'b'), 'Only a Main Bot can interrupt other Bots.')
+ assert.equal(await tool('stop_bot', { bot: 'Writer' }, 'b'), 'Only a Main Bot can stop other Bots.')
+ assert.equal(await tool('interrupt_bot', { to: 'Chief', message: 'x' }, 'a'), 'You cannot interrupt yourself.')
+ assert.equal(await tool('stop_bot', { bot: 'Chief' }, 'a'), 'You cannot stop yourself.')
+ 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)
+
+ assert.match(await tool('stop_bot', { bot: 'Writer' }, 'a'), /not running/)
+
+ 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')
+})