A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Show a group member's messages while it works
Fei24114ad802b82714
diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.jsindex dae8be0e..a174520e 100644--- a/ds-bot/src/host/constants.js+++ b/ds-bot/src/host/constants.js@@ -30,6 +30,8 @@ export const MAX_UNREAD_REQUESTS = 10export const MAX_EXCHANGES = 600export const ROOM_REPLY_TIMEOUT_MS = 240_000export const SOURCE_KIND = 'bot'+// The fixed reply that opens a fresh conversation part; it is never shown or sent on.+export const HANDOFF_ACK = 'Noted. I have my handoff note and carry on from here.'// An answer from a question card, in the shape DSH's own late question replies use.export const REPLY_KIND = 'user-question-reply'// DSH's snapshot of a referenced conversation, logged right after the user's messagediff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex d2aef078..b58b92ec 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -181,13 +181,22 @@ export function install(rt) {})const minutesSince = at => Math.max(1, Math.round((Date.now() - at) / 60000))+ // A member's message in the round: in the log, for the members after it, and in the+ // round's replies, for the user.+ const postInRound = (room, round, member, text) => {+ appendRoom(room, { who: member.name, botId: member.id, text })+ round.replies.push({ botId: member.id, name: member.name, color: member.color, text, time: Date.now() })+ void rt.save().catch(() => {})+ }+// 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, `{ 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, round, by) {+ // called it, which answers what the turn posts after the round moved on. What the+ // member writes before its last step is posted at once and collected in `said`.+ async function roomTurn(room, member, sessionId, text, note, signal, round, by, said = []) {if (signal.aborted) return nullconst exchangeId = randomUUID()const turn = { botId: member.id, sessionId, exchangeId }@@ -210,8 +219,14 @@ export function install(rt) {timer = setTimeout(() => finish({ missed: true }), ROOM_REPLY_TIMEOUT_MS)}const work = () => { grace ??= setTimeout(() => finish({ working: true }), ROOM_WORK_GRACE_MS) }+ const say = (raw) => {+ const step = stripOwnName(member.name, raw)+ if (isPass(step)) return+ said.push(step)+ postInRound(room, round, member, step)+ }touch()- rt.roomWaiters.set(exchangeId, { sessionId, botId: member.id, roomId: room.id, resolve: finish, fail: failure => finish({ failure }), touch, work, approval: () => finish({ approval: true }) })+ rt.roomWaiters.set(exchangeId, { sessionId, botId: member.id, roomId: room.id, resolve: finish, fail: failure => finish({ failure }), touch, work, say, approval: () => finish({ approval: true }) })signal.addEventListener('abort', () => finish(null), { once: true })})try {@@ -342,42 +357,38 @@ 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, slot.by)+ const said = []+ const reply = await roomTurn(room, member, session.id, text, slot.note ?? 'your turn', signal, round, slot.by, said)round.speaking = null+ const final = typeof reply === 'string' && !isPass(reply) ? reply : undefinedif (reply?.failure !== undefined) {// Not a pass: the user sees why the member is silent, and the round goes on.slot.status = 'failed'round.failed.push(member.name)const { code, status, message } = reply.failureround.replies.push({ kind: 'failed', botId: member.id, name: member.name, color: member.color, code, ...(status ? { status } : {}), text: message, time: Date.now() })- continue- }- // The member's turn goes on in the background and posts when it ends.- if (reply?.approval) {+ } else if (reply?.approval) {+ // The member's turn goes on in the background and posts when it ends.slot.status = 'waiting-approval'round.replies.push({ kind: 'approval', botId: member.id, name: member.name, color: member.color, time: Date.now() })- continue- }- if (reply?.working) {+ } else 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)) {+ } else if (final !== undefined || (typeof reply === 'string' && said.length > 0)) {+ slot.status = 'posted'+ if (final !== undefined) postInRound(room, round, member, final)+ } else {slot.status = typeof reply === 'string' ? 'passed' : 'missed'round.passed.push(member.name)if (reply?.missed) round.replies.push({ kind: 'missed', botId: member.id, name: member.name, color: member.color, time: Date.now() })- continue}- slot.status = 'posted'- appendRoom(room, { who: member.name, botId: member.id, text: reply })- round.replies.push({ botId: member.id, name: member.name, color: member.color, text: reply, time: Date.now() })- void rt.save().catch(() => {})+ const spoken = final === undefined ? said : [...said, final]+ if (spoken.length === 0) continue// Only the admin's "@all" calls everyone, so a member cannot set off a storm.const leads = rt.isAdminOf(room, member.id)const everyone = room.members.map(rt.botOf).filter(Boolean)const others = everyone.filter(other => other.id !== member.id)- const { all, found: named } = mentionsIn(reply, everyone)+ const { all, found: named } = mentionsIn(spoken.join('\n\n'), everyone)const found = named.filter(other => other.id !== member.id)const callees = leads && all ? [...found, ...others.filter(other => !found.includes(other))] : foundcallMembers(round, turns, index, callees, `${member.name} mentioned you`, leads ? ROOM_ADMIN_TURNS_EACH : ROOM_TURNS_EACH, member.id)@@ -561,6 +572,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.progress) return foundif (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]@@ -597,6 +609,29 @@ export function install(rt) {}rt.lateRoomReply = lateRoomReply+ // A step's text from a member's turn in its group Session. While the member holds its+ // place in a round, the text joins that round. Later, it joins whatever round runs in+ // the group, or posts on its own. Only the members it calls with @ answer it, and not+ // past the late round limit; the member that asked for the work answers the result.+ rt.roomStepText = async (sessionId, info, raw) => {+ const waiter = info?.role === 'room' ? rt.roomWaiters.get(info.exchangeId) : undefined+ if (waiter !== undefined) return waiter.say(raw)+ const owner = rt.groupOwners.get(sessionId)+ const room = rt.roomOf(owner?.roomId ?? info?.roomId)+ const member = rt.botOf(owner?.botId)+ if (room === undefined || member === undefined || !room.members.includes(member.id)) return+ const text = stripOwnName(member.name, raw)+ if (isPass(text)) return+ ensureRoomLog(room)+ const calls = mentionsIn(text, room.members.map(rt.botOf).filter(Boolean)).found.some(bot => bot.id !== member.id)+ const running = [...rt.roomProgress.values()].find(round => round.roomId === room.id)+ if (!calls && running !== undefined) return postInRound(room, running, member, text)+ const quiet = !calls || (room.lateRounds ?? 0) >= ROOM_LATE_ROUNDS+ if (!quiet) room.lateRounds = (room.lateRounds ?? 0) + 1+ await rt.save()+ await postToRoom(room, member, text, { progress: true, hop: info?.hop ?? 0, ...(quiet ? { quiet: true } : {}) })+ }+// 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) {diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex 37647a7e..73ab3ed5 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -16,7 +16,7 @@// read_own_chat searches every part, the condensed messages included.import { randomUUID } from 'node:crypto'import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'-import { HISTORY_TIMEOUT_MS, REPLY_KIND, SOURCE_KIND } from './constants.js'+import { HANDOFF_ACK, HISTORY_TIMEOUT_MS, REPLY_KIND, SOURCE_KIND } from './constants.js'import { CHECKPOINT_PROMPT, STEWARD_SYSTEM, checkpointCount, checkpointTail, checkpointTailNote, checkpointText, linesFor, parseDecision, stewardRequest } from './steward.js'import { clip, createClock, escapeRegExp, estimateTokens, splitRef, textOf } from './text.js'@@ -140,7 +140,6 @@ export function install(rt) {// A failed connection says nothing about the conversation, so it never moves a part on.const STUCK_CODES = ['INVALID_REQUEST', 'IMAGE_OFFLOAD_REQUIRED']const ORIGINAL_COMPACT = Symbol.for('ds-bot/compaction')- const HANDOFF_ACK = 'Noted. I have my handoff note and carry on from here.'const STEWARD_MAX_TOKENS = 4_096const STEWARD_TIMEOUT_MS = 120_000const STEWARD_LINES = 40diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex 39547082..f062a5e8 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 { REFERENCE_KIND, REPLY_KIND, SOURCE_KIND } from './constants.js'+import { HANDOFF_ACK, REFERENCE_KIND, REPLY_KIND, SOURCE_KIND } from './constants.js'import { textOf } from './text.js'import { reminderText } from './schedules.js'@@ -107,7 +107,7 @@ export function install(rt) {const liveOf = id => {let entry = live.get(id)- if (entry === undefined) live.set(id, entry = { texts: [] })+ if (entry === undefined) live.set(id, entry = { texts: [], shown: 0 })return entry}@@ -166,6 +166,22 @@ export function install(rt) {// Roles whose turn owes the sender a reply: a 'stopped' notice asks the Bot to// acknowledge, exactly like a request.const expectsReply = info => info.role === 'request' || info.role === 'stopped'+ // A group Session speaks only in its group, so what its turns write goes there, also+ // for turns that a finished background job or a fresh part starts; a Bot's private+ // message to it is answered privately.+ const speaksInGroup = (id, info) => rt.groupOwners.has(id) && !(info !== undefined && expectsReply(info))++ // The group sees each step's text while the member works. A text with a tool call is+ // shown at once; one without may be the turn's last, so it waits for the next text or+ // the turn's end, which shows the rest as the turn's reply.+ const showSteps = (id, entry, upTo) => {+ const info = entry.info+ if (!speaksInGroup(id, info) || (info?.role === 'room' && stoppedRoomTurns.has(info.exchangeId))) return+ for (; entry.shown < upTo; entry.shown += 1) {+ const text = stripWrittenCalls(entry.texts[entry.shown])+ if (text !== '') void rt.roomStepText?.(id, info, text)?.catch(error => rt.warn('ds-bot: step text from %s not posted: %s', id, error))+ }+ }// A group Session is hidden as a whole, so its turns need no marking. A handoff// package that only opens a part is acknowledged with a fixed line, also hidden.@@ -291,6 +307,7 @@ export function install(rt) {entry.turn = event.data.turnentry.since = event.time ?? Date.now()entry.texts = []+ entry.shown = 0entry.info = undefined// A turn turned away before its first step may end without a turn/end.entry.switched = false@@ -335,6 +352,7 @@ export function install(rt) {reportBack: source.reportBack === true,hop: source.hop ?? 0,...(source.late ? { late: true } : {}),+ ...(source.progress ? { progress: true } : {}),...(source.quiet ? { quiet: true } : {}),...(source.failed ? { failed: source.failed } : {}),...(source.resumed ? { resumed: true } : {}),@@ -383,22 +401,28 @@ export function install(rt) {case 'assistant/message': {const content = event.data?.message?.contentconst text = textOf(content)- if (text !== '') entry.texts.push(text)+ const called = Array.isArray(content) && content.some(block => block?.type === 'tool-call')+ if (text !== '' && text !== HANDOFF_ACK) {+ entry.texts.push(text)+ if (entry.turn !== undefined) showSteps(id, entry, called ? entry.texts.length : entry.texts.length - 1)+ }entry.lastText = text- entry.lastCalled = Array.isArray(content) && content.some(block => block?.type === 'tool-call')+ entry.lastCalled = calledbreak}case 'turn/end': {setActivity(id, undefined)const info = entry.infoconst joined = entry.joined ?? []- const texts = entry.texts+ // What the group already saw of the turn is not posted again.+ const texts = entry.texts.slice(entry.shown)const { lastText, lastCalled } = entry// A turn stopped for a switch goes on in the next part, which answers instead.const switched = entry.switched === trueentry.turn = undefinedentry.info = undefinedentry.texts = []+ entry.shown = 0entry.switched = falseentry.joined = []entry.since = undefined@@ -467,15 +491,11 @@ export function install(rt) {if (failure !== undefined) void rt.lateRoomFailure?.(id, info, failure)else void rt.lateRoomReply?.(id, info, replyText())}+ } else if (!retry && speaksInGroup(id, info)) {+ if (failure !== undefined) void rt.lateRoomFailure?.(id, info ?? {}, failure)+ else if (reason?.kind !== 'aborted') void rt.lateRoomReply?.(id, info ?? {}, replyText())} else if (!retry && info !== undefined) {- // 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())- }+ answer(info, replyText())}for (const request of joined) {// A failed or stopped turn closes the request like any other; a finisheddiff --git a/ds-bot/test/group-work.test.js b/ds-bot/test/group-work.test.jsindex ffab47e8..b1ffa89e 100644--- a/ds-bot/test/group-work.test.js+++ b/ds-bot/test/group-work.test.js@@ -317,3 +317,141 @@ test('members still at work show in the team view and in the prompts of the othehost.finish('gc', '没问题。')await settle(() => result() !== undefined)})++// A step that says something and calls a tool, as a model writes it while it works.+const step = (host, sessionId, said, callId, name = 'pwsh', args = '{}') => {+ host.emit(sessionId, 'assistant/message', { message: { content: [{ type: 'text', text: said }, { type: 'tool-call', id: callId, name }] } })+ host.emit(sessionId, 'tool/call', { callId, name, arguments: args })+}+const progress = async host => (await host.call('room-progress', { roomId: 'r1' })).value[0]++test('what a member writes while it works shows in the round at once, and its @ calls members', async (t) => {+ const host = await start(t)+ const result = host.round('c1', host.say('@Writer 整理文档'))+ await settle(() => host.agentOf('gb').calls.length === 1)+ host.begin('gb')+ step(host, 'gb', '收到,我先看看 docs/ 的结构。@Tester 你等下帮我验一下', 'k1', 'list_bots')+ await settle(() => true)+ const live = await progress(host)+ assert.deepEqual(live.replies.map(reply => [reply.name, reply.text]), [['Writer', '收到,我先看看 docs/ 的结构。@Tester 你等下帮我验一下']])+ assert.equal(live.speaking, 'b')+ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.finish('gb', '整理好了。')+ await settle(() => host.agentOf('gc').calls.length === 1)+ assert.match(text(host.begin('gc')), /Writer: 收到,我先看看 docs\/ 的结构。[\s\S]*Writer: 整理好了。/)+ host.finish('gc', '验过了。')+ await settle(() => result() !== undefined)+ assert.deepEqual(result().replies.map(reply => [reply.name, reply.text]), [['Writer', '收到,我先看看 docs/ 的结构。@Tester 你等下帮我验一下'], ['Writer', '整理好了。'], ['Tester', '验过了。']])+ const log = JSON.parse(readFileSync(join(host.home, 'state.json'), 'utf8')).rooms.r1.log+ assert.deepEqual(log.map(line => line.who), ['User', 'Writer', 'Writer', 'Tester'])+})++test('a member whose every message went out while it worked counts as posted, not passed', async (t) => {+ const host = await start(t)+ const result = host.round('c1', host.say('@Writer 看一下'))+ await settle(() => host.agentOf('gb').calls.length === 1)+ host.begin('gb')+ step(host, 'gb', '我看一下。', 'k1', 'list_bots')+ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.emit('gb', 'turn/end', { turn: 1, reason: { kind: 'completed' } })+ await settle(() => result() !== undefined)+ assert.deepEqual([result().passed, result().replies.map(reply => reply.text)], [[], ['我看一下。']])+})++test('after the round went on, each step posts to the group; only the result is answered', 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)+ host.begin('gb')+ step(host, 'gb', '收到,开始整理。', 'k1')+ t.mock.timers.tick(ROOM_WORK_GRACE_MS)+ await settle(() => first() !== undefined)+ assert.deepEqual(kinds(first()), [['message', 'Chief'], ['message', 'Writer'], ['working', 'Writer']])++ host.emit('gb', 'tool/result', { callId: 'k1' })+ step(host, 'gb', '目录理好了,在改索引。', 'k2')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const update = host.takePost()+ assert.deepEqual([update.source.progress, update.source.quiet, update.source.askedBy, text(update)], [true, true, undefined, '[Group post from Writer]\n目录理好了,在改索引。'])+ const quiet = host.round('c2', update)+ await settle(() => quiet() !== undefined)+ assert.deepEqual(quiet().replies, [])++ host.emit('gb', 'tool/result', { callId: 'k2' })+ host.finish('gb', '整理好了,在 docs/ 下。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const done = host.takePost()+ assert.deepEqual([done.source.late, done.source.askedBy, text(done)], [true, 'a', '[Group post from Writer]\n整理好了,在 docs/ 下。'])+})++test('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' } })+ 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])+ const result = host.round('c1', post)+ await settle(() => host.agentOf('gc').calls.length === 1)+ assert.equal(host.begin('gc').source.askedBy, 'b')+ host.finish('gc', '测试过了。')+ await settle(() => result() !== undefined)+ assert.deepEqual(host.agentOf('ga').calls, [])+})++test('a step joins a round that is running 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: 'go' }], source: { kind: 'bot', role: 'room', exchangeId: 'x1', roomId: 'r1', hop: 0 } })+ const result = host.round('c1', host.say('@Tester 你怎么看'))+ await settle(() => host.agentOf('gc').calls.length === 1)+ step(host, 'gb', '索引改完了。', 'k1')+ await settle(() => true)+ host.begin('gc')+ host.finish('gc', '没问题。')+ await settle(() => result() !== undefined)+ assert.deepEqual(result().replies.map(reply => [reply.name, reply.text]), [['Writer', '索引改完了。'], ['Tester', '没问题。']])+ assert.deepEqual(host.agentOf('r1').calls, [])+})++test('a turn that a finished background job starts in a group Session posts to 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: 'background job pwsh-3 finished' }], source: { kind: 'tool-jobs', form: 'notice' } })+ step(host, 'gb', '下载完了,开始解压。', 'k1')+ await settle(() => host.agentOf('r1').calls.length === 1)+ assert.equal(text(host.takePost()), '[Group post from Writer]\n下载完了,开始解压。')+ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.finish('gb', '解压好了。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const post = host.takePost()+ assert.deepEqual([post.source.late, post.source.askedBy, text(post)], [true, undefined, '[Group post from Writer]\n解压好了。'])+})++test('a fresh part\'s opening line stays out of 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: '[Handoff · part 2]' }], source: { kind: 'bot', role: 'handoff', handoff: true, exchangeId: 'h1', hop: 0 } })+ host.emit('gb', 'assistant/message', { message: { content: [{ type: 'text', text: 'Noted. I have my handoff note and carry on from here.' }] } })+ host.emit('gb', 'user/message', { content: [{ type: 'text', text: 'background job pwsh-7 finished' }], source: { kind: 'tool-jobs', form: 'notice' } })+ host.finish('gb', 'Ghidra 解压好了。')+ await settle(() => host.agentOf('r1').calls.length === 1)+ assert.equal(text(host.takePost()), '[Group post from Writer]\nGhidra 解压好了。')+})++test('a private message to a group Session is answered privately, without steps 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: '[Message from Tester]\n能帮我看下吗' }], source: { kind: 'bot', role: 'request', senderSessionId: 'c', senderName: 'Tester', exchangeId: 'x1', hop: 0 } })+ step(host, 'gb', '我看一下。', 'k1')+ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.finish('gb', '看过了,没问题。')+ await settle(() => host.agentOf('c').calls.length === 1)+ assert.match(text(host.agentOf('c').calls[0]), /我看一下。\n\n看过了,没问题。/)+ assert.deepEqual(host.agentOf('r1').calls, [])+})