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): stay out of multi-party threads — stricter follow-ups, why-woken hint, stand-down, other bots count (#21728)

Arvin Xub8ee46370ed9
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
index d374fe5e087..5f6c08ec222 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
@@ -31,6 +31,8 @@ describe('parseBotWakeSettings', () => {
expect(parsed.ruleMode).toBe('enforce');
expect(parsed.rules.classifier.mode).toBe('enforce');
+ // A follow-up must be clearly for the bot: 0.5-0.7 is mostly someone talking to someone else.
+ expect(parsed.rules.classifier.threshold).toBe(0.7);
expect(
parseBotWakeSettings({ botWake: { classifier: { threshold: 0.8 } } }).rules.classifier,
).toEqual({ mode: 'enforce', threshold: 0.8 });
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
index 0adcbd6453b..82d9e85e2f2 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
@@ -110,7 +110,7 @@ describe('duty policy', () => {
const judge = judgeScoring(1);
const after = (line: Partial<WakeConversationLine>, at = NOW - 30_000) =>
createDutyPolicy(rules(), judge).evaluate({
- signal: signal(),
+ signal: signal({ applicationId: 'bot-app' }),
state: {
conversation: {
botNames: ['Nasa'],
@@ -127,6 +127,13 @@ describe('duty policy', () => {
expect((await after({}, NOW - 5 * 60_000)).verdict).toBe('allow');
expect((await after({ authorId: 'bot-app', isBot: true })).verdict).toBe('allow');
expect((await after({ authorId: 'bob' })).verdict).toBe('allow');
+
+ // Another agent in the thread: the owner is answering it, not asking this bot.
+ expect(await after({ authorId: 'other-agent', isBot: true })).toMatchObject({
+ reason: 'answering-other',
+ verdict: 'abstain',
+ });
+ expect(judge).toHaveBeenCalledTimes(3);
});
it('does not ask about a message too short to act on', async () => {
@@ -182,7 +189,7 @@ describe('duty policy', () => {
costly: true,
id: DUTY_POLICY_ID,
mode: 'enforce',
- version: 1,
+ version: 2,
});
});
});
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
index 2f2efde3e8a..a25e23eb087 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
@@ -574,6 +574,54 @@ describe('createWakePolicySet', () => {
});
});
+// The bot stepped back after "nasa 就在这瞎捣乱", then was woken by its name two minutes later.
+describe('owner rules policy: a stand-down', () => {
+ const conversation = { botNames: ['Nasa'], recent: [] };
+ const policies = () =>
+ createWakePolicySet({ settings: { botWake: { enabled: true, mode: 'enforce' } } });
+ const decide = (s: Partial<WakeSignal>, c: Partial<WakeChannelState>, explicit = false) =>
+ aggregateWakeVerdictsAsync(policies(), signal(s), {
+ ...snapshot(c),
+ conversation,
+ explicitMention: explicit,
+ });
+ const inWindow = { botLastSpokeAt: NOW - 10_000, followupUntil: NOW + 60_000 };
+
+ it('denies every wake nobody addressed to the bot, its name in the text included', async () => {
+ const stoodDown = { ...inWindow, standDownUntil: NOW + 60_000 };
+
+ for (const message of ['那这个怎么处理?', '其他 agent 为啥不能来看和学习呢?nasa']) {
+ const decision = await decide({ message }, stoodDown);
+ expect([decision.verdict, decision.reason, decision.decidedBy]).toEqual([
+ 'deny',
+ 'stood-down',
+ OWNER_RULES_POLICY_ID,
+ ]);
+ }
+ });
+
+ it('still wakes for an explicit @-mention or reply: those never reach the policies', async () => {
+ const decision = await decide(
+ { message: 'Nasa 你来看下' },
+ { standDownUntil: NOW + 60_000 },
+ true,
+ );
+
+ expect(decision).toMatchObject({ fastPath: true, verdict: 'allow' });
+ });
+
+ it('ends when its time is up', async () => {
+ const over = { ...inWindow, standDownUntil: NOW - 1 };
+
+ expect((await decide({ message: 'Nasa 你怎么看' }, over)).reason).toBe('named-in-text');
+ expect(
+ (await decide({ message: '那这个怎么处理?' }, over)).records.find(
+ (record) => record.policyId === OWNER_RULES_POLICY_ID,
+ )?.reason,
+ ).toBe('inside-followup-window');
+ });
+});
+
describe('policy set aggregation', () => {
const classify = vi.fn<WakeClassify>(async () => ({
addressedToBot: 0.1,
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
index 29f4fc17736..3ec2470ce2f 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
@@ -5,7 +5,9 @@ import type { BotWakeConfig, WakePolicyMode, WakeRules, WakeSchedulerConfig } fr
export const DEFAULT_WAKE_RULES: WakeRules = {
allowChannels: [],
- classifier: { mode: 'enforce', threshold: 0.5 },
+ // A follow-up in the window is answered only when the classifier is fairly sure it is for the bot:
+ // in a thread with several people and bots, 0.5-0.7 is mostly the owner talking to someone else.
+ classifier: { mode: 'enforce', threshold: 0.7 },
denyChannels: [],
// Off until the bot has duties: without the text there is nothing to judge a message against.
duties: { mode: 'enforce', threshold: 0.8 },
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/conversation.ts b/apps/server/src/services/agentSignal/scenarios/botWake/conversation.ts
index e167e877ea0..1c375a9eb00 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/conversation.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/conversation.ts
@@ -1,4 +1,4 @@
-import type { WakeConversationLine } from './types';
+import type { WakeConversation, WakeConversationLine } from './types';
/** A message longer than this is cut: the log keeps context for a model, not an archive. */
export const CONVERSATION_LINE_MAX_CHARS = 500;
@@ -9,6 +9,9 @@ export const CONVERSATION_LOG_MAX_LINES = 200;
/** Messages shown to the classifier. */
export const CONVERSATION_PROMPT_LINES = 20;
+/** Participants named to a woken agent: who is in the room, not a roster. */
+export const MAX_NAMED_PARTICIPANTS = 8;
+
/** A name shorter than this would match inside ordinary words. */
const MIN_BOT_NAME_LENGTH = 2;
@@ -114,6 +117,46 @@ export const describeLine = (
return `${speaker}: ${line.text}`;
};
+/** Someone taking part in a conversation, as the woken agent is told: a name and what they are. */
+export interface WakeParticipant {
+ /** Another bot or agent. */
+ isBot: boolean;
+ /** The bot's owner. */
+ isOwner: boolean;
+ name: string;
+}
+
+/**
+ * Who else has been taking part in a conversation lately, newest first: people and other bots, by
+ * the name they posted under. Names only, never what they said. Leaves out this bot's own lines
+ * (logged under `botAuthorId`) and lines without a name.
+ */
+export const conversationParticipants = (
+ conversation: WakeConversation | undefined,
+ botAuthorId: string | undefined,
+): WakeParticipant[] => {
+ const seen = new Set<string>();
+ const participants: WakeParticipant[] = [];
+
+ for (const line of [...(conversation?.recent ?? [])].reverse()) {
+ if (line.isBot && botAuthorId !== undefined && line.authorId === botAuthorId) continue;
+ const name = line.authorName?.trim();
+ if (!name) continue;
+ const key = line.authorId ?? name;
+ if (seen.has(key)) continue;
+ seen.add(key);
+
+ participants.push({
+ isBot: line.isBot,
+ isOwner: conversation?.ownerId !== undefined && line.authorId === conversation.ownerId,
+ name,
+ });
+ if (participants.length >= MAX_NAMED_PARTICIPANTS) break;
+ }
+
+ return participants;
+};
+
const isWordChar = (char: string | undefined) => !!char && /\w/.test(char);
/**
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/duty.ts b/apps/server/src/services/agentSignal/scenarios/botWake/policies/duty.ts
index e1669446871..cd3a523ed47 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/policies/duty.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/policies/duty.ts
@@ -73,8 +73,8 @@ const degraded = (reason: string): WakePolicyResult => ({
* Returns:
* - `abstain` without a model call for a message too short to act on, and for a reply to someone
* else: the author is answering that person, and the model, which only sees the text, reads the
- * "你" in it as the assistant. The same for a message right after another person spoke
- * (`answering-other`): a conversation between people, reply or not
+ * "你" in it as the assistant. The same for a message right after another participant spoke
+ * (`answering-other`): a person or another bot, anyone but this bot and the author, reply or not
* - `abstain` tagged `degraded` when the model errors or answers late: no answer is not a yes
* - Otherwise `allow` when the score reaches `rules.duties.threshold`, else `deny`; `confidence` is
* the score and `matched` the duty the model named
@@ -96,10 +96,13 @@ export const createDutyPolicy = (
) {
return abstain('reply-to-other');
}
+ // Another bot counts: in a thread with several agents the owner is often answering one of
+ // them. Only this bot's own lines (logged under its application id) do not.
const previous = state.conversation?.recent.at(-1);
+ const isOwnLine = previous?.isBot === true && previous.authorId === signal.applicationId;
if (
previous &&
- !previous.isBot &&
+ !isOwnLine &&
previous.authorId !== undefined &&
previous.authorId !== authorId &&
signal.timestamp - previous.at < ANSWERING_OTHER_MS
@@ -158,5 +161,5 @@ export const createDutyPolicy = (
id: DUTY_POLICY_ID,
mode: rules.duties.mode,
requires: ['channel', 'conversation'],
- version: 1,
+ version: 2,
});
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts b/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts
index 6142d48a5f1..272e023f72c 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts
@@ -11,8 +11,13 @@ const deny = (reason: string): WakePolicyResult => ({
});
/**
- * The bot owner's structured rules: scope, channel allow/deny lists, follow-up window, the
- * silent-wake budget and owner-presence suppression.
+ * The bot owner's structured rules: scope, channel allow/deny lists, a stand-down, follow-up
+ * window, the silent-wake budget and owner-presence suppression.
+ *
+ * A stand-down is the bot stepping back after people told it it was interfering. Until it ends,
+ * every wake nobody explicitly addressed to the bot is denied, its name in the text included:
+ * being mentioned in passing ("nasa 就在这瞎捣乱") is exactly what it stepped back from. An
+ * @-mention or a reply to it never reaches the policies (the fast path), so those still wake it.
*
* Owner presence keeps the bot from joining chatter on its own while the owner is around to
* answer. A message that calls the bot by name asked for the bot, not the owner, so presence does
@@ -26,7 +31,8 @@ const deny = (reason: string): WakePolicyResult => ({
*
* Returns:
* - `deny` with the first rule that matched (checked in a fixed order: scope, deny list, allow
- * list, window, budget, owner presence; owner presence is skipped when the text names the bot)
+ * list, stand-down (`stood-down`), window, budget, owner presence; owner presence is skipped when
+ * the text names the bot)
* - `allow` when the bot spoke within the follow-up window, the author is the person whose message
* woke it there, and nothing denied
* - `abstain` otherwise: outside the window, or for someone else in it, the owner's rules have no
@@ -45,6 +51,10 @@ export const createOwnerRulesPolicy = (mode: WakePolicyMode, rules: WakeRules):
return deny('channel-not-allowed');
}
+ if (channel?.standDownUntil !== undefined && channel.standDownUntil > now) {
+ return deny('stood-down');
+ }
+
const windowOpen =
channel?.followupUntil !== undefined
? channel.followupUntil > now
@@ -93,5 +103,5 @@ export const createOwnerRulesPolicy = (mode: WakePolicyMode, rules: WakeRules):
id: OWNER_RULES_POLICY_ID,
mode,
requires: ['channel', 'conversation'],
- version: 3,
+ version: 4,
});
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts b/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
index 4dfea0ac0e2..369f362069f 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
@@ -209,6 +209,11 @@ export interface WakeChannelState {
* silence.
*/
silentWakes: number;
+ /**
+ * The bot stepped back from this conversation until then: people told it it was interfering.
+ * Only an explicit address (@-mention, reply, DM, command) wakes it before.
+ */
+ standDownUntil?: number;
}
/** Where passive waking may happen. */
diff --git a/apps/server/src/services/bot/AgentBridgeService/execute.ts b/apps/server/src/services/bot/AgentBridgeService/execute.ts
index 995d697e50b..b835cdf5b7f 100644
--- a/apps/server/src/services/bot/AgentBridgeService/execute.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/execute.ts
@@ -55,12 +55,16 @@ export async function executeWithCallback(
opts: {
agentId: string;
botContext?: ChatTopicBotContext;
+ /** The bot's settings; local mode records the bot-wake outcome with them. */
+ botSettings?: Record<string, unknown>;
channelContext?: DiscordChannelContext;
charLimit?: number;
client?: PlatformClient;
displayToolCalls?: boolean;
/** The message falls within the bot's duties; told to the agent with a `followup`. */
duty?: { matched?: string };
+ /** The bot woke in its follow-up window; told to the agent with a `followup`. */
+ followup?: BotPlatformContext['followup'];
/** The bot woke only because its name is in the text; told to the agent with a `followup`. */
named?: boolean;
/** Emoji the owner lets the bot use in this conversation. */
@@ -71,6 +75,8 @@ export async function executeWithCallback(
openingReply?: string;
reactionMode?: BotReactionMode;
replyLocale: BotReplyLocale;
+ /** The agent may step back from this conversation; documented in its prompt. */
+ standDown?: boolean;
topicId?: string;
trigger?: string;
/** `followup` holds visible feedback back until the agent starts acting. Default `mention`. */
@@ -301,6 +307,7 @@ export async function executeWithCallback(
if (deferFeedback && botPlatformContext) {
botPlatformContext.wakeKind = wakeKind;
if (opts.duty) botPlatformContext.duty = opts.duty;
+ if (opts.followup) botPlatformContext.followup = opts.followup;
if (opts.named) botPlatformContext.named = true;
}
if (opts.openingReply && botPlatformContext) botPlatformContext.openingReply = opts.openingReply;
@@ -308,6 +315,7 @@ export async function executeWithCallback(
if (opts.replyStyle) botPlatformContext.replyStyle = opts.replyStyle;
if (opts.replyEmojis?.length) botPlatformContext.replyEmojis = opts.replyEmojis;
}
+ if (opts.standDown && botPlatformContext) botPlatformContext.standDown = true;
// Attach file warnings to botPlatformContext for injection via context engine
if (fileWarnings?.length && botPlatformContext) {
@@ -381,6 +389,7 @@ export async function executeWithCallback(
botContext,
botPlatformContext,
botSender,
+ botSettings: opts.botSettings,
callbackUrl,
charLimit,
channelContext,
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts
index d10ef4d9bdd..b301546d635 100644
--- a/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts
@@ -16,6 +16,7 @@ const mockTopicFindById = vi.hoisted(() => vi.fn());
const mockIsRunningOperationAlive = vi.hoisted(() => vi.fn());
const mockDeferBotMessages = vi.hoisted(() => vi.fn());
const mockRecordNoReplyLabel = vi.hoisted(() => vi.fn());
+const mockRecordWakeRunOutcome = vi.hoisted(() => vi.fn());
vi.mock('../BotMessageRouter', () => ({
getBotMessageRouter: () => ({ replayDeferredMessages: vi.fn() }),
@@ -63,6 +64,9 @@ vi.mock('@/server/services/bot/deferredMessages', () => ({
vi.mock('@/server/services/bot/noReplyLabel', () => ({
recordNoReplyLabel: mockRecordNoReplyLabel,
}));
+vi.mock('@/server/services/bot/wake/scheduler', () => ({
+ recordWakeRunOutcome: mockRecordWakeRunOutcome,
+}));
vi.mock('@/server/services/bot/platforms', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
return { ...actual, platformRegistry: { getPlatform: mockGetPlatform } };
@@ -380,6 +384,20 @@ describe('AgentBridgeService no_reply and deferred follow-up feedback', () => {
expect(execParams().botPlatformContext.named).toBeUndefined();
});
+ it('tells a followup agent woken in its window how sure the check was and who else is here', async () => {
+ runHooks({ onComplete: { lastAssistantContent: 'NO_REPLY', reason: 'done' } });
+ const { client } = createClient();
+ const followup = { participants: [{ isBot: true, name: 'Dario' }], score: 0.56 };
+
+ await subscribed(createThread().thread, client, { followup, wakeKind: 'followup' });
+ expect(execParams().botPlatformContext.followup).toEqual(followup);
+
+ mockExecAgent.mockClear();
+ AgentBridgeService.clearActiveThread(THREAD_ID);
+ await subscribed(createThread().thread, client, { followup });
+ expect(execParams().botPlatformContext.followup).toBeUndefined();
+ });
+
it('a catch-all wake the bot started itself shows nothing until the agent acts', async () => {
runHooks({
onComplete: { lastAssistantContent: 'NO_REPLY', operationId: 'op-1', reason: 'done' },
@@ -400,6 +418,78 @@ describe('AgentBridgeService no_reply and deferred follow-up feedback', () => {
expect(thread.post).not.toHaveBeenCalled();
expect(execParams().botPlatformContext.wakeKind).toBe('followup');
});
+
+ // Local mode has no completion webhook, so the bridge records the wake outcome itself.
+ it('records a stand-down after the reply, and posts the reply without the marker', async () => {
+ runHooks({
+ onComplete: {
+ lastAssistantContent: 'Sorry, I will stay out.\nSTAND_DOWN',
+ operationId: 'op-1',
+ reason: 'done',
+ },
+ });
+ const { progress, thread } = createThread();
+ const { client } = createClient();
+ const botSettings = { botWake: { enabled: true } };
+
+ await subscribed(thread, client, { botSettings, standDown: true });
+
+ // A mention edits its placeholder into the final reply.
+ expect(progress.edit).toHaveBeenLastCalledWith({
+ markdown: renderFinalReply('Sorry, I will stay out.'),
+ });
+ expect(mockRecordWakeRunOutcome).toHaveBeenCalledWith({
+ applicationId: 'app-1',
+ platform: 'discord',
+ platformThreadId: THREAD_ID,
+ settings: botSettings,
+ spoke: true,
+ spoken: { id: 'op-1', text: 'Sorry, I will stay out.' },
+ standDown: true,
+ wakeKind: 'mention',
+ });
+ });
+
+ it('records a silent stand-down (NO_REPLY:stand_down) on a followup', async () => {
+ runHooks({
+ onComplete: {
+ lastAssistantContent: 'NO_REPLY:stand_down',
+ operationId: 'op-1',
+ reason: 'done',
+ },
+ });
+ const { thread } = createThread();
+ const { client } = createClient();
+
+ await subscribed(thread, client, { standDown: true, wakeKind: 'followup' });
+
+ expect(thread.post).not.toHaveBeenCalled();
+ expect(mockRecordWakeRunOutcome).toHaveBeenCalledWith(
+ expect.objectContaining({ spoke: false, standDown: true, wakeKind: 'followup' }),
+ );
+ });
+
+ it('records an ordinary reply as spoken, without a stand-down', async () => {
+ runHooks({ onComplete: { lastAssistantContent: 'here is the fix', reason: 'done' } });
+ const { thread } = createThread();
+ const { client } = createClient();
+
+ await subscribed(thread, client, { wakeKind: 'followup' });
+
+ expect(mockRecordWakeRunOutcome).toHaveBeenCalledWith(
+ expect.objectContaining({ spoke: true, standDown: false }),
+ );
+ });
+
+ it('records nothing for a failed run', async () => {
+ runHooks({ onComplete: { errorMessage: 'boom', operationId: 'op-1', reason: 'error' } });
+ const { thread } = createThread();
+ const { client } = createClient();
+
+ await subscribed(thread, client, { standDown: true });
+
+ expect(mockRecordWakeRunOutcome).not.toHaveBeenCalled();
+ });
});
describe('queue mode', () => {
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.ts b/apps/server/src/services/bot/AgentBridgeService/index.ts
index 9bf7ed43327..9b834faa096 100644
--- a/apps/server/src/services/bot/AgentBridgeService/index.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/index.ts
@@ -395,6 +395,9 @@ export class AgentBridgeService {
client,
displayToolCalls,
duty: opts.duty,
+ followup: opts.followup,
+ standDown: opts.standDown,
+ botSettings: opts.botSettings,
named: opts.named,
replyEmojis: opts.replyEmojis,
replyStyle: opts.replyStyle,
@@ -591,6 +594,9 @@ export class AgentBridgeService {
displayToolCalls,
reactionMode,
duty: opts.duty,
+ followup: opts.followup,
+ standDown: opts.standDown,
+ botSettings: opts.botSettings,
named: opts.named,
replyEmojis: opts.replyEmojis,
replyStyle: opts.replyStyle,
diff --git a/apps/server/src/services/bot/AgentBridgeService/localMode.ts b/apps/server/src/services/bot/AgentBridgeService/localMode.ts
index 122bf142500..5ec85bd2aea 100644
--- a/apps/server/src/services/bot/AgentBridgeService/localMode.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/localMode.ts
@@ -10,7 +10,7 @@ import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewa
import { SystemAgentService } from '@/server/services/systemAgent';
import { createBotCompletionWebhook } from '../createBotCompletionHook';
-import { detectNoReply } from '../noReply';
+import { detectNoReply, extractStandDown } from '../noReply';
import { recordNoReplyLabel } from '../noReplyLabel';
import type { BotReactionMode, BotReplyLocale, PlatformClient } from '../platforms';
import {
@@ -28,6 +28,7 @@ import {
renderStopped,
splitMessage,
} from '../replyTemplate';
+import { recordWakeRunOutcome } from '../wake/scheduler';
import type {
BridgeExecutionDeps,
BridgeExecutionResult,
@@ -52,6 +53,8 @@ export async function executeWithHooksLocalMode(
botContext?: ChatTopicBotContext;
botPlatformContext?: BotPlatformContext;
botSender?: BotSenderMetadata;
+ /** The bot's settings, for the bot-wake bookkeeping done at completion. */
+ botSettings?: Record<string, unknown>;
callbackUrl: string;
charLimit?: number;
channelContext?: DiscordChannelContext;
@@ -84,6 +87,7 @@ export async function executeWithHooksLocalMode(
botContext,
botPlatformContext,
botSender,
+ botSettings,
callbackUrl,
charLimit,
channelContext,
@@ -294,6 +298,32 @@ export async function executeWithHooksLocalMode(
hasAttachments: !!(event.attachments as unknown[] | undefined)?.length,
wakeKind,
});
+ // Bot-wake bookkeeping (follow-up window, silent-wake budget, stand-down), as the
+ // queue-mode callback does: best-effort and a no-op unless bot-wake is enabled.
+ if (botContext?.applicationId && botContext.platformThreadId) {
+ try {
+ await recordWakeRunOutcome({
+ applicationId: botContext.applicationId,
+ platform: botContext.platform,
+ platformThreadId: botContext.platformThreadId,
+ settings: botSettings,
+ spoke: !noReply,
+ // What was posted: without the stand-down marker, which is for the runtime.
+ spoken: {
+ id: event.operationId,
+ text: extractStandDown(lastAssistantContent).content,
+ },
+ // A `STAND_DOWN` line after the reply, or `NO_REPLY:stand_down`.
+ standDown:
+ noReply?.reason === 'stand_down' ||
+ extractStandDown(lastAssistantContent).standDown,
+ wakeKind,
+ });
+ } catch (error) {
+ log('executeWithCallback[local]: recordWakeRunOutcome failed: %O', error);
+ }
+ }
+
if (noReply) {
log(
'onComplete: no_reply reason=%s operationId=%s',
@@ -335,13 +365,15 @@ export async function executeWithHooksLocalMode(
const lastChunkAttachments = hookEventAttachmentsToChatSdk(
event.attachments as any,
);
- const hasText = !!lastAssistantContent;
+ // The stand-down marker is for the runtime, not the channel.
+ const replyText = extractStandDown(lastAssistantContent).content;
+ const hasText = !!replyText;
const hasAttachments = !!lastChunkAttachments?.length;
if (hasText || hasAttachments) {
let chunks: string[];
if (hasText) {
- const replyBody = renderFinalReply(lastAssistantContent!);
+ const replyBody = renderFinalReply(replyText!);
const replyStats = {
elapsedMs: event.duration ?? getElapsedMs(),
llmCalls: event.llmCalls ?? 0,
@@ -392,7 +424,7 @@ export async function executeWithHooksLocalMode(
chunks.length,
lastChunkAttachments?.length ?? 0,
);
- resolve({ reply: lastAssistantContent ?? '', topicId: resolvedTopicId });
+ resolve({ reply: replyText ?? '', topicId: resolvedTopicId });
// Fire-and-forget: summarize topic title in DB. Only when
// we have text to summarize on — image-only replies skip
diff --git a/apps/server/src/services/bot/AgentBridgeService/types.ts b/apps/server/src/services/bot/AgentBridgeService/types.ts
index af0f9f16d64..c891e192878 100644
--- a/apps/server/src/services/bot/AgentBridgeService/types.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/types.ts
@@ -1,3 +1,4 @@
+import type { BotPlatformContext } from '@lobechat/context-engine';
import type { BotNoReplyResult, BotWakeKind, ChatTopicBotContext } from '@lobechat/types';
import type { Message, SentMessage, Thread } from 'chat';
@@ -25,6 +26,11 @@ export interface ThreadState {
export interface BridgeHandlerOpts {
agentId: string;
botContext?: ChatTopicBotContext;
+ /**
+ * The bot's settings. Local mode completes in-process, so it records the bot-wake outcome
+ * (follow-up window, silent-wake budget, stand-down) itself; queue mode reads them in the callback.
+ */
+ botSettings?: Record<string, unknown>;
charLimit?: number;
client?: PlatformClient;
displayToolCalls?: boolean;
@@ -34,6 +40,11 @@ export interface BridgeHandlerOpts {
* `formatBotPlatformContext`.
*/
duty?: { matched?: string };
+ /**
+ * The bot woke in its follow-up window (a `followup` wake): how sure the classifier was and who
+ * else is in the thread. The agent is told why. See `formatBotPlatformContext`.
+ */
+ followup?: BotPlatformContext['followup'];
/**
* The bot woke only because its name is in the text (a `followup` wake): people often talk about
* it rather than to it, and the agent is told so. See `formatBotPlatformContext`.
@@ -59,6 +70,12 @@ export interface BridgeHandlerOpts {
replyLocale?: BotReplyLocale;
/** How the bot talks in this conversation, as the owner wrote it. See `formatBotPlatformContext`. */
replyStyle?: string;
+ /**
+ * The agent may step back from this conversation (`STAND_DOWN`) when people say it is
+ * interfering: a group conversation of a bot whose wake rules enforce. See
+ * `formatBotPlatformContext`.
+ */
+ standDown?: boolean;
/**
* How the bot was woken. `followup` lets the agent end in silence and holds back every visible
* side effect (reaction, typing, progress message) until it decides to speak; `mention`
diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.ts
index 893a7350e1c..b55e9c9aebc 100644
--- a/apps/server/src/services/bot/BotCallbackService.ts
+++ b/apps/server/src/services/bot/BotCallbackService.ts
@@ -24,7 +24,7 @@ import { SystemAgentService } from '@/server/services/systemAgent';
import { AgentBridgeService } from './AgentBridgeService';
import { runDeferredReplay, scheduleDeferredReplay } from './deferredReplay';
-import { detectNoReply } from './noReply';
+import { detectNoReply, extractStandDown } from './noReply';
import { recordNoReplyLabel } from './noReplyLabel';
import type {
BotMessageAttachment,
@@ -249,14 +249,15 @@ export class BotCallbackService {
// In queue mode, the bridge handler's finally block skips this cleanup
// to keep the thread marked active while the agent runs on the job queue.
AgentBridgeService.clearActiveThread(platformThreadId);
- // Bookkeeping for the bot-wake pipeline (follow-up window, silent-wake budget, scheduler).
- // Best-effort and a no-op unless the bot has bot-wake enabled: it never affects delivery.
- await this.recordWakeOutcome(
- body,
- settings,
- platform,
- !noReply && body.reason !== 'error' && body.reason !== 'interrupted',
- );
+ // Bookkeeping for the bot-wake pipeline (follow-up window, silent-wake budget, stand-down,
+ // scheduler). Best-effort and a no-op unless the bot has bot-wake enabled: it never affects
+ // delivery.
+ const finished = body.reason !== 'error' && body.reason !== 'interrupted';
+ // The agent steps back with a `STAND_DOWN` line after its reply, or `NO_REPLY:stand_down`.
+ const standDown =
+ finished &&
+ (noReply?.reason === 'stand_down' || extractStandDown(body.lastAssistantContent).standDown);
+ await this.recordWakeOutcome(body, settings, platform, finished && !noReply, standDown);
if (noReply) {
await this.labelNoReply(body, noReply, platform, workspaceId);
} else {
@@ -322,6 +323,7 @@ export class BotCallbackService {
settings: Record<string, unknown> | null | undefined,
platform: string,
spoke: boolean,
+ standDown: boolean,
): Promise<void> {
try {
await recordWakeRunOutcome({
@@ -330,7 +332,12 @@ export class BotCallbackService {
platformThreadId: body.platformThreadId,
settings,
spoke,
- spoken: { id: body.operationId ?? randomUUID(), text: body.lastAssistantContent },
+ // What was posted: without the stand-down marker, which is for the runtime.
+ spoken: {
+ id: body.operationId ?? randomUUID(),
+ text: extractStandDown(body.lastAssistantContent).content,
+ },
+ standDown,
wakeKind: body.wakeKind,
});
} catch (error) {
@@ -675,7 +682,9 @@ export class BotCallbackService {
// ("\n", " ") through; those collapse to empty text downstream and get
// rejected by Telegram as "message text is empty", silently losing the
// reply. Trim before testing.
- const hasText = !!lastAssistantContent?.trim();
+ // The stand-down marker is for the runtime, not the channel; what came before it is posted.
+ const replyText = extractStandDown(lastAssistantContent).content;
+ const hasText = !!replyText?.trim();
const hasAttachments = !!attachments?.length;
if (!hasText && !hasAttachments) {
// console (not debug) — every one of these is a user-facing "bot went
@@ -700,7 +709,7 @@ export class BotCallbackService {
// attachment-only path still drives `deliverFirstChunk` once.
let chunks: string[];
if (hasText) {
- const msgBody = renderFinalReply(lastAssistantContent!);
+ const msgBody = renderFinalReply(replyText!);
const formattedBody = client.formatMarkdown?.(msgBody) ?? msgBody;
const finalText = client.formatReply?.(formattedBody, stats) ?? formattedBody;
chunks = splitMessage(finalText, charLimit);
diff --git a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
index 788e9fe68cd..ec819b7743d 100644
--- a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
@@ -22,8 +22,10 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
const {
agentId,
applicationId,
+ botSettings,
botWakeEnabled,
bridge,
+ canStandDown,
charLimit,
client,
commands,
@@ -285,6 +287,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
platform,
platformThreadId: thread.id,
}),
+ botSettings,
charLimit,
client,
displayToolCalls,
@@ -292,8 +295,10 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
reactionMode,
replyLocale,
duty: initiation?.reason === 'in-duty' ? { matched: initiation.duty } : undefined,
+ followup: initiation?.reason === 'followup-window' ? initiation.followup : undefined,
named: wakeReason === 'named-in-text',
...replyVoiceFor(thread.id),
+ standDown: await canStandDown(thread),
wakeKind,
});
} catch (error) {
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index 5b3d8e6c1b9..02fa73f0790 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -122,6 +122,8 @@ export function registerHandlers(
* can drive a specific directive ("scan the recent thread for a bug
* report", "summarise the last 20 messages", …).
*/
+ const wakeSettings = parseBotWakeSettings(info.settings);
+ const botWakeEnabled = isBotWakeEnabled(wakeSettings.config);
const watchKeywordEntries = extractWatchKeywordEntries(info.settings);
const watchKeywords: ReadonlyArray<string> = watchKeywordEntries.map((e) => e.keyword);
/**
@@ -446,6 +448,17 @@ export function registerHandlers(
return { openingReply: opening.openingReply, release: opening.release };
};
+ /**
+ * Whether the agent may step back from a conversation when people say it is interfering. Only
+ * where it changes something: a stand-down is enforced by the owner rules, in a group
+ * conversation, once the rollout reaches the bot's owner.
+ */
+ const canStandDown = async (thread: { isDM?: boolean }) =>
+ botWakeEnabled &&
+ wakeSettings.ruleMode === 'enforce' &&
+ !thread.isDM &&
+ (await wakeRecorder.isRolledOut());
+
const gateFollowup = createFollowupGate({
applicationId,
observe: observe as FollowupGateDeps['observe'],
@@ -556,6 +569,7 @@ export function registerHandlers(
platform,
platformThreadId: thread.id,
}),
+ botSettings: info.settings,
charLimit,
client,
displayToolCalls,
@@ -563,6 +577,7 @@ export function registerHandlers(
reactionMode,
replyLocale,
...replyVoiceFor(thread.id),
+ standDown: await canStandDown(thread),
});
} catch (error) {
const operationId = AgentBridgeService.getActiveOperationId(thread.id);
@@ -860,15 +875,18 @@ export function registerHandlers(
platform,
platformThreadId: thread.id,
}),
+ botSettings: info.settings,
charLimit,
client,
displayToolCalls,
duty: wakeReason === 'in-duty' ? { matched: initiation?.duty } : undefined,
+ followup: wakeReason === 'followup-window' ? initiation?.followup : undefined,
named: wakeReason === 'named-in-text',
openingReply,
reactionMode,
replyLocale,
...replyVoiceFor(thread.id),
+ standDown: await canStandDown(thread),
wakeKind,
});
} catch (error) {
@@ -907,9 +925,11 @@ export function registerHandlers(
deviceAllowlist,
agentId,
applicationId,
- botWakeEnabled: isBotWakeEnabled(parseBotWakeSettings(info.settings).config),
replyVoiceFor,
+ botSettings: info.settings,
+ botWakeEnabled,
bridge,
+ canStandDown,
charLimit,
client,
commands,
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts
index 953ea358a8b..0d3eeb2e59e 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts
@@ -197,7 +197,7 @@ describe('mock Discord bot-wake decision records (real database, real router han
]);
for (const row of stored) {
expect(row).toMatchObject({
- pipelineVersion: 'bot-wake@2',
+ pipelineVersion: 'bot-wake@3',
scopeKey: 'discord:app-1',
source: 'bot:discord',
});
@@ -233,7 +233,7 @@ describe('mock Discord bot-wake decision records (real database, real router han
decision: {
llmTracingIds: [tracing.id],
outcome: 'skip',
- pipelineVersion: 'bot-wake@2',
+ pipelineVersion: 'bot-wake@3',
},
scopeKey: 'discord:app-1',
signal: {
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts
index 55c568fafe8..6a9397e3882 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts
@@ -114,7 +114,7 @@ describe('BotMessageRouter bot-wake decision records', () => {
externalId: 'app-1:telegram:chat-1:msg-1',
finalReason: 'explicit-mention',
outcome: 'wake',
- pipelineVersion: 'bot-wake@2',
+ pipelineVersion: 'bot-wake@3',
scopeKey: 'telegram:app-1',
toTag: 'mention',
verdicts: [
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
index 30dec3d3d17..160eac805fa 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
@@ -276,6 +276,91 @@ describe('BotMessageRouter: a message that only names the bot', () => {
expect(mockHandleSubscribedMessage.mock.calls[0][2]).toMatchObject({ wakeKind: 'followup' });
});
+ it('tells the agent woken in its follow-up window how sure the check was and who else is here', async () => {
+ mocks.channel.current = { botLastSpokeAt: Date.now() - 60_000, silentWakes: 0 };
+ mocks.classify.mockResolvedValue({ addressedToBot: 0.8, kind: 'request', reason: 'x' });
+ mocks.logs.set(CHANNEL, [
+ { at: 1, authorId: 'bob-id', authorName: 'bob', id: 'a', isBot: false, text: 'hmm' },
+ ]);
+ await boot(enforcing);
+
+ await catchAll()(thread(), message({ text: '那现在呢?' }));
+ await flush();
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention.mock.calls[0][2]).toMatchObject({
+ followup: { participants: [{ isBot: false, isOwner: false, name: 'bob' }], score: 0.8 },
+ wakeKind: 'followup',
+ });
+ });
+
+ // "nasa 就在这瞎捣乱" → it stood down, then "…其他 agent 为啥不能来看和学习呢?nasa" woke it again.
+ describe('after the bot stood down', () => {
+ beforeEach(() => {
+ mocks.channel.current = {
+ botLastSpokeAt: Date.now() - 60_000,
+ silentWakes: 0,
+ standDownUntil: Date.now() + 20 * 60_000,
+ };
+ });
+
+ it('is not woken by its name in passing, and the decision says why', async () => {
+ await boot(enforcing);
+
+ await catchAll()(
+ thread(),
+ message({ text: '其他 agent 为啥不能来看和学习呢?Shadow Arvin' }),
+ );
+ await flush();
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ const [decision] = decisions();
+ expect([decision.outcome, decision.finalReason]).toEqual(['skip', 'not-addressed']);
+ expect(decision.verdicts.map((v: any) => [v.policyId, v.verdict, v.reason])).toContainEqual([
+ 'bot-wake:owner-rules',
+ 'deny',
+ 'stood-down',
+ ]);
+ });
+
+ it('is not woken in its follow-up window either', async () => {
+ mocks.classify.mockResolvedValue({ addressedToBot: 0.95, kind: 'request', reason: 'x' });
+ await boot(enforcing);
+
+ await subscribed()(thread(`${CHANNEL}:thread-1`), message({ text: '那现在呢?' }));
+ await flush();
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(mocks.classify).not.toHaveBeenCalled();
+ });
+
+ it('still answers an explicit @-mention, and may stand down again', async () => {
+ await boot(enforcing);
+
+ await subscribed()(thread(`${CHANNEL}:thread-1`), message({ isMention: true, text: 'hi' }));
+ await flush();
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ expect(mockHandleSubscribedMessage.mock.calls[0][2]).toMatchObject({
+ standDown: true,
+ wakeKind: 'mention',
+ });
+ });
+ });
+
+ it('offers the agent a stand-down only where it takes effect: enforcing rules, not a DM', async () => {
+ await boot({ enabled: true, mode: 'shadow' });
+ await subscribed()(thread(`${CHANNEL}:thread-1`), message({ isMention: true, text: 'hi' }));
+ expect(mockHandleSubscribedMessage.mock.calls.at(-1)![2].standDown).toBe(false);
+
+ await boot(enforcing);
+ await subscribed()(
+ { ...thread('discord:@me:dm-1'), isDM: true },
+ message({ isMention: true, text: 'hi' }),
+ );
+ expect(mockHandleSubscribedMessage.mock.calls.at(-1)![2].standDown).toBe(false);
+ });
+
it('never wakes for another bot, even one that names it', async () => {
await boot(enforcing);
diff --git a/apps/server/src/services/bot/BotMessageRouter/types.ts b/apps/server/src/services/bot/BotMessageRouter/types.ts
index d650f98c255..9dc53fff8bb 100644
--- a/apps/server/src/services/bot/BotMessageRouter/types.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/types.ts
@@ -127,9 +127,16 @@ export interface BotReplyVoice {
export interface BotHandlerContext {
agentId: string;
applicationId: string;
+ /** The bot's settings, handed to the bridge for the bot-wake bookkeeping of local runs. */
+ botSettings?: Record<string, unknown>;
/** The bot has the bot-wake scenario enabled: it listens to unaddressed channel chatter. */
botWakeEnabled: boolean;
bridge: AgentBridgeService;
+ /**
+ * Whether the agent may step back from this conversation (`STAND_DOWN`): a group conversation
+ * of a bot whose wake rules enforce, once the rollout reaches it.
+ */
+ canStandDown: (thread: { isDM?: boolean }) => Promise<boolean>;
charLimit?: number;
client: PlatformClient;
commands: BotCommand[];
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 fa7e6d0a39d..541f4293c37 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
@@ -201,10 +201,41 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
await expect(recorder.initiate(observation({}, plain))).resolves.toEqual({
addressed: false,
+ followup: { participants: [], score: 0.9 },
reason: 'followup-window',
});
});
+ // Production: the owner talking to a teammate and to another agent woke the bot in its window
+ // every time, and it answered every time. The agent is told how sure the check was and who
+ // else is here, so it can tell a message for it from one for someone else.
+ it('tells the agent how sure the classifier was and who else took part lately', async () => {
+ const state = fakeState(spokeRecently());
+ state.logs.set('discord:g1:c1', [
+ { at: 1, authorId: 'tm', authorName: 'teammate', id: 'a', isBot: false, text: 'hmm' },
+ { at: 2, authorId: APP, id: 'bot:op', isBot: true, text: 'Here is the plan.' },
+ { at: 3, authorId: 'ag', authorName: 'Dario', id: 'b', isBot: true, text: 'Draft v2' },
+ { at: 4, authorId: OWNER, authorName: 'arvin', id: 'c', isBot: false, text: 'nice' },
+ { at: 5, authorId: 'tm', authorName: 'teammate', id: 'd', isBot: false, text: 'ok' },
+ ]);
+ const recorder = make(WITH_CLASSIFIER('enforce'), state, {
+ classify: classifierAnswer(0.56),
+ });
+
+ const initiation = await recorder.initiate(observation({}, plain));
+
+ expect(initiation).toMatchObject({ reason: 'followup-window' });
+ expect(initiation?.followup).toEqual({
+ // Newest first, once each, without the bot itself; names only.
+ participants: [
+ { isBot: false, isOwner: false, name: 'teammate' },
+ { isBot: false, isOwner: true, name: 'arvin' },
+ { isBot: true, isOwner: false, name: 'Dario' },
+ ],
+ score: 0.56,
+ });
+ });
+
it('stays silent when the enforcing classifier says it is not', async () => {
const recorder = make(WITH_CLASSIFIER('enforce'), fakeState(spokeRecently()), {
classify: classifierAnswer(0.1),
@@ -230,6 +261,7 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
await expect(recorder.initiate(observation({}, plain))).resolves.toEqual({
addressed: false,
+ followup: { participants: [], score: 0.1 },
reason: 'followup-window',
});
expect(classify).toHaveBeenCalledTimes(1);
@@ -291,7 +323,7 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
},
});
- await expect(recorder.initiate(observation({}, plain))).resolves.toEqual({
+ await expect(recorder.initiate(observation({}, plain))).resolves.toMatchObject({
addressed: false,
reason: 'followup-window',
});
@@ -342,7 +374,7 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
const recorder = make(WITH_CLASSIFIER('enforce'), state, { classify });
const message = observation({}, { text: '那这个怎么处理?' });
- expect(await recorder.initiate(message)).toEqual({
+ expect(await recorder.initiate(message)).toMatchObject({
addressed: false,
reason: 'followup-window',
});
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
index b8ffff5f35a..b6f97a4765c 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
@@ -151,7 +151,8 @@ describe('bot-wake recorder: the replay of a parked message', () => {
it('runs on the wake decided when it was parked instead of judging again (the reported case)', async () => {
const classify = vi
.fn<WakeClassify>()
- .mockResolvedValueOnce({ addressedToBot: 0.51, kind: 'request', reason: 'p=0.51' })
+ // Reported as 0.51 then 0.13, under the old 0.5 threshold; the flip is the point.
+ .mockResolvedValueOnce({ addressedToBot: 0.71, kind: 'request', reason: 'p=0.71' })
.mockResolvedValueOnce({ addressedToBot: 0.13, kind: 'chitchat', reason: 'p=0.13' });
const state = fakeState(spokeRecently());
const recorder = make(ENFORCE, state, { classify });
@@ -159,7 +160,9 @@ describe('bot-wake recorder: the replay of a parked message', () => {
await expect(recorder.initiate(parked())).resolves.toMatchObject({
reason: 'followup-window',
});
+ // With what the agent is told about it: the score it was woken on, not a new one.
await expect(recorder.initiate(replay())).resolves.toMatchObject({
+ followup: { participants: [], score: 0.71 },
reason: 'followup-window',
});
expect(classify).toHaveBeenCalledOnce();
@@ -169,7 +172,7 @@ describe('bot-wake recorder: the replay of a parked message', () => {
await flush();
expect(
recorded()[0].verdicts.map((v: any) => [v.policyId, v.verdict, v.confidence]),
- ).toContainEqual(['bot-wake:classifier', 'allow', 0.51]);
+ ).toContainEqual(['bot-wake:classifier', 'allow', 0.71]);
});
it('judges again when nothing was kept, or what was kept cannot be read', async () => {
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index 61df81653e9..a848c23c21e 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -14,8 +14,10 @@ import type { LobeChatDatabase } from '@/database/type';
import { recordSignalDecision } from '@/server/services/agentSignal/persistence/recordDecision';
import { aggregateWakeVerdictsAsync } from '@/server/services/agentSignal/scenarios/botWake/aggregator';
import { parseBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
+import type { WakeParticipant } from '@/server/services/agentSignal/scenarios/botWake/conversation';
import {
CONVERSATION_PROMPT_LINES,
+ conversationParticipants,
discordMessageTime,
toConversationLine,
} from '@/server/services/agentSignal/scenarios/botWake/conversation';
@@ -57,7 +59,7 @@ import { buildWakeSignal, type WakeMessageLike } from '../wake/signal';
const log = debug('lobe-server:bot:wake-decision');
/** Revision of the bot-wake pipeline recorded on every decision. Bump when the judgement changes. */
-export const BOT_WAKE_PIPELINE_VERSION = 'bot-wake@2';
+export const BOT_WAKE_PIPELINE_VERSION = 'bot-wake@3';
/** What sets an edit's signal id apart from its first send's: `:edit:<edited at, ms>`. */
const editSuffix = (message: WakeMessageLike) => {
@@ -211,18 +213,38 @@ const INITIATION_TRAITS: Record<BotWakeInitiationReason, { addressed: boolean }>
'named-in-text': { addressed: true },
};
+/**
+ * `followup-window` only: what the woken agent is told about a follow-up nobody addressed to it,
+ * so it can tell a message for it from one for someone else in a busy thread.
+ */
+export interface BotWakeFollowupContext {
+ /** Who else took part in the conversation lately, newest first; names only. */
+ participants: WakeParticipant[];
+ /** 0..1: how sure the addressed classifier was that the message is for the bot. */
+ score?: number;
+}
+
/** A wake the recorder started on its own: the rule that started it, and what that implies. */
export interface BotWakeInitiation {
/** See {@link INITIATION_TRAITS}. */
addressed: boolean;
/** `in-duty` only: the duty the message falls within, when the judge named one. */
duty?: string;
+ /** `followup-window` only. See {@link BotWakeFollowupContext}. */
+ followup?: BotWakeFollowupContext;
reason: BotWakeInitiationReason;
}
-const initiationFor = (reason: BotWakeInitiationReason, duty?: string): BotWakeInitiation => ({
+/** What a wake carries for the agent besides its reason. */
+type InitiationDetails = Pick<BotWakeInitiation, 'duty' | 'followup'>;
+
+const initiationFor = (
+ reason: BotWakeInitiationReason,
+ { duty, followup }: InitiationDetails = {},
+): BotWakeInitiation => ({
...INITIATION_TRAITS[reason],
...(duty && { duty }),
+ ...(followup && { followup }),
reason,
});
@@ -412,6 +434,7 @@ const toChannelState = (fields: BotWakeChannelFields | undefined): WakeChannelSt
followupUntil: fields.followupUntil,
ownerLastSpokeAt: fields.ownerLastSpokeAt,
silentWakes: fields.silentWakes,
+ standDownUntil: fields.standDownUntil,
};
/**
@@ -426,9 +449,7 @@ const summarizeConversation = (conversation?: WakeConversation) =>
};
/** The wake decided for a parked message, as kept for its replay. */
-interface RememberedInitiation {
- /** See {@link BotWakeInitiation.duty}. */
- duty?: string;
+interface RememberedInitiation extends InitiationDetails {
reason: BotWakeInitiationReason;
verdicts: SignalDecisionVerdict[];
}
@@ -446,8 +467,17 @@ const parseRemembered = (raw: string | undefined): RememberedInitiation | undefi
const value = JSON.parse(raw) as Partial<RememberedInitiation>;
if (!isInitiationReason(value.reason)) return;
+ const followup = value.followup;
+
return {
duty: typeof value.duty === 'string' ? value.duty : undefined,
+ followup:
+ followup && Array.isArray(followup.participants)
+ ? {
+ participants: followup.participants,
+ score: typeof followup.score === 'number' ? followup.score : undefined,
+ }
+ : undefined,
reason: value.reason,
verdicts: Array.isArray(value.verdicts) ? value.verdicts : [],
};
@@ -646,20 +676,20 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
observation: BotWakeObservation,
reason: BotWakeInitiationReason,
evaluation: Evaluation,
- duty?: string,
+ details: InitiationDetails = {},
): Promise<BotWakeInitiation> => {
keepEvaluation(observation, evaluation);
await state.rememberInitiation?.(
applicationId,
getOriginMessageId(observation.message),
JSON.stringify({
- duty,
+ ...details,
reason,
verdicts: evaluation.verdicts ?? [],
} satisfies RememberedInitiation),
);
- return initiationFor(reason, duty);
+ return initiationFor(reason, details);
};
/**
@@ -681,7 +711,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
// A shadow judge only scores; a degraded one abstains, so it never lands here.
if (dutyPolicy.mode === 'enforce' && judged.verdict === 'allow') {
const record = judged.records.find((entry) => entry.policyId === DUTY_POLICY_ID);
- return initiated(observation, 'in-duty', evaluation, record?.matched);
+ return initiated(observation, 'in-duty', evaluation, { duty: record?.matched });
}
keepEvaluation(observation, evaluation);
@@ -855,7 +885,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
if (remembered) {
keepEvaluation(observation, { channel, conversation, verdicts: remembered.verdicts });
- return initiationFor(remembered.reason, remembered.duty);
+ return initiationFor(remembered.reason, remembered);
}
}
@@ -906,6 +936,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
// Only the window is open. A classifier the owner enforces must confirm; one that only
// watches is scored for the record and does not stand in the way.
const classifier = policies.find((policy) => policy.id === CLASSIFIER_POLICY_ID);
+ let score: number | undefined;
if (classifier) {
const classified = await aggregateWakeVerdictsAsync([classifier], signal, snapshot);
verdicts.push(...ruleVerdicts(classified));
@@ -920,9 +951,13 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
? await judgeDuty(observation, signal, snapshot, evaluation)
: undefined;
}
+ if (!degraded) score = classified.records[0]?.confidence;
}
- return initiated(observation, 'followup-window', evaluation);
+ // The agent is told why it woke: how sure the classifier was, and who else is talking.
+ return initiated(observation, 'followup-window', evaluation, {
+ followup: { participants: conversationParticipants(conversation, applicationId), score },
+ });
} catch (error) {
botWakeFailureCounter.add(1, { stage: 'initiate' });
log('initiate failed: entry=%s %O', observation.entryPoint, error);
diff --git a/apps/server/src/services/bot/__tests__/BotCallbackService.noReply.test.ts b/apps/server/src/services/bot/__tests__/BotCallbackService.noReply.test.ts
index d143739b7a7..716c00c5615 100644
--- a/apps/server/src/services/bot/__tests__/BotCallbackService.noReply.test.ts
+++ b/apps/server/src/services/bot/__tests__/BotCallbackService.noReply.test.ts
@@ -17,6 +17,7 @@ const mockRecordNoReplyLabel = vi.hoisted(() => vi.fn());
const mockGenerateTopicTitle = vi.hoisted(() => vi.fn());
const mockBotRouterReplay = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
const mockClearActiveThread = vi.hoisted(() => vi.fn());
+const mockRecordWakeRunOutcome = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
vi.mock('@/database/models/agentBotProvider', () => ({
AgentBotProviderModel: {
@@ -66,6 +67,10 @@ vi.mock('@/server/services/messenger/platforms', () => ({
messengerPlatformRegistry: { createBinder: vi.fn(), getPlatform: vi.fn() },
}));
vi.mock('../noReplyLabel', () => ({ recordNoReplyLabel: mockRecordNoReplyLabel }));
+vi.mock('../wake/scheduler', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ recordWakeRunOutcome: mockRecordWakeRunOutcome,
+}));
vi.mock('../platforms', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
const client = {
@@ -174,6 +179,60 @@ describe('BotCallbackService no_reply (queue mode)', () => {
expect(mockGenerateTopicTitle).not.toHaveBeenCalled();
});
+ // "nasa 就在这瞎捣乱": the agent acknowledges once and steps back from the thread.
+ it('stand-down: posts the acknowledgement without the marker and steps back from the thread', async () => {
+ await service.handleCallback(
+ body({
+ lastAssistantContent: '收到,我先退出这个讨论。\nSTAND_DOWN',
+ wakeKind: 'followup',
+ }),
+ );
+
+ expect(mockCreateMessage).toHaveBeenCalledTimes(1);
+ const posted = JSON.stringify(mockCreateMessage.mock.calls[0]);
+ expect(posted).toContain('收到,我先退出这个讨论。');
+ expect(posted).not.toContain('STAND_DOWN');
+ expect(mockRecordNoReplyLabel).not.toHaveBeenCalled();
+ expect(mockRecordWakeRunOutcome).toHaveBeenCalledWith(
+ expect.objectContaining({
+ platformThreadId: 'discord:guild:channel',
+ spoke: true,
+ spoken: { id: 'op-1', text: '收到,我先退出这个讨论。' },
+ standDown: true,
+ }),
+ );
+ });
+
+ it('stand-down in silence: posts nothing, labels it stand_down, and steps back', async () => {
+ for (const content of ['NO_REPLY:stand_down', 'STAND_DOWN']) {
+ vi.clearAllMocks();
+ await service.handleCallback(
+ body({ lastAssistantContent: content, wakeKind: 'followup' }),
+ { strictDelivery: true },
+ );
+
+ expect(mockCreateMessage).not.toHaveBeenCalled();
+ expect(mockRecordNoReplyLabel).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ noReply: { reason: 'stand_down' } }),
+ );
+ expect(mockRecordWakeRunOutcome).toHaveBeenCalledWith(
+ expect.objectContaining({ spoke: false, standDown: true }),
+ );
+ }
+ });
+
+ it('does not step back on a reply without the marker, or a run that failed', async () => {
+ await service.handleCallback(body({ lastAssistantContent: 'here is the fix' }));
+ await service.handleCallback(
+ body({ errorMessage: 'boom', lastAssistantContent: 'STAND_DOWN', reason: 'error' }),
+ );
+
+ for (const [input] of mockRecordWakeRunOutcome.mock.calls) {
+ expect(input.standDown).toBe(false);
+ }
+ });
+
it('followup with a real answer is delivered normally and not labelled', async () => {
await service.handleCallback(
body({ lastAssistantContent: 'here is the fix', wakeKind: 'followup' }),
diff --git a/apps/server/src/services/bot/noReply.test.ts b/apps/server/src/services/bot/noReply.test.ts
index 7d5115be226..48c1d5e4d2c 100644
--- a/apps/server/src/services/bot/noReply.test.ts
+++ b/apps/server/src/services/bot/noReply.test.ts
@@ -1,7 +1,7 @@
import { BOT_NO_REPLY_LABELS, BOT_NO_REPLY_REASONS } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { detectNoReply } from './noReply';
+import { detectNoReply, extractStandDown } from './noReply';
describe('detectNoReply', () => {
it.each([
@@ -58,11 +58,56 @@ describe('detectNoReply', () => {
}
});
+ // "nasa 就在这瞎捣乱": the agent steps back from the thread, with a short acknowledgement or none.
+ describe('standing down', () => {
+ it.each([
+ ['好,我先退出这个讨论。\nSTAND_DOWN', '好,我先退出这个讨论。'],
+ ['Got it, stepping back. STAND_DOWN', 'Got it, stepping back.'],
+ ['Got it.\n`STAND_DOWN`\n', 'Got it.'],
+ ['Got it. [STAND_DOWN].', 'Got it.'],
+ ['STAND_DOWN', ''],
+ ])('reads the marker ending %j and keeps what comes before it', (content, kept) => {
+ expect(extractStandDown(content)).toEqual({ content: kept, standDown: true });
+ });
+
+ it.each([
+ 'Standing down now',
+ 'the STAND_DOWN marker is how I step back, see above',
+ 'NOT_STAND_DOWN',
+ '',
+ ])('leaves other text alone: %j', (content) => {
+ expect(extractStandDown(content)).toEqual({ content, standDown: false });
+ });
+
+ it('is silence with reason stand_down when nothing comes before the marker, on any wake', () => {
+ for (const wakeKind of ['followup', 'mention', undefined] as const) {
+ expect(detectNoReply({ content: 'STAND_DOWN', wakeKind })).toEqual({
+ reason: 'stand_down',
+ });
+ }
+ expect(detectNoReply({ content: 'NO_REPLY:stand_down', wakeKind: 'followup' })).toEqual({
+ reason: 'stand_down',
+ });
+ expect(detectNoReply({ content: 'NO_REPLY\nSTAND_DOWN', wakeKind: 'followup' })).toEqual({
+ reason: 'stand_down',
+ });
+ });
+
+ it('is a reply when the agent acknowledges before the marker', () => {
+ expect(detectNoReply({ content: '好的,我撤。\nSTAND_DOWN', wakeKind: 'followup' })).toBe(
+ undefined,
+ );
+ expect(detectNoReply({ content: 'STAND_DOWN', hasAttachments: true })).toBe(undefined);
+ });
+ });
+
it('labels every reason, as false_wake unless the message was already answered', () => {
expect(Object.keys(BOT_NO_REPLY_LABELS).sort()).toEqual([...BOT_NO_REPLY_REASONS].sort());
expect(BOT_NO_REPLY_LABELS.duplicate).toBe('dup_wake');
expect(BOT_NO_REPLY_LABELS.already_handled).toBe('dup_wake');
expect(BOT_NO_REPLY_LABELS.off_topic).toBe('false_wake');
expect(BOT_NO_REPLY_LABELS.empty_completion).toBe('false_wake');
+ // Stepping back acted on the message: that wake was right.
+ expect(BOT_NO_REPLY_LABELS.stand_down).toBe('correct');
});
});
diff --git a/apps/server/src/services/bot/noReply.ts b/apps/server/src/services/bot/noReply.ts
index bb66446de08..32fc095df25 100644
--- a/apps/server/src/services/bot/noReply.ts
+++ b/apps/server/src/services/bot/noReply.ts
@@ -1,8 +1,29 @@
import type { BotNoReplyResult, BotWakeKind } from '@lobechat/types';
-import { parseBotNoReplyToken } from '@lobechat/types';
+import { BOT_STAND_DOWN_TOKEN, parseBotNoReplyToken } from '@lobechat/types';
+
+/** `STAND_DOWN` ending the text, alone or after the reply, tolerating backticks / brackets. */
+const STAND_DOWN_PATTERN = new RegExp(
+ String.raw`(?:^|[\s\`\[(])${BOT_STAND_DOWN_TOKEN}[\`\])]*[.。]?\s*$`,
+ 'i',
+);
+
+/**
+ * Splits the stand-down marker off a finished run's text: the agent ends its reply with
+ * `STAND_DOWN` to step back from the conversation (people told it it is interfering).
+ *
+ * Returns:
+ * - `standDown` whether the text ended with the marker
+ * - `content` the text to post, without the marker; unchanged when there was none
+ */
+export const extractStandDown = (content?: string): { content?: string; standDown: boolean } => {
+ const match = content ? STAND_DOWN_PATTERN.exec(content.trimEnd()) : null;
+ if (!content || !match) return { content, standDown: false };
+
+ return { content: content.slice(0, match.index).trimEnd(), standDown: true };
+};
export interface DetectNoReplyInput {
- /** The run's final assistant text. */
+ /** The run's final assistant text, as the agent wrote it (a stand-down marker included). */
content?: string;
hasAttachments?: boolean;
/** Only a `followup` wake may end in silence; a `mention` always owes the user an answer. */
@@ -17,6 +38,8 @@ export interface DetectNoReplyInput {
* - A `followup` wake that produced nothing at all (no text, no attachments) → `empty_completion`.
* - A `mention` wake is never silent: an empty completion there stays the fault it always was, and
* the token is just text.
+ * - Standing down (`STAND_DOWN` with nothing before it, or `NO_REPLY:stand_down`) is silence with
+ * reason `stand_down`. The bare marker is silent on a `mention` wake too: there is nothing to post.
*
* Returns `undefined` when the run has something to deliver.
*/
@@ -25,13 +48,16 @@ export const detectNoReply = ({
hasAttachments,
wakeKind,
}: DetectNoReplyInput): BotNoReplyResult | undefined => {
- if (wakeKind !== 'followup') return undefined;
+ const ending = extractStandDown(content);
+ const text = ending.content?.trim() ?? '';
- const text = content?.trim() ?? '';
+ if (ending.standDown && !text && !hasAttachments) return { reason: 'stand_down' };
+ if (wakeKind !== 'followup') return undefined;
if (!text) return hasAttachments ? undefined : { reason: 'empty_completion' };
const reason = parseBotNoReplyToken(text);
+ if (!reason) return undefined;
- return reason ? { reason } : undefined;
+ return { reason: ending.standDown ? 'stand_down' : reason };
};
diff --git a/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts b/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
index 3c5c5166117..8086c18f15c 100644
--- a/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
+++ b/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
mutateScheduler: vi.fn(),
recordBotSpoke: vi.fn(),
recordSilentWake: vi.fn(),
+ recordStandDown: vi.fn(),
rememberMessages: vi.fn(),
},
isLocal: { value: false },
@@ -162,6 +163,25 @@ describe('wake scheduler wiring', () => {
expect(mocks.botWake.recordSilentWake).not.toHaveBeenCalled();
});
+ it('steps back from the thread it replied in for 30 minutes when the agent stood down', async () => {
+ const before = Date.now();
+ await recordWakeRunOutcome({ ...base, spoke: true, standDown: true });
+
+ // The thread only: the rest of the channel is not what the bot was told to leave.
+ expect(mocks.botWake.recordStandDown).toHaveBeenCalledWith(
+ 'discord:app:g:c:t',
+ expect.any(Number),
+ );
+ const until = mocks.botWake.recordStandDown.mock.calls[0][1] as number;
+ expect(until - before).toBeGreaterThanOrEqual(30 * 60 * 1000);
+ expect(until - Date.now()).toBeLessThanOrEqual(30 * 60 * 1000);
+
+ mocks.botWake.recordStandDown.mockClear();
+ await recordWakeRunOutcome({ ...base, spoke: false, wakeKind: 'followup' });
+ await recordWakeRunOutcome({ ...base, settings: {}, spoke: true, standDown: true });
+ expect(mocks.botWake.recordStandDown).not.toHaveBeenCalled();
+ });
+
describe('what the bot said', () => {
const spoken = { id: 'op-1', text: 'Shipped it.' };
diff --git a/apps/server/src/services/bot/wake/scheduler.ts b/apps/server/src/services/bot/wake/scheduler.ts
index 110a22bf7c1..9eed85f452f 100644
--- a/apps/server/src/services/bot/wake/scheduler.ts
+++ b/apps/server/src/services/bot/wake/scheduler.ts
@@ -1,4 +1,5 @@
import { botWakeFlushCounter } from '@lobechat/observability-otel/modules/bot-wake';
+import { BOT_STAND_DOWN_MINUTES } from '@lobechat/types';
import debug from 'debug';
import { appEnv } from '@/envs/app';
@@ -214,6 +215,10 @@ export const wakeKeysFor = (platform: string, applicationId: string, platformThr
*
* `spoke` = the bot posted a reply. A follow-up wake that ended in silence counts against the
* silent-wake budget; speaking opens the follow-up window and resets it.
+ *
+ * `standDown` = the agent stepped back from the conversation (`STAND_DOWN`): for
+ * `BOT_STAND_DOWN_MINUTES` only an explicit address wakes it there. Filed on the conversation's own
+ * key, the thread the run replied in.
*/
export const recordWakeRunOutcome = async (input: {
applicationId: string;
@@ -223,9 +228,19 @@ export const recordWakeRunOutcome = async (input: {
spoke: boolean;
/** What the bot said and the id of the run that said it; kept in the channel's shared log. */
spoken?: { id: string; text?: string };
+ standDown?: boolean;
wakeKind?: 'followup' | 'mention';
}): Promise<void> => {
- const { applicationId, platform, platformThreadId, settings, spoke, spoken, wakeKind } = input;
+ const {
+ applicationId,
+ platform,
+ platformThreadId,
+ settings,
+ spoke,
+ spoken,
+ standDown,
+ wakeKind,
+ } = input;
const { config, rules } = parseBotWakeSettings(settings);
if (!isBotWakeEnabled(config)) return;
@@ -239,6 +254,14 @@ export const recordWakeRunOutcome = async (input: {
await redisService.botWake.recordSilentWake(keys);
}
+ const conversationKey = keys.at(-1);
+ if (standDown && conversationKey) {
+ await redisService.botWake.recordStandDown(
+ conversationKey,
+ Date.now() + BOT_STAND_DOWN_MINUTES * 60 * 1000,
+ );
+ }
+
const scheduler = resolveWakeScheduler(platform, applicationId, settings);
if (scheduler) {
await scheduler.runDone(
diff --git a/apps/server/src/services/redis/botWake.realRedis.test.ts b/apps/server/src/services/redis/botWake.realRedis.test.ts
index 2c9127a787d..22d242c23ab 100644
--- a/apps/server/src/services/redis/botWake.realRedis.test.ts
+++ b/apps/server/src/services/redis/botWake.realRedis.test.ts
@@ -89,6 +89,18 @@ describe.skipIf(!url)('botWake redis domain (real Redis)', () => {
expect(await domain.recordSilentWake(keys)).toBe(1);
});
+ it('keeps a stand-down on the thread the bot left, not on its whole channel', async () => {
+ const keys = ['discord:app:g:c6', 'discord:app:g:c6:t1'];
+ await domain.recordBotSpoke(keys, 1_000, 300_000);
+ await domain.recordStandDown(keys[1], 1_801_000);
+
+ expect(await domain.readChannel(keys)).toMatchObject({
+ followupUntil: 301_000,
+ standDownUntil: 1_801_000,
+ });
+ expect((await domain.readChannel([keys[0]]))?.standDownUntil).toBeUndefined();
+ });
+
it('remembers when the owner last spoke without touching the bot fields', async () => {
const keys = ['discord:app:g:c3'];
await domain.recordBotSpoke(keys, 1_000, 60_000);
diff --git a/apps/server/src/services/redis/botWake.test.ts b/apps/server/src/services/redis/botWake.test.ts
index f2fb644a609..7027f64d0c1 100644
--- a/apps/server/src/services/redis/botWake.test.ts
+++ b/apps/server/src/services/redis/botWake.test.ts
@@ -11,6 +11,17 @@ describe('mergeBotWakeChannelFields', () => {
).toMatchObject({ followupAuthorId: 'new', followupUntil: 2_000, silentWakes: 1 });
});
+ it('keeps the latest stand-down of any key: stepping back from the thread holds', () => {
+ expect(
+ mergeBotWakeChannelFields([
+ { silentWakes: 0 },
+ { silentWakes: 0, standDownUntil: 5_000 },
+ { silentWakes: 0, standDownUntil: 3_000 },
+ ]).standDownUntil,
+ ).toBe(5_000);
+ expect(mergeBotWakeChannelFields([{ silentWakes: 0 }]).standDownUntil).toBeUndefined();
+ });
+
it('has no follow-up author without a window', () => {
expect(
mergeBotWakeChannelFields([{ followupAuthorId: 'u1', silentWakes: 0 }]).followupAuthorId,
diff --git a/apps/server/src/services/redis/botWake.ts b/apps/server/src/services/redis/botWake.ts
index 02509dfccf0..bde9261e305 100644
--- a/apps/server/src/services/redis/botWake.ts
+++ b/apps/server/src/services/redis/botWake.ts
@@ -50,6 +50,8 @@ export interface BotWakeChannelFields {
followupUntil?: number;
ownerLastSpokeAt?: number;
silentWakes: number;
+ /** Until when the bot stays out of this conversation unless explicitly addressed. */
+ standDownUntil?: number;
}
const toNumber = (value: string | undefined) => {
@@ -65,11 +67,13 @@ const parseFields = (hash: Record<string, string> | null | undefined): BotWakeCh
followupUntil: toNumber(hash?.followupUntil),
ownerLastSpokeAt: toNumber(hash?.ownerLastSpokeAt),
silentWakes: toNumber(hash?.silentWakes) ?? 0,
+ standDownUntil: toNumber(hash?.standDownUntil),
});
/**
* Merges the states of the keys a conversation is filed under (channel and Discord thread).
- * Times take the latest; the silent-wake count takes the highest, the stricter reading. The
+ * Times take the latest (a stand-down on any key holds); the silent-wake count takes the highest,
+ * the stricter reading. The
* follow-up author comes from the key whose window ends last, the window it belongs to.
*/
export const mergeBotWakeChannelFields = (
@@ -93,6 +97,7 @@ export const mergeBotWakeChannelFields = (
followupUntil,
ownerLastSpokeAt: max((field) => field.ownerLastSpokeAt),
silentWakes: Math.max(0, ...fields.map((field) => field.silentWakes)),
+ standDownUntil: max((field) => field.standDownUntil),
};
};
@@ -342,6 +347,26 @@ export const botWake = {
}
},
+ /**
+ * The bot stepped back from a conversation (people told it it is interfering): until `until`,
+ * only an explicit address wakes it there. On the conversation's own key, so a thread the bot
+ * left does not silence the rest of the channel.
+ */
+ async recordStandDown(key: string, until: number) {
+ try {
+ const redis = await getClient();
+ if (!redis) return;
+
+ const channelKey = RedisKeys.botWake.channel(key);
+ const pipeline = redis.pipeline();
+ pipeline.hset(channelKey, 'standDownUntil', String(until));
+ pipeline.expire(channelKey, CHANNEL_TTL_SECONDS);
+ await pipeline.exec();
+ } catch (error) {
+ log('recordStandDown failed: %O', error);
+ }
+ },
+
/** The owner posted: remember when, so the bot can stay out of their conversation. */
async recordOwnerSpoke(keys: readonly string[], at: number) {
try {
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index fa8cb3b61f2..99f7f2775ca 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1859,6 +1859,7 @@
"noReply.reason.not_addressed": "Not addressed to me",
"noReply.reason.nothing_to_add": "Nothing to add",
"noReply.reason.off_topic": "Not relevant to me",
+ "noReply.reason.stand_down": "Stepping back from this conversation",
"noReply.title": "Read the message and chose not to reply",
"noSelectedAgents": "No members selected yet",
"opStatusTray.cost": "cost",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index b4a11672ad4..6a863216c92 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1859,6 +1859,7 @@
"noReply.reason.not_addressed": "不是对我说的",
"noReply.reason.nothing_to_add": "没有要补充的",
"noReply.reason.off_topic": "与我无关",
+ "noReply.reason.stand_down": "暂时退出这个对话",
"noReply.title": "分析后决定不回复",
"noSelectedAgents": "还未选择成员",
"opStatusTray.cost": "花费",
diff --git a/packages/context-engine/src/providers/BotPlatformContextInjector.ts b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
index cd421dc27b2..f53e32029f0 100644
--- a/packages/context-engine/src/providers/BotPlatformContextInjector.ts
+++ b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
@@ -14,6 +14,8 @@ export interface BotPlatformContext {
currentChannel?: BotPlatformInfo['currentChannel'];
/** The bot woke on its own because a message falls within its duties (see `formatBotPlatformContext`). */
duty?: BotPlatformInfo['duty'];
+ /** The bot woke in its follow-up window (see `formatBotPlatformContext`). */
+ followup?: BotPlatformInfo['followup'];
/** The bot woke only because its name is in the text (see `formatBotPlatformContext`). */
named?: boolean;
/** Acknowledgement already posted before the run (see `formatBotPlatformContext`). */
@@ -25,6 +27,8 @@ export interface BotPlatformContext {
replyEmojis?: BotPlatformInfo['replyEmojis'];
/** How the bot talks in this conversation (see `formatBotPlatformContext`). */
replyStyle?: BotPlatformInfo['replyStyle'];
+ /** The agent may step back from the conversation (see `formatBotPlatformContext`). */
+ standDown?: boolean;
supportsMarkdown: boolean;
/** `followup` tells the agent it may stay silent (see `formatBotPlatformContext`). */
wakeKind?: BotPlatformInfo['wakeKind'];
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 3f8860f7f58..c7a6e793e9e 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1550,6 +1550,7 @@ export default {
'noReply.reason.not_addressed': 'Not addressed to me',
'noReply.reason.nothing_to_add': 'Nothing to add',
'noReply.reason.off_topic': 'Not relevant to me',
+ 'noReply.reason.stand_down': 'Stepping back from this conversation',
'noReply.title': 'Read the message and chose not to reply',
'noAgentsYet': 'This group has no members yet. Click the + button to invite agents.',
'noAvailableAgents': 'No members available to invite',
diff --git a/packages/prompts/src/prompts/botPlatformContext/index.test.ts b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
index b65a4af0b7d..9ffe142e7e0 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.test.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
@@ -183,6 +183,46 @@ describe('formatBotPlatformContext', () => {
);
// The reason the runtime assigns itself is not offered to the agent.
expect(result).not.toContain('empty_completion');
+ // "嗯,我又抢话乱接了。这条我不接,你们定。": saying it stays out is a reply too.
+ expect(result).toContain('Announcing that you will stay out');
+ expect(result).toContain('is itself a reply');
+ });
+
+ // A multi-party thread: the owner talking to a teammate or to another agent, scored 0.56-0.68,
+ // woke the bot in its follow-up window every time and it answered every time.
+ it('tells an agent woken in its follow-up window why, how sure the check was and who else is here', () => {
+ const base = { platformName: 'Discord', supportsMarkdown: true, wakeKind: 'followup' as const };
+ const result = formatBotPlatformContext({
+ ...base,
+ followup: {
+ participants: [
+ { isOwner: true, name: 'Ava' },
+ { name: 'Sam<i>' },
+ { isBot: true, name: 'Dario' },
+ ],
+ score: 0.56,
+ },
+ });
+
+ expect(result).toContain('you spoke in this conversation a little while ago');
+ expect(result).toContain('a quick check was 56% sure the message is meant for you');
+ // Names only, escaped like any user-controlled text; the owner and other bots are marked.
+ expect(result).toContain(
+ 'Also taking part lately: Ava (your owner), Sam&lt;i&gt;, Dario (a bot).',
+ );
+ expect(result).toContain('You are one participant among several');
+ expect(result).toContain('If the message is addressed to someone else');
+ expect(result).toContain('NO_REPLY:not_addressed');
+
+ // Without a score or anyone else known, it still says why, and nothing empty.
+ const bare = formatBotPlatformContext({ ...base, followup: {} });
+ expect(bare).toContain('replied to you or said your name. You are one participant');
+ expect(bare).not.toContain('sure the message');
+ expect(bare).not.toContain('Also taking part');
+ // Only a follow-up wake carries it.
+ expect(formatBotPlatformContext({ ...base, wakeKind: 'mention', followup: {} })).not.toContain(
+ 'one participant among several',
+ );
});
it('tells an agent woken by its duties which duty, and to act on it or stay silent', () => {
@@ -223,6 +263,8 @@ describe('formatBotPlatformContext', () => {
expect(named).toContain('Decide the way a teammate in the room would');
// Criticism of the bot is answered, not let go.
expect(named).toContain('When someone is unhappy with something you did');
+ // ...once: "我撤了", then two minutes later another reply.
+ expect(named).toContain('Say it once, briefly, then keep to it');
expect(formatBotPlatformContext({ ...base, named: true })).not.toContain('<optional_reply>');
});
@@ -274,6 +316,35 @@ describe('formatBotPlatformContext', () => {
expect(formatBotPlatformContext(base)).not.toContain('<reply_emojis>');
});
+ // "nasa 就在这瞎捣乱" → "我撤了", and two minutes later it replied again.
+ it('tells an agent that may stand down how to step back, and what it costs', () => {
+ const base = { platformName: 'Discord', supportsMarkdown: true };
+ const mention = formatBotPlatformContext({ ...base, standDown: true, wakeKind: 'mention' });
+
+ expect(mention).toContain('<stand_down>');
+ expect(mention).toContain('you are interfering');
+ expect(mention).toContain('acknowledge it once');
+ expect(mention).toContain('a last line that is exactly `STAND_DOWN`');
+ expect(mention).toContain('For the next 30 minutes');
+ expect(mention).toContain('Do not stand down to dodge a question');
+ // Silence is for a follow-up wake only: a mention is always answered.
+ expect(mention).not.toContain('NO_REPLY:stand_down');
+
+ const named = formatBotPlatformContext({
+ ...base,
+ named: true,
+ standDown: true,
+ wakeKind: 'followup',
+ });
+ expect(named).toContain('NO_REPLY:stand_down');
+ expect(named).toContain('stand down (see <stand_down>)');
+
+ // Without it, nothing about standing down, not even the reason.
+ expect(formatBotPlatformContext({ ...base, named: true, wakeKind: 'followup' })).not.toContain(
+ 'stand_down',
+ );
+ });
+
it('leaves the prompt untouched for a mention, or when the wake kind is unknown', () => {
const base = { platformName: 'Discord', supportsMarkdown: true };
diff --git a/packages/prompts/src/prompts/botPlatformContext/index.ts b/packages/prompts/src/prompts/botPlatformContext/index.ts
index 09ca0978708..91e90da8a13 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.ts
@@ -1,5 +1,10 @@
import type { BotWakeKind } from '@lobechat/types';
-import { BOT_NO_REPLY_REASONS, BOT_NO_REPLY_TOKEN } from '@lobechat/types';
+import {
+ BOT_NO_REPLY_REASONS,
+ BOT_NO_REPLY_TOKEN,
+ BOT_STAND_DOWN_MINUTES,
+ BOT_STAND_DOWN_TOKEN,
+} from '@lobechat/types';
/** One prior topic (session) from the same IM channel. */
export interface RecentChannelTopic {
@@ -56,6 +61,16 @@ export interface BotPlatformInfo {
* why, so it acts on the duty or stays silent.
*/
duty?: { matched?: string };
+ /**
+ * The bot woke because it spoke in this conversation lately and the message came after (a
+ * `followup` wake), not because anyone addressed it. `score` is how sure the addressed check was
+ * (0..1); `participants` who else took part lately, by name. The agent is told it is one
+ * participant among several.
+ */
+ followup?: {
+ participants?: { isBot?: boolean; isOwner?: boolean; name: string }[];
+ score?: number;
+ };
/**
* The bot woke only because its name is in the text, with no @-mention or reply (a `followup`
* wake). The agent is told people often talk about it rather than to it.
@@ -76,6 +91,11 @@ export interface BotPlatformInfo {
replyEmojis?: { emoji: string; usage?: string }[];
/** How the bot talks in this conversation, as the owner wrote it (the channel's or the default). */
replyStyle?: string;
+ /**
+ * The agent may step back from this conversation when people say it is interfering: it ends its
+ * reply with `STAND_DOWN`, and for a while only an @-mention or a reply wakes it here.
+ */
+ standDown?: boolean;
supportsMarkdown: boolean;
/**
* How the bot was woken. On `followup` the agent is told it may stay silent; on `mention` (or
@@ -97,6 +117,26 @@ const sanitize = (text: string) =>
(ch) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' })[ch]!,
);
+type FollowupParticipant = NonNullable<
+ NonNullable<BotPlatformInfo['followup']>['participants']
+>[number];
+
+const describeParticipant = ({ isBot, isOwner, name }: FollowupParticipant) =>
+ `${sanitize(name)}${isOwner ? ' (your owner)' : isBot ? ' (a bot)' : ''}`;
+
+/** Why a follow-up-window wake happened, and the rule for a thread with several participants. */
+const followupHint = ({ participants = [], score }: NonNullable<BotPlatformInfo['followup']>) =>
+ [
+ 'Why you were woken: you spoke in this conversation a little while ago and this message came after. Nobody @-mentioned you, replied to you or said your name',
+ score === undefined
+ ? '.'
+ : `; a quick check was ${Math.round(score * 100)}% sure the message is meant for you.`,
+ participants.length > 0
+ ? ` Also taking part lately: ${participants.map(describeParticipant).join(', ')}.`
+ : '',
+ ` You are one participant among several, not the one everyone is talking to. If the message is addressed to someone else, or others are leading the discussion, end with \`${BOT_NO_REPLY_TOKEN}:not_addressed\`. Speak only when the message is clearly for you, or the conversation needs something only you can add.`,
+ ].join('');
+
/**
* Format bot platform context into a system-level instruction.
*
@@ -107,12 +147,14 @@ export const formatBotPlatformContext = ({
canReadHistory = true,
currentChannel,
duty,
+ followup,
named,
openingReply,
platformName,
recentChannelHistory,
replyEmojis,
replyStyle,
+ standDown,
supportsMarkdown,
wakeKind,
warnings,
@@ -208,11 +250,13 @@ export const formatBotPlatformContext = ({
'<optional_reply>',
'You were woken by the conversation itself, not by someone addressing you directly. Speaking is optional.',
`If you have nothing worth adding — the message is not for you, is off topic, repeats something already answered, or was already handled — end your turn with exactly \`${BOT_NO_REPLY_TOKEN}\` and no other text.`,
- `You may append a reason: \`${BOT_NO_REPLY_TOKEN}:<reason>\`, where reason is one of ${BOT_NO_REPLY_REASONS.filter((r) => r !== 'empty_completion').join(', ')}.`,
+ `You may append a reason: \`${BOT_NO_REPLY_TOKEN}:<reason>\`, where reason is one of ${BOT_NO_REPLY_REASONS.filter((r) => r !== 'empty_completion' && (standDown || r !== 'stand_down')).join(', ')}.`,
'Stay silent rather than posting filler. If you do have something useful to say, just reply normally.',
+ `Announcing that you will stay out ("I'll leave this one to you", "这条我不接") is itself a reply and interrupts just the same: when you decide not to take part, end with \`${BOT_NO_REPLY_TOKEN}\` instead of saying so.`,
+ ...(followup ? [followupHint(followup)] : []),
...(named
? [
- `Why you were woken: your name appears in the message, but nobody @-mentioned you or replied to you. People often talk about you rather than to you: commenting on what you did, joking, or asking each other why you spoke up. Decide the way a teammate in the room would: speak when the message asks you to do or answer something, or when you have something the conversation actually needs; let a passing remark or a joke about you go by and end with \`${BOT_NO_REPLY_TOKEN}:not_addressed\`. When someone is unhappy with something you did (you replied when you should not have, got it wrong, were too noisy), do respond: acknowledge it plainly, without defending yourself, and save what you will do differently as <self_improvement> describes.`,
+ `Why you were woken: your name appears in the message, but nobody @-mentioned you or replied to you. People often talk about you rather than to you: commenting on what you did, joking, or asking each other why you spoke up. Decide the way a teammate in the room would: speak when the message asks you to do or answer something, or when you have something the conversation actually needs; let a passing remark or a joke about you go by and end with \`${BOT_NO_REPLY_TOKEN}:not_addressed\`. When someone is unhappy with something you did (you replied when you should not have, got it wrong, were too noisy), do respond: acknowledge it plainly, without defending yourself, and save what you will do differently as <self_improvement> describes. Say it once, briefly, then keep to it: do not apologise again or announce that you are staying out.${standDown ? ' If they say you are interfering or should stay out, stand down (see <stand_down>).' : ''}`,
]
: []),
...(duty
@@ -252,6 +296,21 @@ export const formatBotPlatformContext = ({
);
}
+ if (standDown) {
+ lines.push(
+ '',
+ '<stand_down>',
+ `If people here tell you that you are interfering, talking over them, or should stay out of this conversation, step back: acknowledge it once, in one short sentence, and end your reply with a last line that is exactly \`${BOT_STAND_DOWN_TOKEN}\`. That line is not posted.`,
+ `For the next ${BOT_STAND_DOWN_MINUTES} minutes you are then woken here only when someone @-mentions you or replies to one of your messages. Do not stand down to dodge a question someone asked you.`,
+ ...(wakeKind === 'followup'
+ ? [
+ `To step back without posting anything, end with \`${BOT_NO_REPLY_TOKEN}:stand_down\` instead.`,
+ ]
+ : []),
+ '</stand_down>',
+ );
+ }
+
if (!supportsMarkdown) {
lines.push(
'',
diff --git a/packages/types/src/signal.ts b/packages/types/src/signal.ts
index b96a84de179..3922761c975 100644
--- a/packages/types/src/signal.ts
+++ b/packages/types/src/signal.ts
@@ -123,6 +123,19 @@ export type BotWakeKind = (typeof BOT_WAKE_KINDS)[number];
*/
export const BOT_NO_REPLY_TOKEN = 'NO_REPLY';
+/**
+ * The line an agent ends its reply with to step back from the conversation: people told it it is
+ * interfering. The line is not posted; whatever it wrote before it (a short acknowledgement) is.
+ * `NO_REPLY:stand_down` does the same in silence.
+ */
+export const BOT_STAND_DOWN_TOKEN = 'STAND_DOWN';
+
+/**
+ * How long a bot that stood down stays out of the conversation: only an @-mention, a reply to it,
+ * a DM or a command wakes it until then.
+ */
+export const BOT_STAND_DOWN_MINUTES = 30;
+
/** Why a woken agent chose not to speak. */
export const BOT_NO_REPLY_REASONS = [
'not_addressed',
@@ -130,6 +143,7 @@ export const BOT_NO_REPLY_REASONS = [
'nothing_to_add',
'duplicate',
'already_handled',
+ 'stand_down',
'unspecified',
'empty_completion',
] as const;
@@ -140,6 +154,8 @@ export type BotNoReplyClaimedReason = Exclude<BotNoReplyReason, 'empty_completio
/**
* The decision label each silence reason is written under. Staying silent means the wake was not
* worth an answer (`false_wake`), unless the same message had already been answered (`dup_wake`).
+ * Standing down is the one silence that acted on the message (it told the bot to back off), so
+ * that wake was `correct`.
*/
export const BOT_NO_REPLY_LABELS: Record<BotNoReplyReason, SignalDecisionLabel> = {
already_handled: 'dup_wake',
@@ -148,6 +164,7 @@ export const BOT_NO_REPLY_LABELS: Record<BotNoReplyReason, SignalDecisionLabel>
nothing_to_add: 'false_wake',
not_addressed: 'false_wake',
off_topic: 'false_wake',
+ stand_down: 'correct',
unspecified: 'false_wake',
};