A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Hand off work between Bots as a tree, by state instead of counts (#262)
Fei2411943356f4f124
diff --git a/ds-bot/index.js b/ds-bot/index.jsindex 9cdb56ac..7ba683cf 100644--- a/ds-bot/index.js+++ b/ds-bot/index.js@@ -7,6 +7,7 @@ import * as store from './src/host/store.js'import * as models from './src/host/models.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 delivery from './src/host/delivery.js'import * as roster from './src/host/roster.js'import * as folders from './src/host/folders.js'@@ -40,7 +41,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, permissions, turns, delivery, roster, folders, agents, prompt, timeContext, tools, chatIndex, groups, approvals, resume, memory, parts, images, secrets, connectors, capabilities, schedules, browser, usage, update, dshUpdate, channel]+const MODULES = [diagnostics, store, models, 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, channel]export function apply(ctx, config = {}) {createRuntime(ctx, config)diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex 7ef06846..2e738c13 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -40,7 +40,7 @@ export function install(rt) {...bot, sessionId: rt.chatOf(bot.id), parts: (segments ?? []).map(segment => segment.sessionId), ...(kickoff ? { waiting: true } : {}),})),// `parts`: the members' hidden group Sessions and their earlier segments, for usage.- rooms: Object.values(state.rooms).map(({ log, seen, botRounds, lateRounds, sessions, segments, ...room }) => {+ rooms: Object.values(state.rooms).map(({ log, seen, lateRounds, sessions, segments, ...room }) => {const parts = [...Object.values(sessions ?? {}), ...Object.values(segments ?? {}).flat().map(segment => segment.sessionId)]const last = (log ?? []).filter(line => line.kind === undefined).at(-1)return { ...room, parts, ...(last ? { preview: last.who === 'User' ? last.text : `${last.who}:${last.text}` } : {}) }diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.jsindex 25b64108..7b5e2f92 100644--- a/ds-bot/src/host/constants.js+++ b/ds-bot/src/host/constants.js@@ -20,13 +20,6 @@ export const OCR_RETRY_MS = 120_000export const OCR_CACHE_MAX = 500export const MAX_AVATAR_IMAGE = 160_000export const ROUTE = '/api/bot'-export const MAX_HOPS = 6-// Messages the whole team may send each other (message_bot, post_to_group) while-// nobody outside it speaks: the user, a question card's answer or a scheduled task.-export const MAX_UNATTENDED_MESSAGES = 40-// Bot requests a Bot's own chat may hold unread; past this the Bot is most likely-// stuck, and more messages only pile up behind it.-export const MAX_UNREAD_REQUESTS = 10export const MAX_EXCHANGES = 600// state.json is written whole on every save, so a long message between Bots or a long// group line keeps only its start there. The rest stays where it already is (a message@@ -76,8 +69,6 @@ export const TEAM_TOOLS = ['list_capabilities', 'save_capability', 'delete_capability','attach_capability', 'detach_capability',]-// Rounds Bots may start in one group by posting, before the user speaks there again.-export const ROOM_BOT_ROUNDS = 3// Answers a group gives to what members post after the round moved on (their finished// work, mostly), before the user speaks there again.export const ROOM_LATE_ROUNDS = 10diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.jsindex acae56d0..a6ca72a4 100644--- a/ds-bot/src/host/delivery.js+++ b/ds-bot/src/host/delivery.js@@ -14,15 +14,19 @@ export function install(rt) {return resolved.agent}- const headerFor = (role, fromName, roomName, audience, note = 'new message', deferred = false, { resumed = false, retried = false } = {}) => {+ const headerFor = (role, fromName, roomName, audience, note = 'new message', deferred = false, { resumed = false, retried = false, asker } = {}) => {+ // What came back for work another Bot gave this one says where its answer goes.+ const goesOn = asker === undefined ? '' : ` · for the work ${asker} asked you for; your answer goes to ${asker} once everything you handed on is back`+ if (deferred && role === 'reply') return `[Reply from ${fromName} · you read it during your last task; go on with the work it is for now${goesOn}]`+ if (deferred && role === 'report') return `[Group chat "${roomName}" · replies to your post · you read them during your last task; go on with the work they are for now${goesOn}]`if (deferred) return `[Message from ${fromName} · you read it during your last task; answer it now]`if (retried && role !== 'room') return '[Your last reply wrote a tool call as text, so nothing ran]'if (resumed && role === 'resume') return '[DeepSeek Harness restarted while you were working]'if (resumed && role !== 'room') return `[Message from ${fromName} · DeepSeek Harness restarted while you were working on it]`- if (role === 'reply') return `[Reply from ${fromName}]`+ if (role === 'reply') return `[Reply from ${fromName}${goesOn}]`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 === 'report') return `[Group chat "${roomName}" · replies to your post${goesOn}]`if (role === 'kickoff') return '[Bot team setup]'if (role === 'secret') return '[Secret card]'if (audience === 'user') return `[Message from ${fromName} · the user sees your reply here]`@@ -41,13 +45,16 @@ export function install(rt) {// group turn (groups.js). `fromRoomId`: the group whose Session the sender wrote// from; the reply goes back to that Session (turns.js). `files` go along as file// blocks, which DSH turns into a read-only path the recipient's tools can read.- // `length`: the whole message's length when it went as a file (attachLong).- async function deliver({ fromId, toId, sessionId, text, role, hop = 0, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, askedBy, fromRoomId, files = [], length }) {+ // `length`: the whole message's length when it went as a file (attachLong). `work`:+ // the work (handoffs.js) a result that came back goes on with. `merged`: a request+ // that takes in an earlier one its recipient had not read, under that one's exchange.+ async function deliver({ fromId, toId, sessionId, text, role, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, merged = false, askedBy, fromRoomId, files = [], length, work }) {const from = rt.botOf(fromId)const to = rt.botOf(toId)if (to === undefined) throw new Error(`Unknown Bot ${toId}`)const fromName = from?.name ?? 'You'const room = rt.roomOf(roomId)+ const asker = work === undefined ? undefined : rt.botOf(state.works?.[work]?.from)?.name// Session events reject `undefined` members, so optional fields are omitted instead.const source = {kind: SOURCE_KIND,@@ -55,7 +62,7 @@ export function install(rt) {role,exchangeId,senderName: fromName,- hop,+ ...(work ? { work } : {}),...(fromId ? { senderSessionId: fromId } : {}),...(replyTo ? { replyTo } : {}),...(roomId ? { roomId } : {}),@@ -72,7 +79,10 @@ export function install(rt) {// it back there.const kept = headOf(text, TEXT_KEPT)const whole = length !== undefined ? { length, files } : kept.length < text.length ? { length: text.length, sessionId: targetSessionId } : {}- state.exchanges.push({ id: exchangeId, from: fromId, to: toId, text: kept, ...whole, role, time: Date.now(), ...(replyTo ? { replyTo } : {}), ...(audience === 'user' ? { audience } : {}) })+ const entry = { id: exchangeId, from: fromId, to: toId, text: kept, ...whole, role, time: Date.now(), ...(replyTo ? { replyTo } : {}), ...(audience === 'user' ? { audience } : {}) }+ const earlier = merged ? state.exchanges.findIndex(other => other.id === exchangeId) : -1+ if (earlier === -1) state.exchanges.push(entry)+ else state.exchanges[earlier] = entryvoid rt.save().catch(() => {})}await rt.ensureCapabilities(targetSessionId)@@ -81,7 +91,7 @@ export function install(rt) {// 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, deferred, { resumed, retried })}\n${text}` },+ { type: 'text', text: `${headerFor(role, fromName, room?.name, audience, note, deferred, { resumed, retried, asker })}\n${text}` },...files.map(attachment => ({ type: 'file', attachment })),],source,diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 7d07933f..3817006d 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -293,7 +293,7 @@ export function install(rt) {signal.addEventListener('abort', () => finish(null), { once: true })})try {- await rt.deliver({ fromId: undefined, toId: member.id, sessionId, role: 'room', roomId: room.id, exchangeId, note, text, files, hop: round.hop, ...(by ? { askedBy: by } : {}) })+ await rt.deliver({ fromId: undefined, toId: member.id, sessionId, role: 'room', roomId: room.id, exchangeId, note, text, files, ...(by ? { askedBy: by } : {}) })// Still held by an earlier request: this turn cannot start until the user answers.if (rt.waitsForApproval?.(sessionId)) rt.roomWaiters.get(exchangeId)?.approval()// Still at earlier work: the call waits in its inbox and is answered after that.@@ -377,11 +377,8 @@ export function install(rt) {const note = all || found.length > 0 ? 'the user mentioned you' : 'new message from the user'callMembers(round, turns, index - 1, openingSpeakers(room, { text: line.text }), note, ROOM_ADMIN_TURNS_EACH)}- // The user spoke in this room, so Bots may start their own rounds again. These- // messages never reach the Session as events, so the team's count resets here too.- room.botRounds = 0+ // The user spoke in this room, so late results may call members again.room.lateRounds = 0- rt.userSpoke()void rt.save().catch(() => {})return round.slots.length - before}@@ -490,10 +487,7 @@ export function install(rt) {...(post.files === undefined ? {} : { files: post.files }),})}- if (posts.some(post => !post.botId && !post.kickoff)) {- room.botRounds = 0- room.lateRounds = 0- }+ if (posts.some(post => !post.botId && !post.kickoff)) room.lateRounds = 0await rt.save()// An event post never picks the speakers over a message queued with it.const opener = posts.findLast(post => !event(post)) ?? posts.at(-1)@@ -504,8 +498,6 @@ export function install(rt) {roomId: room.id,members: room.members,startSeq,- // Member turns answer the opener, so they keep its hop; a round the user opens starts at 0.- hop: opener.hop ?? 0,...(opener.kickoff ? { kickoff: true } : {}),...(references.length > 0 ? { references, shown: [] } : {}),slots: openingSpeakers(room, opener).map(member => ({@@ -667,7 +659,7 @@ export function install(rt) {const agent = await rt.resolveAgent(room.id)agent.followup(createUserMessage({content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }, ...files.map(attachment => ({ type: 'file', attachment }))],- source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, hop: 0, ...extra },+ source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, ...extra },}))await ctx.sessions.flush(agent.session)}@@ -690,7 +682,7 @@ export function install(rt) {const quiet = (room.lateRounds ?? 0) >= ROOM_LATE_ROUNDSif (!quiet) room.lateRounds = (room.lateRounds ?? 0) + 1await rt.save()- await postToRoom(room, member, done ? '' : text, { late: true, hop: info.hop ?? 0, ...(done ? { done: true } : {}), ...(info.askedBy ? { askedBy: info.askedBy } : {}), ...(quiet ? { quiet: true } : {}) })+ await postToRoom(room, member, done ? '' : text, { late: true, ...(done ? { done: true } : {}), ...(info.askedBy ? { askedBy: info.askedBy } : {}), ...(quiet ? { quiet: true } : {}) }).catch(error => rt.warn('ds-bot: late group reply from %s failed: %s', member.name, error))}rt.lateRoomReply = lateRoomReply@@ -719,7 +711,7 @@ export function install(rt) {const quiet = !calls || (room.lateRounds ?? 0) >= ROOM_LATE_ROUNDSif (!quiet) room.lateRounds = (room.lateRounds ?? 0) + 1await rt.save()- await postToRoom(room, member, text, { progress: true, hop: info?.hop ?? 0, ...(quiet ? { quiet: true } : {}) })+ await postToRoom(room, member, text, { progress: true, ...(quiet ? { quiet: true } : {}) })}// Lines a member writes close together reach the group as one message, so a burst of@@ -794,7 +786,7 @@ export function install(rt) {const agent = await rt.resolveAgent(room.id)agent.followup(createUserMessage({content: [{ type: 'text', text: '[Group chat created]' }],- source: { kind: SOURCE_KIND, form: 'relay', role: 'kickoff', exchangeId: randomUUID(), senderName: 'You', hop: 0, roomId: room.id },+ source: { kind: SOURCE_KIND, form: 'relay', role: 'kickoff', exchangeId: randomUUID(), senderName: 'You', roomId: room.id },}))await ctx.sessions.flush(agent.session)}@@ -811,7 +803,9 @@ export function install(rt) {round.passed.length > 0 ? `Stayed silent: ${round.passed.join(', ')}.` : '',round.failed.length > 0 ? `Could not answer because their model call failed: ${round.replies.filter(reply => reply.kind === 'failed').map(reply => `${reply.name} (${failureLine({ code: reply.code, status: reply.status, message: reply.text })})`).join(', ')}.` : '',].filter(Boolean).join('\n\n')- await rt.deliver({ toId: post.botId, role: 'report', roomId: room.id, text, hop: post.hop ?? 0 })+ // Replies the poster waited for go on with the work it posted for.+ const work = post.sub === undefined ? undefined : rt.closeWork(post.sub, `Group "${room.name}"`, text)+ await rt.deliver({ toId: post.botId, role: 'report', roomId: room.id, text, ...(work ? { work, replyTo: post.sub } : {}) }).catch(error => rt.warn('ds-bot: group report to %s failed: %s', post.name, error))}diff --git a/ds-bot/src/host/handoffs.js b/ds-bot/src/host/handoffs.jsnew file mode 100644index 00000000..73585fb8--- /dev/null+++ b/ds-bot/src/host/handoffs.js@@ -0,0 +1,172 @@+// Hand-offs: the work Bots give each other, and what each Bot is doing right now.+//+// A Bot's request to another Bot is a piece of work. What the recipient hands on while+// it works on it hangs below it, and the recipient's answer goes up only once all of+// that came back, together with what came back. Results find their way up by+// themselves, so no Bot needs to message one that waits for it, and that is the one+// hand-off refused. The open works are kept in state.json so a restart waits on.+import { TEXT_KEPT } from './constants.js'+import { headOf } from './text.js'++const minutes = since => {+ const count = Math.floor((Date.now() - since) / 60_000)+ return count < 1 ? 'for less than a minute' : `for ${count} min`+}++export function install(rt) {+ const { state } = rt+ const works = () => (state.works ??= {})+ // What came back, whole; state.json keeps the start of each.+ const whole = new Map()+ const save = () => void rt.save().catch(() => {})+ const nameOf = id => rt.botOf(id)?.name++ // The work a turn does: the request it answers, or the work a result that came back+ // (or a turn picked up again) goes on with.+ const workOf = info => (info === undefined ? undefined+ : info.role === 'request' && info.audience !== 'user' ? info.exchangeId : info.work)++ // `parent`: the work the sender was doing when it sent this one.+ function openWork(id, { from, to, parent, fromRoom, room }) {+ const above = parent === undefined ? undefined : works()[parent]+ works()[id] = { ...(from ? { from } : {}), ...(to ? { to } : {}), ...(room ? { room } : {}), ...(above ? { parent } : {}), ...(fromRoom ? { fromRoom } : {}), open: [], results: [], at: Date.now() }+ if (above !== undefined) above.open.push(id)+ save()+ }++ // The answer to work `id` is on its way, with `result` from `name`. Returns the work+ // it goes on with. That work keeps waiting until a turn reads the answer (`taken`).+ function closeWork(id, name, text) {+ const work = works()[id]+ if (work === undefined) return undefined+ delete works()[id]+ // What it still waits for comes back to it alone.+ for (const child of Object.values(works())) if (child.parent === id) delete child.parent+ const above = works()[work.parent]+ if (above !== undefined) {+ above.results.push({ id, name, text: headOf(text, TEXT_KEPT), ...(text.length > TEXT_KEPT ? { length: text.length } : {}) })+ whole.set(id, text)+ }+ for (const result of work.results) whole.delete(result.id)+ save()+ return above === undefined ? undefined : work.parent+ }+ const dropWork = (id) => {+ if (works()[id] === undefined) return+ const { parent } = works()[id]+ delete works()[id]+ const above = works()[parent]+ if (above !== undefined) above.open = above.open.filter(other => other !== id)+ save()+ }++ function taken(workId, id) {+ const work = works()[workId]+ if (work === undefined || !work.open.includes(id)) return+ work.open = work.open.filter(other => other !== id)+ save()+ }++ const owns = (botId, workId) => workId !== undefined && works()[workId]?.to === botId+ const waits = workId => (works()[workId]?.open.length ?? 0) > 0+ function hold(workId, text) {+ const work = works()[workId]+ if (work === undefined || text === '') return+ work.held = headOf(text, TEXT_KEPT)+ save()+ }+ // Who asked for the work, as the turn that answers a request sees its trigger.+ const askedBy = workId => {+ const work = works()[workId]+ return work === undefined ? undefined : { kind: 'bot', role: 'request', exchangeId: workId, senderSessionId: work.from, ...(work.fromRoom ? { senderRoomId: work.fromRoom } : {}) }+ }+ // The answer that goes up: what the Bot said last for this work, then what came back.+ function answerText(workId, reply, botName) {+ const work = works()[workId]+ const said = reply !== '' ? reply : work?.held ?? ''+ const results = (work?.results ?? []).map(result => {+ const text = whole.get(result.id) ?? result.text+ const cut = whole.has(result.id) || result.length === undefined ? '' : `\n[cut at ${TEXT_KEPT} characters by a restart]`+ return `${result.name}:\n${text}${cut}`+ })+ if (results.length === 0) return said || `${botName} finished without a reply.`+ return [said || `${botName} finished and wrote nothing more.`, `[Handed back to ${botName} for this work]`, ...results].join('\n\n')+ }++ // The Bots waiting for the result of these works: whoever asked for each, and on up.+ function upstreamOf(workIds) {+ const bots = new Set()+ for (const workId of workIds) {+ const seen = new Set()+ for (let id = workId; id !== undefined && !seen.has(id) && works()[id] !== undefined; id = works()[id].parent) {+ seen.add(id)+ if (works()[id].from) bots.add(works()[id].from)+ }+ }+ return bots+ }++ // Two requests from one sender belong to the same work when they were sent for it.+ const sameWork = (id, parent) => (works()[id]?.parent ?? undefined) === (works()[parent] === undefined ? undefined : parent)++ // A deleted Bot answers no more work and waits for none.+ function forgetBot(botId) {+ const waiting = Object.entries(works()).filter(([, work]) => work.to === botId).map(([id]) => askedBy(id))+ for (const [id, work] of Object.entries(works())) if (work.from === botId && work.to !== botId) dropWork(id)+ return waiting+ }++ // What a Bot is doing, in one line for the Bots that work with it.+ function statusOf(botId) {+ const chat = rt.chatOf(botId)+ const sessions = [...new Set([chat, ...(rt.groupSessionsOf?.(botId) ?? [])])]+ const place = sessionId => {+ const room = rt.roomOf(rt.groupOwners.get(sessionId)?.roomId)+ return room ? `in group "${room.name}"` : 'in its own chat'+ }+ const forWhom = (sessionId, info) => {+ if (rt.groupOwners.has(sessionId)) return info?.askedBy && nameOf(info.askedBy) ? `, for ${nameOf(info.askedBy)}` : ''+ const asker = info?.role === 'request' || info?.role === 'stopped' ? info.senderSessionId : works()[workOf(info)]?.from+ if (asker !== undefined) return nameOf(asker) ? `, for ${nameOf(asker)}` : ''+ return info === undefined ? ', for the user' : ''+ }+ const doing = (entry) => {+ const what = rt.doingOf?.(entry) ?? {}+ if (what.tool) return `: running ${what.tool}${what.target ? ` on ${what.target}` : ''}`+ return what.said ? `: "${what.said.slice(0, 100)}"` : ''+ }+ const lines = []+ const approval = (rt.approvalsView?.() ?? []).find(entry => entry.botId === botId)+ const switching = [...(rt.switchJobs?.() ?? [])].find(job => job.botId === botId)+ const running = sessions.filter(sessionId => rt.live.get(sessionId)?.turn !== undefined)+ if (approval !== undefined) lines.push(`waiting for the user's approval to run ${approval.tool || 'a tool'} ${place(approval.sessionId)} (${minutes(approval.at)})`)+ else if (switching !== undefined) lines.push(`moving on to a fresh part of its ${switching.roomId ? `conversation in group "${rt.roomOf(switching.roomId)?.name ?? '?'}"` : 'own chat'}`)+ for (const sessionId of approval === undefined && switching === undefined ? running : []) {+ const entry = rt.live.get(sessionId)+ lines.push(`working ${place(sessionId)} ${minutes(entry.since ?? Date.now())}${forWhom(sessionId, entry.info)}${doing(entry)}`)+ }+ const busyWith = new Set(running.map(sessionId => workOf(rt.live.get(sessionId)?.info)).filter(Boolean))+ for (const [id, work] of Object.entries(works())) {+ if (work.to !== botId || work.open.length === 0 || busyWith.has(id)) continue+ const forName = nameOf(work.from) ? `, for ${nameOf(work.from)}` : ''+ // A child that answered already waits only to be read.+ const on = [...new Set(work.open.flatMap((childId) => {+ const child = works()[childId]+ if (child === undefined) return []+ return [child.room ? `group "${rt.roomOf(child.room)?.name ?? 'a group'}"` : nameOf(child.to) ?? 'a teammate']+ }))]+ lines.push(on.length > 0 ? `waiting for ${on.join(' and ')} to hand back work${forName}` : `about to go on with work${forName}, whose results came back`)+ }+ if (lines.length === 0) lines.push('idle')+ if (state.questions?.[chat] !== undefined) lines.push('a question card in its own chat waits for the user\'s answer')+ const unread = new Map()+ for (const args of rt.unreadOf?.(chat) ?? []) {+ const name = nameOf(args.fromId)+ if (name !== undefined) unread.set(name, (unread.get(name) ?? 0) + 1)+ }+ if (unread.size > 0) lines.push(`not read yet: ${[...unread].map(([name, count]) => `${count} from ${name}`).join(', ')}`)+ return lines.join('; ')+ }++ Object.assign(rt, { workOf, openWork, closeWork, dropWork, takenWork: taken, ownsWork: owns, waitsWork: waits, holdWork: hold, workAsker: askedBy, answerText, upstreamOf, sameWork, forgetBotWork: forgetBot, statusOf })+}diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex f20643eb..a0b6855b 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -612,7 +612,7 @@ export function install(rt) {// A turn stopped for a switch goes on with its own source, so its reply still// reaches whoever asked.const handoffSource = (job, resume) => ({- ...(resume && job.info ? job.info : { kind: SOURCE_KIND, form: 'relay', role: 'handoff', senderName: 'DS Bot', hop: 0 }),+ ...(resume && job.info ? job.info : { kind: SOURCE_KIND, form: 'relay', role: 'handoff', senderName: 'DS Bot' }),exchangeId: job.info?.exchangeId ?? randomUUID(),handoff: true,...(resume ? { resume: true } : {}),@@ -693,7 +693,7 @@ export function install(rt) {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 ? { ...job.info, ...carried } : { kind: SOURCE_KIND, form: 'relay', role: 'resume', exchangeId: randomUUID(), senderName: 'DS Bot', hop: 0, ...carried },+ source: job.info ? { ...job.info, ...carried } : { kind: SOURCE_KIND, form: 'relay', role: 'resume', exchangeId: randomUUID(), senderName: 'DS Bot', ...carried },}))}await forward(job, back).catch(error => rt.warn('ds-bot: input for %s was not handed on: %s', agent.id, error))diff --git a/ds-bot/src/host/prompt.js b/ds-bot/src/host/prompt.jsindex 3ab4b475..917012d1 100644--- a/ds-bot/src/host/prompt.js+++ b/ds-bot/src/host/prompt.js@@ -4,8 +4,8 @@const TEAM_RULES = ['## How your Bot team works','- Every Bot is its own long-lived conversation with the user, with its own memory and computer.',- '- The team changes over time. Call list_bots whenever you need to know who exists; do not rely on memory.',- '- message_bot sends a message to another Bot. Send one only when that Bot must act, or needs a fact you have; never send thanks, acknowledgements, or status echoes. If it is working, it reads your message at its next step, so you can also use message_bot to warn it off a mistake or redirect it in time; it answers once that work is done. Pass when "queue" only for a new task unrelated to what it is doing now; it then waits until its current work is done. Its reply arrives later as a new "[Reply from …]" message. Never wait, poll, or resend.',+ '- The team changes over time. Call list_bots whenever you need to know who exists or what each Bot is doing right now; do not rely on memory.',+ '- message_bot sends a message to another Bot. Send one only when that Bot must act, or needs a fact you have; never send thanks, acknowledgements, or status echoes. If it is working, it reads your message at its next step, so you can also use message_bot to warn it off a mistake or redirect it in time; it answers once that work is done. Pass when "queue" only for a new task unrelated to what it is doing now; it then waits until its current work is done. Its reply arrives later as a new "[Reply from …]" message. Never wait, poll, or resend. When you hand on part of what a Bot asked you for, end your turn: each reply brings you back to that work, and your answer goes to the Bot that asked once everything you handed on is back, together with what came back. Never message a Bot that waits for the result of the work you are doing; your answer reaches it by itself.','- 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 …]" opens a turn, your final text in that turn is delivered back to that Bot automatically and the user does not see it. If one arrives while you are working on something else, take it into account in that work but do not answer it there: once the work is done, it comes back to you in a turn of its own to answer. Answer it directly and briefly, as a list of facts. Never invent facts: say "not discussed yet" when you do not know. If the message brings a request or a decision meant for the user, handle it in the same turn too — do the work, or ask the user with ask_user.','- When a "[Message from … · the user sees your reply here]" arrives, your reply is shown to the user in your own chat and is not sent back. Talk to the user directly, as yourself.',diff --git a/ds-bot/src/host/resume.js b/ds-bot/src/host/resume.jsindex 821df2ee..11ba4540 100644--- a/ds-bot/src/host/resume.js+++ b/ds-bot/src/host/resume.js@@ -28,7 +28,7 @@ const triggerOf = info => ({...(info.exchangeId ? { exchangeId: info.exchangeId } : {}),...(info.senderSessionId ? { senderSessionId: info.senderSessionId } : {}),...(info.roomId ? { roomId: info.roomId } : {}),- ...(typeof info.hop === 'number' ? { hop: info.hop } : {}),+ ...(info.work ? { work: info.work } : {}),...(info.audience ? { audience: info.audience } : {}),...(info.askedBy ? { askedBy: info.askedBy } : {}),...(info.senderRoomId ? { senderRoomId: info.senderRoomId } : {}),@@ -112,6 +112,10 @@ export function install(rt) {}}+ // What a Session was sent and no turn has read yet.+ rt.unreadOf = sessionId => (queued[sessionId] ?? []).map(item => item.args)+ rt.forgetDelivery = forgetQueued+// A message is done with once a turn takes it up, or once it leaves the inbox untaken// while DS Bot runs: the user stopped the Bot, or DS Bot moved or withdrew it.ctx.on('agent/inbox/discarded', ({ message } = {}) => {@@ -180,10 +184,11 @@ export function install(rt) {const trigger = record.triggerif ((trigger?.role === 'request' || trigger?.role === 'stopped') && trigger.senderSessionId && trigger.audience !== 'user' && rt.botOf(trigger.senderSessionId)) {// The sender still waits for this turn's answer, so it goes on under the same exchange.- await rt.deliver({ fromId: trigger.senderSessionId, toId: bot.id, role: trigger.role, hop: trigger.hop ?? 0, ...(trigger.exchangeId ? { exchangeId: trigger.exchangeId } : {}), ...(trigger.senderRoomId ? { fromRoomId: trigger.senderRoomId } : {}), resumed: true, text })+ await rt.deliver({ fromId: trigger.senderSessionId, toId: bot.id, role: trigger.role, ...(trigger.exchangeId ? { exchangeId: trigger.exchangeId } : {}), ...(trigger.senderRoomId ? { fromRoomId: trigger.senderRoomId } : {}), resumed: true, text })return}- await rt.deliver({ toId: bot.id, role: 'resume', resumed: true, text })+ // A turn that went on with work another Bot asked for still owes that Bot its answer.+ await rt.deliver({ toId: bot.id, role: 'resume', resumed: true, text, ...(trigger?.work ? { work: trigger.work } : {}) })}// A hard stop keeps the inbox, which the Session runs once it wakes; only what DSHdiff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.jsindex a0bdc8ab..f93913ad 100644--- a/ds-bot/src/host/store.js+++ b/ds-bot/src/host/store.js@@ -12,7 +12,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: {}, questions: {}, prefs: {}, revision: 0 }+ const state = { version: 1, mainBotIds: [], bots: {}, rooms: {}, agents: {}, capabilities: { items: {} }, exchanges: [], exchangeTurns: {}, works: {}, questions: {}, prefs: {}, revision: 0 }let loaded = nulllet writing = Promise.resolve()const { warn } = rt@@ -152,6 +152,13 @@ export function install(rt) {state.prefs.theme = LEGACY_THEMES[state.prefs.theme]migrated = true}+ if (state.works === null || typeof state.works !== 'object' || Array.isArray(state.works)) state.works = {}+ // LEGACY: Bots no longer count the rounds they start in a group.+ for (const room of Object.values(state.rooms)) {+ if (!('botRounds' in room)) continue+ delete room.botRounds+ migrated = true+ }// Groups from before group settings existed reply in turn, led by a Main Bot member.for (const room of Object.values(state.rooms)) {if (room.admin !== undefined && ROOM_MODES.includes(room.mode)) continuediff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.jsindex 19af8881..7df36822 100644--- a/ds-bot/src/host/tools.js+++ b/ds-bot/src/host/tools.js@@ -2,7 +2,7 @@// question card. Group rounds and reading chats are in groups.js.import { randomUUID } from 'node:crypto'import { defineTool } from '@deepseek-ai/dsh-tools'-import { COLORS, EXTRA_COLORS, MAX_HOPS, MAX_UNATTENDED_MESSAGES, MAX_UNREAD_REQUESTS, MESSAGE_INLINE_MAX, ROOM_BOT_ROUNDS, ROOM_MODES, SOURCE_KIND } from './constants.js'+import { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js'import { unquote } from './text.js'import { mentionSpans } from '../shared/mentions.js'@@ -46,7 +46,7 @@ export function install(rt) {ctx.tools.register(defineTool({name: 'list_bots',- description: 'List every Bot on the user\'s team with its role and what it does, and the group chats you can see.',+ description: 'List every Bot on the user\'s team with its role, what it does and what it is doing right now, and the group chats you can see.',parameters: {},output,async execute(_args, exec) {@@ -56,7 +56,8 @@ export function install(rt) {const model = bot.appliedModel ?? bot.modelconst tags = [bot.role, model ? `model ${model}` : '', bot.workDir ? `works in ${bot.workDir}` : '', rt.isMain(bot.id) ? 'Main Bot' : '', bot.id === self ? 'you' : ''].filter(Boolean).join(', ')const job = bot.instructions ? ` — ${bot.instructions.split('\n')[0].slice(0, 120)}` : ''- return `- ${bot.name}${tags ? ` (${tags})` : ''}${job}`+ const now = bot.id === self ? '' : `\n now: ${rt.statusOf(bot.id)}`+ return `- ${bot.name}${tags ? ` (${tags})` : ''}${job}${now}`})if (lines.length === 0) return 'No Bots yet.'const rooms = visibleRooms(self)@@ -81,26 +82,32 @@ export function install(rt) {const room = rt.roomOf(rt.groupOwners.get(sessionId)?.roomId)return room ? `group "${room.name}"` : 'its own chat'}- // Delivered but not read yet: no step or turn has taken them out of the inbox.- const unreadRequests = agent => [...(agent.inbox?.nextStep ?? []), ...(agent.inbox?.nextTurn ?? [])]- .filter(message => message.source?.kind === SOURCE_KIND && message.source.role === 'request').length+ // A Bot request still in the inbox: no step or turn has taken it out yet.+ const unreadRequest = (agent, senderId, toUser) => {+ for (const [message, steered] of [...(agent.inbox?.nextStep ?? []).map(message => [message, true]), ...(agent.inbox?.nextTurn ?? []).map(message => [message, false])]) {+ const source = message.source+ if (source?.kind === SOURCE_KIND && source.role === 'request' && source.senderSessionId === senderId+ && (source.audience === 'user') === toUser && !source.deferred && !source.resumed) return { message, steered }+ }+ return undefined+ }+ // A message's own words and files, without its header line.+ const bodyOf = (message) => {+ const content = Array.isArray(message.content) ? message.content : []+ const first = content.find(block => block?.type === 'text')?.text ?? ''+ return { text: first.slice(first.indexOf('\n') + 1), files: content.filter(block => block?.type === 'file' && block.attachment !== undefined).map(block => block.attachment) }+ }// A tool that throws shows as failed in the chat, instead of as sent or stopped.const refuse = (message) => { throw new Error(message) }- // A message a Bot sends is one hop past the turn that sends it, while a reply keeps- // the hop of the request it answers (turns.js): any chain, forwarded or back and- // forth, reaches MAX_HOPS.- const nextHop = (exec) => {+ // The works (handoffs.js) the calling turn does: what it answers, and the requests+ // that joined it.+ const worksOf = (exec) => {const turn = rt.live.get(exec.agent?.id)- return 1 + Math.max(turn?.info?.hop ?? 0, ...(turn?.joined ?? []).map(joined => joined.info?.hop ?? 0))+ return [rt.workOf(turn?.info), ...(turn?.joined ?? []).map(joined => rt.workOf(joined.info))].filter(Boolean)}- const CHAIN_TOO_LONG = 'This chain of Bot messages is already long. Stop here and report to the user instead.'const tooLong = text => `Not sent: the message has ${text.length} characters, more than ${MESSAGE_INLINE_MAX}, and this DeepSeek Harness cannot send it as a file. Write it to a file in your working folder and send its path instead.`- const checkUnattended = () => {- if (rt.unattended.sent < MAX_UNATTENDED_MESSAGES) return- refuse(`Not sent: the team has sent ${MAX_UNATTENDED_MESSAGES} Bot messages since the user last wrote. Stop messaging other Bots and tell the user what is still open.`)- }// 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.@@ -150,21 +157,38 @@ export function install(rt) {const posted = calledInPosts.get(exec.agent?.id)const postedIn = posted !== undefined && posted.turn === turnOf(exec) ? posted.calls.get(target.id) : undefinedif (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.`)- const hop = nextHop(exec)- if (hop > MAX_HOPS) return CHAIN_TOO_LONG- checkUnattended()- const chat = rt.chatOf(target.id)- const unread = unreadRequests(await rt.resolveAgent(chat))- if (unread >= MAX_UNREAD_REQUESTS) {- refuse(`Not sent: ${target.name} has not read the last ${unread} messages from Bots yet, so it is most likely stuck, for example waiting for the user. Do not send it more; tell the user that ${target.name} is not responding.`)+ // Whoever waits for this work gets the answer by itself; a message there only+ // sends the work round in a circle.+ const works = worksOf(exec)+ if (rt.upstreamOf(works).has(target.id)) {+ refuse(`Not sent: ${target.name} is waiting for the result of the work you are doing, and your answer reaches it by itself. Finish the work and end your turn; to ask ${target.name} something, end your turn with the question.`)}- const long = await rt.attachLong(String(args.message), `Message from ${sender.name}.txt`)- if (long === undefined) return tooLong(String(args.message))+ const text = String(args.message)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`) ?? longconst working = rt.live.get(chat)?.turn !== undefined- const steer = args.when !== 'queue' && !toUser- await rt.deliver({ fromId: sender.id, toId: target.id, text: long.text, files: long.files, length: long.length, role: 'request', hop, steer, ...(toUser ? { audience: 'user' } : {}) })- rt.unattended.sent += 1+ 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@@ -172,17 +196,18 @@ export function install(rt) {: 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.`- // "Delivered" only means it is in the inbox; say so when it may sit there a while.+ const asker = rt.ownsWork(sender.id, work) ? rt.botOf(state.works[work].from)?.name : undefinedconst notes = [- rt.waitsForApproval?.(chat) ? `${target.name} is waiting for the user's approval, so it reads your message only after the user answers.` : '',- unread > 0 ? `${target.name} has not read ${unread === 1 ? 'an earlier message' : `${unread} earlier messages`} from Bots yet.` : '',+ 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 status = notes.length === 0 ? sent : `${sent} ${notes.join(' ')}`+ 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 status+ if (groups.length === 0) return outconst stop = rt.isMain(sender.id) ? ' If it must not go on there, use stop_bot.' : ''- return `${status} ${target.name} is also working in ${groups.map(whereOf).join(' and ')}; your message does not reach that work.${stop}`+ return `${out} Your message does not reach its work in ${groups.map(whereOf).join(' and ')}.${stop}`},}))@@ -443,20 +468,20 @@ export function install(rt) {if (!rt.isMain(self) && !rt.isAdminOf(room, self)) return `Only a Main Bot or the admin of "${room.name}" can post there. Use message_bot to reach its members.`const info = rt.live.get(exec.agent?.id)?.infoif (info?.role === 'room' && info.roomId === room.id) return `You are speaking in "${room.name}" right now. Write your message as your reply instead.`- const hop = nextHop(exec)- if (hop > MAX_HOPS) return CHAIN_TOO_LONGconst text = String(args.message ?? '').trim()if (text === '') return 'Write a message to post.'- if ((room.botRounds ?? 0) >= ROOM_BOT_ROUNDS) return `Bots already started ${ROOM_BOT_ROUNDS} rounds in "${room.name}" since the user last spoke there. Wait for the user.`- checkUnattended()const long = await rt.attachLong(text, `Post from ${sender.name}.txt`)if (long === undefined) return tooLong(text)- room.botRounds = (room.botRounds ?? 0) + 1- await rt.save()const reportBack = args.report_back === true+ // Replies the poster waits for, while it works on what a Bot asked it for, are+ // work handed on for that request (handoffs.js).+ const work = reportBack ? worksOf(exec).find(id => rt.ownsWork(self, id)) : undefined+ const sub = work === undefined ? undefined : randomUUID()+ if (sub !== undefined) rt.openWork(sub, { from: self, room: room.id, parent: work })try {- await rt.postToRoom(room, sender, long.text, { hop, ...(reportBack ? { reportBack: true } : {}), ...(long.length ? { length: long.length } : {}) }, long.files)+ await rt.postToRoom(room, sender, long.text, { ...(reportBack ? { reportBack: true } : {}), ...(sub ? { sub } : {}), ...(long.length ? { length: long.length } : {}) }, long.files)} catch (failure) {+ if (sub !== undefined) rt.dropWork(sub)return `Could not post in "${room.name}": ${failure.message}`}const named = mentionSpans(text, room.members.map(rt.botOf).filter(Boolean)).flatMap(span => (span.bot ? [span.bot.id] : []))@@ -467,8 +492,9 @@ export function install(rt) {for (const id of named) calls.set(id, room.name)calledInPosts.set(exec.agent?.id, { turn, calls })}- rt.unattended.sent += 1- return `Posted in "${room.name}". Members reply there, where the user reads them${reportBack ? '; their replies also come back to you as a new message when the round ends' : ', and nothing comes back to you'}.`+ const asker = sub === undefined ? undefined : rt.botOf(state.works[work]?.from)?.name+ const waits = asker ? ` End your turn when you have handed on everything: the replies bring you back to this work, and your answer goes to ${asker} once all of it is back.` : ''+ return `Posted in "${room.name}". Members reply there, where the user reads them${reportBack ? '; their replies also come back to you as a new message when the round ends' : ', and nothing comes back to you'}.${waits}`},}))diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex f33e996f..f5c32a68 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -2,7 +2,7 @@// triggered, the waiters and inboxes of group rounds, and routing a finished turn's reply.//// Turn tracking: which turns were triggered by another Bot, and what they said.-import { HANDOFF_ACK, REFERENCE_KIND, REPLY_KIND, SOURCE_KIND } from './constants.js'+import { HANDOFF_ACK, MESSAGE_INLINE_MAX, REFERENCE_KIND, REPLY_KIND, SOURCE_KIND } from './constants.js'import { textOf } from './text.js'import { reminderText } from './schedules.js'@@ -59,8 +59,8 @@ export function install(rt) {sessionId: id,role: keeps ? info.role : 'retry',...(keeps && info.roomId ? { roomId: info.roomId } : {}),- hop: keeps ? info.hop ?? 0 : 0,...(keeps && info.exchangeId ? { exchangeId: info.exchangeId } : {}),+ ...(info?.work ? { work: info.work } : {}),...(keeps && info.audience ? { audience: info.audience } : {}),...(keeps && info.askedBy ? { askedBy: info.askedBy } : {}),...(keeps && info.senderRoomId ? { fromRoomId: info.senderRoomId } : {}),@@ -76,15 +76,11 @@ export function install(rt) {const roomWaiters = new Map()/** @type {Map<string, {roomId:string, replies:any[], members:string[], speaking:string|null}>} */const roomProgress = new Map()- /** @type {Map<string, {text:string, botId?:string, name?:string, reportBack?:boolean, hop?:number, kickoff?:boolean, references?:{labels:string[], text:string}[]}[]>} messages a room's next relay posts */+ /** @type {Map<string, {text:string, botId?:string, name?:string, reportBack?:boolean, kickoff?:boolean, references?:{labels:string[], text:string}[]}[]>} messages a room's next relay posts */const roomInbox = new Map()const queueRoomMessage = (roomId, item) => roomInbox.set(roomId, [...(roomInbox.get(roomId) ?? []), item])// Member turns of a group round the user stopped: what they end with stays out of the group.const stoppedRoomTurns = new Set()- // Bot messages sent since someone outside the team last spoke. Process-local: a- // restart is itself a pause, so the count starts afresh.- const unattended = { sent: 0 }- const userSpoke = () => { unattended.sent = 0 }// A stopped round stops the member work it started: the turn that answers it, or the// delivery still waiting for the member's Session. An earlier turn there keeps going.@@ -184,17 +180,21 @@ export function install(rt) {}// The reply a sender waits for, also when it wrote from a group, where it gets the- // reply in its Session there while it is still a member.- const tellSender = (id, source, text) => {+ // reply in its Session there while it is still a member. A sender that asked for it+ // while working on another Bot's request goes on with that work when it reads it.+ // `long`: the text as attachLong sends it, when it went as a file.+ const tellSender = (id, source, text, long) => {const back = rt.roomOf(source.senderRoomId)?.sessions?.[source.senderSessionId]+ const work = rt.closeWork?.(source.exchangeId, rt.botOf(rt.selfOf(id))?.name ?? 'The other Bot', text)void rt.deliver({fromId: rt.selfOf(id),toId: source.senderSessionId,...(back ? { sessionId: back } : {}),- text,+ text: long?.text ?? text,+ ...(long?.length === undefined ? {} : { files: long.files, length: long.length }),role: 'reply',- hop: source.hop ?? 0,replyTo: source.exchangeId,+ ...(work ? { work } : {}),}).catch(error => rt.warn('ds-bot: reply delivery failed: %s', error))}@@ -218,6 +218,10 @@ export function install(rt) {live.delete(id)setActivity(id, undefined)}+ // Work it was asked for and still waits on, outside any running turn.+ for (const source of rt.forgetBotWork?.(botId) ?? []) {+ if (!waiting.has(source.exchangeId)) waiting.set(source.exchangeId, [rt.chatOf(botId), source])+ }for (const [id, source] of waiting.values()) tellSender(id, source, text)}@@ -382,6 +386,7 @@ export function install(rt) {entry.answers = falseentry.opened = falseentry.joined = []+ entry.later = []if (entry.pending !== undefined) {claimTrigger(id, entry, entry.pending)entry.pending = undefined@@ -389,7 +394,8 @@ export function install(rt) {breakcase 'user/message': {const source = event.data?.source- if (source?.kind === 'user' || source?.kind === REPLY_KIND || source?.kind === 'schedule') userSpoke()+ // A result that came back counts as taken once a turn reads it.+ if (source?.kind === SOURCE_KIND && source.work !== undefined && source.replyTo !== undefined) rt.takenWork?.(source.work, source.replyTo)// A message that shares a step with a bare handoff package is what the turn// answers, so the turn is not a hidden acknowledgement.const bare = info => info?.handoff === true && info.resume !== true@@ -421,7 +427,7 @@ export function install(rt) {botId: source.senderSessionId,name: source.senderName,reportBack: source.reportBack === true,- hop: source.hop ?? 0,+ ...(source.sub ? { sub: source.sub } : {}),...(source.late ? { late: true } : {}),...(source.progress ? { progress: true } : {}),...(source.quiet ? { quiet: true } : {}),@@ -437,7 +443,11 @@ export function install(rt) {} else if (source?.kind === SOURCE_KIND) {if (entry.turn === undefined) entry.pending = sourceelse if (!opened) claimTrigger(id, entry, source)- else if (expectsReply(source) && !answersUser(source)+ else if (source.work !== undefined && source.work !== rt.workOf?.(entry.info) && !expectsReply(source)) {+ // A result for other work than this turn's informs it, and comes back in a+ // turn of its own once this one ends, which goes on with that work.+ entry.later = [...(entry.later ?? []), { info: source, text: textOf(event.data.content).replace(/^\[[^\]\n]*\]\n?/, '') }]+ } 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 steers that work but is@@ -506,6 +516,21 @@ export function install(rt) {entry.calls = undefinedentry.lastText = undefinedentry.lastCalled = undefined+ const later = entry.later ?? []+ entry.later = []+ for (const result of later) {+ void rt.deliver({+ fromId: result.info.senderSessionId,+ toId: rt.selfOf(id),+ text: result.text,+ role: result.info.role,+ exchangeId: result.info.exchangeId,+ replyTo: result.info.replyTo,+ work: result.info.work,+ ...(result.info.roomId ? { roomId: result.info.roomId } : {}),+ deferred: true,+ }).catch(error => rt.warn('ds-bot: handing back a result failed: %s', error))+ }const reason = event.data?.reasonconst failure = reason?.kind === 'error' && !switched ? turnFailure(reason.error) : undefinedif (failure !== undefined) noteTurnFailure(id, failure)@@ -525,9 +550,9 @@ export function install(rt) {const groupReply = () => rt.withRoomSteps?.(held, replyText()) ?? replyText()// 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.+ const name = rt.botOf(rt.selfOf(id))?.name ?? 'The other Bot'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.tellSender(id, source, `${name} could not answer your message: its model call failed (${failureLine(failure)}). Tell the user if it matters; do not retry right away.`)@@ -537,6 +562,22 @@ export function install(rt) {tellSender(id, source, reply !== '' ? reply : `${name} was stopped before it could answer your message.`)}}+ // Work a Bot asked for, also when what came back for it opens the turn: while+ // anything handed on for it is still out, the answer waits; then it goes up with+ // what came back. A failed or stopped turn answers at once.+ const finish = (source, reply) => {+ const work = rt.workOf?.(source)+ if (!rt.ownsWork?.(rt.selfOf(id), work)) return answer(source, reply)+ const asker = rt.workAsker(work)+ if (failure !== undefined || reason?.kind === 'aborted') return answer(asker, reply)+ if (rt.waitsWork(work)) return rt.holdWork(work, reply)+ // With what came back, the answer may pass what one message carries.+ const text = rt.answerText(work, reply, name)+ if (text.length <= MESSAGE_INLINE_MAX) return tellSender(id, asker, text)+ void rt.attachLong(text, `Answer from ${name}.txt`)+ .then(long => tellSender(id, asker, text, long))+ .catch(error => rt.warn('ds-bot: answer from %s not sent: %s', name, error))+ }// A retried turn answers the same waiter or sender, so this one passes nothing on.if (!retry && info?.role === 'room') {const waiter = roomWaiters.get(info.exchangeId)@@ -554,7 +595,7 @@ export function install(rt) {if (failure !== undefined) void rt.lateRoomFailure?.(id, info ?? {}, failure)else if (reason?.kind !== 'aborted') void rt.lateRoomReply?.(id, info ?? {}, groupReply(), { shown })} else if (!retry && info !== undefined) {- answer(info, replyText())+ finish(info, replyText())}for (const request of joined) {// A failed or stopped turn closes the request like any other; a finished@@ -569,7 +610,6 @@ export function install(rt) {sessionId: id,text: request.text,role: 'request',- hop: request.info.hop ?? 0,exchangeId: request.info.exchangeId,...(request.info.senderRoomId ? { fromRoomId: request.info.senderRoomId } : {}),deferred: true,@@ -580,5 +620,5 @@ export function install(rt) {}})- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, callDetail, stopRoomTurn, unattended, userSpoke, releaseBot })+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, callDetail, doingOf, stopRoomTurn, releaseBot })}diff --git a/ds-bot/test/bot-messages.test.js b/ds-bot/test/bot-messages.test.jsindex ef62204b..11a55ff2 100644--- a/ds-bot/test/bot-messages.test.js+++ b/ds-bot/test/bot-messages.test.js@@ -8,7 +8,7 @@ import { apply } from '../index.js'import { fakeAttachments, fakeContext } from './fake-ctx.js'import { install as installTurns } from '../src/host/turns.js'import { install as installParts } from '../src/host/parts.js'-import { MAX_HOPS, MAX_UNATTENDED_MESSAGES, REPLY_KIND, SOURCE_KIND } from '../src/host/constants.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 } = {}) {@@ -50,7 +50,17 @@ async function start(seed) {cancel(cause) { calls.push(['cancel', cause]) },async whenIdle() {},async runMaintenance(fn) { return fn(AbortSignal.timeout(60_000)) },- inbox: { nextStep: [], nextTurn: [], remove() {} },+ 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)@@ -117,7 +127,7 @@ test('message_bot steers by default; on an idle Bot it opens the next turn', asy// Running: the message cuts into that turn instead of queuing.emit('b', 'turn/start', { turn: 1 })const busy = await tool('message_bot', { to: 'Writer', message: 'watch out' }, 'a')- assert.equal(busy, 'Delivered to Writer while it is working: it reads your message at its next step and answers once that work is done. Its reply will arrive later as a new message; do not wait for it.')+ assert.equal(busy, 'Delivered to Writer while it is working: it reads your message at its next step and answers once that work is done. Its reply will arrive later as a new message; do not wait for it. Writer now: working in its own chat for less than a minute, for the user; not read yet: 1 from Chief.')assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer', 'steer'])})@@ -127,11 +137,11 @@ test('message_bot when "queue" waits for the current work, and reply_to "user" aemit('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.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. Writer now: working in its own chat for less than a minute, for the user.')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.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. Writer now: working in its own chat for less than a minute, for the user; not read yet: 1 from Chief.')assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['followup', 'followup'])assert.equal(agents.get('b').calls[1][1].source.audience, 'user')})@@ -144,14 +154,14 @@ test('a Bot busy in a group gets the message in its own chat, and the sender isemit('gb', 'turn/start', { turn: 1 })const out = await tool('message_bot', { to: 'Writer', message: 'status?' }, 'a')- assert.equal(out, 'Delivered to Writer. Its reply will arrive later as a new message; do not wait for it. Writer is also working in group "Ops"; your message does not reach that work. If it must not go on there, use stop_bot.')+ assert.equal(out, 'Delivered to Writer. Its reply will arrive later as a new message; do not wait for it. Writer now: working in group "Ops" for less than a minute. Your message does not reach its work in group "Ops". If it must not go on there, use stop_bot.')assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer'])assert.equal(agents.get('gb'), undefined)// A non-Main sender gets no stop_bot hint.emit('ga', 'turn/start', { turn: 1 })const back = await tool('message_bot', { to: 'Chief', message: 'done' }, 'b')- assert.equal(back, 'Delivered to Chief. Its reply will arrive later as a new message; do not wait for it. Chief is also working in group "Ops"; your message does not reach that work.')+ assert.equal(back, 'Delivered to Chief. Its reply will arrive later as a new message; do not wait for it. Chief now: working in group "Ops" for less than a minute. Your message does not reach its work in group "Ops".')})test('a request steered into a running turn is recorded once and answered in a turn of its own', async (t) => {@@ -187,7 +197,7 @@ test('a request steered into a running turn is recorded once and answered in a tassert.deepEqual((await exchanges()).map(entry => entry.role), ['request', 'reply'])})-test('message_bot names the messages a Bot has not read yet, and stops sending to a stuck Bot', async (t) => {+test('a message its recipient has not read yet takes in the next one, however many come', async (t) => {const { ctx, agentOf, emit, tool, exchanges, stop } = await start(team())t.after(stop)// Writer's turn waits on something and never reaches its next step.@@ -195,22 +205,47 @@ test('message_bot names the messages a Bot has not read yet, and stops sending twriter.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' }, 'a')- assert.equal(first, 'Delivered to Writer while it is working: it reads your message at its next step and answers once that work is done. Its reply will arrive later as a new message; do not wait for it.')- assert.match(await tool('message_bot', { to: 'Writer', message: 'task 2' }, 'a'), /Writer has not read an earlier message from Bots yet\.$/)- for (let index = 3; index <= 10; index += 1) await tool('message_bot', { to: 'Writer', message: `task ${index}` }, 'a')- assert.match(await tool('message_bot', { to: 'Writer', message: 'task 10b' }, 'a').catch(error => error.message), /^Not sent: Writer has not read the last 10 messages from Bots yet/)- assert.equal(writer.calls.length, 10)- assert.equal((await exchanges()).length, 10)-- // Once a step takes them up, messages go through again.+ await tool('message_bot', { to: 'Writer', message: 'task 1' }, 'a')+ const second = await tool('message_bot', { to: 'Writer', message: 'task 2', when: 'queue' }, 'a')+ assert.match(second, /Writer had not read your earlier message yet, so this one was added to it, and it answers both at once\. Writer now: working in its own chat for less than a minute, for the user; not read yet: 1 from Chief\.$/)+ for (let index = 3; index <= 12; index += 1) await tool('message_bot', { to: 'Writer', message: `task ${index}` }, 'a')+ // One message, still steered, under the first one's exchange.+ assert.equal(writer.inbox.nextStep.length, 1)+ const [waiting] = writer.inbox.nextStep+ assert.equal(textOf(waiting.content), `[Message from Chief]\n${Array.from({ length: 12 }, (_, index) => `task ${index + 1}`).join('\n\n')}`)+ assert.equal(waiting.source.exchangeId, writer.calls[0][1].source.exchangeId)+ assert.deepEqual((await exchanges()).map(entry => entry.text.split('\n\n').length), [12])+ assert.match(await tool('list_bots', {}, 'a'), /- Writer \(Write\)\n {2}now: working in its own chat for less than a minute, for the user; not read yet: 1 from Chief\n/)++ // Once a step takes it up, the next message is a new one.+ emit('b', 'user/message', { content: waiting.content, source: waiting.source })writer.inbox.nextStep.length = 0- assert.match(await tool('message_bot', { to: 'Writer', message: 'task 11' }, 'a'), /^Delivered to Writer while it is working/)+ assert.match(await tool('message_bot', { to: 'Writer', message: 'task 13' }, 'a'), /^Delivered to Writer while it is working[^]*Writer now: working in its own chat for less than a minute, for Chief\.$/)+ assert.equal((await exchanges()).length, 2)- // An approval the Bot waits for holds its messages too.- writer.inbox.nextStep.length = 0+ // An approval the Bot waits for shows in what the sender is told.for (const listener of ctx.listeners.get('approval/request')) void listener({ agent: { session: { id: 'b' } }, toolName: 'bash', reason: 'rm' }, () => new Promise(() => {}))- assert.match(await tool('message_bot', { to: 'Writer', message: 'task 12' }, 'a'), /Writer is waiting for the user's approval, so it reads your message only after the user answers\.$/)+ assert.match(await tool('message_bot', { to: 'Writer', message: 'task 14' }, 'a'), /Writer now: waiting for the user's approval to run bash in its own chat \(for less than a minute\); not read yet: 1 from Chief\.$/)+})++test('requests from two Bots, or for different work, stay apart', async (t) => {+ const seed = team()+ seed.bots.c = { id: 'c', name: 'Tester', role: 'Test', sessionId: 'c', createdAt: 3 }+ const { agentOf, emit, tool, stop } = await start(seed)+ t.after(stop)+ const writer = agentOf('b')+ writer.steer = (message) => { writer.calls.push(['steer', message]); writer.inbox.nextStep.push(message) }+ emit('b', 'turn/start', { turn: 1 })++ await tool('message_bot', { to: 'Writer', message: 'from Chief' }, 'a')+ assert.doesNotMatch(await tool('message_bot', { to: 'Writer', message: 'from Tester' }, 'c'), /added to it/)+ // Tester, now working on what Chief asked it for, writes for that work.+ await tool('message_bot', { to: 'Tester', message: 'check it' }, 'a')+ const ask = agentOf('c').calls.at(-1)[1]+ emit('c', 'turn/start', { turn: 1 })+ emit('c', 'user/message', { content: ask.content, source: ask.source })+ assert.doesNotMatch(await tool('message_bot', { to: 'Writer', message: 'for that check' }, 'c'), /added to it/)+ assert.equal(writer.inbox.nextStep.length, 3)})test('a non-Main Bot can steer a message to a Main Bot', async (t) => {@@ -277,7 +312,7 @@ function turnsHost() {return { rt, emit, delivered }}-const replySource = (role, extra = {}) => ({ kind: SOURCE_KIND, role, senderSessionId: 'a', senderName: 'Chief', exchangeId: 'x1', hop: 0, ...extra })+const replySource = (role, extra = {}) => ({ kind: SOURCE_KIND, role, senderSessionId: 'a', senderName: 'Chief', exchangeId: 'x1', ...extra })const textBlock = (content) => [{ type: 'text', text: content }]const assistantText = text => ({ message: { content: textBlock(text) } })@@ -296,25 +331,25 @@ test('a stopped notice routes the acknowledgement back like a request', () => {})// What the turn hands back for a joined request: the request itself, to answer next.-const deferredOf = job => [job.fromId, job.toId, job.sessionId, job.role, job.exchangeId, job.hop, job.deferred, job.text]+const deferredOf = job => [job.fromId, job.toId, job.sessionId, job.role, job.exchangeId, job.deferred, job.text]test('a request that joins a user-started turn is handed back, not answered with the turn\'s text', () => {const { rt, emit, delivered } = turnsHost()emit('b', 'turn/start', { turn: 1 })emit('b', 'user/message', { content: textBlock('write the letter'), source: { kind: 'user' } })emit('b', 'assistant/message', assistantText('first half'))- emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmake it shorter'), source: replySource('request', { exchangeId: 'e1', hop: 2 }) })+ 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.deepEqual(delivered.map(deferredOf), [['a', 'b', 'b', 'request', 'e1', 2, true, 'make it shorter']])+ assert.deepEqual(delivered.map(deferredOf), [['a', 'b', 'b', 'request', 'e1', true, 'make it shorter']])assert.deepEqual(rt.state.exchangeTurns, {})// The handed-back request opens a hidden turn whose text is the reply.emit('b', 'turn/start', { turn: 2 })- emit('b', 'user/message', { content: textBlock('[Message from Chief · you read it during your last task; answer it now]\nmake it shorter'), source: replySource('request', { exchangeId: 'e1', hop: 2, deferred: true }) })+ emit('b', 'user/message', { content: textBlock('[Message from Chief · you read it during your last task; answer it now]\nmake it shorter'), source: replySource('request', { exchangeId: 'e1', deferred: true }) })emit('b', 'assistant/message', assistantText('done, it is shorter'))emit('b', 'turn/end', { turn: 2, reason: { kind: 'completed' } })- assert.deepEqual(delivered.slice(1).map(job => [job.toId, job.role, job.replyTo, job.hop, job.text]), [['a', 'reply', 'e1', 2, 'done, it is shorter']])+ assert.deepEqual(delivered.slice(1).map(job => [job.toId, job.role, job.replyTo, job.text]), [['a', 'reply', 'e1', 'done, it is shorter']])assert.deepEqual(rt.state.exchangeTurns, { b: [2] })})@@ -427,17 +462,6 @@ test('a joined request crosses a part switch and is handed back in the new part'assert.equal(textOf(handedBack()[1].content), '[Message from Chief · you read it during your last task; answer it now]\nmore')})-test('a message goes one hop past 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, 5)-})-// Each Session takes up the newest message it was sent as its next turn.function turnTaker(agents, emit) {const turns = new Map()@@ -459,94 +483,168 @@ function turnTaker(agents, emit) {}return { take, end, userTurn }}-const allCalls = agents => [...agents.values()].reduce((sum, agent) => sum + agent.calls.length, 0)--test('every forwarded message counts a hop, and the one past MAX_HOPS is not sent', async (t) => {+const settled = async (check) => {+ for (let count = 0; count < 200 && !check(); count += 1) await delay(5)+}+const threeBots = () => {const seed = team()seed.bots.c = { id: 'c', name: 'Tester', role: 'Test', sessionId: 'c', createdAt: 3 }- const { agents, emit, tool, stop } = await start(seed)- t.after(stop)- const { take, end, userTurn } = turnTaker(agents, emit)- const ring = [['a', 'Writer', 'b'], ['b', 'Tester', 'c'], ['c', 'Chief', 'a']]-- userTurn('a', 'ask Writer to pass it on')- const hops = []- let refused- for (let step = 0; step < MAX_HOPS + 3 && refused === undefined; step += 1) {- const [from, to, toId] = ring[step % ring.length]- if (step > 0) take(from)- const before = allCalls(agents)- const out = await tool('message_bot', { to, message: 'pass it on' }, from)- end(from)- if (out.startsWith('Delivered')) hops.push(agents.get(toId).calls.at(-1)[1].source.hop)- else {- refused = out- assert.equal(allCalls(agents), before)- }- }- assert.deepEqual(hops, Array.from({ length: MAX_HOPS }, (_, index) => index + 1))- assert.equal(refused, 'This chain of Bot messages is already long. Stop here and report to the user instead.')+ return seed+}+const callsOf = (agents, id) => agents.get(id)?.calls ?? []+// Read once the saves are done: a read while one renames the file over makes it fail on Windows.+const worksIn = async (home) => {+ await delay(50)+ return JSON.parse(readFileSync(join(home, 'state.json'), 'utf8')).works ?? {}+}++// Chief asks Writer, which hands part of it on to Tester.+async function handedOn({ agents, emit, tool }) {+ const turns = turnTaker(agents, emit)+ turns.userTurn('a', 'have Writer do it')+ await tool('message_bot', { to: 'Writer', message: 'carry out the plan' }, 'a')+ turns.end('a', 'asked Writer')+ turns.take('b')+ const handed = await tool('message_bot', { to: 'Tester', message: 'review my work' }, 'b')+ return { ...turns, handed }+}++test('a Bot\'s answer waits for the work it handed on, and carries what came back', async (t) => {+ const team = await start(threeBots())+ t.after(team.stop)+ const { agents, tool, home } = team+ const { take, end, handed } = await handedOn(team)+ assert.match(handed, /When you have handed on everything, end your turn: each reply brings you back to this work, and your answer goes to Chief once all of it is back\.$/)+ end('b', 'handed it to Tester')+ // Nothing goes up yet; Writer waits, and the team can see it.+ assert.match(await tool('list_bots', {}, 'a'), /- Writer \(Write\)\n {2}now: waiting for Tester to hand back work, for Chief\n/)+ assert.deepEqual(Object.values(await worksIn(home)).map(work => [work.from, work.to, work.open.length, work.held]), [['a', 'b', 1, 'handed it to Tester'], ['b', 'c', 0, undefined]])+ assert.deepEqual(callsOf(agents, 'a'), [])++ take('c')+ end('c', 'two things to fix')+ await settled(() => callsOf(agents, 'b').length === 2)+ const back = take('b')+ assert.equal(textOf(back.content), '[Reply from Tester · for the work Chief asked you for; your answer goes to Chief once everything you handed on is back]\ntwo things to fix')+ end('b', 'fixed both')+ await settled(() => callsOf(agents, 'a').length === 1)+ assert.equal(textOf(callsOf(agents, 'a')[0][1].content), '[Reply from Writer]\nfixed both\n\n[Handed back to Writer for this work]\n\nTester:\ntwo things to fix')+ assert.match(await tool('list_bots', {}, 'a'), /- Writer \(Write\)\n {2}now: idle\n/)+ assert.deepEqual(await worksIn(home), {})})-test('a back-and-forth between two Bots ends at MAX_HOPS', async (t) => {- const { agents, emit, tool, stop } = await start(team())- t.after(stop)- const { take, end, userTurn } = turnTaker(agents, emit)- const replies = () => (agents.get('a')?.calls ?? []).length-- userTurn('a', 'work it out with Writer')- const asked = []- for (let round = 0; round < MAX_HOPS + 3; round += 1) {- const out = await tool('message_bot', { to: 'Writer', message: 'and now?' }, 'a')- end('a')- if (!out.startsWith('Delivered')) break- asked.push(take('b').source.hop)- const before = replies()- end('b', 'here is my part')- for (let count = 0; count < 200 && replies() === before; count += 1) await delay(5)- const reply = take('a')- assert.equal(reply.source.role, 'reply')- }- assert.deepEqual(asked, Array.from({ length: MAX_HOPS }, (_, index) => index + 1))+test('a Bot may take part in the same work again, but not message one that waits for its result', async (t) => {+ const team = await start(threeBots())+ t.after(team.stop)+ const { agents, tool } = team+ // Chief designs, Writer builds, Tester reviews; then Chief accepts.+ const { take, end } = await handedOn(team)+ end('b')+ take('c')+ const refused = { message: /^Not sent: (Chief|Writer) is waiting for the result of the work you are doing, and your answer reaches it by itself\./ }+ await assert.rejects(tool('message_bot', { to: 'Chief', message: 'please accept it' }, 'c'), refused)+ await assert.rejects(tool('message_bot', { to: 'Writer', message: 'it passes' }, 'c'), refused)+ assert.deepEqual(callsOf(agents, 'a'), [])+ assert.equal(callsOf(agents, 'b').length, 1)+ end('c', 'it passes')+ await settled(() => callsOf(agents, 'b').length === 2)+ take('b')+ end('b', 'built and reviewed')+ await settled(() => callsOf(agents, 'a').length === 1)+ take('a')+ // With the result in hand, Chief asks Tester again, and Tester may ask Writer.+ assert.match(await tool('message_bot', { to: 'Tester', message: 'check the last part once more' }, 'a'), /^Delivered to Tester/)+ end('a')+ take('c')+ assert.match(await tool('message_bot', { to: 'Writer', message: 'what did you change last?' }, 'c'), /^Delivered to Writer/)+ await assert.rejects(tool('message_bot', { to: 'Chief', message: 'done' }, 'c'), refused)})-const spentBudget = { message: new RegExp(`^Not sent: the team has sent ${MAX_UNATTENDED_MESSAGES} Bot messages since the user last wrote`) }+test('a stopped turn answers at once, and what it handed on comes back to it alone', async (t) => {+ const team = await start(threeBots())+ t.after(team.stop)+ const { agents, emit } = team+ const { take, end } = await handedOn(team)+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } })+ await settled(() => callsOf(agents, 'a').length === 1)+ assert.equal(textOf(callsOf(agents, 'a')[0][1].content), '[Reply from Writer]\nWriter was stopped before it could answer your message.')++ take('c')+ end('c', 'reviewed')+ await settled(() => callsOf(agents, 'b').length === 2)+ assert.equal(textOf(callsOf(agents, 'b')[1][1].content), '[Reply from Tester]\nreviewed')+ take('b')+ end('b', 'noted')+ await delay(20)+ assert.equal(callsOf(agents, 'a').length, 1)+})-test('the team sends no more Bot messages past the unattended limit, counting group posts', async (t) => {- const { agents, tool, stop } = await start(team({ group: true }))- t.after(stop)- const send = () => tool('message_bot', { to: 'Writer', message: 'ping' }, 'a')+test('a result read during other work comes back in a turn of its own and goes on with its work', async (t) => {+ const team = await start(threeBots())+ t.after(team.stop)+ const { agents, emit } = team+ const { take, end, userTurn } = await handedOn(team)+ end('b', 'handed it on')+ take('c')+ end('c', 'reviewed')+ await settled(() => callsOf(agents, 'b').length === 2)+ const [, result] = callsOf(agents, 'b')[1]+ // The user's turn reads the result along with the user's message.+ userTurn('b', 'an unrelated question')+ emit('b', 'user/message', { content: result.content, source: result.source })+ end('b', 'the answer for the user')+ await settled(() => callsOf(agents, 'b').length === 3)+ const [kind, again] = callsOf(agents, 'b')[2]+ assert.equal(kind, 'followup')+ assert.equal(textOf(again.content), '[Reply from Tester · you read it during your last task; go on with the work it is for now · for the work Chief asked you for; your answer goes to Chief once everything you handed on is back]\nreviewed')+ assert.deepEqual(callsOf(agents, 'a'), [])+ take('b')+ end('b', 'done after the review')+ await settled(() => callsOf(agents, 'a').length === 1)+ assert.equal(textOf(callsOf(agents, 'a')[0][1].content), '[Reply from Writer]\ndone after the review\n\n[Handed back to Writer for this work]\n\nTester:\nreviewed')+})++test('deleting a Bot that waits for work it handed on tells the Bot that asked', async (t) => {+ const team = await start(threeBots())+ t.after(team.stop)+ const { agents, call, home } = team+ const { end } = await handedOn(team)+ end('b', 'handed it on')+ assert.equal((await call('delete-bot', { id: 'b' })).ok, true)+ await settled(() => callsOf(agents, 'a').length === 1)+ assert.equal(textOf(callsOf(agents, 'a')[0][1].content), '[Reply from Writer]\nWriter was deleted before it could answer your message.')+ assert.deepEqual(await worksIn(home), {})+})- for (let count = 1; count < MAX_UNATTENDED_MESSAGES; count += 1) await send()- assert.match(await tool('post_to_group', { group: 'Ops', message: 'note' }, 'a'), /^Posted in "Ops"/)- await assert.rejects(send(), spentBudget)- await assert.rejects(tool('post_to_group', { group: 'Ops', message: 'again' }, 'a'), spentBudget)- assert.equal(agents.get('b').calls.length, MAX_UNATTENDED_MESSAGES - 1)- assert.equal(agents.get('r1').calls.length, 1)+test('an answer that grows past 20,000 characters with what came back goes as a file', async (t) => {+ const team = await start(threeBots())+ t.after(team.stop)+ const { ctx, agents } = team+ const store = fakeAttachments()+ ctx.get = name => (name === 'attachments' ? store : undefined)+ const { take, end } = await handedOn(team)+ end('b', 'handed it on')+ take('c')+ const review = '审查意见。'.repeat(3000)+ end('c', review)+ await settled(() => callsOf(agents, 'b').length === 2)+ take('b')+ end('b', '改好了。'.repeat(1500))+ await settled(() => callsOf(agents, 'a').length === 1)+ const [text, file] = callsOf(agents, 'a')[0][1].content+ const whole = `${'改好了。'.repeat(1500)}\n\n[Handed back to Writer for this work]\n\nTester:\n${review}`+ assert.ok(text.text.startsWith(`[Reply from Writer]\n[A long message: ${whole.length} characters.`))+ assert.equal(file.attachment.name, 'Answer from Writer.txt')+ assert.equal(new TextDecoder().decode(store.files.get(file.attachment.attachmentId)), whole)})-test('the user, a question card\'s answer and a scheduled task each reset the unattended count; a goal does not', async (t) => {- const { emit, tool, stop } = await start(team({ group: true }))+test('Bots keep messaging and posting with no count of messages or rounds', async (t) => {+ const { agents, tool, stop } = await start(team({ group: true }))t.after(stop)- const send = () => tool('message_bot', { to: 'Writer', message: 'ping' }, 'a')- const spend = async (count) => {- for (let sent = 0; sent < count; sent += 1) await send()- await assert.rejects(send(), spentBudget)- }- const arrive = (id, source) => emit(id, 'user/message', { content: textBlock('next'), source })-- await spend(MAX_UNATTENDED_MESSAGES)- arrive('b', { kind: 'goal' })- await assert.rejects(send(), spentBudget)-- arrive('r1', { kind: 'user' })- await spend(MAX_UNATTENDED_MESSAGES)- arrive('a', { kind: REPLY_KIND })- await spend(MAX_UNATTENDED_MESSAGES)- arrive('b', { kind: 'schedule' })- await spend(MAX_UNATTENDED_MESSAGES)- arrive('a', { kind: 'user' })- assert.match(await send(), /^Delivered to Writer/)+ for (let count = 0; count < 60; count += 1) assert.match(await tool('message_bot', { to: 'Writer', message: `ping ${count}` }, 'a'), /^Delivered to Writer/)+ for (let count = 0; count < 5; count += 1) assert.match(await tool('post_to_group', { group: 'Ops', message: `note ${count}` }, 'a'), /^Posted in "Ops"/)+ assert.equal(agents.get('b').calls.length, 60)+ assert.equal(agents.get('r1').calls.length, 5)})test('an earlier part keeps the request its Bot answered', async () => {diff --git a/ds-bot/test/diagnostics.test.js b/ds-bot/test/diagnostics.test.jsindex 4b3e33c8..6749a271 100644--- a/ds-bot/test/diagnostics.test.js+++ b/ds-bot/test/diagnostics.test.js@@ -187,13 +187,12 @@ const failed = { kind: 'error', error: { code: 'SERVER', message: 'upstream busytest('a failed reply to message_bot tells the sender instead of leaving it waiting', () => {const { emit, delivered, noted } = turnsHost()emit('b', 'turn/start', { turn: 1 })- emit('b', 'user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: SOURCE_KIND, role: 'request', senderSessionId: 'a', exchangeId: 'x1', hop: 1 } })+ emit('b', 'user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: SOURCE_KIND, role: 'request', senderSessionId: 'a', exchangeId: 'x1' } })emit('b', 'turn/end', { turn: 1, reason: failed })assert.equal(delivered.length, 1)assert.equal(delivered[0].toId, 'a')assert.equal(delivered[0].role, 'reply')assert.equal(delivered[0].replyTo, 'x1')- assert.equal(delivered[0].hop, 1)assert.match(delivered[0].text, /^Writer could not answer your message: its model call failed \(SERVER 503: upstream busy\)/)assert.deepEqual(noted.map(entry => [entry.source, entry.code, entry.bot, entry.where]), [['turn', 'SERVER', 'Writer', 'own chat']])})diff --git a/ds-bot/test/group-work.test.js b/ds-bot/test/group-work.test.jsindex 199bd5bd..f89d0091 100644--- a/ds-bot/test/group-work.test.js+++ b/ds-bot/test/group-work.test.js@@ -266,36 +266,25 @@ test('late work the user asked for directly ends without a post once its resultassert.deepEqual(host.agentOf('r1').calls, [])})-test('a Bot\'s post keeps its hop through the round, the members it calls and the member\'s late reply', async (t) => {- t.mock.timers.enable({ apis: ['setTimeout'] })+test('replies a post waits for are work handed on: the answer to the Bot that asked waits for them and carries them', async (t) => {const host = await start(t)- host.emit('a', 'turn/start', { turn: 1 })- host.emit('a', 'user/message', { content: [{ type: 'text', text: '[Message from Tester]\npost it' }], source: { kind: 'bot', role: 'request', senderSessionId: 'c', senderName: 'Tester', exchangeId: 'x1', hop: 2 } })- await host.tool('post_to_group', { group: 'Ops', message: '@Writer 看一下文档' }, 'a')- const post = host.takePost()- assert.equal(post.source.hop, 3)-- const first = host.round('c1', post)+ await host.tool('message_bot', { to: 'Chief', message: '让群里看一下文档' }, 'c')+ host.begin('a')+ const posted = await host.tool('post_to_group', { group: 'Ops', message: '@Writer 看一下文档', report_back: true }, 'a')+ assert.match(posted, /your answer goes to Tester once all of it is back\.$/)+ host.finish('a', '已经让 Writer 去看了。')+ const done = host.round('c1', host.takePost())await settle(() => host.agentOf('gb').calls.length === 1)- assert.equal(host.begin('gb').source.hop, 3)- await host.tool('message_bot', { to: 'Tester', message: '帮我确认一下' }, 'gb')- host.emit('gb', 'tool/call', { callId: 'k1', name: 'pwsh', arguments: '{}' })- t.mock.timers.tick(ROOM_WORK_GRACE_MS)- await settle(() => host.agentOf('gc').calls.length === 1)- assert.equal(host.begin('gc').source.hop, 3)- host.finish('gc', '[PASS]')- await settle(() => first() !== undefined)-- host.emit('gb', 'tool/result', { callId: 'k1' })- host.finish('gb', '看完了。')- await settle(() => host.agentOf('r1').calls.length === 1)- const late = host.takePost()- assert.deepEqual([late.source.late, late.source.hop], [true, 3])- const second = host.round('c2', late)- await settle(() => host.agentOf('ga').calls.length === 1)- assert.equal(host.begin('ga').source.hop, 3)- host.finish('ga', '[PASS]')- await settle(() => second() !== undefined)+ host.begin('gb')+ host.finish('gb', '文档没问题。')+ await settle(() => done() !== undefined)+ await settle(() => host.agentOf('a').calls.length === 2)+ assert.deepEqual(host.agentOf('c').calls, [])+ const report = host.begin('a')+ assert.match(text(report), /^\[Group chat "Ops" · replies to your post · for the work Tester asked you for; your answer goes to Tester once everything you handed on is back\]/)+ host.finish('a', 'Writer 看过了,没问题。')+ await settle(() => host.agentOf('c').calls.length === 1)+ assert.equal(text(host.agentOf('c').calls[0]), '[Reply from Chief]\nWriter 看过了,没问题。\n\n[Handed back to Chief for this work]\n\nGroup "Ops":\nReplies to your post (oldest first):\nWriter: 文档没问题。')})test('a member called while still at earlier work lets the round go on at once', async (t) => {@@ -524,11 +513,11 @@ test('after the round went on, lines a member writes close together reach the grtest('a step that calls a member with @ after the round went on starts a round for that member', async (t) => {const host = await start(t)host.emit('gb', 'turn/start', { turn: 1 })- host.emit('gb', 'user/message', { content: [{ type: 'text', text: 'go' }], source: { kind: 'bot', role: 'room', exchangeId: 'x1', roomId: 'r1', hop: 1, askedBy: 'a' } })+ host.emit('gb', 'user/message', { content: [{ type: 'text', text: 'go' }], source: { kind: 'bot', role: 'room', exchangeId: 'x1', roomId: 'r1', askedBy: 'a' } })step(host, 'gb', '@Tester 帮我跑一下测试', 'k1')await settle(() => host.agentOf('r1').calls.length === 1)const post = host.takePost()- assert.deepEqual([post.source.progress, post.source.quiet, post.source.hop], [true, undefined, 1])+ assert.deepEqual([post.source.progress, post.source.quiet], [true, undefined])const result = host.round('c1', post)await settle(() => host.agentOf('gc').calls.length === 1)assert.equal(host.begin('gc').source.askedBy, 'b')diff --git a/ds-bot/test/rounds.test.js b/ds-bot/test/rounds.test.jsindex 196c8ea3..1e865c79 100644--- a/ds-bot/test/rounds.test.js+++ b/ds-bot/test/rounds.test.js@@ -253,32 +253,6 @@ test('in admin mode a plain mid-round message goes to the admin', async (t) => {assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer', 'User', 'Chief'])})-test('a mid-round user line resets the room\'s bot-round budget', async (t) => {- const { call, emit, userMessage, compose, relay, answer, stop, sent, ctx, home } = start()- t.after(stop)- const room = await team(call, sent)-- await emit(room.id, userMessage('Start'))- const running = relay(room.id, 'relay')- const first = await turnFor(sent)- await answer(first.sessionId, first.message.source.exchangeId, 'one', 1)- const second = await turnFor(sent, first)-- // A Main Bot posts into the room while the last member is still answering:- // that spends one bot-round budget.- const posted = await ctx.registeredTools.get('post_to_group').execute({ group: 'R1', message: 'bot note' }, { agent: { id: first.sessionId } })- const roomState = () => JSON.parse(readFileSync(join(home, 'state.json'), 'utf8')).rooms[room.id]- assert.equal(roomState().botRounds, 1, String(posted))-- // The user's mid-round message counts as the user speaking: the budget reopens.- await compose(room.id, '@Writer user back mid-round')- await answer(second.sessionId, second.message.source.exchangeId, 'two', 2)- const third = await turnFor(sent, first, second)- await answer(third.sessionId, third.message.source.exchangeId, 'three', 3)- JSON.parse(await running)- assert.equal(roomState().botRounds, 0)-})-test('a message with an image or a chat reference waits for its own round, and so does what follows it', async (t) => {const { call, emit, userMessage, compose, relay, inboxOf, answer, stop, sent } = start()t.after(stop)