A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Merge dev into feat/262-bot-handoffs
Fei24116d95a78d2997
diff --cc ds-bot/client.jsindex 0447abcb,f14c4a95..56c50e35--- a/ds-bot/client.js+++ b/ds-bot/client.js@@@ -4199,18 -4283,27 +4284,27 @@@ function TriggerCell({ node, sessionIdif (source.role === "kickoff" || source.role === "room") return null;if (source.role === "secret" || deferred) return null;if (source.role === "post") {- if (source.failed !== void 0 || source.resumed === true || source.stopped === true) return null;+ if (source.failed !== void 0 || source.resumed === true || source.stopped === true || source.done === true) return null;const room2 = roster.roomsById[sessionId];const poster = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t("a Bot"), color: "gray" };- const post = { bot: poster, text: stripHeader(contentText(data.content)), room: room2, roster, actions, msgKey: `${sessionId}:${data.turn}:post`, useUi };const file = source.length === void 0 ? void 0 : (data.content ?? []).find((block) => block?.type === "file")?.attachment;- return file ? (0, import_react6.createElement)(LongPost, { ...post, file, length: source.length }) : (0, import_react6.createElement)(GroupMessage, post);+ const text = stripHeader(contentText(data.content));+ return (0, import_react7.createElement)(GroupMessage, {+ bot: poster,+ text: file ? stripLongNote(text) : text,+ room: room2,+ roster,+ actions,+ msgKey: `${sessionId}:post:${data.seq ?? node.key}`,+ useUi,+ whole: file ? { length: source.length, load: () => actions.fileText(file) } : void 0+ });}if (source.role === "report") {- return (0, import_react6.createElement)(GroupEvent, { prefix: t("Replies from"), room: roster.roomsById[source.roomId], name: t("a group chat"), roster, actions });+ return (0, import_react7.createElement)(GroupEvent, { prefix: t("Replies from"), room: roster.roomsById[source.roomId], name: t("a group chat"), roster, actions });}- if (source.role === "resume" || source.resumed === true) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Picked up its work after a restart"));- if (source.role === "retry" || source.retried === true) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Asked to make the tool call it wrote as text"));+ if (source.role === "resume" || source.resumed === true) return (0, import_react7.createElement)("div", { className: "bt-event" }, t("Picked up its work after a restart"));+ if (source.role === "retry" || source.retried === true) return (0, import_react7.createElement)("div", { className: "bt-event" }, t("Asked to make the tool call it wrote as text"));const run = relayed ? commRunOf(order.split(",").filter(Boolean).map(Number),Object.fromEntries(peers.split(",").filter(Boolean).map((pair) => [Number(pair.slice(0, pair.indexOf(":"))), pair.slice(pair.indexOf(":") + 1)])),@@@ -4479,12 -4572,9 +4573,12 @@@ function GroupReplies({ sessionId, call);}if (reply.kind === "stopped") {- return (0, import_react6.createElement)("div", { key: `${reply.botId}-${index}`, className: "bt-event" }, t("You stopped {name}'s work", { name: bot.name }));+ return (0, import_react7.createElement)("div", { key: `${reply.botId}-${index}`, className: "bt-event" }, t("You stopped {name}'s work", { name: bot.name }));}+ if (reply.kind === "done") {- return (0, import_react6.createElement)("div", { key: `${reply.botId}-${index}`, className: "bt-event" }, t("{name} finished its work", { name: bot.name }));++ return (0, import_react7.createElement)("div", { key: `${reply.botId}-${index}`, className: "bt-event" }, t("{name} finished its work", { name: bot.name }));+ }- return (0, import_react6.createElement)(GroupMessage, { key: `${reply.botId}-${index}`, bot, texts: texts2, room: room2, roster, actions, msgKey: callId ? `${sessionId}:${callId}:${index}` : void 0, useUi });+ return (0, import_react7.createElement)(GroupMessage, { key: `${reply.botId}-${index}`, bot, texts: texts2, room: room2, roster, actions, msgKey: callId ? `${sessionId}:${callId}:${index}` : void 0, useUi });}),pending.map((id) => {const bot = roster.byId[id];diff --cc ds-bot/src/client/cells.jsindex df251a0e,24c00cad..feb42b25--- a/ds-bot/src/client/cells.js+++ b/ds-bot/src/client/cells.js@@@ -376,14 -372,19 +372,19 @@@ export function TriggerCell({ node, ses// The secret card itself shows what the user did; the note to the Bot stays out.if (source.role === 'secret' || deferred) return nullif (source.role === 'post') {- // A member's late failure, its work picked up after a restart, or its work the user- // stopped shows as an event of the round it opens.- if (source.failed !== undefined || source.resumed === true || source.stopped === true) return null+ // A member's late failure, its work picked up after a restart, its work the user+ // stopped, or the end of its work shows as an event of the round it opens.+ if (source.failed !== undefined || source.resumed === true || source.stopped === true || source.done === true) return nullconst room = roster.roomsById[sessionId]const poster = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t('a Bot'), color: 'gray' }- const post = { bot: poster, text: stripHeader(contentText(data.content)), room, roster, actions, msgKey: `${sessionId}:${data.turn}:post`, useUi }+ // A post past what a message holds came as a file, with its start only.const file = source.length === undefined ? undefined : (data.content ?? []).find(block => block?.type === 'file')?.attachment- return file ? h(LongPost, { ...post, file, length: source.length }) : h(GroupMessage, post)+ const text = stripHeader(contentText(data.content))+ // A trigger's data carries no turn; its event seq is the one durable name of this post.+ return h(GroupMessage, {+ bot: poster, text: file ? stripLongNote(text) : text, room, roster, actions, msgKey: `${sessionId}:post:${data.seq ?? node.key}`, useUi,+ whole: file ? { length: source.length, load: () => actions.fileText(file) } : undefined,+ })}if (source.role === 'report') {return h(GroupEvent, { prefix: t('Replies from'), room: roster.roomsById[source.roomId], name: t('a group chat'), roster, actions })diff --cc ds-bot/src/host/tools.jsindex 7df36822,e890b3c4..dcd264ad--- a/ds-bot/src/host/tools.js+++ b/ds-bot/src/host/tools.js@@@ -2,9 -2,9 +2,10 @@@// 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 { absoluteLinks } from './links.js'import { unquote } from './text.js'+import { mentionSpans } from '../shared/mentions.js'export const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] }export const GROUP_REF = { type: 'string', required: true, description: 'Exact group chat name from list_bots' }@@@ -152,43 -128,22 +153,43 @@@ export function install(rt)if (target === undefined) return `No Bot named ${args.to}. Team: ${Object.values(state.bots).map(bot => bot.name).join(', ')}`if (target.id === sender.id) return 'You cannot message yourself.'if (String(args.message ?? '').trim() === '') return 'Write a message to send.'- const 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.`)- }+ const text = absoluteLinks(String(args.message), rt.sessionFolder?.(exec.agent?.session ?? exec.agent))- const long = await rt.attachLong(text, `Message from ${sender.name}.txt`)- if (long === undefined) return tooLong(text)+ const room = rt.roomOf(rt.groupOwners.get(exec.agent?.id)?.roomId)- if (room !== undefined) return callInGroup(exec, room, sender, target, String(args.message ?? '').trim())++ if (room !== undefined) return callInGroup(exec, room, sender, target, text.trim())+ const posted = calledInPosts.get(exec.agent?.id)+ const postedIn = posted !== undefined && posted.turn === turnOf(exec) ? posted.calls.get(target.id) : undefined+ if (postedIn !== undefined) refuse(`Not sent: you called ${target.name} in "${postedIn}" in this turn, and it works on that there. Send each task one way only; to add to it, post in that group.`)+ // 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 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' } : callerRoom(exec)) })- 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@@@ -468,33 -422,24 +469,33 @@@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 text = String(args.message ?? '').trim()- const hop = nextHop(exec)- if (hop > MAX_HOPS) return CHAIN_TOO_LONG+ const text = absoluteLinks(String(args.message ?? '').trim(), rt.sessionFolder?.(exec.agent?.session ?? exec.agent))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}`}- 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 named = mentionSpans(text, room.members.map(rt.botOf).filter(Boolean)).flatMap(span => (span.bot ? [span.bot.id] : []))+ if (named.length > 0) {+ const turn = turnOf(exec)+ const earlier = calledInPosts.get(exec.agent?.id)+ const calls = new Map(earlier !== undefined && earlier.turn === turn ? earlier.calls : [])+ for (const id of named) calls.set(id, room.name)+ calledInPosts.set(exec.agent?.id, { turn, calls })+ }+ 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 --cc ds-bot/src/host/turns.jsindex f5c32a68,98e71958..c19e32b3--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@@ -2,7 -2,8 +2,8 @@@// 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 { absoluteLinks } from './links.js'import { textOf } from './text.js'import { reminderText } from './schedules.js'@@@ -589,13 -525,16 +591,16 @@@ export function install(rt)} else if (!stopped && reason?.kind !== 'aborted') {// The round moved on without this member; how its turn ends still reaches the group.if (failure !== undefined) void rt.lateRoomFailure?.(id, info, failure)- else void rt.lateRoomReply?.(id, info, groupReply())+ else void rt.lateRoomReply?.(id, info, groupReply(), { shown })}} else if (!retry && speaksInGroup(id, info)) {- if (failure !== undefined) void rt.lateRoomFailure?.(id, info ?? {}, failure)+ // A turn that failed before it took any input (DSH can turn it down before its+ // first step) never names its call, so the call waiting on this Session fails.+ const inRound = failure !== undefined && info === undefined && rt.failRoomTurn?.(id, failure) === true+ if (failure !== undefined) { if (!inRound) void rt.lateRoomFailure?.(id, info ?? {}, failure) }- else if (reason?.kind !== 'aborted') void rt.lateRoomReply?.(id, info ?? {}, groupReply())+ 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 finisheddiff --cc ds-bot/test/bot-messages.test.jsindex 11a55ff2,ef62204b..cfb21203--- a/ds-bot/test/bot-messages.test.js+++ b/ds-bot/test/bot-messages.test.js@@@ -483,168 -459,94 +483,169 @@@ 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)++// What state.json holds once the saves made so far are done: a save waits for the earlier++// ones, and a read while one renames the file over makes that save fail on Windows.++const worksIn = async ({ call, home }) => {++ await call('set-prefs', {})+ 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 { agents, tool } = 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(Object.values(await worksIn(team)).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), {})++ assert.deepEqual(await worksIn(team), {})})-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')-- 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('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 { agents, call } = 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), {})++ assert.deepEqual(await worksIn(team), {})+})++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 --cc ds-bot/test/rounds.test.jsindex 1e865c79,63d300fe..417ce93a--- a/ds-bot/test/rounds.test.js+++ b/ds-bot/test/rounds.test.js@@@ -322,6 -348,93 +322,94 @@@ test('a message sent between rounds stiassert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer'])})+ // #217: DSH opens a relative file link from the folder of the Session that shows it. A+ // member wrote the link in its own group Session, which works in the group's folder; the+ // group's Session and other Bots work elsewhere, so the link reaches them in full.+ test('a relative file link a member writes reaches the group, and another Bot, as a full path', async (t) => {+ const { call, emit, userMessage, relay, answer, stop, sent, ctx, rt } = start()+ t.after(stop)+ const folder = realpathSync.native(mkdtempSync(join(tmpdir(), 'ds-bot-links-')))+ t.after(() => rmSync(folder, { recursive: true, force: true }))+ const room = await team(call, sent)+ assert.equal((await call('update-room', { id: room.id, workDir: folder })).ok, true)+ const full = path => join(folder, path).replace(/\\/g, '/').replace(/ /g, '%20')+ await emit(room.id, userMessage('Where is the draft?'))+ const running = relay(room.id, 'relay')+ const first = await turnFor(sent)+ await answer(first.sessionId, first.message.source.exchangeId, 'It is in [a.txt](sub/a.txt).', 1)+ const second = await turnFor(sent, first)+ // The next member reads it in its prompt, and the group shows it, with the full path.+ assert.ok(second.message.content[0].text.includes(`[a.txt](${full('sub/a.txt')})`))+ await answer(second.sessionId, second.message.source.exchangeId, 'Thanks.', 2)+ const result = JSON.parse(await running)+ assert.equal(result.replies[0].text, `It is in [a.txt](${full('sub/a.txt')}).`)+- // A Bot that works in the folder sends the same link to another Bot.++ // A Bot that works in the folder sends the same link to another Bot; from its group++ // Session that calls the Bot in the group (#165).+ const chief = rt.state.mainBotIds[0]+ const writer = rt.state.rooms[room.id].members.find(id => id !== chief)+ sent.length = 0+ await ctx.registeredTools.get('message_bot').execute({ to: rt.botOf(writer).name, message: 'Read [notes](notes.md#L3)', when: 'queue' }, {+ agent: { id: first.sessionId, session: { id: first.sessionId, header: { cwd: folder } }, inbox: { nextStep: [], nextTurn: [] } }, callId: 'c1',+ })- const delivered = await waitFor(() => sent.find(entry => entry.message.source?.role === 'request'))++ const delivered = await waitFor(() => sent.find(entry => entry.sessionId === room.id && entry.message.source?.role === 'post'))+ assert.ok(delivered.message.content.map(block => block.text).join('\n').includes(`[notes](${full('notes.md')}#L3)`))+ })++ // #209: DSH can fail a member's turn before its first step (DSH 0.2.1 does so for a folder+ // that is gone), so the turn never takes the round's call. The round counts the failure at+ // once instead of waiting minutes for a reply that cannot come.+ test('a member turn that fails before it takes the call fails that member in the round at once', async (t) => {+ const { call, emit, userMessage, relay, answer, stop, sent } = 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 emit(first.sessionId, { type: 'turn/start', data: { turn: 1 } })+ await emit(first.sessionId, { type: 'turn/end', data: { reason: { kind: 'error', error: { message: 'working-directory: directory does not exist: "/gone"', code: 'UNKNOWN' } } } })+ const second = await turnFor(sent, first)+ assert.ok(second, 'the next member speaks without waiting for the reply timeout')+ await answer(second.sessionId, second.message.source.exchangeId, 'Writer here.', 1)+ const result = JSON.parse(await running)+ assert.deepEqual(result.replies.map(reply => [reply.kind ?? 'reply', reply.name]), [['failed', 'Chief'], ['reply', 'Writer']])+ })++ // A member deleted while its group Session is made sits the round out; the Session it was+ // getting belongs to no one, so it is archived instead of left over.+ test('a member deleted while its group Session is made is left out, and the Session is not kept', async (t) => {+ const { call, emit, userMessage, relay, answer, stop, sent, ctx, rt } = start()+ t.after(stop)+ const room = await team(call, sent)+ const writer = rt.state.rooms[room.id].members.find(id => !rt.isMain(id))+ const archived = []+ ctx.workspaceRegistry.archiveSession = async (sessionId) => { archived.push(sessionId) }+ await emit(room.id, userMessage('Start'))+ const running = relay(room.id, 'relay')+ const first = await turnFor(sent)++ let release+ const gate = new Promise(resolve => { release = resolve })+ let made+ const making = new Promise(resolve => { made = resolve })+ const create = ctx.sessionController.create+ ctx.sessionController.create = async (options) => {+ const result = await create(options)+ made(result.sessionId)+ await gate+ return result+ }+ await answer(first.sessionId, first.message.source.exchangeId, 'Chief here.', 1)+ const sessionId = await making+ assert.equal((await call('delete-bot', { id: writer })).ok, true)+ release()++ const result = JSON.parse(await running)+ assert.deepEqual(result.replies.map(reply => [reply.kind ?? 'reply', reply.name]), [['reply', 'Chief']])+ assert.ok(archived.includes(sessionId))+ assert.equal(rt.state.rooms[room.id].sessions?.[writer], undefined)+ })+// #206: state.json is written whole on every save, so a long group line keeps its start// there and its whole text in a file of its own. Members still read it whole.test('a long group line keeps its start in state.json, and members and read_group_chat read it whole', async (t) => {