Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(bot-wake): keyword wakes may stay silent, keywords can be the bot's names, only the owner edits bot settings (#21725)

Arvin Xua59a0df0e509
diff --git a/apps/cli/src/commands/bot.test.ts b/apps/cli/src/commands/bot.test.ts
index 96171e6d3d4..de48733e63b 100644
--- a/apps/cli/src/commands/bot.test.ts
+++ b/apps/cli/src/commands/bot.test.ts
@@ -456,4 +456,83 @@ describe('bot command', () => {
expect(exitSpy).toHaveBeenCalledWith(1);
});
});
+
+ describe('watch-keywords', () => {
+ const withKeywords = (watchKeywords: unknown[]) => {
+ mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
+ { agentId: 'agent1', id: 'b1', platform: 'discord' },
+ ]);
+ mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
+ { id: 'b1', platform: 'discord', settings: { dmPolicy: 'open', watchKeywords } },
+ ]);
+ };
+ const savedKeywords = () =>
+ mockTrpcClient.agentBotProvider.update.mutate.mock.calls[0][0].settings.watchKeywords;
+
+ it('adds a keyword as one of the bot names with --as-name', async () => {
+ withKeywords([{ keyword: 'bug' }]);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'watch-keywords',
+ 'add',
+ 'b1',
+ 'Canis',
+ '--as-name',
+ ]);
+
+ expect(savedKeywords()).toEqual([
+ { instruction: undefined, keyword: 'bug' },
+ { asName: true, keyword: 'canis' },
+ ]);
+ });
+
+ it('keeps the name mark on existing entries when another keyword is added', async () => {
+ withKeywords([{ asName: true, keyword: 'canis' }]);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'watch-keywords',
+ 'add',
+ 'b1',
+ 'bug',
+ ]);
+
+ expect(savedKeywords()).toEqual([
+ { asName: true, instruction: undefined, keyword: 'canis' },
+ { keyword: 'bug' },
+ ]);
+ });
+
+ it('marks an existing keyword as a name when re-added with --as-name', async () => {
+ withKeywords([{ instruction: 'look', keyword: 'canis' }]);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'watch-keywords',
+ 'add',
+ 'b1',
+ 'canis',
+ '--as-name',
+ ]);
+
+ expect(savedKeywords()).toEqual([{ asName: true, instruction: 'look', keyword: 'canis' }]);
+ });
+
+ it('shows which keywords are bot names in the list', async () => {
+ withKeywords([{ asName: true, keyword: 'canis' }, { keyword: 'bug' }]);
+
+ await createProgram().parseAsync(['node', 'test', 'bot', 'watch-keywords', 'list', 'b1']);
+
+ const printed = consoleSpy.mock.calls.map((call) => String(call[0]));
+ expect(printed[0]).toContain('BOT NAME');
+ expect(printed.find((line) => line.includes('canis'))).toContain('yes');
+ });
+ });
});
diff --git a/apps/cli/src/commands/bot.ts b/apps/cli/src/commands/bot.ts
index 27db3b1d733..b7f609cc0e7 100644
--- a/apps/cli/src/commands/bot.ts
+++ b/apps/cli/src/commands/bot.ts
@@ -279,20 +279,27 @@ function registerAllowlistCommand(bot: Command, opts: AllowlistGroupOptions) {
// ── Watch keywords subcommand factory ──────────────────
interface WatchKeywordEntry {
+ /** The keyword is one of the bot's names: saying it calls the bot. Kept only when true. */
+ asName?: boolean;
instruction?: string;
keyword: string;
}
/**
* Normalise `settings.watchKeywords` into the canonical
- * `{keyword, instruction?}[]` shape. Mirrors `extractWatchKeywordEntries`
+ * `{keyword, instruction?, asName?}[]` shape. Mirrors `extractWatchKeywordEntries`
* in `src/server/services/bot/platforms/const.ts` so the CLI accepts the
* same legacy on-disk shapes (`string`, `string[]`, `{keyword, …}[]`)
* the runtime is forgiving about — including the rare comma/whitespace
* separated string from a hand-pasted upgrade.
*/
function normalizeWatchKeywords(raw: unknown): WatchKeywordEntry[] {
- const push = (out: Map<string, WatchKeywordEntry>, keyword: unknown, instruction?: unknown) => {
+ const push = (
+ out: Map<string, WatchKeywordEntry>,
+ keyword: unknown,
+ instruction?: unknown,
+ asName?: unknown,
+ ) => {
if (typeof keyword !== 'string') return;
const normalised = keyword.trim().toLowerCase();
if (!normalised) return;
@@ -300,10 +307,15 @@ function normalizeWatchKeywords(raw: unknown): WatchKeywordEntry[] {
typeof instruction === 'string' && instruction.trim() ? instruction.trim() : undefined;
const existing = out.get(normalised);
if (!existing) {
- out.set(normalised, { instruction: trimmedInstruction, keyword: normalised });
+ out.set(normalised, {
+ instruction: trimmedInstruction,
+ keyword: normalised,
+ ...(asName === true && { asName: true }),
+ });
return;
}
if (!existing.instruction && trimmedInstruction) existing.instruction = trimmedInstruction;
+ if (asName === true) existing.asName = true;
};
const collected = new Map<string, WatchKeywordEntry>();
if (typeof raw === 'string') {
@@ -315,8 +327,8 @@ function normalizeWatchKeywords(raw: unknown): WatchKeywordEntry[] {
continue;
}
if (entry && typeof entry === 'object' && 'keyword' in entry) {
- const obj = entry as { instruction?: unknown; keyword?: unknown };
- push(collected, obj.keyword, obj.instruction);
+ const obj = entry as { asName?: unknown; instruction?: unknown; keyword?: unknown };
+ push(collected, obj.keyword, obj.instruction, obj.asName);
}
}
}
@@ -369,8 +381,12 @@ function registerWatchKeywordsCommand(bot: Command) {
}
printTable(
- entries.map((e) => [e.keyword, e.instruction ?? pc.dim('-')]),
- ['KEYWORD', 'INSTRUCTION'],
+ entries.map((e) => [
+ e.keyword,
+ e.asName ? 'yes' : pc.dim('-'),
+ e.instruction ?? pc.dim('-'),
+ ]),
+ ['KEYWORD', 'BOT NAME', 'INSTRUCTION'],
);
});
@@ -381,48 +397,69 @@ function registerWatchKeywordsCommand(bot: Command) {
'--instruction <text>',
'Prompt prepended to the user message when this keyword fires (omit for "just wake the bot")',
)
- .action(async (botId: string, keyword: string, options: { instruction?: string }) => {
- const trimmedKeyword = keyword.trim().toLowerCase();
- if (!trimmedKeyword) {
- log.error('Keyword cannot be empty.');
- process.exit(1);
- return;
- }
-
- const trimmedInstruction = options.instruction?.trim();
+ .option(
+ '--as-name',
+ 'Mark the keyword as one of the bot\'s names (an alias such as "canis"): saying it calls the bot',
+ )
+ .action(
+ async (
+ botId: string,
+ keyword: string,
+ options: { asName?: boolean; instruction?: string },
+ ) => {
+ const trimmedKeyword = keyword.trim().toLowerCase();
+ if (!trimmedKeyword) {
+ log.error('Keyword cannot be empty.');
+ process.exit(1);
+ return;
+ }
- const client = await getTrpcClient();
- const b = await findBot(client, botId);
- const entries = readEntries(b);
+ const trimmedInstruction = options.instruction?.trim();
- const existing = entries.find((e) => e.keyword === trimmedKeyword);
- if (existing) {
- // Upsert instruction on duplicate keyword — operators commonly
- // re-run `add` to tweak the prompt without remembering to remove first.
- if (trimmedInstruction && existing.instruction !== trimmedInstruction) {
- existing.instruction = trimmedInstruction;
- await client.agentBotProvider.update.mutate(buildPayload(b, entries) as any);
- console.log(
- `${pc.green('✓')} Updated instruction for ${pc.bold(trimmedKeyword)} (${entries.length} entr${entries.length === 1 ? 'y' : 'ies'})`,
- );
+ const client = await getTrpcClient();
+ const b = await findBot(client, botId);
+ const entries = readEntries(b);
+
+ const existing = entries.find((e) => e.keyword === trimmedKeyword);
+ if (existing) {
+ // Upsert on duplicate keyword — operators commonly re-run `add` to tweak
+ // the prompt or mark a name without remembering to remove first. Leaving
+ // out `--as-name` never unmarks a name; remove and re-add for that.
+ const changes = [
+ trimmedInstruction && existing.instruction !== trimmedInstruction && 'instruction',
+ options.asName && !existing.asName && 'bot name',
+ ].filter(Boolean);
+ if (changes.length > 0) {
+ if (trimmedInstruction) existing.instruction = trimmedInstruction;
+ if (options.asName) existing.asName = true;
+ await client.agentBotProvider.update.mutate(buildPayload(b, entries) as any);
+ console.log(
+ `${pc.green('✓')} Updated ${changes.join(' and ')} for ${pc.bold(trimmedKeyword)} (${entries.length} entr${entries.length === 1 ? 'y' : 'ies'})`,
+ );
+ return;
+ }
+ log.info(`${trimmedKeyword} is already on watchKeywords — nothing to do.`);
return;
}
- log.info(`${trimmedKeyword} is already on watchKeywords — nothing to do.`);
- return;
- }
- const next = [
- ...entries,
- trimmedInstruction
- ? { instruction: trimmedInstruction, keyword: trimmedKeyword }
- : { keyword: trimmedKeyword },
- ];
+ const next: WatchKeywordEntry[] = [
+ ...entries,
+ {
+ keyword: trimmedKeyword,
+ ...(trimmedInstruction && { instruction: trimmedInstruction }),
+ ...(options.asName && { asName: true }),
+ },
+ ];
- await client.agentBotProvider.update.mutate(buildPayload(b, next) as any);
- console.log(
- `${pc.green('✓')} Added ${pc.bold(trimmedKeyword)}${trimmedInstruction ? ' (with instruction)' : ''} to watchKeywords (now ${next.length} entr${next.length === 1 ? 'y' : 'ies'})`,
- );
- });
+ await client.agentBotProvider.update.mutate(buildPayload(b, next) as any);
+ const notes = [options.asName && 'as a bot name', trimmedInstruction && 'with instruction']
+ .filter(Boolean)
+ .join(', ');
+ console.log(
+ `${pc.green('✓')} Added ${pc.bold(trimmedKeyword)}${notes ? ` (${notes})` : ''} to watchKeywords (now ${next.length} entr${next.length === 1 ? 'y' : 'ies'})`,
+ );
+ },
+ );
group
.command('remove <botId> <keyword>')
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
index 1aabf8d6d30..575442434a1 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
@@ -174,3 +174,24 @@ describe('environment stop between tool steps', () => {
},
);
});
+
+describe('what a server tool learns about the run', () => {
+ it('hands the tool who in the IM conversation asked for the run', async () => {
+ const fixture = setup([]);
+ const bot = {
+ applicationId: 'app-1',
+ isOwner: false,
+ platform: 'discord',
+ platformThreadId: 'discord:g1:c1',
+ senderExternalUserId: 'stranger-id',
+ };
+ fixture.state.principal = { actor: { bot } };
+
+ await fixture.step();
+
+ expect(fixture.execute).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botContext: bot }),
+ );
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 2e27f8b5d17..32948172579 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -278,6 +278,9 @@ export class ServerToolTransport implements ToolTransport {
...(agentVisibility !== undefined && { agentVisibility }),
// Assistant message owning this tool call (≠ source user message).
assistantMessageId: context.parentMessageId,
+ // Who in the IM conversation asked for this run; tools that act for the owner
+ // (changing a bot's settings) refuse anyone else.
+ botContext: context.state.principal?.actor?.bot,
clientIp: context.state.principal?.audit?.clientIp,
currentTodos: context.currentTodos,
deviceCapable: context.state.plan?.execution
diff --git a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
index 453c8f9a1fd..33d3bb22b95 100644
--- a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
@@ -4,16 +4,16 @@ import debug from 'debug';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { buildBotContext } from '../buildBotContext';
-import { getSameSenderMessages } from '../mergeMessages';
-import { messageMatchesWatchKeyword } from '../platforms';
import { renderInlineError } from '../replyTemplate';
import type { BotHandlerContext } from './types';
import {
applyWatchKeywordInstructions,
+ burstMatchesWatchKeyword,
dispatchTextCommand,
mergeSkippedMessages,
summarizeMessageAttachments,
} from './utils';
+import { botWakeKindFor, type BotWakeReason } from './wakeDecision';
const log = debug('lobe-server:bot:message-router');
@@ -32,7 +32,9 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
dmSettings,
gateFollowup,
initiate,
+ isBotWakeRolledOut,
isMessageMonitoringAllowed,
+ nameKeywords,
observe,
observeBurst,
operatorUserId,
@@ -89,10 +91,10 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
const matchesWatchKeyword =
!isDM &&
keywordCatchAllEnabled &&
- (messageMatchesWatchKeyword(message.text, watchKeywords) ||
- getSameSenderMessages(message, context?.skipped).some((m) =>
- messageMatchesWatchKeyword(m.text, watchKeywords),
- ) === true);
+ burstMatchesWatchKeyword(message, context?.skipped, watchKeywords);
+ // A keyword the owner marked as the bot's name calls the bot rather than just waking it.
+ const calledByKeywordName =
+ matchesWatchKeyword && burstMatchesWatchKeyword(message, context?.skipped, nameKeywords);
// If neither path applies, return so the regex doesn't act as a
// channel-wide hijack. DMs still need the dmCatchAllEnabled gate
@@ -193,15 +195,23 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
}
}
+ const wakeReason: BotWakeReason =
+ initiation?.reason ??
+ (matchesWatchKeyword
+ ? calledByKeywordName
+ ? 'named-in-text'
+ : 'watch-keyword'
+ : 'direct-message');
+
// Last check before a keyword wake runs: enforced policies, then the scheduler. Before the
// reply below is opened, so a parked message does not leave an empty thread behind.
if (
(matchesWatchKeyword || initiation) &&
(await gateFollowup({
entryPoint: 'catchAll',
- // Already judged by `initiate`: do not judge again. A message addressed to the bot
- // does not wait for the scheduler's collect window.
- immediate: initiation?.addressed,
+ // Already judged by `initiate`: do not judge again. A message addressed to the bot (by
+ // name, keyword names included) does not wait for the scheduler's collect window.
+ immediate: initiation?.addressed || wakeReason === 'named-in-text',
initiated: !!initiation,
merged,
parked: [...(context?.skipped ?? []), message],
@@ -211,9 +221,14 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
return;
}
- // A wake the bot started itself may end in silence (`NO_REPLY`) and holds back its
- // reactions and typing until it decides to speak.
- const wakeKind = initiation ? 'followup' : 'mention';
+ // Only a wake nobody asked for (a keyword, or one the bot started itself) may end in silence
+ // (`NO_REPLY`), holding back its reactions and typing until it decides to speak; and only
+ // once the bot-wake rollout reaches this bot's owner, exactly as in a subscribed thread. A DM
+ // is always answered and never asks.
+ const wakeKind =
+ wakeReason !== 'direct-message' && (await isBotWakeRolledOut())
+ ? botWakeKindFor(wakeReason)
+ : 'mention';
// Where the reply goes and what is said before the run (see `startReply`). Keyword and name
// wakes in a channel used to get their own reply thread, since the chat-sdk Discord adapter
// only auto-creates one on @-mention; that stays the behaviour when the bot does not decide.
@@ -222,7 +237,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
legacyOpensThread: matchesWatchKeyword || !!initiation,
message: merged,
rawMessage: (message as { raw?: unknown }).raw,
- reason: initiation?.reason ?? (matchesWatchKeyword ? 'watch-keyword' : 'direct-message'),
+ reason: wakeReason,
thread,
wakeKind,
});
@@ -274,7 +289,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
reactionMode,
replyLocale,
duty: initiation?.reason === 'in-duty' ? { matched: initiation.duty } : undefined,
- named: initiation?.reason === 'named-in-text',
+ named: wakeReason === 'named-in-text',
wakeKind,
});
} catch (error) {
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index c47c22705f7..743a3d19519 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -22,7 +22,6 @@ import {
getBotReplyLocale,
type GroupSettings,
type GuestSettings,
- messageMatchesWatchKeyword,
normalizeBotReactionMode,
normalizeBotReplyLocale,
normalizeBotReplyPlacementMode,
@@ -50,6 +49,7 @@ import { createReplyOpening } from './replyOpening';
import type { BotCommand, BotHandlerContext, ResolvedAgentInfo } from './types';
import {
applyWatchKeywordInstructions,
+ burstMatchesWatchKeyword,
dispatchTextCommand,
mergeSkippedMessages,
summarizeMessageAttachments,
@@ -112,6 +112,13 @@ export function registerHandlers(
*/
const watchKeywordEntries = extractWatchKeywordEntries(info.settings);
const watchKeywords: ReadonlyArray<string> = watchKeywordEntries.map((e) => e.keyword);
+ /**
+ * Keywords the owner marked as the bot's names (`asName`). Saying one calls the bot: the wake is
+ * `named-in-text`, answered at once, and bot-wake counts them among the bot's names.
+ */
+ const nameKeywords: ReadonlyArray<string> = watchKeywordEntries
+ .filter((e) => e.asName)
+ .map((e) => e.keyword);
/**
* Watch-keyword wakes ride on passive channel monitoring, which is a
@@ -252,6 +259,7 @@ export function registerHandlers(
workspaceId: workspaceId ?? undefined,
}),
identity: createWakeIdentityLoader({ agentId, db: serverDB, userId }),
+ nameKeywords,
operatorUserId,
platform,
settings: info.settings,
@@ -611,12 +619,10 @@ export function registerHandlers(
// subscribed group thread. Skipped (debounced) siblings are inspected
// too so a keyword queued behind a non-trigger still fires — same
// pattern as the mention check above.
- const matchesWatchKeyword =
- watchKeywords.length > 0 &&
- (messageMatchesWatchKeyword(message.text, watchKeywords) ||
- getSameSenderMessages(message, context?.skipped).some((m) =>
- messageMatchesWatchKeyword(m.text, watchKeywords),
- ) === true);
+ const matchesWatchKeyword = burstMatchesWatchKeyword(message, context?.skipped, watchKeywords);
+ // A keyword the owner marked as the bot's name calls the bot rather than just waking it.
+ const calledByKeywordName =
+ matchesWatchKeyword && burstMatchesWatchKeyword(message, context?.skipped, nameKeywords);
// Nobody addressed the bot. With the rules enforcing it may still speak up: its name is in the
// text, or it spoke lately and the classifier agrees. Judged on the whole burst, as it would run.
@@ -756,7 +762,9 @@ export function registerHandlers(
: isSoloBotConversation
? 'solo-conversation'
: matchesWatchKeyword && !isCommand
- ? 'watch-keyword'
+ ? calledByKeywordName
+ ? 'named-in-text'
+ : 'watch-keyword'
: (initiation?.reason ?? 'addressed');
// Only a wake nobody asked for may end in silence; a DM, @mention, command or solo
// conversation is always answered, exactly as before. Until the bot-wake rollout reaches this
@@ -767,9 +775,9 @@ export function registerHandlers(
(await gateFollowup({
entryPoint: 'onSubscribedMessage',
merged,
- // Already judged by `initiate`: do not judge again. A message addressed to the bot does
- // not wait for the scheduler's collect window.
- immediate: initiation?.addressed,
+ // Already judged by `initiate`: do not judge again. A message addressed to the bot (by
+ // name, keyword names included) does not wait for the scheduler's collect window.
+ immediate: initiation?.addressed || wakeReason === 'named-in-text',
initiated: !!initiation,
parked: [...(context?.skipped ?? []), message],
thread,
@@ -883,7 +891,9 @@ export function registerHandlers(
dmSettings,
gateFollowup,
initiate,
+ isBotWakeRolledOut: wakeRecorder.isRolledOut,
isMessageMonitoringAllowed,
+ nameKeywords,
observeBurst,
operatorUserId,
passGatesOrNotify,
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
index 0dc850a094e..1d5b96f4878 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
@@ -265,6 +265,22 @@ describe('BotMessageRouter: the bot opens its own reply', () => {
expect(opts).toMatchObject({ openingReply: undefined, wakeKind: 'followup' });
});
+ it('a watch-keyword wake in the channel also answers there, so a silent run leaves no empty thread', async () => {
+ await boot({ watchKeywords: [{ keyword: 'deploy' }, { asName: true, keyword: 'canis' }] });
+
+ await catchAll()(thread(), message({ isMention: false, text: 'the deploy is stuck' }));
+ await catchAll()(thread(), message({ id: 'msg-2', isMention: false, text: 'canis 在吗' }));
+ await flush();
+
+ expect(mocks.opener).not.toHaveBeenCalled();
+ expect(mockOpenThreadForChannelWake).not.toHaveBeenCalled();
+ const [[keywordThread, , keywordOpts], [nameThread, , nameOpts]] = mockHandleMention.mock.calls;
+ expect(keywordThread.id).toBe(CHANNEL);
+ expect(keywordOpts).toMatchObject({ named: false, wakeKind: 'followup' });
+ expect(nameThread.id).toBe(CHANNEL);
+ expect(nameOpts).toMatchObject({ named: true, wakeKind: 'followup' });
+ });
+
describe('when the owner keeps "always open a thread"', () => {
it('lets the adapter open @-mention threads and never asks the model', async () => {
await boot({ replyPlacement: 'thread' });
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.rolloutFlag.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.rolloutFlag.test.ts
index 0c5cd628e13..99f3e8892a2 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.rolloutFlag.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.rolloutFlag.test.ts
@@ -118,6 +118,15 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
expect(mockHandleSubscribedMessage.mock.calls[0][2]).toMatchObject({ wakeKind: 'mention' });
expect(mockRecordSignalDecision).not.toHaveBeenCalled();
});
+
+ it('answers a channel keyword wake through the catch-all as before', async () => {
+ await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+
+ await catchAllHandler()(thread(), message({ id: 'm7', text: 'please deploy now' }));
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention.mock.calls[0][2]).not.toMatchObject({ wakeKind: 'followup' });
+ });
});
describe('flag on', () => {
@@ -135,6 +144,31 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
expect(mockRecordSignalDecision).toHaveBeenCalledTimes(1);
});
+ it('lets a channel keyword wake through the catch-all end in silence, as in a subscribed thread', async () => {
+ flag.on = true;
+ await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+
+ await catchAllHandler()(thread(), message({ id: 'm8', text: 'please deploy now' }));
+ await flush();
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention.mock.calls[0][2]).toMatchObject({
+ named: false,
+ wakeKind: 'followup',
+ });
+ });
+
+ it('always answers a DM through the catch-all, keyword or not', async () => {
+ flag.on = true;
+ await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+
+ await catchAllHandler()(thread({ isDM: true }), message({ id: 'm9', text: 'deploy now' }));
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention.mock.calls[0][2]).not.toMatchObject({ wakeKind: 'followup' });
+ expect(mockHandleMention.mock.calls[0][1].text).toBe('deploy now');
+ });
+
it('still answers an @mention without any chance of silence', async () => {
flag.on = true;
await boot();
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
index 09cafd0cd93..0539ce0da4f 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
@@ -206,6 +206,54 @@ describe('BotMessageRouter follow-up scheduling', () => {
expect(mocks.submit).not.toHaveBeenCalled();
});
+ it('answers a keyword the owner marked as the bot name at once, as a named wake', async () => {
+ await boot({
+ ...settings,
+ watchKeywords: [
+ { keyword: 'bug' },
+ { asName: true, instruction: 'Reply as the team helper.', keyword: 'canis' },
+ ],
+ });
+
+ await subscribed()(thread(), message({ text: 'canis, are you there?' }));
+ await catchAll()(
+ thread({ id: 'telegram:group-9' }),
+ message({ id: 'msg-9', text: 'canis, are you there?' }),
+ );
+ await flush();
+
+ expect(mocks.submit).not.toHaveBeenCalled();
+ expect(mocks.defer).not.toHaveBeenCalled();
+ expect(mockHandleSubscribedMessage.mock.calls[0][2]).toMatchObject({
+ named: true,
+ wakeKind: 'followup',
+ });
+ expect(mockHandleMention.mock.calls[0][2]).toMatchObject({
+ named: true,
+ wakeKind: 'followup',
+ });
+ // The name still carries its instruction, like any keyword.
+ expect(mockHandleMention.mock.calls[0][1].text).toBe(
+ 'Reply as the team helper.\n\ncanis, are you there?',
+ );
+ expect(decisions().map((d) => [d.outcome, d.finalReason])).toEqual([
+ ['wake', 'named-in-text'],
+ ['wake', 'named-in-text'],
+ ]);
+ });
+
+ it('still parks an unflagged keyword next to a keyword name', async () => {
+ await boot({
+ ...settings,
+ watchKeywords: [{ keyword: 'bug' }, { asName: true, keyword: 'canis' }],
+ });
+
+ await subscribed()(thread(), message());
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(mocks.defer).toHaveBeenCalledTimes(1);
+ });
+
it('parks a catch-all keyword wake before a reply thread is opened for it', async () => {
await boot(settings);
diff --git a/apps/server/src/services/bot/BotMessageRouter/testUtils.ts b/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
index 333c7c3c614..9555e928257 100644
--- a/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
@@ -409,16 +409,19 @@ export const platformsModule = async () => ({
// gate and the instruction-injection branch.
extractWatchKeywordEntries: (
settings: Record<string, unknown> | null | undefined,
- ): Array<{ instruction?: string; keyword: string }> => {
+ ): Array<{ asName?: boolean; instruction?: string; keyword: string }> => {
const raw = settings?.watchKeywords;
- const byKeyword = new Map<string, { instruction?: string; keyword: string }>();
+ const byKeyword = new Map<
+ string,
+ { asName?: boolean; instruction?: string; keyword: string }
+ >();
if (Array.isArray(raw)) {
for (const entry of raw) {
if (typeof entry === 'string') {
const k = entry.trim().toLowerCase();
if (k && !byKeyword.has(k)) byKeyword.set(k, { keyword: k });
} else if (entry && typeof entry === 'object' && 'keyword' in entry) {
- const obj = entry as { instruction?: unknown; keyword?: unknown };
+ const obj = entry as { asName?: unknown; instruction?: unknown; keyword?: unknown };
if (typeof obj.keyword !== 'string') continue;
const k = obj.keyword.trim().toLowerCase();
if (!k) continue;
@@ -427,7 +430,12 @@ export const platformsModule = async () => ({
? obj.instruction.trim()
: undefined;
const existing = byKeyword.get(k);
- if (!existing) byKeyword.set(k, { instruction, keyword: k });
+ if (!existing)
+ byKeyword.set(k, {
+ instruction,
+ keyword: k,
+ ...(obj.asName === true && { asName: true }),
+ });
else if (!existing.instruction && instruction) existing.instruction = instruction;
}
}
diff --git a/apps/server/src/services/bot/BotMessageRouter/types.ts b/apps/server/src/services/bot/BotMessageRouter/types.ts
index 2fba1116c15..3f5a12dffab 100644
--- a/apps/server/src/services/bot/BotMessageRouter/types.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/types.ts
@@ -141,7 +141,14 @@ export interface BotHandlerContext {
thread: { id: string },
threadSubscribed?: boolean,
) => Promise<BotWakeInitiation | undefined>;
+ /**
+ * The `bot_wake` rollout flag for this bot's owner. Until it is on, every wake is answered, as
+ * it was before the pipeline existed.
+ */
+ isBotWakeRolledOut: () => Promise<boolean>;
isMessageMonitoringAllowed: (caller: string, threadId: string) => Promise<boolean>;
+ /** Watch keywords the owner marked as the bot's names (`asName`); a subset of `watchKeywords`. */
+ nameKeywords: ReadonlyArray<string>;
/** Records the wake decision a branch just made. Observation only; never throws. */
observe: (
entryPoint: BotWakeEntryPoint,
diff --git a/apps/server/src/services/bot/BotMessageRouter/utils.ts b/apps/server/src/services/bot/BotMessageRouter/utils.ts
index 2361bcb53a4..d9c02be0bd8 100644
--- a/apps/server/src/services/bot/BotMessageRouter/utils.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/utils.ts
@@ -1,7 +1,11 @@
import type { Message } from 'chat';
-import { mergeBotMessages } from '../mergeMessages';
-import { findMatchingWatchKeywordEntries, type WatchKeywordEntry } from '../platforms';
+import { getSameSenderMessages, mergeBotMessages } from '../mergeMessages';
+import {
+ findMatchingWatchKeywordEntries,
+ messageMatchesWatchKeyword,
+ type WatchKeywordEntry,
+} from '../platforms';
import type { BotCommand } from './types';
/**
@@ -43,6 +47,21 @@ export function mergeSkippedMessages(message: Message, context?: { skipped?: Mes
return mergeBotMessages(message, context?.skipped);
}
+/**
+ * Whether the message, or a debounced message the same sender queued before it, contains one of
+ * `keywords`. Inspecting the siblings lets a keyword queued behind a non-trigger still fire.
+ */
+export const burstMatchesWatchKeyword = (
+ message: Message,
+ skipped: Message[] | undefined,
+ keywords: ReadonlyArray<string>,
+): boolean =>
+ keywords.length > 0 &&
+ (messageMatchesWatchKeyword(message.text, keywords) ||
+ getSameSenderMessages(message, skipped).some((m) =>
+ messageMatchesWatchKeyword(m.text, keywords),
+ ) === true);
+
/**
* Prepend the operator-authored `instruction` of every matched watch
* keyword to the merged user message. Used on the keyword-wake paths
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
index b7e8cfec8a1..fa7e6d0a39d 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
@@ -409,6 +409,63 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
});
});
+describe('bot-wake recorder: watch keywords marked as the bot names', () => {
+ const SOMEONE = { author: { isBot: false, isMe: false, userId: 'someone-else' } };
+ const OWNER_AROUND = {
+ botWake: { enabled: true, mode: 'enforce', rules: { ownerPresenceSeconds: 120 } },
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockRecordSignalDecision.mockResolvedValue({ persisted: false });
+ });
+
+ it('wakes as named-in-text on a keyword name, even when the platform name lookup fails', async () => {
+ const recorder = make(ENFORCE, fakeState(), {
+ botNames: async () => {
+ throw new Error('discord down');
+ },
+ classify: classifierAnswer(0.1),
+ nameKeywords: ['canis', '倏昱'],
+ });
+
+ await expect(recorder.initiate(observation({}, { text: 'canis 你看下这个' }))).resolves.toEqual(
+ { addressed: true, reason: 'named-in-text' },
+ );
+ await expect(
+ recorder.initiate(observation({}, { id: 'm-2', text: '倏昱在吗' })),
+ ).resolves.toEqual({ addressed: true, reason: 'named-in-text' });
+ });
+
+ it('hands the classifier the keyword names beside the platform names', async () => {
+ const classify = classifierAnswer(0.9);
+ const recorder = make(WITH_CLASSIFIER('enforce'), fakeState(spokeRecently()), {
+ classify,
+ nameKeywords: ['canis'],
+ });
+
+ await recorder.initiate(observation({}, { text: 'what about the release?' }));
+
+ const [input] = (classify as ReturnType<typeof vi.fn>).mock.calls[0];
+ expect(input.conversation.botNames).toEqual([BOT_NAME, 'canis']);
+ });
+
+ it('keeps a keyword-name wake from being vetoed by owner presence; a plain keyword still is', async () => {
+ const state = fakeState({ ownerLastSpokeAt: Date.now() - 10_000, silentWakes: 0 });
+ const recorder = make(OWNER_AROUND, state, { nameKeywords: ['canis'] });
+ const keywordWake = (text: string) =>
+ observation({ outcome: 'wake', reason: 'watch-keyword' }, { ...SOMEONE, text });
+
+ expect(
+ (await recorder.judge(keywordWake('canis, can you check the build?')))?.verdict,
+ ).not.toBe('deny');
+ expect(await recorder.judge(keywordWake('the mobile build is broken'))).toMatchObject({
+ reason: 'owner-present',
+ verdict: 'deny',
+ });
+ });
+});
+
describe('bot-wake recorder: remembering what was said', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index 860d56b95f1..106be81700c 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -245,6 +245,11 @@ export interface BotWakeRecorderOptions {
agentTitle?: string;
ownerNames?: readonly string[];
}>;
+ /**
+ * Watch keywords the owner marked as names the bot answers to (`asName`: "canis", "倏昱"). Read
+ * as names wherever `botNames` are, and kept when the platform lookup fails.
+ */
+ nameKeywords?: readonly string[];
/** The bot owner's user id on this platform (`settings.userId`). */
operatorUserId?: string;
platform: string;
@@ -522,13 +527,14 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
// No cache here: the platform client owns the names and refreshes them on its own schedule, so
// a renamed bot answers to the new name and stops answering to the old one. A failed lookup is
// retried on the next message.
+ const nameKeywords = options.nameKeywords ?? [];
const resolveBotNames = async (platformThreadId: string): Promise<readonly string[]> => {
try {
- return (await options.botNames?.(platformThreadId)) ?? [];
+ return [...((await options.botNames?.(platformThreadId)) ?? []), ...nameKeywords];
} catch (error) {
log('bot name lookup failed: %O', error);
- return [];
+ return nameKeywords;
}
};
diff --git a/apps/server/src/services/bot/platforms/__tests__/const.test.ts b/apps/server/src/services/bot/platforms/__tests__/const.test.ts
index 1afd5fde5a0..65e422a75dc 100644
--- a/apps/server/src/services/bot/platforms/__tests__/const.test.ts
+++ b/apps/server/src/services/bot/platforms/__tests__/const.test.ts
@@ -914,6 +914,25 @@ describe('extractWatchKeywordEntries', () => {
).toEqual([{ instruction: 'first instruction', keyword: 'bug' }]);
});
+ it('keeps the name flag only when it is true, and on any duplicate that sets it', () => {
+ expect(
+ extractWatchKeywordEntries({
+ watchKeywords: [
+ { asName: true, instruction: 'Answer as the team bot', keyword: 'Canis' },
+ { asName: false, keyword: 'mobile' },
+ { asName: 'yes', keyword: 'deploy' },
+ { keyword: '倏昱' },
+ { asName: true, keyword: '倏昱' },
+ ],
+ }),
+ ).toEqual([
+ { asName: true, instruction: 'Answer as the team bot', keyword: 'canis' },
+ { instruction: undefined, keyword: 'mobile' },
+ { instruction: undefined, keyword: 'deploy' },
+ { asName: true, instruction: undefined, keyword: '倏昱' },
+ ]);
+ });
+
it('returns entries with no instruction for the string and string[] fallbacks', () => {
expect(extractWatchKeywordEntries({ watchKeywords: ['Bug', 'outage'] })).toEqual([
{ instruction: undefined, keyword: 'bug' },
diff --git a/apps/server/src/services/bot/platforms/const.ts b/apps/server/src/services/bot/platforms/const.ts
index f886db39311..fd8ebbfe1f2 100644
--- a/apps/server/src/services/bot/platforms/const.ts
+++ b/apps/server/src/services/bot/platforms/const.ts
@@ -421,8 +421,15 @@ export function normalizeAllowFromEntries(raw: unknown): Array<{ id: string; nam
* "bug" can carry a directive like "Scan the recent thread and reply if you
* spot an actionable bug report"). When `instruction` is empty/absent the
* keyword just wakes the bot with the user's raw text — same as a mention.
+ *
+ * `asName` marks the keyword as one of the bot's names ("canis", "倏昱"): saying it calls the bot
+ * the way its display name does. It still wakes like any keyword (and still carries its
+ * `instruction`), and bot-wake reads it as `named-in-text`: answered at once rather than held in
+ * the scheduler's collect window, not silenced by the owner's presence, and listed among the bot's
+ * names for the classifier.
*/
export interface WatchKeywordEntry {
+ asName?: boolean;
instruction?: string;
keyword: string;
}
@@ -433,11 +440,12 @@ export interface WatchKeywordEntry {
* these keywords. Empty (default) preserves the today behaviour of only
* responding to mentions / DMs / subscribed-thread mentions.
*
- * Stored as `Array<{ keyword, instruction? }>`. The optional `instruction`
+ * Stored as `Array<{ keyword, instruction?, asName? }>`. The optional `instruction`
* is appended as a user-side prompt prefix when the keyword wakes the bot —
* letting operators wire each trigger to an explicit directive ("scan the
* thread for a bug report", "summarise the last 20 messages", …) rather
- * than only routing the raw message.
+ * than only routing the raw message. `asName` makes the keyword one of the
+ * bot's names (see {@link WatchKeywordEntry}).
*/
export const watchKeywordsField: FieldSchema = {
key: 'watchKeywords',
@@ -464,6 +472,12 @@ export const watchKeywordsField: FieldSchema = {
placeholder: 'channel.watchKeywordInstructionPlaceholder',
type: 'string',
},
+ {
+ description: 'channel.watchKeywordAsNameHint',
+ key: 'asName',
+ label: 'channel.watchKeywordAsNameLabel',
+ type: 'boolean',
+ },
],
},
};
@@ -472,21 +486,23 @@ export const watchKeywordsField: FieldSchema = {
* Parse `settings.watchKeywords` into the canonical entry list. Accepts
* three shapes for forward-compat with any future schema migrations:
*
- * 1. `Array<{ keyword, instruction? }>` — current form-produced shape
+ * 1. `Array<{ keyword, instruction?, asName? }>` — current form-produced shape
* 2. `string[]` — flat array fallback (no instructions attached)
* 3. `string` — comma / newline / whitespace-separated text (legacy / paste)
*
* Keywords are lowercased and deduplicated (matching is case-insensitive,
* so we normalise once at parse time rather than per-message). The first
* non-empty `instruction` wins on duplicates so the operator's authoring
- * order is preserved.
+ * order is preserved; a keyword is a name when any of its duplicates says so.
+ * `asName` is kept only when `true`, so an entry without the flag reads
+ * exactly as it did before the flag existed.
*/
export function extractWatchKeywordEntries(
settings: Record<string, unknown> | null | undefined,
): WatchKeywordEntry[] {
const raw = settings?.watchKeywords;
const byKeyword = new Map<string, WatchKeywordEntry>();
- const push = (keyword: unknown, instruction?: unknown) => {
+ const push = (keyword: unknown, instruction?: unknown, asName?: unknown) => {
if (typeof keyword !== 'string') return;
const normalised = keyword.trim().toLowerCase();
if (!normalised) return;
@@ -494,7 +510,11 @@ export function extractWatchKeywordEntries(
typeof instruction === 'string' && instruction.trim() ? instruction.trim() : undefined;
const existing = byKeyword.get(normalised);
if (!existing) {
- byKeyword.set(normalised, { keyword: normalised, instruction: trimmedInstruction });
+ byKeyword.set(normalised, {
+ keyword: normalised,
+ instruction: trimmedInstruction,
+ ...(asName === true && { asName: true }),
+ });
return;
}
// Keep the first non-empty instruction so the operator's authoring order
@@ -502,6 +522,7 @@ export function extractWatchKeywordEntries(
if (!existing.instruction && trimmedInstruction) {
existing.instruction = trimmedInstruction;
}
+ if (asName === true) existing.asName = true;
};
if (typeof raw === 'string') {
for (const piece of raw.split(/[\s,]+/)) push(piece);
@@ -512,8 +533,8 @@ export function extractWatchKeywordEntries(
continue;
}
if (entry && typeof entry === 'object' && 'keyword' in entry) {
- const obj = entry as { instruction?: unknown; keyword?: unknown };
- push(obj.keyword, obj.instruction);
+ const obj = entry as { asName?: unknown; instruction?: unknown; keyword?: unknown };
+ push(obj.keyword, obj.instruction, obj.asName);
}
}
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ownerOnly.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ownerOnly.test.ts
new file mode 100644
index 00000000000..c3e3ef6a807
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ownerOnly.test.ts
@@ -0,0 +1,154 @@
+import type { ChatTopicBotContext } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ToolExecutionContext } from '../../types';
+
+const mocks = vi.hoisted(() => ({
+ delete: vi.fn(),
+ findById: vi.fn(),
+ linkDeleteByPlatform: vi.fn(),
+ startClient: vi.fn(),
+ update: vi.fn(),
+}));
+
+vi.mock('@/database/models/agentBotProvider', () => ({
+ AgentBotProviderModel: vi.fn().mockImplementation(function () {
+ return { delete: mocks.delete, findById: mocks.findById, update: mocks.update };
+ }),
+}));
+vi.mock('@/database/models/messengerAccountLink', () => ({
+ MessengerAccountLinkModel: vi.fn().mockImplementation(function () {
+ return { deleteByPlatform: mocks.linkDeleteByPlatform, list: vi.fn(async () => []) };
+ }),
+}));
+vi.mock('@/server/services/gateway', () => ({
+ GatewayService: vi.fn().mockImplementation(function () {
+ return { startClient: mocks.startClient };
+ }),
+}));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({}) },
+}));
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));
+vi.mock('@/server/services/messenger', () => ({
+ getMessengerRouter: () => ({ invalidateBot: vi.fn() }),
+ messengerPlatformRegistry: { listSerializedPlatforms: vi.fn(() => []) },
+}));
+vi.mock('@/server/services/messenger/push', () => ({ sendMessengerPush: vi.fn() }));
+// Keeps the settings helpers' transitive imports (BotMessageRouter -> ModelRuntime) out of the
+// test runtime; the guard under test runs before any of them.
+vi.mock('@/server/services/bot/agentBotProviderSettings', () => ({
+ assertBotAccessSettings: vi.fn(),
+ assertWatchKeywordsWritable: vi.fn(),
+ invalidateBotAfterUpdate: vi.fn().mockResolvedValue(undefined),
+ mergeBotSettingsForPersist: vi.fn((_platform: string, settings: unknown) => settings),
+ mergeBotSettingsPatch: vi.fn(
+ (
+ _platform: string,
+ existing: Record<string, unknown> | null,
+ patch: Record<string, unknown>,
+ ) => ({
+ ...existing,
+ ...patch,
+ }),
+ ),
+}));
+
+const { messageRuntime } = await import('./index');
+
+const OWNER_ONLY = "Only the bot's owner can change its settings";
+
+const botContext = (isOwner: boolean): ChatTopicBotContext => ({
+ applicationId: 'app-1',
+ isOwner,
+ platform: 'discord',
+ platformThreadId: 'discord:g1:c1',
+ senderExternalUserId: isOwner ? 'owner-id' : 'stranger-id',
+});
+
+const runtimeFor = (bot?: ChatTopicBotContext) =>
+ messageRuntime.factory({
+ botContext: bot,
+ serverDB: {} as any,
+ toolManifestMap: {},
+ userId: 'user-1',
+ } satisfies ToolExecutionContext);
+
+const BOT_ROW = {
+ applicationId: 'app-1',
+ enabled: true,
+ id: 'bot-1',
+ platform: 'discord',
+ settings: { dmPolicy: 'open', watchKeywords: [] },
+ workspaceId: null,
+};
+
+describe('messageRuntime: only the owner changes a bot from a bot conversation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findById.mockResolvedValue(BOT_ROW);
+ mocks.startClient.mockResolvedValue('connecting');
+ });
+
+ it('refuses every bot and messenger mutation when someone else is talking to the bot', async () => {
+ const runtime = await runtimeFor(botContext(false));
+
+ const results = [
+ await runtime.updateBot({
+ botId: 'bot-1',
+ settings: { watchKeywords: [{ asName: true, keyword: 'canis' }] },
+ }),
+ await runtime.toggleBot({ botId: 'bot-1', enabled: false }),
+ await runtime.deleteBot({ botId: 'bot-1' }),
+ await runtime.connectBot({ botId: 'bot-1' }),
+ await runtime.createBot({
+ agentId: 'agt-1',
+ applicationId: 'app-2',
+ credentials: { botToken: 'x' },
+ platform: 'discord',
+ }),
+ await runtime.uninstallMessenger({ installationId: 'inst-1' }),
+ await runtime.setMessengerActiveAgent({ agentId: null, platform: 'slack' }),
+ await runtime.unlinkMessenger({ platform: 'slack' }),
+ ];
+
+ for (const result of results) {
+ expect(result.success).toBe(false);
+ expect(result.content).toContain(OWNER_ONLY);
+ }
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(mocks.delete).not.toHaveBeenCalled();
+ expect(mocks.startClient).not.toHaveBeenCalled();
+ expect(mocks.linkDeleteByPlatform).not.toHaveBeenCalled();
+ });
+
+ it('still lets anyone read the bot settings', async () => {
+ const runtime = await runtimeFor(botContext(false));
+
+ const result = await runtime.getBotDetail({ botId: 'bot-1' });
+
+ expect(result.success).toBe(true);
+ });
+
+ it('lets the owner change the bot from a bot conversation', async () => {
+ const runtime = await runtimeFor(botContext(true));
+ const settings = { watchKeywords: [{ asName: true, keyword: 'canis' }] };
+
+ const result = await runtime.updateBot({ botId: 'bot-1', settings });
+
+ expect(result.success).toBe(true);
+ // Through the partial-update merge: keys the agent did not send keep their stored values.
+ expect(mocks.update).toHaveBeenCalledWith('bot-1', {
+ settings: { dmPolicy: 'open', watchKeywords: settings.watchKeywords },
+ });
+ });
+
+ it('leaves a run outside any bot conversation unchanged', async () => {
+ const runtime = await runtimeFor();
+
+ const result = await runtime.toggleBot({ botId: 'bot-1', enabled: false });
+
+ expect(result.success).toBe(true);
+ expect(mocks.update).toHaveBeenCalledWith('bot-1', { enabled: false });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
index 84f09b38cd5..5c26b1091eb 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
@@ -417,8 +417,24 @@ export const messageRuntime: ServerRuntimeRegistration = {
const service = new MessageDispatcherService(serviceFactories, { resolveRoute });
+ /**
+ * Bot runs act with the owner's credentials, so whoever talks to the bot in a shared channel
+ * could otherwise talk it into rewiring itself. Every call that changes a bot or messenger
+ * connection refuses unless the person who sent the message this run answers is the owner.
+ * Keyed on the run's own sender (`botContext`, built per inbound message), not the topic's
+ * first author; a run outside an IM conversation carries none and is unaffected.
+ */
+ const assertOwnerMayManageBots = () => {
+ if (context.botContext && !context.botContext.isOwner) {
+ throw new Error(
+ "Only the bot's owner can change its settings. Ask them to make this change.",
+ );
+ }
+ };
+
const botProvider: BotProviderQuery = {
connectBot: async (botId) => {
+ assertOwnerMayManageBots();
const bot = await providerModel.findById(botId);
if (!bot) throw new Error(`Bot not found: ${botId}`);
await assertBotFeatureAccess({
@@ -433,6 +449,7 @@ export const messageRuntime: ServerRuntimeRegistration = {
return { status };
},
createBot: async (params) => {
+ assertOwnerMayManageBots();
await assertBotFeatureAccess({
action: 'manage',
applicationId: params.applicationId,
@@ -453,6 +470,7 @@ export const messageRuntime: ServerRuntimeRegistration = {
return { id: result.id, platform: params.platform };
},
deleteBot: async (botId) => {
+ assertOwnerMayManageBots();
const existing = await providerModel.findById(botId);
await providerModel.delete(botId);
if (existing) {
@@ -519,6 +537,7 @@ export const messageRuntime: ServerRuntimeRegistration = {
});
},
toggleBot: async (botId, enabled) => {
+ assertOwnerMayManageBots();
const existing = await providerModel.findById(botId);
if (!existing) throw new Error(`Bot not found: ${botId}`);
if (enabled) {
@@ -541,6 +560,7 @@ export const messageRuntime: ServerRuntimeRegistration = {
);
},
updateBot: async (botId, params) => {
+ assertOwnerMayManageBots();
const existing = await providerModel.findById(botId);
if (!existing) throw new Error(`Bot not found: ${botId}`);
await assertBotFeatureAccess({
@@ -702,6 +722,7 @@ export const messageRuntime: ServerRuntimeRegistration = {
},
uninstallMessenger: async (installationId) => {
+ assertOwnerMayManageBots();
if (!context.userId || !context.serverDB) {
throw new Error('userId and serverDB are required to uninstall');
}
@@ -791,6 +812,7 @@ export const messageRuntime: ServerRuntimeRegistration = {
},
setMessengerActiveAgent: async (params) => {
+ assertOwnerMayManageBots();
if (!context.userId || !context.serverDB) {
throw new Error('userId and serverDB are required');
}
@@ -834,6 +856,7 @@ export const messageRuntime: ServerRuntimeRegistration = {
},
unlinkMessenger: async (params) => {
+ assertOwnerMayManageBots();
if (!context.userId || !context.serverDB) {
throw new Error('userId and serverDB are required');
}
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index d4440dfd87a..e21cb860347 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -3,6 +3,7 @@ import { type LobeChatDatabase } from '@lobechat/database';
import {
type AgentShareVisitorContext,
type ChatToolPayload,
+ type ChatTopicBotContext,
type ClientSecretPayload,
type DeviceUnavailableErrorData,
type ExecSubAgentParams,
@@ -215,6 +216,13 @@ export interface ToolExecutionContext {
* `messageId`.
*/
assistantMessageId?: string;
+ /**
+ * Who started this run from an IM conversation (`state.principal.actor.bot`): the platform
+ * sender of the message the run answers and whether they are the bot's owner. Built per inbound
+ * message by the bot / messenger routers, so it names the current speaker, not whoever opened
+ * the topic. Absent outside bot conversations.
+ */
+ botContext?: ChatTopicBotContext;
/** Originating request IP propagated through the operation metadata. */
clientIp?: string;
/**
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index cb30877de46..f65a9f5733f 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -506,6 +506,8 @@
"channel.wake.section.more": "More",
"channel.wake.section.pace": "Pace",
"channel.wake.section.paceDesc": "How soon, and how often, the bot speaks up on its own.",
+ "channel.watchKeywordAsNameHint": "Saying this word calls the bot, like its own name: it answers right away, even while you're active in the channel. Leave it off for topic words like \"bug\".",
+ "channel.watchKeywordAsNameLabel": "Bot name",
"channel.watchKeywordInstructionLabel": "Instruction",
"channel.watchKeywordInstructionPlaceholder": "e.g. Scan the recent thread and reply if there is an actionable bug report",
"channel.watchKeywordLabel": "Keyword",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 514ad6032a8..e4e4f05dbea 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -506,6 +506,8 @@
"channel.wake.section.more": "更多",
"channel.wake.section.pace": "节奏",
"channel.wake.section.paceDesc": "机器人多快、多频繁地主动插话。",
+ "channel.watchKeywordAsNameHint": "把这个词当作机器人的名字:有人说到它就是在叫机器人,会立刻回应,即使你正在频道里发言。「bug」这类话题词不要勾选。",
+ "channel.watchKeywordAsNameLabel": "机器人名字",
"channel.watchKeywordInstructionLabel": "指令",
"channel.watchKeywordInstructionPlaceholder": "如 浏览近期消息,若发现可处理的 bug 报告则回复",
"channel.watchKeywordLabel": "关键词",
diff --git a/packages/builtin-tool-message/src/manifest.ts b/packages/builtin-tool-message/src/manifest.ts
index c596a429c99..d8762e876cf 100644
--- a/packages/builtin-tool-message/src/manifest.ts
+++ b/packages/builtin-tool-message/src/manifest.ts
@@ -239,10 +239,15 @@ const botSettingsSchema = {
},
watchKeywords: {
description:
- 'Channel-side keyword wake list. When a non-mention message in a non-DM channel contains any of these keywords (case-insensitive, whole-word), the bot wakes without an @mention. If the matched entry has an `instruction`, it is prepended to the user message as an extra prompt before being sent to the AI — so a bare trigger like "bug" can carry a directive ("Scan the recent thread and reply if there is a real bug report"). Empty/absent instructions just wake the bot with the raw user text. Same overwrite-replace semantics as allowFrom — read-modify-write via getBotDetail to add/remove entries.',
+ 'Channel-side keyword wake list. When a non-mention message in a non-DM channel contains any of these keywords (case-insensitive, whole-word), the bot wakes without an @mention. If the matched entry has an `instruction`, it is prepended to the user message as an extra prompt before being sent to the AI — so a bare trigger like "bug" can carry a directive ("Scan the recent thread and reply if there is a real bug report"). Empty/absent instructions just wake the bot with the raw user text. Set `asName: true` on an entry to make the keyword one of the bot\'s names (a nickname or alias such as "canis" or "倏昱"): saying it calls the bot like its display name does. Same overwrite-replace semantics as allowFrom — read-modify-write via getBotDetail to add/remove entries.',
items: {
additionalProperties: false,
properties: {
+ asName: {
+ description:
+ 'Mark this keyword as a name the bot answers to (an alias or nickname). A message that says it is treated as calling the bot by name: answered right away, even while the owner is active in the channel. Omit (or false) for an ordinary trigger word like "bug" or "mobile". Its `instruction`, if any, still applies.',
+ type: 'boolean',
+ },
instruction: {
description:
'Optional operator-authored prompt prepended to the user message when this keyword fires. Omit for "just wake the bot" behaviour.',
diff --git a/packages/builtin-tool-message/src/systemRole.ts b/packages/builtin-tool-message/src/systemRole.ts
index 08056d931f7..2154ba51842 100644
--- a/packages/builtin-tool-message/src/systemRole.ts
+++ b/packages/builtin-tool-message/src/systemRole.ts
@@ -111,7 +111,7 @@ Typical asks → action:
**groupPolicy** + **groupAllowFrom** — same shape but for group/channel/thread traffic. \`groupAllowFrom\` items are channel/group/thread IDs (e.g. Discord channel IDs from "Copy Channel ID"), not user IDs.
-**watchKeywords** — channel-side keyword triggers, format \`[{ keyword, instruction? }]\`. When a non-mention message in a subscribed channel contains a \`keyword\` (case-insensitive whole-word for ASCII, substring for CJK), the bot wakes without an @mention; the optional \`instruction\` is prepended to that user message as a prompt prefix before the agent is invoked.
+**watchKeywords** — channel-side keyword triggers, format \`[{ keyword, instruction?, asName? }]\`. When a non-mention message in a subscribed channel contains a \`keyword\` (case-insensitive whole-word for ASCII, substring for CJK), the bot wakes without an @mention; the optional \`instruction\` is prepended to that user message as a prompt prefix before the agent is invoked. \`asName: true\` makes the keyword one of the bot's names ("people also call you canis / 倏昱"): saying it calls the bot like its display name, so it is answered at once. Use it only for names and nicknames, never for topic words like "bug".
**The \`instruction\` is a future prompt for your future self — NOT a task to execute now.** When the user says "if X appears in channel, do Y", the right action is: read existing \`settings.watchKeywords\`, upsert \`{ keyword: X, instruction: Y }\`, write the array back. **Do NOT pre-resolve any references the directive mentions** — team names, user handles, channel names, project IDs, status labels, etc. The future-self runs when the keyword fires, in the same channel context with the same tools you have today, and will look those up against fresh data at trigger time. Pre-resolving now bakes IDs that may go stale and turns a 1-tool-call save into a long lookup chain.
@@ -119,6 +119,7 @@ Transcribe the user's directive into \`instruction\` faithfully (preserve origin
Typical asks → action:
- "when 'bug' appears in the channel, create an issue in our tracker and assign it to me" → \`getBotDetail\` → append \`{ keyword: 'bug', instruction: '<verbatim user directive in original language>' }\` → \`updateBot({ settings: { watchKeywords: [...newArray] } })\` → acknowledge. **Stop there.** Do not list teams, users, statuses, channels, or any other reference now.
+- "people also call you canis" → \`getBotDetail\` → append \`{ keyword: 'canis', asName: true }\` → \`updateBot\` with the whole array.
- "stop watching 'bug'" → \`getBotDetail\` → \`filter\` out the entry → \`updateBot\` with the trimmed array.
- "show me the watch keywords" → \`getBotDetail\` → render \`settings.watchKeywords\` (or treat missing as "none configured").
@@ -133,6 +134,8 @@ Skipping step 1 will silently wipe other entries.
**botWakeDuties** — the bot's duties (职责边界): free text, one duty per line, describing what the bot is responsible for in its channels. With bot-wake on, a message from anyone that nobody addressed to the bot but that falls within these duties may wake it; empty turns this off. \`botWakeDutiesThreshold\` (0..1, default 0.8) is how sure it must be. Only change the duties when the bot's owner asks. The text is written as a whole: \`getBotDetail\` → edit \`settings.botWakeDuties\` (keep every duty you did not mean to touch, in the owner's language) → \`updateBot({ settings: { botWakeDuties: '<full text>' } })\`.
**Validation behaviour:** the server validates settings before persisting and returns \`updateBot error: <field>: <reason>\` when something fails (e.g. \`userId: Pairing policy requires the owner's Platform User ID.\`). Surface that message to the user and ask for the missing value rather than retrying blindly.
+
+**Owner only:** inside a bot conversation (Discord, Slack, …) only the bot's owner may change a bot or messenger connection (\`updateBot\`, \`toggleBot\`, \`deleteBot\`, \`connectBot\`, \`createBot\`, and the messenger unlink / uninstall / active-agent calls). When anyone else asks, the call fails with "Only the bot's owner can change its settings"; tell them to ask the owner instead of retrying or looking for another way to make the change.
</access_policies>
<messaging_capabilities>
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index b1c0eb5a1d3..d3842ec4413 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -435,6 +435,9 @@ export default {
'channel.watchKeywordInstructionLabel': 'Instruction',
'channel.watchKeywordInstructionPlaceholder':
'e.g. Scan the recent thread and reply if there is an actionable bug report',
+ 'channel.watchKeywordAsNameLabel': 'Bot name',
+ 'channel.watchKeywordAsNameHint':
+ 'Saying this word calls the bot, like its own name: it answers right away, even while you\'re active in the channel. Leave it off for topic words like "bug".',
'channel.watchKeywordsAdd': 'Add keyword',
'channel.watchKeywordsEmpty':
'No keywords added yet — bot only wakes on @mention or DM in subscribed channels.',
diff --git a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
index 96e8e4576d8..d950eaf2608 100644
--- a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
+++ b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
@@ -1,8 +1,18 @@
'use client';
import { isMaskedBotCredential } from '@lobechat/const';
-import type { SelectOption } from '@lobehub/ui';
-import { ActionIcon, Button, Flexbox, InputNumber, Select, Switch, Tag, Text } from '@lobehub/ui';
+import type { CheckboxProps, SelectOption } from '@lobehub/ui';
+import {
+ ActionIcon,
+ Button,
+ Checkbox,
+ Flexbox,
+ InputNumber,
+ Select,
+ Switch,
+ Tag,
+ Text,
+} from '@lobehub/ui';
import { Form, useFormInstance, useWatch } from '@lobehub/ui/form';
import { Plus, Trash2 } from 'lucide-react';
import { memo } from 'react';
@@ -329,6 +339,19 @@ const FormChoiceList = ({
'value'?: string;
}) => <ChoiceList {...props} value={value ?? ''} onChange={(next) => onChange?.(next)} />;
+/**
+ * {@link Checkbox} bound to a form field. A row saved before the property existed has no value;
+ * it reads as unchecked instead of leaving the checkbox uncontrolled.
+ */
+const FormCheckbox = ({
+ onChange,
+ value,
+ ...props
+}: Omit<CheckboxProps, 'checked' | 'onChange'> & {
+ onChange?: (checked: boolean) => void;
+ value?: boolean;
+}) => <Checkbox {...props} checked={value === true} onChange={(next) => onChange?.(next)} />;
+
// --------------- Object-list field (e.g. allowFrom: [{id, name?}]) ---------------
interface ObjectListFieldProps {
@@ -393,28 +416,46 @@ const ObjectListField = memo<ObjectListFieldProps>(
)}
{rows.map(({ index, key, name }) => (
<Flexbox horizontal align="center" gap={8} key={key}>
- {itemProps.map((sub, subIndex) => (
- <div key={sub.key} style={{ flex: subIndex === 0 ? 1 : 2, minWidth: 0 }}>
- <Form.Field
- bare
- name={`${name}.${sub.key}`}
- validate={
- sub.required
- ? (value?: string) => (value?.trim() ? undefined : t(sub.label))
- : undefined
- }
- >
- <FormInput
- disabled={editDisabled}
- placeholder={
- sub.placeholder
- ? t(sub.placeholder as 'channel.allowFromIdPlaceholder')
- : t(sub.label)
+ {itemProps.map((sub, subIndex) =>
+ // A per-row switch (e.g. "this keyword is one of the bot's names") sits after
+ // the text inputs at its natural width, its explanation in the tooltip.
+ sub.type === 'boolean' ? (
+ <Flexbox horizontal align="center" flex="none" gap={4} key={sub.key}>
+ <Form.Field bare name={`${name}.${sub.key}`}>
+ <FormCheckbox disabled={editDisabled}>
+ {t(sub.label as 'channel.watchKeywordAsNameLabel')}
+ </FormCheckbox>
+ </Form.Field>
+ {sub.description && (
+ <InfoTooltip
+ size={'small'}
+ title={t(sub.description as 'channel.watchKeywordAsNameHint')}
+ />
+ )}
+ </Flexbox>
+ ) : (
+ <div key={sub.key} style={{ flex: subIndex === 0 ? 1 : 2, minWidth: 0 }}>
+ <Form.Field
+ bare
+ name={`${name}.${sub.key}`}
+ validate={
+ sub.required
+ ? (value?: string) => (value?.trim() ? undefined : t(sub.label))
+ : undefined
}
- />
- </Form.Field>
- </div>
- ))}
+ >
+ <FormInput
+ disabled={editDisabled}
+ placeholder={
+ sub.placeholder
+ ? t(sub.placeholder as 'channel.allowFromIdPlaceholder')
+ : t(sub.label)
+ }
+ />
+ </Form.Field>
+ </div>
+ ),
+ )}
<ActionIcon
aria-label={removeLabel}
disabled={disabled}