A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Hold a new Bot's or group's name until it is written
Fei24110a28b8cfa2a3
diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.jsindex 981bc34a..92f493f9 100644--- a/ds-bot/src/host/roster.js+++ b/ds-bot/src/host/roster.js@@ -3,7 +3,7 @@import { mkdir } from 'node:fs/promises'import { join } from 'node:path'import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOTICE_MAX } from './constants.js'-import { currentColor, isColor, unquote } from './text.js'+import { currentColor, isColor, normalize, unquote } from './text.js'import { nameProblem } from '../shared/mentions.js'export function install(rt) {@@ -59,21 +59,42 @@ export function install(rt) {return Object.keys(avatar).length > 0 ? avatar : undefined}+ // A new Bot or group is written only after its Session is made, several awaits after+ // its name was checked. The name is held from the check until the create ends, so a+ // create or rename that runs meanwhile cannot take it too.+ const held = { bot: new Set(), room: new Set() }+ const isHeld = (kind, name) => held[kind].has(normalize(name))+ async function holdName(kind, name, work) {+ const key = normalize(name)+ if (key === '') return work()+ held[kind].add(key)+ try {+ return await work()+ } finally {+ held[kind].delete(key)+ }+ }+ const botNameTaken = name => rt.findBot(name) !== undefined || isHeld('bot', name)+const freshName = (base) => {const stem = base.slice(0, 34)- if (!rt.findBot(stem)) return stem+ if (!botNameTaken(stem)) return stemlet index = 2- while (rt.findBot(`${stem} ${index}`)) index += 1+ while (botNameTaken(`${stem} ${index}`)) index += 1return `${stem} ${index}`}// `pickModel` leaves the model to the user: the chat opens on a model card, and the// greeting waits until a model is chosen. So does a Bot made when no model is served.- async function createBot({ name: botName, role = '', instructions = '', color, brief = '', createdBy, main = false, avatar, model, effort, workDir, copyOf, pickModel = false }) {- const cleanName = String(botName ?? '').trim().slice(0, 40)+ async function createBot(options) {+ const cleanName = String(options.name ?? '').trim().slice(0, 40)const problem = nameProblem(cleanName)if (problem !== undefined) throw new Error(problem)- if (rt.findBot(cleanName)) throw new Error(`A Bot named ${cleanName} already exists`)+ if (botNameTaken(cleanName)) throw new Error(`A Bot named ${cleanName} already exists`)+ return holdName('bot', cleanName, () => buildBot(cleanName, options))+ }++ async function buildBot(cleanName, { role = '', instructions = '', color, brief = '', createdBy, main = false, avatar, model, effort, workDir, copyOf, pickModel = false }) {const cleanAvatarValue = cleanAvatar(avatar)// The model is fixed at creation, so a later change of the DSH default leaves it alone.const modelRef = model ? await rt.resolveModel(model) : pickModel ? undefined : await rt.defaultModel()@@ -156,6 +177,9 @@ export function install(rt) {const bot = rt.botOf(id)if (bot === undefined) throw new Error('Unknown Bot')const served = (await rt.catalog()).some(entry => entry.ref === bot.model)+ // A folder that went away since leaves the copy in the team workspace.+ const workDir = bot.workDir !== undefined && await rt.isFolder(bot.workDir) ? bot.workDir : undefined+ // No await from here to createBot's check, so two copies at once get different names.return createBot({name: freshName(`${bot.name} copy`),role: bot.role,@@ -164,8 +188,7 @@ export function install(rt) {avatar: bot.avatar,model: served ? bot.model : undefined,effort: served ? bot.effort : undefined,- // A folder that went away since leaves the copy in the team workspace.- workDir: bot.workDir !== undefined && await rt.isFolder(bot.workDir) ? bot.workDir : undefined,+ workDir,copyOf: bot.id,})}@@ -179,7 +202,8 @@ export function install(rt) {if (patch.name !== undefined) {const next = String(patch.name).trim().slice(0, 40)const clash = rt.findBot(next)- if (next === '' || (clash && clash.id !== id)) throw new Error(`Name ${next} is not available`)+ const pending = isHeld('bot', next) && normalize(next) !== normalize(bot.name)+ if (next === '' || (clash && clash.id !== id) || pending) throw new Error(`Name ${next} is not available`)// A name saved before the rule stays usable until it changes.const problem = next === bot.name ? undefined : nameProblem(next)if (problem !== undefined) throw new Error(problem)@@ -251,7 +275,7 @@ export function install(rt) {function cleanRoomName(text, selfId) {const next = unquote(text).replace(/\s+/g, ' ').slice(0, ROOM_NAME_MAX)- if (next !== '' && rt.findRooms(next).some(room => room.id !== selfId)) throw new Error(`Another group chat is already called "${next}"`)+ if (next !== '' && (rt.findRooms(next).some(room => room.id !== selfId) || isHeld('room', next))) throw new Error(`Another group chat is already called "${next}"`)return next}@@ -289,6 +313,10 @@ export function install(rt) {const adminId = admin !== undefined ? admin : (members.includes(createdBy) ? createdBy : members.find(rt.isMain) ?? null)if (adminId !== null && !members.includes(adminId)) throw new Error('The admin must be a member of the group')if (mode !== undefined && !ROOM_MODES.includes(mode)) throw new Error(`Reply mode must be one of ${ROOM_MODES.join(', ')}`)+ return holdName('room', custom, () => buildRoom({ members, custom, notice, mode, adminId, createdBy }))+ }++ async function buildRoom({ members, custom, notice, mode, adminId, createdBy }) {const title = custom || autoRoomName(members)// The group's own Session only relays, so it stays in the team workspace; the// group's folder is for its members' Sessions.@@ -339,7 +367,6 @@ export function install(rt) {admin = null}if (patch.mode !== undefined && !ROOM_MODES.includes(patch.mode)) throw new Error(`Reply mode must be one of ${ROOM_MODES.join(', ')}`)- const name = patch.name === undefined ? undefined : cleanRoomName(patch.name, room.id)const notice = patch.notice === undefined ? undefined : cleanNotice(patch.notice)const moving = patch.workDir !== undefinedif (moving && byAdmin) throw new Error(`Only the user or a Main Bot can set the folder of "${room.name}"`)@@ -347,6 +374,9 @@ export function install(rt) {// A Bot's own permissions are the user's to set, so a group's are too.if (patch.permission !== undefined && actorId !== undefined) throw new Error(`Only the user can set the permissions of "${room.name}"`)const permission = patch.permission === undefined ? undefined : rt.cleanRoomPermission(patch.permission)+ // Checked after the last await before the rename, so no other change can take the+ // name in between.+ const name = patch.name === undefined ? undefined : cleanRoomName(patch.name, room.id)const changes = []const names = ids => ids.map(member => rt.botOf(member)?.name).filter(Boolean).join(', ')@@ -376,9 +406,6 @@ export function install(rt) {else room.workDir = workDirchanges.push(workDir ? `every member now works in ${workDir} here` : 'every member works in its own folder again')}- if (permission !== undefined && await rt.setRoomPermission(room, permission)) {- changes.push(permission ? `every member now works with the ${permission} permissions here` : 'every member uses its own permissions again')- }const before = room.nameif (name !== undefined) {if (name !== '') {@@ -389,6 +416,9 @@ export function install(rt) {}}if (!room.named) room.name = autoRoomName(room.members)+ if (permission !== undefined && await rt.setRoomPermission(room, permission)) {+ changes.push(permission ? `every member now works with the ${permission} permissions here` : 'every member uses its own permissions again')+ }if (room.name !== before) {changes.push(`renamed it "${room.name}"`)await retitleRoom(room)diff --git a/ds-bot/test/roster.test.js b/ds-bot/test/roster.test.jsindex 06052599..2e28901d 100644--- a/ds-bot/test/roster.test.js+++ b/ds-bot/test/roster.test.js@@ -528,3 +528,85 @@ test('a write that fails at save time archives the Session it made', async (t) =const saved = JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))assert.equal(Object.values(saved.bots).some(bot => bot.name === 'Phantom'), false)})++// 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)+})