A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Let a group round go on while a member works
Fei24114d87b334a5fa
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex 1f90bba4..640051a4 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, sessions, segments, ...room }) => {+ rooms: Object.values(state.rooms).map(({ log, seen, botRounds, 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}` } : {}) }@@ -67,10 +67,11 @@ export function install(rt) {})// What changes without a new revision, sent with every state answer. `memoryNews`:// per Bot, its latest memory change; `memoryReviews`: memory reviews waiting or- // running; `work`: per Bot, the turn it runs and its tool, and the approvals waiting.+ // running; `work`: per Bot, the turn it runs and its tool; per group, the members whose+ // turn there runs; and the approvals waiting.const live = () => ({activity: rt.activityView(),- work: { bots: rt.workView(), approvals: rt.approvalsView() },+ work: { bots: rt.workView(), rooms: rt.roomWorkView(), approvals: rt.approvalsView() },memoryNews: rt.memoryNews(),memoryReviews: rt.memoryReviews(),connectors: rt.connectorsView(),@@ -205,6 +206,8 @@ export function install(rt) {case 'approval-answer':rt.answerApproval(body.id, body.choice)return ok(true)+ case 'stop-member-work':+ return ok(await rt.stopMemberWork(String(body.roomId ?? ''), String(body.botId ?? '')))case 'dismiss-question':await rt.load()if (state.questions[body.sessionId] !== undefined) {diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.jsindex 0810dcf6..83064d41 100644--- a/ds-bot/src/host/constants.js+++ b/ds-bot/src/host/constants.js@@ -52,6 +52,12 @@ export const TEAM_TOOLS = []// 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 = 10+// A member still at work this long after its first tool call lets the round go on; it+// posts its reply when the work is done.+export const ROOM_WORK_GRACE_MS = 15_000export const OWN_CHAT_LINE_MAX = 400// The message an anchor points at is shown whole (up to this), so a long draft takesdiff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.jsindex 8471b10e..8b886ce0 100644--- a/ds-bot/src/host/delivery.js+++ b/ds-bot/src/host/delivery.js@@ -35,8 +35,9 @@ export function install(rt) {// turn of its own; its exchange was recorded when it first arrived. `resumed` and// `retried` carry on a turn that a restart cut off or that wrote its tool call as// text (resume.js, turns.js), and `resent` is a message a shutdown cancelled; their- // exchange is recorded already too.- 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 }) {+ // exchange is recorded already too. `askedBy` is the member whose @mention called a+ // group turn (groups.js).+ 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 }) {const from = rt.botOf(fromId)const to = rt.botOf(toId)if (to === undefined) throw new Error(`Unknown Bot ${toId}`)@@ -57,6 +58,7 @@ export function install(rt) {...(deferred ? { deferred: true } : {}),...(resumed ? { resumed: true } : {}),...(retried ? { retried: true } : {}),+ ...(askedBy ? { askedBy } : {}),}if (EXCHANGE_ROLES.has(role) && !deferred && !resumed && !retried && !resent) {state.exchanges.push({ id: exchangeId, from: fromId, to: toId, text, role, time: Date.now(), ...(replyTo ? { replyTo } : {}), ...(audience === 'user' ? { audience } : {}) })diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 3dc6ee50..c7c1fb5c 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -9,10 +9,15 @@// goes to every member in roster order, admin first, or to the admin alone in admin// mode; "@Name" picks members. A reply that @mentions a member calls that member// next, bounded per member and per round; the admin's calls reach further.+//+// Work does not hold a round up: a member that is still busy with tools a little after+// it started, or that is called while still at earlier work, lets the round go on. Its+// turn keeps running in its group Session, and what it ends with is posted to the group,+// where the member that asked for it answers.import { randomUUID } from 'node:crypto'import { createUserMessage } from '@deepseek-ai/dsh-llm'import { defineTool } from '@deepseek-ai/dsh-tools'-import { ROOM_BOT_ROUNDS, ROOM_REPLY_TIMEOUT_MS, SOURCE_KIND } from './constants.js'+import { ROOM_LATE_ROUNDS, ROOM_REPLY_TIMEOUT_MS, ROOM_WORK_GRACE_MS, SOURCE_KIND, TEAM_TOOLS } from './constants.js'import { escapeRegExp, splitRef, textOf } from './text.js'import { mentionSpans } from '../shared/mentions.js'import { GROUP_REF, output } from './tools.js'@@ -52,6 +57,7 @@ const lineText = (line) => {if (line.kind === 'lookup') return `[${line.who} looked up its own chat${line.text ? ` for "${line.text}"` : ''}]`if (line.kind === 'resumed') return `[${line.who}'s work here was cut off when DeepSeek Harness restarted; it is picking it back up and posts when done]`if (line.kind === 'cut') return `[${line.who}'s work here was cut off by a restart again, so it stopped; ask it to go on if it still matters]`+ if (line.kind === 'stopped') return `[The user stopped ${line.who}'s work here]`return `${line.who}: ${line.text}`}const transcript = lines => lines.map(lineText).join('\n')@@ -79,13 +85,15 @@ export const referenceNote = references => (references?.length? `Conversations the user referenced in this round:\n\n${references.map(reference => reference.text).join('\n\n')}`: '')-const ROOM_REPLY = 'Reply with your message for the group: one or two short messages, no name prefix. Reply [PASS] to stay silent when you have nothing new to add or the message is for someone else.'+const ROOM_REPLY = 'Reply with your message for the group, no name prefix: in a discussion, one or two short messages. When you are asked to do something, do it now with your tools. The group does not wait for you, and your final reply is posted here when you finish, so give the result, never a promise to do it later. Reply [PASS] to stay silent when you have nothing new to add or the message is for someone else.'+const ROOM_CALLS = 'Writing "@Name" calls that member next, to answer or to do what you ask; when it finishes work you gave it, you answer its result.'const slotLabel = (slot) => {if (slot.status === 'speaking') return `${slot.name} (you, now)`if (slot.status === 'posted') return `${slot.name} (posted)`if (slot.status === 'passed') return `${slot.name} (passed)`if (slot.status === 'missed') return `${slot.name} (no answer)`+ if (slot.status === 'working') return `${slot.name} (working on it; posts when done)`if (slot.status === 'waiting-approval') return `${slot.name} (waiting for the user's approval; posts when done)`if (slot.status === 'failed') return `${slot.name} (could not answer: error)`if (slot.status === 'left') return `${slot.name} (left the group)`@@ -95,7 +103,7 @@ const slotLabel = (slot) => {const adminNote = room => ['You are this group\'s admin.',room.mode === 'admin' ? 'Plain messages come to you first: answer them, or call the members who should answer with @Name.' : '',- 'Writing "@Name" calls that member to speak right after you, and "@all" calls every member. When the user asks, change the group with update_group.',+ '"@all" calls every member. When the user asks, change the group with update_group.',].filter(Boolean).join(' ')// The opening turn of a group the user just made without a first message.@@ -141,9 +149,10 @@ export function install(rt) {const index = round.slots.findIndex(slot => slot.status === 'speaking')const before = indexconst after = round.slots.length - index - 1- const members = `Members: the user${peers.length ? `, ${peers.join(', ')}` : ''} and you${leads ? ' (admin)' : ''}. Members speak one at a time; each message is posted before the next speaker starts.`+ const members = `Members: the user${peers.length ? `, ${peers.join(', ')}` : ''} and you${leads ? ' (admin)' : ''}. Members speak one at a time; each message is posted before the next speaker starts. ${ROOM_CALLS}`const notice = room.notice ? `Group notice (shared instructions for every member):\n${room.notice}` : ''if (round.kickoff) return [members, notice, leads ? adminNote(room) : '', roomKickoff(rt.uiLanguage?.())].filter(Boolean).join('\n\n')+ const working = workingIn(room).filter(item => item.bot.id !== member.id)return [members,notice,@@ -153,26 +162,41 @@ export function install(rt) {? `This round so far${spokeThisRound ? ', since your last message' : ', starting with the new message'} (oldest first):\n${transcript(current)}`: 'Nothing new in this round since your last message.',round.shown?.includes(member.id) ? '' : referenceNote(round.references),+ working.length > 0 ? `Still at work on what they were asked; each posts here when done: ${working.map(item => `${item.bot.name} (${minutesSince(item.since)} min)`).join(', ')}.` : '',`Speaking order for this round: ${round.slots.map(slotLabel).join(' → ')}.`,`You are number ${index + 1} of ${round.slots.length}. ${before === 0 ? 'Nobody spoke before you' : `${before} went before you`}${after === 0 ? ', and you are the last.' : `; ${after} after you will see your message.`}`,ROOM_REPLY,].filter(Boolean).join('\n\n')}+ // Members whose turn in this group is running, and since when.+ const workingIn = room => room.members.flatMap((id) => {+ const entry = rt.live.get(room.sessions?.[id])+ const bot = rt.botOf(id)+ return entry?.turn !== undefined && bot !== undefined ? [{ bot, since: entry.since ?? Date.now() }] : []+ })+ const minutesSince = at => Math.max(1, Math.round((Date.now() - at) / 60000))+// One member turn inside the room; resolves to its final text, `{ failure }` when its// model call failed, `{ missed }` when it went quiet for too long, `{ approval }` when- // it waits for the user's approval, or null when the round was stopped. The wait- // restarts on each event of the member's Session, so a member at work is never cut off.- async function roomTurn(room, member, sessionId, text, note, signal, started) {+ // it waits for the user's approval, `{ working }` when it goes on working without the+ // round, or null when the round was stopped. The wait restarts on each event of the+ // member's Session, so a member at work is never cut off. `by` is the member that+ // called it, which answers what the turn posts after the round moved on.+ async function roomTurn(room, member, sessionId, text, note, signal, started, by) {if (signal.aborted) return nullconst exchangeId = randomUUID()const turn = { botId: member.id, sessionId, exchangeId }started.push(turn)room.seen[member.id] = room.seq+ // Checked before the delivery, which may start the turn at once.+ const busy = rt.live.get(sessionId)?.turn !== undefinedconst done = new Promise((resolve) => {let timer+ let graceconst finish = (value) => {clearTimeout(timer)+ clearTimeout(grace)rt.roomWaiters.delete(exchangeId)resolve(value)}@@ -180,14 +204,17 @@ export function install(rt) {clearTimeout(timer)timer = setTimeout(() => finish({ missed: true }), ROOM_REPLY_TIMEOUT_MS)}+ const work = () => { grace ??= setTimeout(() => finish({ working: true }), ROOM_WORK_GRACE_MS) }touch()- rt.roomWaiters.set(exchangeId, { sessionId, botId: member.id, roomId: room.id, resolve: finish, fail: failure => finish({ failure }), touch, approval: () => finish({ approval: true }) })+ rt.roomWaiters.set(exchangeId, { sessionId, botId: member.id, roomId: room.id, resolve: finish, fail: failure => finish({ failure }), touch, work, approval: () => finish({ approval: true }) })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 })+ await rt.deliver({ fromId: undefined, toId: member.id, sessionId, role: 'room', roomId: room.id, exchangeId, note, text, ...(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.+ else if (busy) rt.roomWaiters.get(exchangeId)?.resolve({ working: true })} catch (error) {rt.warn('ds-bot: group delivery to %s failed: %s', member.name, error)rt.roomWaiters.get(exchangeId)?.resolve(null)@@ -208,17 +235,25 @@ export function install(rt) {}rt.touchRoomTurn = (sessionId) => { for (const waiter of waitersOf(sessionId)) waiter.touch() }rt.yieldRoomTurn = (sessionId) => { for (const waiter of waitersOf(sessionId)) waiter.approval() }+ // The team's own tools are quick; any other tool is the start of work.+ const QUICK_TOOLS = new Set(TEAM_TOOLS)+ rt.workRoomTurn = (sessionId, tool) => {+ if (QUICK_TOOLS.has(tool)) return+ for (const waiter of waitersOf(sessionId)) waiter.work()+ }// A called member moves up if it is still waiting, or gets one more turn if it// already spoke; either way it goes right after slot `index`. `cap` is the caller's- // per-member turn bound for the round.- function callMembers(round, turns, index, callees, note, cap) {+ // per-member turn bound for the round; `by` is the calling member, if a member called.+ function callMembers(round, turns, index, callees, note, cap, by) {let next = index + 1for (const peer of callees) {if ((turns.get(peer.id) ?? 0) >= cap) continueconst waiting = round.slots.findIndex((other, at) => at > index && other.id === peer.id && other.status === 'waiting')const called = waiting === -1 ? { id: peer.id, name: peer.name, status: 'waiting' } : round.slots.splice(waiting, 1)[0]called.note = note+ if (by === undefined) delete called.by+ else called.by = byround.slots.splice(next, 0, called)next += 1}@@ -261,6 +296,7 @@ export function install(rt) {}// The user spoke in this room, so Bots may start their own rounds again.room.botRounds = 0+ room.lateRounds = 0void rt.save().catch(() => {})return round.slots.length - before}@@ -299,7 +335,7 @@ export function install(rt) {const prompt = roomPrompt(room, member, round)round.shown?.push(member.id)const text = session.brief === undefined ? prompt : `${session.brief}\n\n${prompt}`- const reply = await roomTurn(room, member, session.id, text, slot.note ?? 'your turn', signal, round.started)+ const reply = await roomTurn(room, member, session.id, text, slot.note ?? 'your turn', signal, round.started, slot.by)round.speaking = nullif (reply?.failure !== undefined) {// Not a pass: the user sees why the member is silent, and the round goes on.@@ -315,6 +351,11 @@ export function install(rt) {round.replies.push({ kind: 'approval', botId: member.id, name: member.name, color: member.color, time: Date.now() })continue}+ if (reply?.working) {+ slot.status = 'working'+ round.replies.push({ kind: 'working', botId: member.id, name: member.name, color: member.color, time: Date.now() })+ continue+ }if (reply === null || reply?.missed || isPass(reply)) {slot.status = typeof reply === 'string' ? 'passed' : 'missed'round.passed.push(member.name)@@ -332,7 +373,7 @@ export function install(rt) {const { all, found: named } = mentionsIn(reply, everyone)const found = named.filter(other => other.id !== member.id)const callees = leads && all ? [...found, ...others.filter(other => !found.includes(other))] : found- callMembers(round, turns, index, callees, `${member.name} mentioned you`, leads ? ROOM_ADMIN_TURNS_EACH : ROOM_TURNS_EACH)+ callMembers(round, turns, index, callees, `${member.name} mentioned you`, leads ? ROOM_ADMIN_TURNS_EACH : ROOM_TURNS_EACH, member.id)}}@@ -353,26 +394,37 @@ export function install(rt) {const posts = queued.length > 0 ? queued : [{ text: '' }]const startSeq = room.seq + 1// The opening greeting is a cue for the admin, not a line of the group; a member's- // late failure, or its work picked up after a restart, is an event of the round.- for (const post of posts.filter(item => !item.kickoff && !item.failed && !item.resumed)) {+ // late failure, its work picked up after a restart, or its work the user stopped is+ // an event of the round.+ const event = item => item.failed || item.resumed || item.stopped+ for (const post of posts.filter(item => !item.kickoff && !event(item))) {// Image readings go into the log only; `@` names are picked from what the user typed.const text = post.images === undefined ? post.text : [post.text, ...await rt.imagesForGroup(post.images, room.id)].filter(Boolean).join('\n')appendRoom(room, post.botId? { who: rt.botOf(post.botId)?.name ?? post.name ?? 'Bot', botId: post.botId, text }: { who: 'User', text })}- if (posts.some(post => !post.botId && !post.kickoff)) room.botRounds = 0+ if (posts.some(post => !post.botId && !post.kickoff)) {+ room.botRounds = 0+ room.lateRounds = 0+ }await rt.save()// An event post never picks the speakers over a message queued with it.- const opener = posts.findLast(post => !post.failed && !post.resumed) ?? posts.at(-1)+ const opener = posts.findLast(post => !event(post)) ?? posts.at(-1)const references = posts.flatMap(post => post.references ?? [])+ // A member a Bot's post calls by name works for that Bot.+ const named = opener.botId === undefined ? [] : mentionsIn(opener.text ?? '', room.members.map(rt.botOf).filter(Boolean)).foundconst round = {roomId: room.id,members: room.members,startSeq,...(opener.kickoff ? { kickoff: true } : {}),...(references.length > 0 ? { references, shown: [] } : {}),- slots: openingSpeakers(room, opener).map(member => ({ id: member.id, name: member.name, status: 'waiting', ...(opener.kickoff ? { note: 'the group was just created' } : {}) })),+ slots: openingSpeakers(room, opener).map(member => ({+ id: member.id, name: member.name, status: 'waiting',+ ...(opener.kickoff ? { note: 'the group was just created' } : {}),+ ...(named.includes(member) ? { by: opener.botId } : {}),+ })),speaking: null,turns: 0,replies: [],@@ -387,13 +439,14 @@ export function install(rt) {round.replies.push({ kind: 'failed', botId: post.botId, name: bot?.name ?? post.name, color: bot?.color, code, ...(status ? { status } : {}), text: message, time: Date.now() })}// The log line tells the admin and the other members on their next turn.- for (const post of posts.filter(item => item.resumed)) {+ for (const post of posts.filter(item => item.resumed || item.stopped)) {const bot = rt.botOf(post.botId)const name = bot?.name ?? post.name- appendRoom(room, { who: name, botId: post.botId, kind: post.again ? 'cut' : 'resumed', text: '' })- round.replies.push({ kind: post.again ? 'cut' : 'resumed', botId: post.botId, name, color: bot?.color, time: Date.now() })+ const kind = post.stopped ? 'stopped' : post.again ? 'cut' : 'resumed'+ appendRoom(room, { who: name, botId: post.botId, kind, text: '' })+ round.replies.push({ kind, botId: post.botId, name, color: bot?.color, time: Date.now() })}- if (posts.some(post => post.resumed)) await rt.save()+ if (posts.some(post => post.resumed || post.stopped)) await rt.save()rt.roomProgress.set(exec.callId, round)try {await runRound(room, round, exec.signal, exec.agent)@@ -488,7 +541,9 @@ export function install(rt) {}))// A Bot that posts never answers its own post. @mentions choose the speakers; else- // the admin answers alone in admin mode, or first of everyone.+ // the admin answers alone in admin mode, or first of everyone. What a member posts+ // after its round moved on is answered by the member that asked for it; work the+ // user asked for is left for the user to read.function openingSpeakers(room, opener) {const everyone = room.members.map(rt.botOf).filter(Boolean)const members = everyone.filter(bot => bot.id !== opener.botId)@@ -497,7 +552,7 @@ export function install(rt) {if (opener.quiet) return []const { all, found: named } = mentionsIn(opener.text, everyone, opener.references)const found = named.filter(bot => bot.id !== opener.botId)- if (opener.late) return found.length > 0 ? found : admin ? [admin] : []+ if (opener.late) return found.length > 0 ? found : members.filter(bot => bot.id === opener.askedBy)if (found.length > 0 && !all) return foundif (!all && room.mode === 'admin' && admin) return [admin]return admin ? [admin, ...members.filter(bot => bot !== admin)] : members@@ -514,9 +569,10 @@ export function install(rt) {}rt.postToRoom = postToRoom- // A member the round moved on from (it went quiet or waited for an approval) posts- // what its turn ended with. Only the admin and anyone it names answer, and past the- // Bot round limit nobody does, so late posts cannot keep a group talking.+ // A member the round moved on from (it went on working, went quiet or waited for an+ // approval) posts what its turn ended with. The member that asked for it and anyone+ // it names answer; past the late round limit nobody does, so late posts cannot keep a+ // group talking.async function lateRoomReply(sessionId, info, reply) {const owner = rt.groupOwners.get(sessionId)const room = rt.roomOf(owner?.roomId ?? info.roomId)@@ -524,14 +580,29 @@ export function install(rt) {if (room === undefined || member === undefined || !room.members.includes(member.id)) returnconst text = stripOwnName(member.name, reply)if (isPass(text)) return- const quiet = (room.botRounds ?? 0) >= ROOM_BOT_ROUNDS- if (!quiet) room.botRounds = (room.botRounds ?? 0) + 1+ const quiet = (room.lateRounds ?? 0) >= ROOM_LATE_ROUNDS+ if (!quiet) room.lateRounds = (room.lateRounds ?? 0) + 1await rt.save()- await postToRoom(room, member, text, { late: true, ...(quiet ? { quiet: true } : {}) })+ await postToRoom(room, member, text, { late: 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+ // The user stops a member's work in this group from the group's details. Messages+ // still waiting for that member here go with it.+ async function stopMemberWork(roomId, botId) {+ await rt.load()+ const room = rt.roomOf(roomId)+ const member = rt.botOf(botId)+ const sessionId = room?.sessions?.[botId]+ if (room === undefined || member === undefined || sessionId === undefined || rt.live.get(sessionId)?.turn === undefined) return false+ const agent = await rt.resolveAgent(sessionId)+ agent.cancel({ kind: 'user' })+ await postToRoom(room, member, '', { quiet: true, stopped: true })+ return true+ }+ rt.stopMemberWork = stopMemberWork+// The round said such a member posts when done; a failed model call is how it ended.// Nobody answers it.async function lateRoomFailure(sessionId, info, failure) {@@ -562,8 +633,10 @@ export function install(rt) {async function reportRound(room, post, round) {const lines = round.replies.filter(reply => reply.kind === undefined).map(reply => `${reply.name}: ${reply.text}`)const waiting = round.replies.filter(reply => reply.kind === 'approval').map(reply => reply.name)+ const working = round.replies.filter(reply => reply.kind === 'working').map(reply => reply.name)const text = [lines.length > 0 ? `Replies to your post (oldest first):\n${lines.join('\n')}` : 'Nobody replied to your post.',+ working.length > 0 ? `Still working on it: ${working.join(', ')}. Each posts its result in the group when done, not to you; read_group_chat shows it.` : '',waiting.length > 0 ? `Waiting for the user's approval: ${waiting.join(', ')}. What they say afterwards is posted in the group, not sent to you; read_group_chat shows it.` : '',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(', ')}.` : '',diff --git a/ds-bot/src/host/prompt.js b/ds-bot/src/host/prompt.jsindex 41637ad9..33ab64cf 100644--- a/ds-bot/src/host/prompt.js+++ b/ds-bot/src/host/prompt.js@@ -15,7 +15,7 @@ const TEAM_RULES = ['- For "[Group chat …]", "[Message from …]", or "[Reply from …]" messages, do not write plans or progress updates: use tools silently, then reply with the answer. Simple answers do not need progress messages.','- Offer choices with ask_user (a tap-to-answer card) instead of long option lists in text. Calling it ends your turn at once, so write everything you want to say before the call, in the same reply. The answer arrives as the user\'s next message. Never use ask_user_question: it blocks you, and messages from other Bots would queue behind it.','- update_bot changes your own settings: name, role label, color, model, or instructions. Leave out bot to change yourself. Use it when the user asks you to change how you are set up. Only a Main Bot can change other Bots; when another Bot needs changing, ask a Main Bot.',- '- You may be in group chats with the user and other Bots. You speak in each group from a separate conversation of yours, apart from your own chat with the user. There your turn arrives as a "[Group chat …]" message that shows the speaking order, and your reply is posted to the group. In a group, read_own_chat shows your own chat (the group sees that you looked; share only what the group needs). In your own chat, read_group_chat shows what was said in a group. A group may have an admin, who steers it: the admin can call members with @Name, change the group with update_group, and start a new discussion there with post_to_group.',+ '- You may be in group chats with the user and other Bots. You speak in each group from a separate conversation of yours, apart from your own chat with the user. There your turn arrives as a "[Group chat …]" message that shows the speaking order, and your reply is posted to the group. When someone there asks you to do something, do the work in that turn: the group goes on without waiting, and your final reply is posted when you finish. Any member can hand work to another with @Name, and the one that asked answers the result. In a group, read_own_chat shows your own chat (the group sees that you looked; share only what the group needs). In your own chat, read_group_chat shows what was said in a group. A group may have an admin, who steers it: the admin can call members with @Name, change the group with update_group, and start a new discussion there with post_to_group.','- When you need a key, token, or password, call request_secret: the user types it into a secure card and you never see it. Never ask the user to paste one into the chat. Use it through its environment variable ($DSH_SECRET_<NAME> in bash, $env:DSH_SECRET_<NAME> in PowerShell) and never print it. list_secrets shows which keys exist.','- web_search results say which search backend answered. If web_search fails, never guess URLs or present pages you remember as search results: use a browser tool if you have one, otherwise tell the user that search is unavailable and the reason it gave.','- Your conversations are long-lived. When one grows long, either its older messages are condensed in place into a summary you wrote (a "[Checkpoint N]" message), or it moves on to a fresh part that opens with a handoff note you wrote and your latest messages (a "[Handoff · part N]" message). What leaves your working context stays saved. When you need the exact earlier wording or a detail the summary or note does not show in full (a full path, a figure, every item of a complete list or a final summary), call read_own_chat with words to look for, or with part N to read the note that closed an earlier part; never fill such a detail in from memory. Each line it returns starts with an anchor such as [part 2 #1234 · 10-08 14:22]; pass the anchor as around to read what was said around it.',diff --git a/ds-bot/src/host/resume.js b/ds-bot/src/host/resume.jsindex 86a9e930..d6e83ce6 100644--- a/ds-bot/src/host/resume.js+++ b/ds-bot/src/host/resume.js@@ -30,6 +30,7 @@ const triggerOf = info => ({...(info.roomId ? { roomId: info.roomId } : {}),...(typeof info.hop === 'number' ? { hop: info.hop } : {}),...(info.audience ? { audience: info.audience } : {}),+ ...(info.askedBy ? { askedBy: info.askedBy } : {}),})const readNotes = (file) => {@@ -158,7 +159,7 @@ export function install(rt) {// A turn already picked up once and cut off again stays stopped: a restart loop// must not run it forever.if (record.resumed) return- await rt.deliver({ toId: bot.id, sessionId: room.sessions?.[bot.id] ?? sessionId, role: 'room', roomId: room.id, note: 'picking up after a restart', resumed: true, text })+ await rt.deliver({ toId: bot.id, sessionId: room.sessions?.[bot.id] ?? sessionId, role: 'room', roomId: room.id, note: 'picking up after a restart', resumed: true, text, ...(record.trigger?.askedBy ? { askedBy: record.trigger.askedBy } : {}) })return}if (record.resumed) returndiff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex 72e816a5..951a41b0 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -58,6 +58,7 @@ export function install(rt) {hop: keeps ? info.hop ?? 0 : 0,...(keeps && info.exchangeId ? { exchangeId: info.exchangeId } : {}),...(keeps && info.audience ? { audience: info.audience } : {}),+ ...(keeps && info.askedBy ? { askedBy: info.askedBy } : {}),note: 'your tool call did not run',retried: true,text: RETRY_TEXT,@@ -187,6 +188,24 @@ export function install(rt) {return bots}+ // Per group, the members whose turn there is running; the round's current speaker is+ // marked, since its round shows it.+ const roomWorkView = () => {+ const speaking = new Set([...roomProgress.values()].map(round => `${round.roomId}:${round.speaking}`))+ const rooms = {}+ for (const [id, entry] of live) {+ const owner = rt.groupOwners.get(id)+ if (entry.turn === undefined || owner === undefined) continue+ rooms[owner.roomId] = [...(rooms[owner.roomId] ?? []), {+ botId: owner.botId,+ since: entry.since,+ ...(entry.tool ? { tool: entry.tool } : {}),+ ...(speaking.has(`${owner.roomId}:${owner.botId}`) ? { speaking: true } : {}),+ }]+ }+ return rooms+ }+// What a running tool call is about, for an approval card: its own description and// the command, path or address it acts on.const callDetail = (sessionId, callId) => {@@ -227,6 +246,7 @@ export function install(rt) {const name = String(event.data?.name ?? '')setActivity(id, name === 'ask_user' ? undefined : activityOf(name))entry.tool = name+ if (rt.groupOwners.has(id)) rt.workRoomTurn?.(id, name)if (typeof event.data?.callId === 'string') (entry.calls ??= new Map()).set(event.data.callId, String(event.data.arguments ?? ''))break}@@ -287,6 +307,8 @@ export function install(rt) {...(source.failed ? { failed: source.failed } : {}),...(source.resumed ? { resumed: true } : {}),...(source.again ? { again: true } : {}),+ ...(source.stopped ? { stopped: true } : {}),+ ...(source.askedBy ? { askedBy: source.askedBy } : {}),})} else if (source?.kind === SOURCE_KIND && source.role === 'kickoff' && rt.roomOf(id)) {queueRoomMessage(id, { text: '', kickoff: true })@@ -409,7 +431,14 @@ export function install(rt) {else void rt.lateRoomReply?.(id, info, replyText())}} else if (!retry && info !== undefined) {- answer(info, replyText())+ // A group Session speaks only in its group: the turn that takes a reply to a+ // message it sent from there posts what it ends with.+ if (rt.groupOwners.has(id) && (info.role === 'reply' || info.role === 'retry')) {+ if (failure !== undefined) void rt.lateRoomFailure?.(id, info, failure)+ else if (reason?.kind !== 'aborted') void rt.lateRoomReply?.(id, info, replyText())+ } else {+ answer(info, replyText())+ }}for (const request of joined) {// A failed or stopped turn closes the request like any other; a finished@@ -434,5 +463,5 @@ export function install(rt) {}})- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, callDetail, stopRoomTurn })+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, callDetail, stopRoomTurn })}diff --git a/ds-bot/test/group-status.test.js b/ds-bot/test/group-status.test.jsindex c30f33d3..8ffcc140 100644--- a/ds-bot/test/group-status.test.js+++ b/ds-bot/test/group-status.test.js@@ -147,13 +147,14 @@ test('an own chat\'s approval stays with DSH and is listed while it waits', asynassert.equal(await host.askApproval('elsewhere'), 'from-dsh')})-test('a member at work keeps its turn; one quiet for the whole wait is missed, and a later [PASS] stays out of the group', async (t) => {+test('a member still going keeps its turn; one quiet for the whole wait is missed, and a later [PASS] stays out of the group', async (t) => {t.mock.timers.enable({ apis: ['setTimeout'] })const host = await start()t.after(host.stop)const result = await openTurn(t, host)t.mock.timers.tick(ROOM_REPLY_TIMEOUT_MS - 1000)- host.emit('gb', 'tool/call', { callId: 'k1', name: 'shell', arguments: '{}' })+ // A team tool is quick: it does not let the round go on without the member.+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'list_bots', arguments: '{}' })t.mock.timers.tick(ROOM_REPLY_TIMEOUT_MS - 1000)await settle(() => true)assert.equal(result(), undefined)diff --git a/ds-bot/test/group-work.test.js b/ds-bot/test/group-work.test.jsnew file mode 100644index 00000000..38ac82ac--- /dev/null+++ b/ds-bot/test/group-work.test.js@@ -0,0 +1,244 @@+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 { test } from 'node:test'+import { apply } from '../index.js'+import { fakeContext } from './fake-ctx.js'+import { ROOM_LATE_ROUNDS, ROOM_WORK_GRACE_MS } from '../src/host/constants.js'++// Chief, the admin of group 'r1', speaks there from 'ga'; Writer from 'gb'; Tester from 'gc'.+const seed = (room = {}) => ({+ 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 },+ c: { id: 'c', name: 'Tester', role: 'Test', sessionId: 'c', createdAt: 3 },+ },+ rooms: { r1: { id: 'r1', name: 'Ops', members: ['a', 'b', 'c'], mode: 'admin', admin: 'a', named: true, sessions: { a: 'ga', b: 'gb', c: 'gc' }, log: [], seq: 0, seen: {}, ...room } },+ agents: {},+ exchanges: [],+ exchangeTurns: {},+ questions: {},+ prefs: {},+ revision: 0,+})++async function start(t, room) {+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-work-'))+ writeFileSync(join(home, 'state.json'), JSON.stringify(seed(room)))+ const ctx = fakeContext()+ const agents = new Map()+ const agentOf = (sessionId) => {+ if (!agents.has(sessionId)) {+ const calls = []+ const cancelled = []+ const held = []+ const inbox = {+ nextStep: [],+ nextTurn: held,+ remove(id) {+ const at = held.findIndex(message => message.id === id)+ if (at === -1) return false+ held.splice(at, 1)+ return true+ },+ }+ const keep = (message) => { calls.push(message); held.push(message) }+ agents.set(sessionId, { session: { id: sessionId }, calls, cancelled, inbox, followup: keep, steer: keep, cancel(reason) { cancelled.push(reason) } })+ }+ return agents.get(sessionId)+ }+ Object.assign(ctx, {+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },+ workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} },+ sessionController: { create: async () => ({ sessionId: 's1' }), resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }), selectModel: async () => {} },+ sessionTitle: { rename: async () => {} },+ sessions: { flush: async () => {} },+ })+ let route+ const register = ctx.connection.fetch.register+ ctx.connection.fetch.register = (options) => { route = options; return register(options) }+ apply(ctx, { home })+ t.after(async () => {+ await ctx.dispose()+ rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 })+ })+ let seq = 0+ const turns = new Map()+ 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, exec = {}) => ctx.registeredTools.get(name).execute(args, { agent: { id: sessionId }, ...exec })+ const call = async (endpoint, payload) => (await route.fetch(new Request('http://localhost/api/bot', { method: 'POST', body: JSON.stringify({ endpoint, payload }) }))).json()+ // A Session takes up the newest message it was sent, as a new turn.+ const begin = (sessionId) => {+ const message = agentOf(sessionId).calls.at(-1)+ agentOf(sessionId).inbox.nextTurn.length = 0+ const turn = (turns.get(sessionId) ?? 0) + 1+ turns.set(sessionId, turn)+ emit(sessionId, 'turn/start', { turn })+ emit(sessionId, 'user/message', { content: message.content, source: message.source })+ return message+ }+ const finish = (sessionId, reply) => {+ emit(sessionId, 'assistant/message', { message: { content: [{ type: 'text', text: reply }] } })+ emit(sessionId, 'turn/end', { turn: turns.get(sessionId), reason: { kind: 'completed' } })+ }+ // The user's message in the group, or a Bot's post the group Session took up, and the+ // round it starts.+ const round = (callId, message) => {+ emit('r1', 'user/message', message)+ let result+ const stop = new AbortController()+ t.after(() => stop.abort())+ void tool('group_relay', {}, 'r1', { callId, signal: stop.signal }).then((value) => { result = JSON.parse(value) })+ const read = () => result+ return read+ }+ const say = text => ({ content: [{ type: 'text', text }], source: { kind: 'user' } })+ const takePost = () => {+ const post = agentOf('r1').calls.shift()+ return { content: post.content, source: post.source }+ }+ await tool('list_bots', {}, 'a')+ return { home, agentOf, emit, tool, call, begin, finish, round, say, takePost }+}++const settle = async (check) => {+ const until = Date.now() + 3000+ while (!check() && Date.now() < until) await new Promise(resolve => setImmediate(resolve))+ assert.ok(check(), 'condition not reached')+}+const text = message => message.content.map(block => block.text ?? '').join('\n')+const kinds = result => result.replies.map(reply => [reply.kind ?? 'message', reply.name])++test('work past the grace lets the round go on, and the member that asked answers the result', async (t) => {+ t.mock.timers.enable({ apis: ['setTimeout'] })+ const host = await start(t)+ const first = host.round('c1', host.say('@Chief 安排一下文档'))+ await settle(() => host.agentOf('ga').calls.length === 1)+ host.begin('ga')+ host.finish('ga', '@Writer 把文档整理好')+ await settle(() => host.agentOf('gb').calls.length === 1)+ const called = host.begin('gb')+ assert.equal(called.source.askedBy, 'a')+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'pwsh', arguments: '{}' })+ t.mock.timers.tick(ROOM_WORK_GRACE_MS - 1)+ await settle(() => true)+ assert.equal(first(), undefined)+ t.mock.timers.tick(1)+ await settle(() => first() !== undefined)+ assert.deepEqual(kinds(first()), [['message', 'Chief'], ['working', 'Writer']])++ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.finish('gb', '整理好了,在 docs/ 下。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const post = host.takePost()+ assert.deepEqual([post.source.late, post.source.askedBy, text(post)], [true, 'a', '[Group post from Writer]\n整理好了,在 docs/ 下。'])+ const second = host.round('c2', post)+ await settle(() => host.agentOf('ga').calls.length === 2)+ assert.match(text(host.agentOf('ga').calls[1]), /Writer: 整理好了,在 docs\/ 下。/)+ host.begin('ga')+ host.finish('ga', '[PASS]')+ await settle(() => second() !== undefined)+ assert.deepEqual(host.agentOf('gc').calls, [])+})++test('a member called while still at earlier work lets the round go on at once', async (t) => {+ const host = await start(t)+ host.emit('gb', 'turn/start', { turn: 1 })+ const result = host.round('c1', host.say('@Writer 再看看这个'))+ await settle(() => result() !== undefined)+ assert.deepEqual(kinds(result()), [['working', 'Writer']])+ // The call waits for the work before it.+ assert.equal(host.agentOf('gb').inbox.nextTurn.length, 1)+})++test('a quick team tool does not let the round go on', async (t) => {+ t.mock.timers.enable({ apis: ['setTimeout'] })+ const host = await start(t)+ const result = host.round('c1', host.say('@Writer 谁在群里?'))+ await settle(() => host.agentOf('gb').calls.length === 1)+ host.begin('gb')+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'list_bots', arguments: '{}' })+ t.mock.timers.tick(ROOM_WORK_GRACE_MS * 2)+ await settle(() => true)+ assert.equal(result(), undefined)+ host.finish('gb', 'Chief、Tester 和我。')+ await settle(() => result() !== undefined)+ assert.deepEqual(kinds(result()), [['message', 'Writer']])+})++test('work the user asked for is left for the user to read, and the user\'s message resets the late limit', async (t) => {+ t.mock.timers.enable({ apis: ['setTimeout'] })+ const host = await start(t, { lateRounds: ROOM_LATE_ROUNDS - 1 })+ const first = host.round('c1', host.say('@Writer 整理文档'))+ await settle(() => host.agentOf('gb').calls.length === 1)+ host.begin('gb')+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'write', arguments: '{}' })+ t.mock.timers.tick(ROOM_WORK_GRACE_MS)+ await settle(() => first() !== undefined)+ // The user's message resets the limit.+ assert.equal(JSON.parse(readFileSync(join(host.home, 'state.json'), 'utf8')).rooms.r1.lateRounds, 0)+ host.finish('gb', '好了。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const post = host.takePost()+ assert.deepEqual([post.source.late, post.source.askedBy, post.source.quiet], [true, undefined, undefined])+ const second = host.round('c2', post)+ await settle(() => second() !== undefined)+ assert.deepEqual(second().replies, [])+ assert.deepEqual([host.agentOf('ga').calls.length, host.agentOf('gc').calls.length], [0, 0])+})++test('the late round limit makes a late post quiet', async (t) => {+ const host = await start(t, { lateRounds: ROOM_LATE_ROUNDS })+ 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: 0, askedBy: 'a' } })+ host.finish('gb', '做完了。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ assert.equal(host.takePost().source.quiet, true)+})++test('a group Session\'s turn that takes a reply posts what it ends with in the group', async (t) => {+ const host = await start(t)+ host.emit('gb', 'turn/start', { turn: 1 })+ host.emit('gb', 'user/message', { content: [{ type: 'text', text: '[Reply from Tester]\nok' }], source: { kind: 'bot', role: 'reply', exchangeId: 'x1', senderName: 'Tester', senderSessionId: 'c', hop: 1 } })+ host.finish('gb', 'Tester 说可以,我继续。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const post = host.takePost()+ assert.deepEqual([post.source.late, text(post)], [true, '[Group post from Writer]\nTester 说可以,我继续。'])+})++test('the user stops a member\'s work in a group, and the group shows it', async (t) => {+ const host = await start(t)+ assert.equal((await host.call('stop-member-work', { roomId: 'r1', botId: 'b' })).value, false)+ host.emit('gb', 'turn/start', { turn: 1 })+ assert.equal((await host.call('stop-member-work', { roomId: 'r1', botId: 'b' })).value, true)+ assert.deepEqual(host.agentOf('gb').cancelled, [{ kind: 'user' }])+ await settle(() => host.agentOf('r1').calls.length === 1)+ const post = host.takePost()+ assert.deepEqual([post.source.stopped, post.source.quiet], [true, true])+ const result = host.round('c1', post)+ await settle(() => result() !== undefined)+ assert.deepEqual(kinds(result()), [['stopped', 'Writer']])+ const log = JSON.parse(readFileSync(join(host.home, 'state.json'), 'utf8')).rooms.r1.log+ assert.deepEqual(log.map(line => [line.who, line.kind]), [['Writer', 'stopped']])+})++test('members still at work show in the team view and in the prompts of the others', async (t) => {+ const host = await start(t)+ host.emit('gb', 'turn/start', { turn: 1 })+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'pwsh', arguments: '{}' })+ const result = host.round('c1', host.say('@Tester 你怎么看'))+ await settle(() => host.agentOf('gc').calls.length === 1)+ assert.match(text(host.agentOf('gc').calls[0]), /Still at work on what they were asked; each posts here when done: Writer \(1 min\)\./)+ host.begin('gc')+ const { value } = await host.call('state', {})+ assert.deepEqual(value.work.rooms.r1.map(entry => [entry.botId, entry.tool, entry.speaking]), [['b', 'pwsh', undefined], ['c', undefined, true]])+ host.finish('gc', '没问题。')+ await settle(() => result() !== undefined)+})