A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Read "@Name" by one rule in the group host and the bubbles
Fei24110b520372401b
diff --git a/ds-bot/package.json b/ds-bot/package.jsonindex a8a3d9bc..1a834741 100644--- a/ds-bot/package.json+++ b/ds-bot/package.json@@ -32,6 +32,7 @@"files": ["index.js","src/host/",+ "src/shared/","client.js","web-search.js","cordis.patch.yml",diff --git a/ds-bot/src/client/create-bot.js b/ds-bot/src/client/create-bot.jsindex 55b7ba4a..5c53b75a 100644--- a/ds-bot/src/client/create-bot.js+++ b/ds-bot/src/client/create-bot.js@@ -6,7 +6,8 @@ import { ChevronLeftIcon, CloseIcon } from './icons.js'import { useEscape } from './overlay-hooks.js'import { createPayload, freshBotName, startModel } from './bot-draft.js'import { ModelMenu } from './model-menu.js'-import { t } from './i18n.js'+import { hostText, t } from './i18n.js'+import { nameProblem } from '../shared/mentions.js'const pick = list => list[Math.floor(Math.random() * list.length)]const randomLook = (avoid = {}) => {@@ -33,8 +34,9 @@ export function CreateBot({ roster, actions, start, brief = '', onBack, canGoBacconst fallbackName = freshBotName(roster, t('New Bot'))const finalName = name.trim() || fallbackNameconst clash = roster.bots.some(bot => bot.name.toLowerCase() === finalName.toLowerCase())+ const problem = nameProblem(finalName)const create = async () => {- if (busy || clash) return+ if (busy || clash || problem) returnsetError('')setBusy(true)try {@@ -76,7 +78,8 @@ export function CreateBot({ roster, actions, start, brief = '', onBack, canGoBaconChange: event => setName(event.target.value),onKeyDown: (event) => { if (event.key === 'Enter' && !event.nativeEvent.isComposing) { event.preventDefault(); void create() } },}),- clash ? h('span', { className: 'bt-note bt-danger' }, t('A Bot named {name} already exists', { name: finalName })) : null),+ problem ? h('span', { className: 'bt-note bt-danger' }, hostText(problem))+ : clash ? h('span', { className: 'bt-note bt-danger' }, t('A Bot named {name} already exists', { name: finalName })) : null),h('div', { className: 'bt-field' },h('span', { className: 'bt-field-label' }, t('Model')),h(ModelMenu, { bot: { id: 'new-bot', name: finalName, model: model || undefined, effort }, roster, actions, wide: true, onPick: ref => { setModel(ref); setEffort(undefined) }, onPickEffort: setEffort }),@@ -86,7 +89,7 @@ export function CreateBot({ roster, actions, start, brief = '', onBack, canGoBacerror ? h('div', { className: 'bt-error', role: 'alert', style: { padding: 0 } }, error) : null,h('div', { className: 'bt-create-foot' },h('button', { type: 'button', className: 'bt-soft', onClick: onBack }, canGoBack ? t('Back') : t('Cancel')),- h('button', { type: 'button', className: 'bt-send bt-create-go', disabled: busy || clash, onClick: () => void create() }, busy ? t('Creating…') : t('Create'))))+ h('button', { type: 'button', className: 'bt-send bt-create-go', disabled: busy || clash || Boolean(problem), onClick: () => void create() }, busy ? t('Creating…') : t('Create'))))if (inline) return h('div', { ref: frame, className: 'bt-create-inline', role: 'group', 'aria-label': t('Create Bot') }, card)return h('div', { className: 'bt-create', role: 'dialog', 'aria-label': t('Create Bot') },h('div', { className: 'bt-create-head' },diff --git a/ds-bot/src/client/text.js b/ds-bot/src/client/text.jsindex 66d5c07c..c52f6a12 100644--- a/ds-bot/src/client/text.js+++ b/ds-bot/src/client/text.js@@ -1,28 +1,23 @@// -------------------------------------------------------------------------// Text helpersimport { dateLocale, t } from './i18n.js'+import { mentionSpans } from '../shared/mentions.js'export const MENTION_ORIGIN = 'https://bots.local/'-const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')--// Only "@Name" is a mention, the same rule the group host reads (mentionsIn): a bare-// name is ordinary text, so a Bot called "测试" leaves the word "测试" alone.+// The Bots a text calls, by the rule the group host reads (shared/mentions.js). The+// speaker's own name takes part so that it is never read as a shorter name inside it+// ("@新 Bot" in "@新 Bot 2"); it then stays plain text.export function linkMentions(text, bots, selfId) {- if (!text || bots.length === 0 || text.includes('```') || !text.includes('@')) return text- // The speaker's own name takes part so that, longest first, it is never read as a- // shorter name inside it ("@新 Bot" in "@新 Bot 2"); it then stays plain text.- const names = bots.filter(bot => bot.name).sort((a, b) => b.name.length - a.name.length)- if (!names.some(bot => bot.id !== selfId)) return text- const byName = new Map(names.map(bot => [bot.name.toLowerCase(), bot]))- // A letter, digit, "_" or "." before "@" is an address ("a@b"); a letter, digit, "_"- // or "-" after the name means a longer word ("@Mi" in "@MiniMax").- const pattern = new RegExp(`(\\[[^\\]]*\\]\\([^)]*\\)|\`[^\`]*\`)|(?<![A-Za-z0-9_.])@(${names.map(bot => escapeRegExp(bot.name)).join('|')})(?![A-Za-z0-9_-])`, 'gi')- return text.replace(pattern, (match, skip, name) => {- if (skip) return skip- const bot = byName.get(name.toLowerCase())- return bot && bot.id !== selfId ? `[${name}](${MENTION_ORIGIN}${bot.id})` : match- })+ if (!text || !text.includes('@')) return text+ let out = ''+ let cursor = 0+ for (const span of mentionSpans(text, bots)) {+ if (!span.bot || span.bot.id === selfId) continue+ out += `${text.slice(cursor, span.start)}[${text.slice(span.start + 1, span.end).replace(/[[\]\\]/g, '\\$&')}](${MENTION_ORIGIN}${span.bot.id})`+ cursor = span.end+ }+ return cursor === 0 ? text : out + text.slice(cursor)}export function mentionTarget(event) {diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 27ce08bd..fc7502d5 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -14,6 +14,7 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm'import { defineTool } from '@deepseek-ai/dsh-tools'import { ROOM_REPLY_TIMEOUT_MS, SOURCE_KIND } from './constants.js'import { escapeRegExp, splitRef, textOf } from './text.js'+import { mentionSpans } from '../shared/mentions.js'import { GROUP_REF, output } from './tools.js'import { failureLine } from './turns.js'@@ -56,41 +57,20 @@ const transcript = lines => lines.map(lineText).join('\n')export const stripOwnName = (name, text) => text.replace(new RegExp(`^\\s*\\**${escapeRegExp(name)}\\**\\s*[::]\\s*`), '').trim()export const isPass = text => text === '' || /^\s*[[【((]\s*pass\s*[\]】))]|^\s*pass\s*[.。!!]?\s*$/i.test(text)-// "@Name" mentions in order of appearance. Longest names match first so "@Mx" never-// reads as "@M"; only ASCII letters and digits continue a name, so "@K你好" is K.-const ROOM_ALL = ['all', 'everyone', '所有人', '全体']-const NAME_GOES_ON = /^[a-z0-9_-]/i-export const mentionsIn = (text, members) => {- const byLength = [...members].sort((a, b) => b.name.length - a.name.length)+// Who "@" calls, in order, by the same rule the bubbles draw. `references` are the+// round's referenced conversations: each one's "@label" is a reference, not a call.+// Pass every member, the speaker too, so "@新 Bot 2" said by 新 Bot 2 is never read as+// a call to 新 Bot; the caller drops the speaker.+export const mentionsIn = (text, members, references = []) => {const found = []let all = false- for (let at = text.indexOf('@'); at !== -1; at = text.indexOf('@', at + 1)) {- if (at > 0 && /[a-z0-9_.]/i.test(text[at - 1])) continue- const rest = text.slice(at + 1)- const starts = word => rest.toLowerCase().startsWith(word.toLowerCase()) && !NAME_GOES_ON.test(rest.slice(word.length))- if (ROOM_ALL.some(starts)) all = true- const hit = byLength.find(member => starts(member.name))- if (hit && !found.includes(hit)) found.push(hit)+ for (const span of mentionSpans(text, members, { references: references.flatMap(reference => reference.labels) })) {+ if (span.all) all = true+ else if (!found.includes(span.bot)) found.push(span.bot)}return { all, found }}-// DSH writes each referenced conversation into the message as one "@label"; that is not-// a call, even when the label starts with a member's name. Only that one "@label" goes,-// so a "@Name" the user typed with the same text still calls.-const dropMention = (text, label) => {- const mention = `@${label}`- for (let at = text.indexOf(mention); at !== -1; at = text.indexOf(mention, at + 1)) {- const end = at + mention.length- if ((at === 0 || !/[a-z0-9_.]/i.test(text[at - 1])) && !NAME_GOES_ON.test(text.slice(end))) return text.slice(0, at) + text.slice(end)- }- return text-}-export const withoutReferences = (text, references = []) => references- .flatMap(reference => reference.labels)- .sort((a, b) => b.length - a.length)- .reduce(dropMention, text)-// What the user referenced in this round, for a member that has not been shown it yet.export const referenceNote = references => (references?.length? `Conversations the user referenced in this round:\n\n${references.map(reference => reference.text).join('\n\n')}`@@ -313,8 +293,10 @@ export function install(rt) {void rt.save().catch(() => {})// Only the admin's "@all" calls everyone, so a member cannot set off a storm.const leads = rt.isAdminOf(room, member.id)- const others = room.members.filter(id => id !== member.id).map(rt.botOf).filter(Boolean)- const { all, found } = mentionsIn(reply, others)+ 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 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)}@@ -454,10 +436,12 @@ 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.function openingSpeakers(room, opener) {- const members = room.members.map(rt.botOf).filter(bot => bot && bot.id !== opener.botId)+ const everyone = room.members.map(rt.botOf).filter(Boolean)+ const members = everyone.filter(bot => bot.id !== opener.botId)const admin = members.find(bot => rt.isAdminOf(room, bot.id))if (opener.kickoff) return admin ? [admin] : []- const { all, found } = mentionsIn(withoutReferences(opener.text, opener.references), members)+ const { all, found: named } = mentionsIn(opener.text, everyone, opener.references)+ const found = named.filter(bot => bot.id !== opener.botId)if (found.length > 0 && !all) return foundif (!all && room.mode === 'admin' && admin) return [admin]return admin ? [admin, ...members.filter(bot => bot !== admin)] : membersdiff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.jsindex 8e4a5da8..6a2f61a0 100644--- a/ds-bot/src/host/roster.js+++ b/ds-bot/src/host/roster.js@@ -4,6 +4,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 { nameProblem } from '../shared/mentions.js'export function install(rt) {const { ctx, config, home, defaults, state } = rt@@ -56,7 +57,8 @@ export function install(rt) {// 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, copyOf, pickModel = false }) {const cleanName = String(botName ?? '').trim().slice(0, 40)- if (cleanName === '') throw new Error('A Bot needs a name')+ const problem = nameProblem(cleanName)+ if (problem !== undefined) throw new Error(problem)if (rt.findBot(cleanName)) throw new Error(`A Bot named ${cleanName} already exists`)const cleanAvatarValue = cleanAvatar(avatar)// The model is fixed at creation, so a later change of the DSH default leaves it alone.@@ -153,6 +155,9 @@ export function install(rt) {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`)+ // 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)bot.name = nextconst agent = await rt.resolveAgent(rt.chatOf(id))await ctx.sessionTitle.rename(agent.session, next)diff --git a/ds-bot/src/shared/mentions.js b/ds-bot/src/shared/mentions.jsnew file mode 100644index 00000000..6085d13e--- /dev/null+++ b/ds-bot/src/shared/mentions.js@@ -0,0 +1,63 @@+// "@Name" is read by one rule everywhere: the group host picks who answers with it,+// and the client draws the same mentions in the bubbles, so what the user sees called+// is what gets called. Pure, so both sides import it.++export const ALL_WORDS = ['all', 'everyone', '所有人', '全体']+// A letter, digit, "_" or "-" after a name means a longer word ("@Mi" in "@MiniMax");+// a letter, digit, "_" or "." before "@" means an address ("a@b").+const NAME_GOES_ON = /^[a-z0-9_-]/i+const ADDRESS_BEFORE = /[a-z0-9_.]/i+// Code and Markdown links are literal text.+const LITERAL = /```[\s\S]*?(?:```|$)|`[^`\n]*`|\[[^\]\n]*\]\([^)\s]*\)/g++const fitsAt = (text, at, word) => text.slice(at, at + word.length).toLowerCase() === word.toLowerCase()+ && !NAME_GOES_ON.test(text.slice(at + word.length))+const overlaps = (spans, start, end) => spans.some(span => start < span.end && span.start < end)++// What a Bot may be named: something "@" can call without a second reading.+export function nameProblem(name) {+ const text = String(name ?? '').trim()+ if (text === '') return 'A Bot needs a name'+ if (/[@`\r\n]/.test(text)) return 'A Bot name cannot contain @, ` or a line break'+ if (ALL_WORDS.includes(text.toLowerCase())) return `"${text}" calls everyone in a group, so it cannot be a Bot name`+ return undefined+}++// DSH writes each referenced conversation into the message once as "@label"; that one+// occurrence per listed label is a reference, not a call. Longest labels go first so+// "@K notes" is never read as the label "K".+export function referenceSpans(text, labels = []) {+ const spans = []+ for (const label of [...labels].sort((a, b) => b.length - a.length)) {+ const mention = `@${label}`+ for (let at = text.indexOf(mention); at !== -1; at = text.indexOf(mention, at + 1)) {+ const end = at + mention.length+ if ((at > 0 && ADDRESS_BEFORE.test(text[at - 1])) || NAME_GOES_ON.test(text.slice(end)) || overlaps(spans, at, end)) continue+ spans.push({ start: at, end, label })+ break+ }+ }+ return spans.sort((a, b) => a.start - b.start)+}++// Every "@Name" and "@all" outside code, links and references, in order. Longest names+// match first, so "@新 Bot 2" is never "@新 Bot"; a name may hold spaces.+export function mentionSpans(text, bots, { references = [] } = {}) {+ const value = String(text ?? '')+ const skip = [+ ...[...value.matchAll(LITERAL)].map(match => ({ start: match.index, end: match.index + match[0].length })),+ ...referenceSpans(value, references),+ ]+ const byLength = bots.filter(bot => bot?.name).sort((a, b) => b.name.length - a.name.length)+ const spans = []+ for (let at = value.indexOf('@'); at !== -1; at = value.indexOf('@', at + 1)) {+ if ((at > 0 && ADDRESS_BEFORE.test(value[at - 1])) || overlaps(skip, at, at + 1)) continue+ const bot = byLength.find(candidate => fitsAt(value, at + 1, candidate.name))+ const all = bot ? undefined : ALL_WORDS.find(word => fitsAt(value, at + 1, word))+ if (!bot && !all) continue+ const end = at + 1 + (bot ? bot.name.length : all.length)+ spans.push(bot ? { start: at, end, bot } : { start: at, end, all: true })+ at = end - 1+ }+ return spans+}diff --git a/ds-bot/test/groups.test.js b/ds-bot/test/groups.test.jsindex e56f68c0..642ca18e 100644--- a/ds-bot/test/groups.test.js+++ b/ds-bot/test/groups.test.js@@ -1,6 +1,6 @@import assert from 'node:assert/strict'import { test } from 'node:test'-import { isPass, mentionsIn, referenceNote, stripOwnName, withoutReferences } from '../src/host/groups.js'+import { isPass, mentionsIn, referenceNote, stripOwnName } from '../src/host/groups.js'import { attachReference } from '../src/host/turns.js'const members = [{ name: 'M' }, { name: 'Mx' }, { name: 'K' }, { name: 'Writer' }]@@ -42,18 +42,18 @@ test('a referenced conversation rides with the user\'s queued message, not a Bottest('a reference label is not a call, even when it starts with a member\'s name', () => {const references = [{ labels: ['K notes', 'K'] }]- assert.deepEqual(names(mentionsIn(withoutReferences('see @K notes, then @Writer', references), members)), { all: false, found: ['Writer'] })- assert.deepEqual(names(mentionsIn(withoutReferences('@K notes', undefined), members)), { all: false, found: ['K'] })+ assert.deepEqual(names(mentionsIn('see @K notes, then @Writer', members, references)), { all: false, found: ['Writer'] })+ assert.deepEqual(names(mentionsIn('@K notes', members)), { all: false, found: ['K'] })assert.equal(referenceNote([]), '')assert.equal(referenceNote([{ text: 'A' }, { text: 'B' }]), 'Conversations the user referenced in this round:\n\nA\n\nB')})test('a reference takes out only its own "@label", so a typed call with the same text stays', () => {const writer = [{ labels: ['Writer'] }]- assert.deepEqual(names(mentionsIn(withoutReferences('Read @Writer, then @Writer please answer.', writer), members)), { all: false, found: ['Writer'] })- assert.deepEqual(names(mentionsIn(withoutReferences('see @Writer', writer), members)), { all: false, found: [] })- assert.deepEqual(names(mentionsIn(withoutReferences('see @Writer and @Writer', [...writer, ...writer]), members)), { all: false, found: [] })+ assert.deepEqual(names(mentionsIn('Read @Writer, then @Writer please answer.', members, writer)), { all: false, found: ['Writer'] })+ assert.deepEqual(names(mentionsIn('see @Writer', members, writer)), { all: false, found: [] })+ assert.deepEqual(names(mentionsIn('see @Writer and @Writer', members, [...writer, ...writer])), { all: false, found: [] })// "@Kate" is not the reference "K", so the "@K" after it is the one taken out.- assert.deepEqual(names(mentionsIn(withoutReferences('@Kate, @K', [{ labels: ['K'] }]), [...members, { name: 'Kate' }])), { all: false, found: ['Kate'] })- assert.deepEqual(names(mentionsIn(withoutReferences('@K notes and @K', [{ labels: ['K notes'] }]), members)), { all: false, found: ['K'] })+ assert.deepEqual(names(mentionsIn('@Kate, @K', [...members, { name: 'Kate' }], [{ labels: ['K'] }])), { all: false, found: ['Kate'] })+ assert.deepEqual(names(mentionsIn('@K notes and @K', members, [{ labels: ['K notes'] }])), { all: false, found: ['K'] })})diff --git a/ds-bot/test/roster.test.js b/ds-bot/test/roster.test.jsindex 2b68ff81..84b534ea 100644--- a/ds-bot/test/roster.test.js+++ b/ds-bot/test/roster.test.js@@ -109,6 +109,16 @@ test('other Bots start on the default model and greet at once', async (t) => {assert.deepEqual(sent.map(entry => entry.sessionId), [writer.id])})+test('a new name must be one "@" can call; a name saved before the rule still saves', async (t) => {+ const { call, stop } = start(undefined, { models: ['deepseek-v4-flash'] })+ t.after(stop)+ await call('state', {})+ for (const name of ['a@b', 'All', '所有人']) assert.equal((await call('create-bot', { name })).ok, false, name)+ const writer = (await call('create-bot', { name: 'Writer 2' })).value+ assert.equal((await call('update-bot', { id: writer.id, name: 'Writer@home' })).ok, false)+ assert.equal((await call('update-bot', { id: writer.id, name: '新 Writer' })).ok, true)+})+test('a group the user makes without a first message opens with its admin asking what it is for', async (t) => {const { call, stop, sent, ctx, home } = start(undefined, { models: ['deepseek-v4-flash'] })t.after(stop)