Skip to content

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

Deduplicate named Bot message requests across restarts

klarkxy65971423301a
diff --git a/docs/plans/2026-10-16-bot-handoffs.md b/docs/plans/2026-10-16-bot-handoffs.md
index 97997e75..80f4a8b5 100644
--- a/docs/plans/2026-10-16-bot-handoffs.md
+++ b/docs/plans/2026-10-16-bot-handoffs.md
@@ -57,6 +57,20 @@ Bot 之间派活原来按数量拦,不看对方的状态:
- Y 已经读了(消息进了 Y 正在跑的回合),X 再发就是一条新消息,和原来一样。
- 所以收件箱里每个发件人最多一条没读的消息,不再有未读上限。
+### 请求身份(request_id)
+
+- `message_bot` 多一个可选参数 `request_id`:发活的人自己给这件活起个名字。同一个名字加同一份内容是同一件活。
+- 名字属于发活的人:范围是「发活的 Bot + 说话的场合(私聊或者哪个群)+ 名字」。别人用同一个名字是另一件活;Bot 换到新的一段对话(`state.json` 里的会话分段)也还是同一个名字;Bot 被删掉又重建,拿到的是新 id,名字也跟着是新的,不和旧活串。
+- 记下来的是这件事本身:收件人(按 id)、正文(去掉首尾空白、换行统一)、`reply_to`、`when` 的一份指纹。
+- 结果:
+ - 同一个名字、同一份内容:不再发一次,把第一次的回执原样给回去。
+ - 同一个名字、别的内容:拒绝,不发。名字是一件活的名字,不是一个模板。
+ - 不给名字:和原来一样,不记、不拦。
+- 回执在消息发出去之前就写进 `state.json`:所以重启之后、或者对方已经读了消息,重试都只是拿回原来的回执,不会再发一次。
+- 结果不确定的时候不重发:发送途中失败,或者消息发出去以后 DS Bot 停了,这一次的结果就是「不知道」。工具告诉发活的人这件事没有再发,让人先看对方收到没有,别拿同一个名字再发。
+- 群里也一样:群里用 `message_bot` 叫人就是往群里发一条 `@名字`,同一个名字不会发两次。合并没有读过的消息也一样:合的是第一次那件活,回执还是各自的那一份。
+- 请求身份和回执随团队保留,不因时间或条数自动淘汰。否则旧请求重试会被当成新活,重复执行。需要再次做同样的工作时,调用方明确换一个 `request_id`;回执归档或清理策略另行设计。
+
### 派活树
- 一件活:一个 Bot 用 `message_bot` 发给另一个 Bot、要对方回复的消息(`reply_to: "user"` 的不算)。B 在回答 A 这件活的回合里,以及之后接着做它的回合里,派出去的活都是这件活下面的活。
@@ -99,6 +113,7 @@ Bot 之间派活原来按数量拦,不看对方的状态:
- 不主动通知派活的 Bot「对方卡住了」:每条通知都会让派活的 Bot 再跑一次模型;用户在界面上已经看得到在等批准的 Bot。派活的 Bot 下次调 `list_bots` 或 `message_bot` 时能看到。
- 不做看板式的任务对象:活仍在 Bot 的会话里,派活仍是消息。任务对象、进度查询和「只提问不动手」留给独立 app。
- 不设总量、链长或轮数的兜底上限。
+- 不做批量派活的接口,也不给 `request_id` 加别的用法:它只是发活的人给自己那件活起的名字。
## 已知限制
@@ -106,8 +121,10 @@ Bot 之间派活原来按数量拦,不看对方的状态:
- 下面的活一直不交回(比如对方在等用户批准),上面就一直等;DSH 没有超时。状态里看得到在等谁。
- 状态只在内存里,DSH 重启后从新的事件重建,和界面上的状态一样;等待关系除外,它存在 `state.json` 里。
- X 自己把同一件活拆成几条不同的请求、分给不同的 Bot,不算重复。
+- 一个 `request_id` 只对应一份内容:改一个字就是另一件活,会被拒绝。发活的人要改内容,就另起一个名字。
## 变更
- 2026-10-16:定下(#262)。
- 2026-10-16:Bot 的形象动画表示「在等别的 Bot」(#262)。
+- 2026-10-23:`message_bot` 可以带 `request_id`:同一件活重试只发一次并拿回原来的回执,同名不同内容拒绝,结果不确定时不重发(#480)。
diff --git a/ds-bot/index.js b/ds-bot/index.js
index 31a0a815..a3aaaa41 100644
--- a/ds-bot/index.js
+++ b/ds-bot/index.js
@@ -9,6 +9,7 @@ import * as providers from './src/host/providers.js'
import * as permissions from './src/host/permissions.js'
import * as turns from './src/host/turns.js'
import * as handoffs from './src/host/handoffs.js'
+import * as requests from './src/host/requests.js'
import * as delivery from './src/host/delivery.js'
import * as roster from './src/host/roster.js'
import * as folders from './src/host/folders.js'
@@ -44,7 +45,7 @@ export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'ses
// the functions other modules call; they call them through `rt` at run time, never during
// install. Listeners run and tools are listed in registration order, so this order holds:
// usage meters model requests after every listener that rewrites them.
-const MODULES = [diagnostics, store, models, providers, permissions, turns, handoffs, delivery, roster, folders, agents, prompt, timeContext, tools, chatIndex, groups, approvals, resume, memory, parts, images, secrets, connectors, capabilities, schedules, browser, usage, update, dshUpdate, thinking, feed, channel]
+const MODULES = [diagnostics, store, models, providers, permissions, turns, handoffs, requests, delivery, roster, folders, agents, prompt, timeContext, tools, chatIndex, groups, approvals, resume, memory, parts, images, secrets, connectors, capabilities, schedules, browser, usage, update, dshUpdate, thinking, feed, channel]
export function apply(ctx, config = {}) {
createRuntime(ctx, config)
diff --git a/ds-bot/src/host/requests.js b/ds-bot/src/host/requests.js
new file mode 100644
index 00000000..17e62afb
--- /dev/null
+++ b/ds-bot/src/host/requests.js
@@ -0,0 +1,125 @@
+// Request identities: a request a Bot names itself is sent once, however often it repeats it.
+//
+// message_bot merges what the recipient has not read yet, but a request that was read and
+// whose answer was lost could be sent again, and the work would be done twice. A caller
+// that names its request (`request_id`) gets that guarantee: the name belongs to the
+// caller and to the conversation the request was made from, what the request stands for
+// is remembered with a fingerprint of what was asked, and the receipt of the first call
+// is given back instead of a second delivery. The receipt is written before the message
+// goes out, so a restart cannot turn a lost answer into a second delivery either; when
+// the outcome of an admission is not known, the request is not sent again.
+//
+// Accepted identities stay with the team: expiring one would permit an old retry to
+// repeat side effects. Removing receipts needs a separate, explicit retention policy.
+import { createHash, randomUUID } from 'node:crypto'
+
+// A request name this long is a mistake, not an identity.
+export const NAME_MAX = 200
+
+export function install(rt) {
+ const { state } = rt
+ // This run's name: a receipt left pending by another run has an unknown outcome.
+ const run = randomUUID()
+ const receipts = () => (state.requests ??= {})
+ // Requests being admitted now, so that two at once admit one.
+ const inflight = new Map()
+
+ // What the request asked for, as a short hash: the same name with the same content is
+ // the same request, and the same name with other content is a mistake.
+ const print = payload => createHash('sha256').update(JSON.stringify(payload)).digest('hex')
+
+ // The name of a request in the caller's own space: its Bot, the conversation the request
+ // was made from, and the name the caller gave it. The Bot, not its Session: a Bot that
+ // moves to a fresh part of its conversation keeps its name.
+ const identity = ({ caller, context, name, payload }) => ({
+ key: `${caller}\u0000${context}\u0000${name}`,
+ print: print(payload),
+ })
+
+ // What a request that was admitted before means for the caller now: its receipt, a
+ // conflict, or an outcome that is not known. Undefined when it was never admitted.
+ const verdict = (request, record) => {
+ if (record.fingerprint !== request.print) return { status: 'conflict' }
+ if (record.outcome === 'delivered') {
+ // The receipt is gone, but the name stays taken: it is not used again by accident.
+ return record.receipt === undefined ? { status: 'expired' } : { status: 'replay', receipt: record.receipt }
+ }
+ if (record.outcome === 'uncertain') return { status: 'uncertain' }
+ // Admitted, not settled: the call is still going, or it was cut short.
+ return undefined
+ }
+
+ // What is known about a request that was admitted before. Undefined when the request
+ // was never admitted.
+ const known = async (request) => {
+ const record = rt.own(receipts(), request.key)
+ if (record === undefined) return undefined
+ const seen = verdict(request, record)
+ if (seen !== undefined) return seen
+ // Admitted, not settled: the call is still going in this run, or another run left it
+ // in the air, and then its outcome is not known.
+ if (record.run !== run) return { status: 'uncertain' }
+ const promise = inflight.get(request.key)
+ if (promise === undefined) return { status: 'uncertain' }
+ await promise.catch(() => {})
+ const settled = rt.own(receipts(), request.key)
+ if (settled === undefined) return undefined
+ return verdict(request, settled) ?? { status: 'uncertain' }
+ }
+
+ // Admits the request once and runs it. `work` sends the message and gives the receipt
+ // the caller gets. The receipt is written before the message goes out, so that a restart
+ // knows the request was admitted.
+ const admit = async (request, work) => {
+ // The receipt is looked for and written without an await in between, so that two
+ // calls at once cannot both admit the same request.
+ const record = rt.own(receipts(), request.key)
+ if (record !== undefined) {
+ const seen = verdict(request, record)
+ if (seen !== undefined) return seen
+ if (record.run !== run) return { status: 'uncertain' }
+ const promise = inflight.get(request.key)
+ if (promise === undefined) return { status: 'uncertain' }
+ await promise.catch(() => {})
+ // The attempt that was going on gave up before it sent anything (its receipt could
+ // not be saved), so the request is free to be admitted again.
+ if (rt.own(receipts(), request.key) === undefined) return admit(request, work)
+ return known(request)
+ }
+ // A receipt that cannot be saved cannot stop a second delivery later.
+ if (rt.readOnly() !== undefined) return { status: 'readonly' }
+ const fresh = { fingerprint: request.print, outcome: 'pending', at: Date.now(), run }
+ receipts()[request.key] = fresh
+ const promise = (async () => {
+ try {
+ await rt.save()
+ } catch (error) {
+ delete receipts()[request.key]
+ rt.warn('ds-bot: the receipt of the request was not saved: %s', error)
+ throw error
+ }
+ try {
+ const receipt = await work()
+ fresh.outcome = 'delivered'
+ fresh.receipt = receipt
+ fresh.at = Date.now()
+ await rt.save().catch(() => {})
+ return receipt
+ } catch (error) {
+ // The message may have gone out; it is not sent again.
+ fresh.outcome = 'uncertain'
+ fresh.at = Date.now()
+ await rt.save().catch(() => {})
+ throw error
+ }
+ })()
+ inflight.set(request.key, promise)
+ try {
+ return { status: 'sent', receipt: await promise }
+ } finally {
+ inflight.delete(request.key)
+ }
+ }
+
+ Object.assign(rt, { requestIdentity: identity, knownRequest: known, admitRequest: admit })
+}
diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.js
index 9299901d..cfea6367 100644
--- a/ds-bot/src/host/store.js
+++ b/ds-bot/src/host/store.js
@@ -19,7 +19,7 @@ export function install(rt) {
const { ctx, home, statePath } = rt
/** @type {{version:1, workspaceId?:string, mainBotIds:string[], bots:Record<string,any>, rooms:Record<string,any>, agents:Record<string,any>, capabilities:{items:Record<string,any>}, exchanges:any[], exchangeTurns:Record<string,number[]>, revision:number}} */
- const state = { version: 1, mainBotIds: [], bots: {}, rooms: {}, agents: {}, capabilities: { items: {} }, exchanges: [], exchangeTurns: {}, works: {}, questions: {}, views: {}, prefs: {}, switching: {}, revision: 0 }
+ const state = { version: 1, mainBotIds: [], bots: {}, rooms: {}, agents: {}, capabilities: { items: {} }, exchanges: [], exchangeTurns: {}, works: {}, requests: {}, questions: {}, views: {}, prefs: {}, switching: {}, revision: 0 }
let loaded = null
let writing = Promise.resolve()
const { warn } = rt
@@ -160,6 +160,7 @@ export function install(rt) {
migrated = true
}
if (state.works === null || typeof state.works !== 'object' || Array.isArray(state.works)) state.works = {}
+ if (state.requests === null || typeof state.requests !== 'object' || Array.isArray(state.requests)) state.requests = {}
if (state.views === null || typeof state.views !== 'object' || Array.isArray(state.views)) state.views = {}
// LEGACY: aside cards lived in this file only before the feature shipped;
// they are kept under btw/ per part now. A saved copy is dropped, not moved.
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 14a99047..074a798b 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -6,6 +6,7 @@ import { readAvatar } from './avatar.js'
import { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js'
import { within } from './folders.js'
import { absoluteLinks } from './links.js'
+import { NAME_MAX } from './requests.js'
import { unquote } from './text.js'
import { mentionSpans } from '../shared/mentions.js'
import { checkShownView } from '../shared/views.js'
@@ -120,11 +121,13 @@ export function install(rt) {
// Work for a group stays in it: from a group Session, message_bot calls a member there
// exactly as an "@Name" line would, and never reaches a Bot outside the group.
+ const groupRefusal = (room, sender, target) => {
+ if (room.members.includes(target.id)) return undefined
+ const add = rt.isMain(sender.id) || rt.isAdminOf(room, sender.id) ? ', or add it yourself with update_group first' : ''
+ return `Not sent: ${target.name} is not in "${room.name}", and work for this group stays in it. Ask the user to add ${target.name} to the group${add}.`
+ }
+
const callInGroup = async (exec, room, sender, target, message) => {
- if (!room.members.includes(target.id)) {
- const add = rt.isMain(sender.id) || rt.isAdminOf(room, sender.id) ? ', or add it yourself with update_group first' : ''
- refuse(`Not sent: ${target.name} is not in "${room.name}", and work for this group stays in it. Ask the user to add ${target.name} to the group${add}.`)
- }
const call = `@${target.name}`
await rt.roomStepText(exec.agent.id, rt.live.get(exec.agent.id)?.info, message.startsWith(call) ? message : `${call} ${message}`, false)
return `Called ${target.name} in "${room.name}" with your message, as writing "${call}" there does: it works on it in the group, and you answer its result there. Nothing went to its own chat.`
@@ -137,7 +140,7 @@ export function install(rt) {
ctx.tools.register(defineTool({
name: 'message_bot',
- description: 'Send a message to another Bot on the team. If that Bot is working, it reads your message at its next step and can change course, then answers once that work is done; if it is idle, it starts on it right away. Its reply arrives later as a new message to you; with reply_to "user" it answers the user in its own chat instead. In a group chat it reaches only members of that group, as writing "@Name" there does.',
+ description: 'Send a message to another Bot on the team. If that Bot is working, it reads your message at its next step and can change course, then answers once that work is done; if it is idle, it starts on it right away. Its reply arrives later as a new message to you; with reply_to "user" it answers the user in its own chat instead. In a group chat it reaches only members of that group, as writing "@Name" there does. With request_id you name the request yourself: a repeat of that name with the same message is not sent again, but gives the receipt of the first call back.',
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' },
@@ -151,6 +154,10 @@ export function install(rt) {
enum: ['now', 'queue'],
description: '"now" (default): a working Bot reads your message at its next step, between its current actions, and answers once its current work is done; use it for questions, information it needs, corrections and warnings. "queue": it reads your message only after its current work is done, as a separate task; use it only for a new task unrelated to what it is doing now. With reply_to "user" the message always queues.',
},
+ request_id: {
+ type: 'string',
+ description: `Your own name for this request, up to ${NAME_MAX} characters, so that a repeat of it is not sent twice. Send the same request_id with the same message when you repeat a call: the receipt of the first call comes back and nothing is sent again. A request_id names one request: with other content it is refused.`,
+ },
},
output,
async execute(args, exec) {
@@ -161,9 +168,41 @@ export function install(rt) {
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.'
if (String(args.message ?? '').trim() === '') return 'Write a message to send.'
+ const name = typeof args.request_id === 'string' ? args.request_id.trim() : ''
+ if (name.length > NAME_MAX) return `The request_id is ${name.length} characters long; a request name is at most ${NAME_MAX}.`
const text = absoluteLinks(String(args.message), rt.sessionFolder?.(exec.agent?.session ?? exec.agent))
const room = rt.roomOf(rt.groupOwners.get(exec.agent?.id)?.roomId)
- if (room !== undefined) return callInGroup(exec, room, sender, target, text.trim())
+ // The request the caller named: it is admitted once, and a repeat of it is not sent again.
+ const request = name === '' ? undefined : rt.requestIdentity({
+ caller: sender.id,
+ context: room === undefined ? 'chat' : `room:${room.id}`,
+ name,
+ payload: {
+ to: target.id,
+ message: String(args.message ?? '').replace(/\r\n?/g, '\n').trim(),
+ reply_to: args.reply_to === 'user' ? 'user' : 'me',
+ when: args.when === 'queue' ? 'queue' : 'now',
+ },
+ })
+ // What the caller gets for a request that was admitted before.
+ const answer = (outcome) => {
+ if (outcome.status === 'replay') return outcome.receipt
+ if (outcome.status === 'conflict') refuse(`Not sent: request_id "${name}" was already used for a different request. A request_id names one request; send this one under a new name.`)
+ if (outcome.status === 'uncertain') refuse(`Not sent again: the outcome of request_id "${name}" is not known (the delivery failed, or DS Bot restarted while it was in flight), so it was not sent again. Check whether ${target.name} got it before sending it under a new name.`)
+ if (outcome.status === 'expired') return `Nothing was sent again: request_id "${name}" was admitted before, but its receipt is no longer kept, so only the fact that it was sent is left. Send the work under a new request_id if it must be done again.`
+ if (outcome.status === 'readonly') refuse(`Not sent: this window cannot save the Bot team, so it cannot record the request_id "${name}". Send it from the window that owns the team, or leave the request_id out.`)
+ return outcome.receipt
+ }
+ if (request !== undefined) {
+ const seen = await rt.knownRequest(request)
+ if (seen !== undefined) return answer(seen)
+ }
+ if (room !== undefined) {
+ const refusal = groupRefusal(room, sender, target)
+ if (refusal !== undefined) refuse(refusal)
+ const send = () => callInGroup(exec, room, sender, target, text.trim())
+ return request === undefined ? await send() : answer(await rt.admitRequest(request, send))
+ }
const posted = calledInPosts.get(exec.agent?.id)
const postedIn = posted !== undefined && posted.turn === turnOf(exec) ? posted.calls.get(target.id) : undefined
if (postedIn !== undefined) refuse(`Not sent: you called ${target.name} in "${postedIn}" in this turn, and it works on that there. Send each task one way only; to add to it, post in that group.`)
@@ -175,50 +214,53 @@ export function install(rt) {
if (rt.upstreamOf(works).has(target.id)) {
return `Not sent: ${target.name} is waiting for the result of the work you are doing, and your answer reaches it by itself once everything you handed on is back. Finish the work and end your turn; to ask ${target.name} something, end your turn with the question.`
}
- const toUser = args.reply_to === 'user'
- const work = toUser ? undefined : works[0]
- const chat = rt.chatOf(target.id)
- const agent = await rt.resolveAgent(chat)
- const status = rt.statusOf(target.id)
- // A request it has not read yet, sent for the same work, takes this one in, so
- // messages to a Bot that cannot read them do not pile up.
- const earlier = unreadRequest(agent, sender.id, toUser)
- const joinable = earlier !== undefined && (toUser || rt.sameWork(earlier.message.source.exchangeId, work))
- const before = joinable ? bodyOf(earlier.message) : undefined
- let long = await rt.attachLong(before ? `${before.text}\n\n${text}` : text, `Message from ${sender.name}.txt`)
- if (long === undefined) return tooLong(text)
- const joins = before !== undefined && agent.inbox?.remove?.(earlier.message.id) === true
- if (before !== undefined && !joins) long = await rt.attachLong(text, `Message from ${sender.name}.txt`) ?? long
- const working = rt.live.get(chat)?.turn !== undefined
- const steer = (args.when !== 'queue' && !toUser) || (joins && earlier.steered)
- const exchangeId = joins ? earlier.message.source.exchangeId : randomUUID()
- if (joins) rt.forgetDelivery?.(exchangeId)
- else if (!toUser) rt.openWork(exchangeId, { from: sender.id, to: target.id, parent: work })
- try {
- await rt.deliver({ fromId: sender.id, toId: target.id, text: long.text, files: [...long.files, ...(joins ? before.files : [])], length: long.length, role: 'request', steer, exchangeId, ...(joins ? { merged: true } : {}), ...(toUser ? { audience: 'user' } : {}) })
- } catch (error) {
- if (!joins) rt.dropWork(exchangeId)
- throw error
+ const send = async () => {
+ const toUser = args.reply_to === 'user'
+ const work = toUser ? undefined : works[0]
+ const chat = rt.chatOf(target.id)
+ const agent = await rt.resolveAgent(chat)
+ const status = rt.statusOf(target.id)
+ // A request it has not read yet, sent for the same work, takes this one in, so
+ // messages to a Bot that cannot read them do not pile up.
+ const earlier = unreadRequest(agent, sender.id, toUser)
+ const joinable = earlier !== undefined && (toUser || rt.sameWork(earlier.message.source.exchangeId, work))
+ const before = joinable ? bodyOf(earlier.message) : undefined
+ let long = await rt.attachLong(before ? `${before.text}\n\n${text}` : text, `Message from ${sender.name}.txt`)
+ if (long === undefined) return tooLong(text)
+ const joins = before !== undefined && agent.inbox?.remove?.(earlier.message.id) === true
+ if (before !== undefined && !joins) long = await rt.attachLong(text, `Message from ${sender.name}.txt`) ?? long
+ const working = rt.live.get(chat)?.turn !== undefined
+ const steer = (args.when !== 'queue' && !toUser) || (joins && earlier.steered)
+ const exchangeId = joins ? earlier.message.source.exchangeId : randomUUID()
+ if (joins) rt.forgetDelivery?.(exchangeId)
+ else if (!toUser) rt.openWork(exchangeId, { from: sender.id, to: target.id, parent: work })
+ try {
+ await rt.deliver({ fromId: sender.id, toId: target.id, text: long.text, files: [...long.files, ...(joins ? before.files : [])], length: long.length, role: 'request', steer, exchangeId, ...(joins ? { merged: true } : {}), ...(toUser ? { audience: 'user' } : {}) })
+ } catch (error) {
+ if (!joins) rt.dropWork(exchangeId)
+ throw error
+ }
+ const sent = toUser
+ ? `Delivered to ${target.name}. It will answer the user in its own chat; nothing comes back to you, so point the user to ${target.name}'s chat instead of relaying.`
+ : working && steer
+ ? `Delivered to ${target.name} while it is working: it reads your message at its next step and answers once that work is done. Its reply will arrive later as a new message; do not wait for it.`
+ : working
+ ? `Queued for ${target.name}: it reads your message after its current work. Its reply will arrive later as a new message; do not wait for it.`
+ : `Delivered to ${target.name}. Its reply will arrive later as a new message; do not wait for it.`
+ const asker = rt.ownsWork(sender.id, work) ? rt.botOf(state.works[work].from)?.name : undefined
+ const notes = [
+ joins ? `${target.name} had not read your earlier message yet, so this one was added to it, and it answers both at once.` : '',
+ status === 'idle' ? '' : `${target.name} now: ${status}.`,
+ asker ? `When you have handed on everything, end your turn: each reply brings you back to this work, and your answer goes to ${asker} once all of it is back.` : '',
+ ].filter(Boolean)
+ const out = [sent, ...notes].join(' ')
+ // Messages reach a Bot's own chat only; work in a group goes on without them.
+ const groups = activeSessions(target.id).running.filter(sessionId => sessionId !== chat)
+ if (groups.length === 0) return out
+ const stop = rt.isMain(sender.id) ? ' If it must not go on there, use stop_bot.' : ''
+ return `${out} Your message does not reach its work in ${groups.map(whereOf).join(' and ')}.${stop}`
}
- const sent = toUser
- ? `Delivered to ${target.name}. It will answer the user in its own chat; nothing comes back to you, so point the user to ${target.name}'s chat instead of relaying.`
- : working && steer
- ? `Delivered to ${target.name} while it is working: it reads your message at its next step and answers once that work is done. Its reply will arrive later as a new message; do not wait for it.`
- : working
- ? `Queued for ${target.name}: it reads your message after its current work. Its reply will arrive later as a new message; do not wait for it.`
- : `Delivered to ${target.name}. Its reply will arrive later as a new message; do not wait for it.`
- const asker = rt.ownsWork(sender.id, work) ? rt.botOf(state.works[work].from)?.name : undefined
- const notes = [
- joins ? `${target.name} had not read your earlier message yet, so this one was added to it, and it answers both at once.` : '',
- status === 'idle' ? '' : `${target.name} now: ${status}.`,
- asker ? `When you have handed on everything, end your turn: each reply brings you back to this work, and your answer goes to ${asker} once all of it is back.` : '',
- ].filter(Boolean)
- const out = [sent, ...notes].join(' ')
- // Messages reach a Bot's own chat only; work in a group goes on without them.
- const groups = activeSessions(target.id).running.filter(sessionId => sessionId !== chat)
- if (groups.length === 0) return out
- const stop = rt.isMain(sender.id) ? ' If it must not go on there, use stop_bot.' : ''
- return `${out} Your message does not reach its work in ${groups.map(whereOf).join(' and ')}.${stop}`
+ return request === undefined ? await send() : answer(await rt.admitRequest(request, send))
},
}))
diff --git a/ds-bot/test/request-id.test.js b/ds-bot/test/request-id.test.js
new file mode 100644
index 00000000..d778e965
--- /dev/null
+++ b/ds-bot/test/request-id.test.js
@@ -0,0 +1,332 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, readFileSync, 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 { createRuntime } from '../index.js'
+import { fakeContext } from './fake-ctx.js'
+import { install as installRequests } from '../src/host/requests.js'
+
+test('old identities survive age and receipt volume without permitting another delivery', async () => {
+ const rt = { state: {}, own: (object, key) => Object.hasOwn(object, key) ? object[key] : undefined, readOnly: () => undefined, save: async () => {}, warn() {} }
+ installRequests(rt)
+ const original = rt.requestIdentity({ caller: 'a', context: 'chat', name: 'original', payload: { message: 'do it' } })
+ await rt.admitRequest(original, async () => 'first receipt')
+ rt.state.requests[original.key].at = 0
+ for (let i = 0; i < 2001; i += 1) rt.state.requests[`other-${i}`] = { at: i, outcome: 'delivered', fingerprint: 'x', receipt: 'kept' }
+ const fresh = rt.requestIdentity({ caller: 'a', context: 'chat', name: 'fresh', payload: { message: 'next' } })
+ await rt.admitRequest(fresh, async () => 'next receipt')
+ const result = await rt.admitRequest(original, async () => { throw new Error('duplicate delivery') })
+ assert.deepEqual(result, { status: 'replay', receipt: 'first receipt' })
+})
+
+// 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: {},
+ works: {},
+ questions: {},
+ prefs: {},
+ revision: 0,
+ }
+}
+
+// The plugin in a home of its own, with a stand-in DSH around it. The seed is written the
+// first time; a later boot keeps the state the first run saved.
+async function boot(home, seed) {
+ if (seed !== undefined) 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(id) {
+ for (const list of [this.nextStep, this.nextTurn]) {
+ const at = list.findIndex(message => message.id === id)
+ if (at !== -1) return list.splice(at, 1).length === 1
+ }
+ return false
+ },
+ },
+ })
+ }
+ 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 () => {} },
+ })
+ const rt = createRuntime(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 stop = async () => { await ctx.dispose() }
+ // Loading once fills the Session-owner indexes turns.js filters events by.
+ await tool('list_bots', {}, 'a')
+ return { ctx, rt, agents, agentOf, emit, tool, stop }
+}
+
+const tempHome = () => mkdtempSync(join(tmpdir(), 'ds-bot-request-'))
+const cleanup = home => rmSync(home, { recursive: true, force: true, maxRetries: 5 })
+
+test('a request with an id is delivered once, and a repeat gives the first receipt back', async (t) => {
+ const home = tempHome()
+ const { agents, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ const first = await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ assert.equal(first, 'Delivered to Writer. Its reply will arrive later as a new message; do not wait for it.')
+ assert.equal(agents.get('b').calls.length, 1)
+
+ const again = await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ assert.equal(again, first)
+ assert.equal(agents.get('b').calls.length, 1)
+})
+
+test('the same request id with other content is refused, and nothing goes out', async (t) => {
+ const seed = team()
+ seed.bots.c = { id: 'c', name: 'Tester', role: 'Test', sessionId: 'c', createdAt: 3 }
+ const home = tempHome()
+ const { agents, tool, stop } = await boot(home, seed)
+ t.after(async () => { await stop(); cleanup(home) })
+
+ await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ await assert.rejects(tool('message_bot', { to: 'Writer', message: 'do another thing', request_id: 'r-1' }, 'a'), /request_id "r-1" was already used for a different request/)
+ assert.equal(agents.get('b').calls.length, 1)
+ // Another target under the same name is another request, and is refused as well.
+ await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-2' }, 'c')
+ await assert.rejects(tool('message_bot', { to: 'Chief', message: 'do the thing', request_id: 'r-2' }, 'c'), /request_id "r-2" was already used for a different request/)
+ assert.equal(agents.get('a')?.calls.length ?? 0, 0)
+})
+
+test('two callers with the same request id do not collide', async (t) => {
+ const seed = team()
+ seed.bots.c = { id: 'c', name: 'Tester', role: 'Test', sessionId: 'c', createdAt: 3 }
+ const home = tempHome()
+ const { agents, tool, stop } = await boot(home, seed)
+ t.after(async () => { await stop(); cleanup(home) })
+
+ await tool('message_bot', { to: 'Writer', message: 'from Chief', request_id: 'r-1' }, 'a')
+ await tool('message_bot', { to: 'Writer', message: 'from Tester', request_id: 'r-1' }, 'c')
+ assert.equal(agents.get('b').calls.length, 2)
+})
+
+test('two calls at once with the same request id admit it once', async (t) => {
+ const home = tempHome()
+ const { agents, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ const [first, second] = await Promise.all([
+ tool('message_bot', { to: 'Writer', message: 'same request', request_id: 'r-1' }, 'a'),
+ tool('message_bot', { to: 'Writer', message: 'same request', request_id: 'r-1' }, 'a'),
+ ])
+ assert.equal(first, second)
+ assert.equal(agents.get('b').calls.length, 1)
+})
+
+test('a repeat after a restart gives the receipt back and sends nothing', async (t) => {
+ const home = tempHome()
+ const first = await boot(home, team())
+ const receipt = await first.tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ await first.stop()
+
+ const again = await boot(home)
+ t.after(async () => { await again.stop(); cleanup(home) })
+ const out = await again.tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ assert.equal(out, receipt)
+ assert.equal(again.agentOf('b').calls.length, 0)
+})
+
+test('a repeat after the recipient read the message does not send it again', async (t) => {
+ const home = tempHome()
+ const { agents, emit, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ const first = await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ const delivered = agents.get('b').calls[0][1]
+ emit('b', 'user/message', { content: delivered.content, source: delivered.source })
+ const again = await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ assert.equal(again, first)
+ assert.equal(agents.get('b').calls.length, 1)
+})
+
+test('a request whose delivery failed is not sent again', async (t) => {
+ const home = tempHome()
+ const { agentOf, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ const writer = agentOf('b')
+ const steer = writer.steer
+ writer.steer = () => { throw new Error('dsh is down') }
+ await assert.rejects(tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a'), /dsh is down/)
+ writer.steer = steer
+ // The outcome of that admission is not known, so it is not sent again.
+ await assert.rejects(tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a'), /outcome of request_id "r-1" is not known/)
+ assert.equal(writer.calls.length, 0)
+})
+
+test('a request with an id takes in the message before it, and a repeat merges nothing', async (t) => {
+ const home = tempHome()
+ const { agentOf, emit, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ const writer = agentOf('b')
+ writer.steer = (message) => { writer.calls.push(['steer', message]); writer.inbox.nextStep.push(message) }
+ emit('b', 'turn/start', { turn: 1 })
+
+ const first = await tool('message_bot', { to: 'Writer', message: 'task 1', request_id: 'r-1' }, 'a')
+ const second = await tool('message_bot', { to: 'Writer', message: 'task 2', request_id: 'r-2' }, 'a')
+ assert.match(second, /had not read your earlier message yet/)
+ assert.equal(writer.inbox.nextStep.length, 1)
+
+ const again = await tool('message_bot', { to: 'Writer', message: 'task 1', request_id: 'r-1' }, 'a')
+ assert.equal(again, first)
+ assert.equal(writer.inbox.nextStep.length, 1)
+ assert.equal(writer.inbox.nextStep[0].source.exchangeId, writer.calls[0][1].source.exchangeId)
+})
+
+test('a request with an id that queues, or that answers the user, goes out once', async (t) => {
+ const home = tempHome()
+ const { agents, emit, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ // Writer is working, so a request that waits for its current work is queued.
+ emit('b', 'turn/start', { turn: 1 })
+ const queued = await tool('message_bot', { to: 'Writer', message: 'later', when: 'queue', request_id: 'r-1' }, 'a')
+ assert.match(queued, /^Queued for Writer/)
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['followup'])
+ assert.equal(await tool('message_bot', { to: 'Writer', message: 'later', when: 'queue', request_id: 'r-1' }, 'a'), queued)
+
+ const toUser = await tool('message_bot', { to: 'Writer', message: 'tell them', reply_to: 'user', request_id: 'r-2' }, 'a')
+ assert.match(toUser, /It will answer the user in its own chat/)
+ assert.equal(await tool('message_bot', { to: 'Writer', message: 'tell them', reply_to: 'user', request_id: 'r-2' }, 'a'), toUser)
+ assert.equal(agents.get('b').calls.length, 2)
+})
+
+test('a request with an id in a group calls the member once', async (t) => {
+ const seed = team({ group: true })
+ seed.rooms.r1.sessions.a = 'ga'
+ const home = tempHome()
+ const { rt, tool, stop } = await boot(home, seed)
+ t.after(async () => { await stop(); cleanup(home) })
+
+ let posts = 0
+ rt.roomStepText = async () => { posts += 1 }
+ const first = await tool('message_bot', { to: 'Writer', message: 'do it', request_id: 'r-1' }, 'ga')
+ assert.match(first, /^Called Writer in "Ops"/)
+ assert.equal(posts, 1)
+ assert.equal(await tool('message_bot', { to: 'Writer', message: 'do it', request_id: 'r-1' }, 'ga'), first)
+ assert.equal(posts, 1)
+})
+
+test('a request that was in the air when DS Bot stopped is not sent again', async (t) => {
+ const home = tempHome()
+ const first = await boot(home, team())
+ // The delivery hangs, as it would when DS Bot stops in the middle of it.
+ first.ctx.sessions.flush = async () => new Promise(() => {})
+ const inFlight = first.tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ inFlight.catch(() => {})
+ for (let count = 0; count < 200 && Object.keys(first.rt.state.requests).length === 0; count += 1) await delay(10)
+ assert.equal(Object.keys(first.rt.state.requests).length, 1)
+ assert.equal(Object.values(first.rt.state.requests)[0].outcome, 'pending')
+ await first.stop()
+
+ const again = await boot(home)
+ t.after(async () => { await again.stop(); cleanup(home) })
+ // The outcome of that admission is not known, so it is not sent again.
+ await assert.rejects(again.tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a'), /outcome of request_id "r-1" is not known/)
+ assert.equal(again.agentOf('b').calls.length, 0)
+})
+
+test('a name whose receipt is no longer kept is not used again', async (t) => {
+ const home = tempHome()
+ const { rt, agents, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ // The receipt falls out of what is kept; the name itself stays taken.
+ for (const record of Object.values(rt.state.requests)) record.receipt = undefined
+ const out = await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ assert.match(out, /Nothing was sent again: request_id "r-1" was admitted before/)
+ assert.equal(agents.get('b').calls.length, 1)
+})
+
+test('a request whose receipt cannot be saved is not sent', async (t) => {
+ const home = tempHome()
+ const { rt, agents, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ const save = rt.save
+ rt.save = async () => { throw new Error('the disk is full') }
+ await assert.rejects(tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a'), /the disk is full/)
+ assert.equal(agents.get('b')?.calls.length ?? 0, 0)
+ // Nothing went out, so the name is free again.
+ rt.save = save
+ const out = await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ assert.match(out, /^Delivered to Writer/)
+ assert.equal(agents.get('b').calls.length, 1)
+})
+
+test('calls without a request id are sent as they were', async (t) => {
+ const home = tempHome()
+ const { agents, tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ await tool('message_bot', { to: 'Writer', message: 'one' }, 'a')
+ await tool('message_bot', { to: 'Writer', message: 'two' }, 'a')
+ assert.equal(agents.get('b').calls.length, 2)
+})
+
+test('the receipt of a request is kept in the team file', async (t) => {
+ const home = tempHome()
+ const { tool, stop } = await boot(home, team())
+ t.after(async () => { await stop(); cleanup(home) })
+
+ await tool('message_bot', { to: 'Writer', message: 'do the thing', request_id: 'r-1' }, 'a')
+ const saved = JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))
+ const receipts = Object.values(saved.requests)
+ assert.equal(receipts.length, 1)
+ assert.equal(receipts[0].outcome, 'delivered')
+ assert.match(receipts[0].receipt, /^Delivered to Writer/)
+})