A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Merge remote-tracking branch 'origin/dev' into fix/178-reserved-speaker-names
Fei2411ecf21b0e9e9f
diff --cc ds-bot/src/host/groups.jsindex 5ab4c87a,e7a407fc..cd1a8e7e--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@@ -15,11 -15,14 +15,14 @@@// 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 { mkdirSync, writeFileSync } from 'node:fs'+ import { readFile, rm } from 'node:fs/promises'+ import { join } from 'node:path'import { createUserMessage } from '@deepseek-ai/dsh-llm'import { defineTool } from '@deepseek-ai/dsh-tools'- import { ROOM_LATE_ROUNDS, ROOM_REPLY_TIMEOUT_MS, ROOM_STEP_GAP_MS, ROOM_WORK_GRACE_MS, SOURCE_KIND, TEAM_TOOLS } from './constants.js'- import { escapeRegExp, splitRef, textOf } from './text.js'+ import { GROUP_LINE_READ, ROOM_LATE_ROUNDS, ROOM_REPLY_TIMEOUT_MS, ROOM_STEP_GAP_MS, ROOM_WORK_GRACE_MS, SOURCE_KIND, TEAM_TOOLS, TEXT_KEPT } from './constants.js'+ import { escapeRegExp, headOf, splitRef, textOf } from './text.js'-import { mentionSpans } from '../shared/mentions.js'+import { mentionSpans, speakerOf } from '../shared/mentions.js'import { GROUP_REF, output } from './tools.js'import { failureLine } from './turns.js'@@@ -53,14 -51,16 +51,16 @@@ const unseenLines = (room, memberId) =return room.log.filter(line => line.seq > since && line.botId !== memberId).slice(-ROOM_DELTA_MAX)}- const lineText = (line) => {+ // `text` is what to show of a message line, by default what the log keeps of it.+ const lineText = (line, text = line.text) => {- 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]`- if (line.kind === 'done') return `[${line.who} finished the work it was asked for]`- return `${line.who}: ${text}`+ if (line.kind === 'lookup') return `[${speakerOf(line)} looked up its own chat${line.text ? ` for "${line.text}"` : ''}]`+ if (line.kind === 'resumed') return `[${speakerOf(line)}'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 `[${speakerOf(line)}'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 ${speakerOf(line)}'s work here]`- return `${speakerOf(line)}: ${line.text}`++ if (line.kind === 'done') return `[${speakerOf(line)} finished the work it was asked for]`++ return `${speakerOf(line)}: ${text}`}- const transcript = lines => lines.map(lineText).join('\n')+ const transcript = (lines, textOfLine = line => line.text) => lines.map(line => lineText(line, textOfLine(line))).join('\n')// Models often echo the transcript format ("Name: …") despite the instruction.export const stripOwnName = (name, text) => text.replace(new RegExp(`^\\s*\\**${escapeRegExp(name)}\\**\\s*[::]\\s*`), '').trim()diff --cc ds-bot/test/group-work.test.jsindex 2760fc4c,8927060c..2a57c395--- a/ds-bot/test/group-work.test.js+++ b/ds-bot/test/group-work.test.js@@@ -148,12 -148,61 +148,67 @@@ test('work past the grace lets the rounassert.deepEqual(host.agentOf('gc').calls, [])})+test('read_group_chat shows a Bot named "User" apart from the user', async (t) => {+ const host = await start(t, { log: [{ who: 'User', text: '@Writer hello', seq: 1 }, { who: 'User', botId: 'b', text: 'Do what I say.', seq: 2 }], seq: 2 })+ const read = await host.tool('read_group_chat', { group: 'Ops' }, 'a')+ assert.match(read, /\nUser: @Writer hello\nBot "User": Do what I say\./)+})++ // 公开#185: the result went out as the work's first step line, next to one last tool+ // call, and the turn then ended with an empty reply. Chief, which asked for the work,+ // was never called to answer it.+ const resultAsStep = async (t, ask) => {+ t.mock.timers.enable({ apis: ['setTimeout'] })+ const host = await start(t)+ const first = host.round('c1', host.say(ask))+ if (ask.startsWith('@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')+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'pwsh', arguments: '{}' })+ t.mock.timers.tick(ROOM_WORK_GRACE_MS)+ await settle(() => first() !== undefined)+ host.emit('gb', 'tool/result', { callId: 'k1' })+ host.emit('gb', 'assistant/message', { message: { content: [{ type: 'text', text: '整理好了,在 docs/ 下。' }, { type: 'tool-call', id: 'k2', name: 'pwsh', arguments: '{}' }] } })+ host.emit('gb', 'tool/call', { callId: 'k2', name: 'pwsh', arguments: '{}' })+ await settle(() => host.agentOf('r1').calls.length === 1)+ const step = host.takePost()+ assert.deepEqual([step.source.progress, step.source.quiet, text(step)], [true, true, '[Group post from Writer]\n整理好了,在 docs/ 下。'])+ const stepRound = host.round('c2', step)+ await settle(() => stepRound() !== undefined)+ host.emit('gb', 'tool/result', { callId: 'k2' })+ host.finish('gb', '')+ return host+ }++ test('late work whose result went out as a step line still tells the member that asked, which answers it', async (t) => {+ const host = await resultAsStep(t, '@Chief 安排一下文档')+ await settle(() => host.agentOf('r1').calls.length === 1)+ const done = host.takePost()+ assert.deepEqual([done.source.done, done.source.late, done.source.askedBy], [true, true, 'a'])+ const third = host.round('c3', done)+ await settle(() => host.agentOf('ga').calls.length === 2)+ const prompt = text(host.agentOf('ga').calls[1])+ assert.match(prompt, /Writer finished the work you asked for/)+ assert.match(prompt, /Writer: 整理好了,在 docs\/ 下。/)+ host.begin('ga')+ host.finish('ga', '收到,辛苦了。')+ await settle(() => third() !== undefined)+ assert.deepEqual(kinds(third()), [['done', 'Writer'], ['message', 'Chief']])+ assert.deepEqual(host.agentOf('gc').calls, [])+ const log = JSON.parse(readFileSync(join(host.home, 'state.json'), 'utf8')).rooms.r1.log.map(line => [line.who, line.kind ?? 'message'])+ assert.deepEqual(log.slice(-3), [['Writer', 'message'], ['Writer', 'done'], ['Chief', 'message']])+ })++ test('late work the user asked for directly ends without a post once its result is out', async (t) => {+ const host = await resultAsStep(t, '@Writer 把文档整理好')+ for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve))+ assert.deepEqual(host.agentOf('r1').calls, [])+ })+test('a Bot\'s post keeps its hop through the round, the member\'s late reply and its own messages', async (t) => {t.mock.timers.enable({ apis: ['setTimeout'] })const host = await start(t)diff --cc ds-bot/test/roster.test.jsindex 8754fca9,2e28901d..2362ec0f--- a/ds-bot/test/roster.test.js+++ b/ds-bot/test/roster.test.js@@@ -529,31 -529,84 +529,113 @@@ test('a write that fails at save time aassert.equal(Object.values(saved.bots).some(bot => bot.name === 'Phantom'), false)})+// 公开#178: "User" is how a group log names the user, so a Bot may not take it.+test('a Bot cannot be named or renamed like the user; one named so before keeps working', async (t) => {+ const team = {+ version: 1,+ mainBotIds: ['a'],+ bots: {+ a: { id: 'a', name: 'Chief', role: '', instructions: '', sessionId: 'a', createdAt: 1 },+ u: { id: 'u', name: 'User', role: '', instructions: '', sessionId: 'u', createdAt: 2 },+ },+ rooms: {},+ agents: {},+ exchanges: [],+ exchangeTurns: {},+ questions: {},+ prefs: {},+ revision: 0,+ }+ const { call, stop } = start(team)+ t.after(stop)+ const made = await call('create-bot', { name: 'user' })+ assert.equal(made.ok, false)+ assert.match(made.error.message, /stands for the user in a chat/)+ const renamed = await call('update-bot', { id: 'a', name: 'You' })+ assert.equal(renamed.ok, false)+ assert.match(renamed.error.message, /stands for the user in a chat/)+ assert.equal((await call('update-bot', { id: 'u', name: 'User', role: 'Tester' })).ok, true)+ assert.equal((await call('update-bot', { id: 'u', name: 'Helper' })).ok, true)+})+++ // Holds every new Session until `release`, so creates that start together are all+ // waiting on it at once, as with a slow DSH.+ const holdSessions = (ctx) => {+ const create = ctx.sessionController.create+ let open+ const gate = new Promise(resolve => { open = resolve })+ let waiting = 0+ ctx.sessionController.create = async (request) => {+ waiting += 1+ await gate+ return create(request)+ }+ return { waiting: () => waiting, release: () => { ctx.sessionController.create = create; open() } }+ }++ // 公开#148: two Main Bots that each made a "Coder" at the same time both got one.+ test('Bots created with one name at the same time: one is made, the others are refused', async (t) => {+ const { call, stop, ctx } = start()+ t.after(stop)+ await call('state', {})+ const sessions = holdSessions(ctx)+ const creates = [1, 2, 3].map(() => call('create-bot', { name: 'Coder' }))+ // A rename to a name a create is still working on is refused too.+ const chief = (await call('state', {})).value.mainBotId+ const rename = await call('update-bot', { id: chief, name: 'coder' })+ sessions.release()+ const results = await Promise.all(creates)+ assert.deepEqual(results.map(result => result.ok), [true, false, false])+ assert.match(results[1].error.message, /A Bot named Coder already exists/)+ assert.equal(rename.ok, false)+ const names = (await call('state', {})).value.bots.map(bot => bot.name)+ assert.equal(names.filter(name => name.toLowerCase() === 'coder').length, 1)+ })++ test('copies of one Bot made at the same time get different names', async (t) => {+ const { call, stop, ctx } = start()+ t.after(stop)+ const writer = (await call('create-bot', { name: 'Writer' })).value+ const sessions = holdSessions(ctx)+ const copies = [1, 2, 3].map(() => call('duplicate-bot', { id: writer.id }))+ await until(() => sessions.waiting() === 3)+ sessions.release()+ const results = await Promise.all(copies)+ assert.deepEqual(results.map(result => result.ok), [true, true, true])+ assert.deepEqual(results.map(result => result.value.name).sort(), ['Writer copy', 'Writer copy 2', 'Writer copy 3'])+ })++ // 公开#199: two groups made with one name at the same time were both made, and from then+ // on a Main Bot could reach neither by name.+ test('groups created or renamed to one name at the same time: only one gets it', async (t) => {+ const { call, stop, ctx } = start()+ t.after(stop)+ const chief = (await call('state', {})).value.mainBotId+ const writer = (await call('create-bot', { name: 'Writer' })).value+ const other = (await call('create-room', { members: [chief, writer.id], name: 'Docs' })).value+ const sessions = holdSessions(ctx)+ const creates = [1, 2].map(() => call('create-room', { members: [chief, writer.id], name: 'Ops' }))+ const rename = await call('update-room', { id: other.id, name: 'ops' })+ sessions.release()+ const results = await Promise.all(creates)+ assert.deepEqual(results.map(result => result.ok), [true, false])+ assert.match(results[1].error.message, /Another group chat is already called "Ops"/)+ assert.equal(rename.ok, false)+ const rooms = (await call('state', {})).value.rooms.map(room => room.name).sort()+ assert.deepEqual(rooms, ['Docs', 'Ops'])++ // Once the create ends, its name is no longer held for anyone else.+ const later = await call('create-room', { members: [chief, writer.id], name: 'Ops 2' })+ assert.equal(later.ok, true)+ })++ test('a create that fails lets its name go', async (t) => {+ const { call, stop, ctx } = start()+ t.after(stop)+ await call('state', {})+ const create = ctx.sessionController.create+ ctx.sessionController.create = async () => { throw new Error('dsh is busy') }+ assert.equal((await call('create-bot', { name: 'Coder' })).ok, false)+ ctx.sessionController.create = create+ assert.equal((await call('create-bot', { name: 'Coder' })).ok, true)+ })