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.

♻️ refactor(bot-wake): make the wake pipeline a platform-neutral conversationWake service (#22447)

Arvin Xu31200fc959eb
diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.ts
index 74e201d3ab8..7411f159a31 100644
--- a/apps/server/src/routers/lambda/agentBotProvider.ts
+++ b/apps/server/src/routers/lambda/agentBotProvider.ts
@@ -12,7 +12,6 @@ import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { LobeChatDatabase } from '@/database/type';
import { authedProcedure, router } from '@/libs/trpc/lambda';
-import { flattenBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
import {
assertBotAccessSettings,
assertWatchKeywordsWritable,
@@ -38,6 +37,7 @@ import {
beginFeishuAppRegistration,
pollFeishuAppRegistration,
} from '@/server/services/bot/platforms/feishu/registration';
+import { flattenBotWakeSettings } from '@/server/services/conversationWake/config';
import { GatewayService } from '@/server/services/gateway';
import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';
diff --git a/apps/server/src/routers/lambda/agentBotWake.ts b/apps/server/src/routers/lambda/agentBotWake.ts
index 9f1c4ff8e72..c8c9aa32ae6 100644
--- a/apps/server/src/routers/lambda/agentBotWake.ts
+++ b/apps/server/src/routers/lambda/agentBotWake.ts
@@ -24,7 +24,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { BOT_WAKE_FOLLOWUP_REASONS } from '@/server/services/bot/BotMessageRouter/wakeDecision';
import { NO_REPLY_LABEL_SOURCE } from '@/server/services/bot/noReplyLabel';
-import { pickWakeJudgeScore } from '@/server/services/bot/wake/judgeScore';
+import { pickWakeJudgeScore } from '@/server/services/conversationWake/judgeScore';
import {
agentBotProviderProcedure,
diff --git a/apps/server/src/services/agentSignal/emitter.ts b/apps/server/src/services/agentSignal/emitter.ts
index 28f4552858c..b4e46446a32 100644
--- a/apps/server/src/services/agentSignal/emitter.ts
+++ b/apps/server/src/services/agentSignal/emitter.ts
@@ -12,13 +12,14 @@ import {
} from '@lobechat/agent-signal/source';
import type { LobeChatDatabase } from '@/database/type';
+import type { BotWakeConfig } from '@/server/services/conversationWake/types';
import {
executeAgentSignalSourceEvent,
type GeneratedAgentSignalEmissionResult,
} from './orchestrator';
import type { CreateDefaultAgentSignalPoliciesOptions } from './policies';
-import type { BotWakeConfig, CreateBotWakePolicyOptions } from './scenarios/botWake';
+import type { CreateBotWakePolicyOptions } from './scenarios/botWake';
import { getAgentSignalScenarioMeta, isAgentSignalScenarioEnabled } from './scenarios/meta';
import type { AgentSignalScenarioId } from './scenarios/types';
diff --git a/apps/server/src/services/agentSignal/orchestrator.ts b/apps/server/src/services/agentSignal/orchestrator.ts
index 2784fc36dcf..34ed6327acf 100644
--- a/apps/server/src/services/agentSignal/orchestrator.ts
+++ b/apps/server/src/services/agentSignal/orchestrator.ts
@@ -10,6 +10,7 @@ import type {
import type { AgentSignalSourceType } from '@lobechat/agent-signal/source';
import { createSourceEvent } from '@lobechat/agent-signal/source';
+import type { WakeDecision } from '@/server/services/conversationWake/types';
import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';
import { acquireAgentSignalDailyBudget } from './budget';
@@ -25,7 +26,7 @@ import { createDefaultAgentSignalPolicies } from './policies';
import { createProcedurePolicyOptions } from './procedure';
import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';
import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
-import type { AgentSignalScenarioId, WakeDecision } from './scenarios';
+import type { AgentSignalScenarioId } from './scenarios';
import { AGENT_SIGNAL_SCENARIO_IDS, createScenarioPolicies } from './scenarios';
import { persistAgentSignalReceipts, projectAgentSignalReceipts } from './services/receiptService';
import { createSelfIterationCompletionHandler } from './services/selfIteration/completion';
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicy.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicy.test.ts
index 7dfeafff0bf..ee61a907882 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicy.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicy.test.ts
@@ -1,9 +1,10 @@
// @vitest-environment node
import { createSourceEvent } from '@lobechat/agent-signal/source';
+import type { WakePolicy, WakeStateSnapshot } from '@/server/services/conversationWake/types';
+
import { createAgentSignalRuntime } from '../../runtime/AgentSignalRuntime';
import { createBotWakePolicy } from '../botWake/policy';
-import type { WakePolicy, WakeStateSnapshot } from '../botWake/types';
const denyAll: WakePolicy = {
evaluate: () => ({ confidence: 1, reason: 'quiet-hours', tags: ['t'], verdict: 'deny' }),
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/gates.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/gates.test.ts
index 91dbc9ebc1d..d0e8340d1d6 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/gates.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/gates.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment node
+import { isBotWakeEnabled } from '@/server/services/conversationWake/gate';
+
import { resetAgentSignalUserGateCache } from '../../featureGate';
-import { isBotWakeEnabled } from '../botWake/gate';
import { isAgentSignalScenarioEnabled } from '../meta';
const mocks = vi.hoisted(() => ({ getUserPreference: vi.fn() }));
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/index.ts b/apps/server/src/services/agentSignal/scenarios/botWake/index.ts
index 059d7923f3c..62d5b849e4d 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/index.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/index.ts
@@ -1,8 +1 @@
-export * from './aggregator';
-export * from './config';
-export * from './facts';
-export * from './gate';
-export * from './policies';
export * from './policy';
-export * from './scheduler';
-export * from './types';
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policy.ts b/apps/server/src/services/agentSignal/scenarios/botWake/policy.ts
index 4ec6fcb1fb1..aaeef1e987b 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/policy.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/policy.ts
@@ -1,8 +1,14 @@
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { aggregateWakeVerdictsAsync } from '@/server/services/conversationWake/aggregator';
+import type {
+ WakeDecision,
+ WakePolicy,
+ WakeSignal,
+ WakeStateSnapshot,
+} from '@/server/services/conversationWake/types';
+
import { defineAgentSignalHandlers, defineSourceHandler } from '../../runtime/middleware';
-import { aggregateWakeVerdictsAsync } from './aggregator';
-import type { WakeDecision, WakePolicy, WakeSignal, WakeStateSnapshot } from './types';
export const EMPTY_WAKE_STATE: WakeStateSnapshot = {
explicitMention: false,
diff --git a/apps/server/src/services/agentSignal/scenarios/meta.ts b/apps/server/src/services/agentSignal/scenarios/meta.ts
index 78cd9bf2b53..fe1092d355c 100644
--- a/apps/server/src/services/agentSignal/scenarios/meta.ts
+++ b/apps/server/src/services/agentSignal/scenarios/meta.ts
@@ -1,5 +1,6 @@
+import { isBotWakeEnabled } from '@/server/services/conversationWake/gate';
+
import { isAgentSignalEnabledForUser } from '../featureGate';
-import { isBotWakeEnabled } from './botWake/gate';
import type {
AgentSignalScenarioGateInput,
AgentSignalScenarioId,
diff --git a/apps/server/src/services/agentSignal/scenarios/types.ts b/apps/server/src/services/agentSignal/scenarios/types.ts
index 6caf4e57c6d..5e532e4fc64 100644
--- a/apps/server/src/services/agentSignal/scenarios/types.ts
+++ b/apps/server/src/services/agentSignal/scenarios/types.ts
@@ -1,8 +1,9 @@
import type { LobeChatDatabase } from '@/database/type';
+import type { BotWakeConfig } from '@/server/services/conversationWake/types';
import type { CreateDefaultAgentSignalPoliciesOptions } from '../policies';
import type { AgentSignalMiddleware } from '../runtime/middleware';
-import type { BotWakeConfig, CreateBotWakePolicyOptions } from './botWake';
+import type { CreateBotWakePolicyOptions } from './botWake';
export const AGENT_SIGNAL_SCENARIO_IDS = {
botWake: 'bot-wake',
diff --git a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts b/apps/server/src/services/bot/BotMessageRouter/followupGate.ts
index b9535350317..8c31a82ec8b 100644
--- a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/followupGate.ts
@@ -2,11 +2,11 @@ import { botWakeSchedulerCounter } from '@lobechat/observability-otel/modules/bo
import type { Message } from 'chat';
import debug from 'debug';
-import { resolveChannelKeys } from '@/server/services/agentSignal/scenarios/botWake/facts';
-import type { WakeScheduler } from '@/server/services/agentSignal/scenarios/botWake/scheduler';
+import type { WakeScheduler } from '@/server/services/conversationWake/scheduler';
import { deferBotMessages } from '../deferredMessages';
import { getOriginMessageId } from '../mergeMessages';
+import { resolveChannelKeys } from '../wake/platformFacts';
import type { BotWakeEntryPoint, BotWakeRecorder } from './wakeDecision';
const log = debug('lobe-server:bot:followup-gate');
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index 1c89abf82d8..e2ae2cc8304 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -4,9 +4,13 @@ import debug from 'debug';
import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';
import type { LobeChatDatabase } from '@/database/type';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
-import { parseBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
-import { resolveChannelKeys } from '@/server/services/agentSignal/scenarios/botWake/facts';
-import { isBotWakeEnabled } from '@/server/services/agentSignal/scenarios/botWake/gate';
+import { resolveChannelKeys } from '@/server/services/bot/wake/platformFacts';
+import { createWakeClassify } from '@/server/services/conversationWake/classify';
+import { parseBotWakeSettings } from '@/server/services/conversationWake/config';
+import { createWakeDutyJudge } from '@/server/services/conversationWake/dutyJudge';
+import { isBotWakeEnabled } from '@/server/services/conversationWake/gate';
+import { createWakeIdentityLoader } from '@/server/services/conversationWake/identity';
+import type { WakeInitiation } from '@/server/services/conversationWake/initiation';
import { AgentBridgeService } from '../AgentBridgeService';
import { buildBotContext } from '../buildBotContext';
@@ -32,9 +36,6 @@ import {
} from '../platforms';
import { extractDeviceAllowlist } from '../platforms/deviceAccess';
import { renderThrownAgentError } from '../renderThrownError';
-import { createWakeClassify } from '../wake/classify';
-import { createWakeDutyJudge } from '../wake/dutyJudge';
-import { createWakeIdentityLoader } from '../wake/identity';
import { createReplyOpener } from '../wake/opener';
import { resolveWakeScheduler } from '../wake/scheduler';
import type { WakeMessageLike } from '../wake/signal';
@@ -54,7 +55,6 @@ import {
} from './utils';
import {
type BotWakeEntryPoint,
- type BotWakeInitiation,
botWakeKindFor,
type BotWakeObservation,
type BotWakeReason,
@@ -389,7 +389,7 @@ export function registerHandlers(
message: WakeMessageLike,
thread: { id: string },
threadSubscribed = false,
- ): Promise<BotWakeInitiation | undefined> =>
+ ): Promise<WakeInitiation | undefined> =>
wakeRecorder.initiate(
observationOf(entryPoint, message, thread, 'skip', 'not-addressed', threadSubscribed),
);
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 79ea1d374c4..6c18743ea66 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
@@ -45,14 +45,14 @@ vi.mock('../wake/scheduler', () => ({
recordWakeRunOutcome: vi.fn(),
resolveWakeScheduler: () => undefined,
}));
-vi.mock('../wake/classify', () => ({
+vi.mock('@/server/services/conversationWake/classify', () => ({
createWakeClassify: () => vi.fn(),
}));
-vi.mock('../wake/dutyJudge', () => ({
+vi.mock('@/server/services/conversationWake/dutyJudge', () => ({
createWakeDutyJudge: () => vi.fn(),
}));
vi.mock('../wake/opener', () => ({ createReplyOpener: () => mocks.opener }));
-vi.mock('../wake/identity', () => ({
+vi.mock('@/server/services/conversationWake/identity', () => ({
createWakeIdentityLoader: () => async () => ({ agentName: 'Nasa', ownerNames: ['Arvin'] }),
}));
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
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 ccfeb8ce359..12a65c84261 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
@@ -46,13 +46,13 @@ vi.mock('../wake/scheduler', () => ({
resolveWakeScheduler: (_platform: string, _app: string, settings: any) =>
settings?.botWake?.scheduler?.mode === 'enforce' ? { submit: mocks.submit } : undefined,
}));
-vi.mock('../wake/classify', () => ({
+vi.mock('@/server/services/conversationWake/classify', () => ({
createWakeClassify: () => mocks.classify,
}));
-vi.mock('../wake/dutyJudge', () => ({
+vi.mock('@/server/services/conversationWake/dutyJudge', () => ({
createWakeDutyJudge: () => mocks.duty,
}));
-vi.mock('../wake/identity', () => ({
+vi.mock('@/server/services/conversationWake/identity', () => ({
createWakeIdentityLoader: () => async () => ({
agentName: 'Arvin Agent',
agentTitle: 'Release helper',
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 32e550bb89d..1a9c89b0115 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
@@ -28,10 +28,10 @@ vi.mock('../wake/scheduler', () => ({
resolveWakeScheduler: (_platform: string, _app: string, settings: any) =>
settings?.botWake?.scheduler?.mode === 'enforce' ? { submit: mocks.submit } : undefined,
}));
-vi.mock('../wake/classify', () => ({
+vi.mock('@/server/services/conversationWake/classify', () => ({
createWakeClassify: () => vi.fn(),
}));
-vi.mock('../wake/dutyJudge', () => ({
+vi.mock('@/server/services/conversationWake/dutyJudge', () => ({
createWakeDutyJudge: () => vi.fn(),
}));
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
diff --git a/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts b/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts
index 833e9647f3a..549a2ac7af3 100644
--- a/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts
@@ -1,8 +1,8 @@
import type { BotWakeKind, SignalDecisionVerdict } from '@lobechat/types';
import debug from 'debug';
-import { describeLine } from '@/server/services/agentSignal/scenarios/botWake/conversation';
-import type { WakeConversation } from '@/server/services/agentSignal/scenarios/botWake/types';
+import { describeLine } from '@/server/services/conversationWake/conversation';
+import type { WakeConversation } from '@/server/services/conversationWake/types';
import type { BotReplyPlacementMode, PlatformClient, ReplyTargets } from '../platforms';
import type { ReplyOpener, ReplyOpening } from '../wake/opener';
diff --git a/apps/server/src/services/bot/BotMessageRouter/types.ts b/apps/server/src/services/bot/BotMessageRouter/types.ts
index 91e4e2c44c5..eafd018ff08 100644
--- a/apps/server/src/services/bot/BotMessageRouter/types.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/types.ts
@@ -1,6 +1,7 @@
import type { Chat, Message, MessageContext } from 'chat';
import type { LobeChatDatabase } from '@/database/type';
+import type { WakeInitiation } from '@/server/services/conversationWake/initiation';
import type { AgentBridgeService } from '../AgentBridgeService';
import type {
@@ -13,7 +14,7 @@ import type {
} from '../platforms';
import type { WakeMessageLike } from '../wake/signal';
import type { FollowupGate } from './followupGate';
-import type { BotWakeEntryPoint, BotWakeInitiation, BotWakeReason } from './wakeDecision';
+import type { BotWakeEntryPoint, BotWakeReason } from './wakeDecision';
export interface ResolvedAgentInfo {
agentId: string;
@@ -156,7 +157,7 @@ export interface BotHandlerContext {
message: WakeMessageLike,
thread: { id: string },
threadSubscribed?: boolean,
- ) => Promise<BotWakeInitiation | undefined>;
+ ) => Promise<WakeInitiation | undefined>;
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>;
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts
index f3815923355..b747bca8efc 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts
@@ -1,9 +1,6 @@
// @vitest-environment node
-import type {
- WakeClassify,
- WakeDutyJudge,
-} from '@/server/services/agentSignal/scenarios/botWake/policies';
-import type { WakeConversationLine } from '@/server/services/agentSignal/scenarios/botWake/types';
+import type { WakeClassify, WakeDutyJudge } from '@/server/services/conversationWake/policies';
+import type { WakeConversationLine } from '@/server/services/conversationWake/types';
import { createBotWakeRecorder, type WakeStatePort } from './wakeDecision';
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 3634c5cb2d4..c3dc0277a91 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
-import type { WakeClassify } from '@/server/services/agentSignal/scenarios/botWake/policies';
-import type { WakeConversationLine } from '@/server/services/agentSignal/scenarios/botWake/types';
+import type { WakeClassify } from '@/server/services/conversationWake/policies';
+import type { WakeConversationLine } from '@/server/services/conversationWake/types';
import { createBotWakeRecorder, type WakeStatePort } from './wakeDecision';
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
index d19295f7e76..60f73265727 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import type { WakeClassify } from '@/server/services/agentSignal/scenarios/botWake/policies';
+import type { WakeClassify } from '@/server/services/conversationWake/policies';
import { createBotWakeRecorder, type WakeStatePort } from './wakeDecision';
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 88019bd2e42..8801fbff88e 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
-import type { WakeClassify } from '@/server/services/agentSignal/scenarios/botWake/policies';
-import type { WakeConversationLine } from '@/server/services/agentSignal/scenarios/botWake/types';
+import type { WakeClassify } from '@/server/services/conversationWake/policies';
+import type { WakeConversationLine } from '@/server/services/conversationWake/types';
import { createBotWakeRecorder, type WakeStatePort } from './wakeDecision';
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index 3c5f5f9f747..5ceb488671f 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -12,35 +12,32 @@ import debug from 'debug';
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 { aggregateWakeVerdictsAsync } from '@/server/services/conversationWake/aggregator';
+import { parseBotWakeSettings } from '@/server/services/conversationWake/config';
import {
CONVERSATION_PROMPT_LINES,
- conversationParticipants,
- discordMessageTime,
toConversationLine,
-} from '@/server/services/agentSignal/scenarios/botWake/conversation';
-import {
- hasConversationLog,
- judgeExplicitMention,
- resolveChannelKeys,
- resolveConversationLogKey,
- wakeStateKeys,
-} from '@/server/services/agentSignal/scenarios/botWake/facts';
-import { isBotWakeEnabled } from '@/server/services/agentSignal/scenarios/botWake/gate';
+} from '@/server/services/conversationWake/conversation';
+import { judgeExplicitMention, wakeStateKeys } from '@/server/services/conversationWake/facts';
+import { isBotWakeEnabled } from '@/server/services/conversationWake/gate';
import type {
- WakeClassify,
- WakeDutyJudge,
-} from '@/server/services/agentSignal/scenarios/botWake/policies';
+ WakeInitiation,
+ WakeInitiationDetails,
+ WakeInitiationReason,
+} from '@/server/services/conversationWake/initiation';
+import {
+ canInitiateWake,
+ decideWakeInitiation,
+ initiationFor,
+ isWakeInitiationReason,
+ toWakeVerdicts,
+} from '@/server/services/conversationWake/initiation';
+import type { WakeClassify, WakeDutyJudge } from '@/server/services/conversationWake/policies';
import {
CLASSIFIER_POLICY_ID,
createDutyPolicy,
createWakePolicySet,
- DUTY_HELPFUL_TAG,
- DUTY_POLICY_ID,
- OWNER_RULES_POLICY_ID,
-} from '@/server/services/agentSignal/scenarios/botWake/policies';
+} from '@/server/services/conversationWake/policies';
import type {
BotWakeConfig,
WakeChannelState,
@@ -50,11 +47,17 @@ import type {
WakePolicy,
WakeSignal,
WakeStateSnapshot,
-} from '@/server/services/agentSignal/scenarios/botWake/types';
+} from '@/server/services/conversationWake/types';
import { redisService } from '@/server/services/redis';
import type { BotWakeChannelFields } from '@/server/services/redis/botWake';
import { getOriginMessageId, isReplayMessage } from '../mergeMessages';
+import {
+ discordMessageTime,
+ hasConversationLog,
+ resolveChannelKeys,
+ resolveConversationLogKey,
+} from '../wake/platformFacts';
import { buildWakeSignal, type WakeMessageLike } from '../wake/signal';
const log = debug('lobe-server:bot:wake-decision');
@@ -202,71 +205,6 @@ export interface WakeStatePort {
/** How many of a conversation's newest messages are read to find the bot's last words. */
const CONVERSATION_READ_LINES = 50;
-/** The reasons `initiate` can wake the bot for. */
-export type BotWakeInitiationReason = Extract<
- BotWakeReason,
- 'followup-window' | 'in-duty' | 'named-in-text'
->;
-
-/**
- * What each way of starting a wake on its own means for how the wake is handled.
- *
- * - `addressed`: the message is meant for the bot (it says the bot's name), so it is answered at
- * once like an @mention. The scheduler's collect window is for merging a burst of chatter nobody
- * addressed; making someone who called the bot wait for it only makes the bot look dead.
- *
- * Declared here, where the reason is decided, and read by the handlers as a fact about the
- * initiation: a new reason does not compile until it says what it is, and no call site has to
- * remember to list it.
- */
-const INITIATION_TRAITS: Record<BotWakeInitiationReason, { addressed: boolean }> = {
- 'followup-window': { addressed: false },
- // Nobody asked: it waits in the scheduler like any other unaddressed wake, and may end in silence.
- 'in-duty': { addressed: false },
- '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;
- /**
- * `in-duty` only: woken because stepping in would help (an open question nobody answered that the
- * bot can settle), not because the message falls within the duties.
- */
- helpful?: boolean;
- reason: BotWakeInitiationReason;
-}
-
-/** What a wake carries for the agent besides its reason. */
-type InitiationDetails = Pick<BotWakeInitiation, 'duty' | 'followup' | 'helpful'>;
-
-const initiationFor = (
- reason: BotWakeInitiationReason,
- { duty, followup, helpful }: InitiationDetails = {},
-): BotWakeInitiation => ({
- ...INITIATION_TRAITS[reason],
- ...(duty && { duty }),
- ...(followup && { followup }),
- ...(helpful && { helpful }),
- reason,
-});
-
export interface BotWakeRecorderOptions {
agentId: string;
applicationId: string;
@@ -346,7 +284,7 @@ export interface BotWakeRecorder {
*
* The evaluation is remembered, so the `record()` that follows does not judge the message again.
*/
- initiate: (observation: BotWakeObservation) => Promise<BotWakeInitiation | undefined>;
+ initiate: (observation: BotWakeObservation) => Promise<WakeInitiation | undefined>;
/**
* Evaluates the policies that the owner switched to `enforce`, with their real modes.
*
@@ -373,17 +311,6 @@ export interface BotWakeRecorder {
const asShadow = (policy: WakePolicy): WakePolicy => ({ ...policy, mode: 'shadow' });
-const ruleVerdicts = (decision: WakeDecision): SignalDecisionVerdict[] =>
- decision.records.map((record) => ({
- confidence: record.confidence,
- latencyMs: record.latencyMs,
- mode: record.mode,
- policyId: record.policyId,
- reason: record.reason,
- verdict: record.verdict,
- version: record.policyVersion,
- }));
-
/**
* Builds the verdict list for one observation: the router's own judgement first, then whatever the
* scenario's shadow policies said.
@@ -424,7 +351,7 @@ export const buildWakeVerdicts = async (
buildSnapshot(observation, signal, state, conversation),
);
- return [...verdicts, ...ruleVerdicts(decision)];
+ return [...verdicts, ...toWakeVerdicts(decision)];
};
const buildSnapshot = (
@@ -463,14 +390,11 @@ const summarizeConversation = (conversation?: WakeConversation) =>
};
/** The wake decided for a parked message, as kept for its replay. */
-interface RememberedInitiation extends InitiationDetails {
- reason: BotWakeInitiationReason;
+interface RememberedInitiation extends WakeInitiationDetails {
+ reason: WakeInitiationReason;
verdicts: SignalDecisionVerdict[];
}
-const isInitiationReason = (value: unknown): value is BotWakeInitiationReason =>
- typeof value === 'string' && value in INITIATION_TRAITS;
-
/**
* A stored decision, or `undefined` for none, a malformed one, or a reason this build lacks (one
* kept by an earlier build, such as `proactive-help`: the replay is judged again).
@@ -479,7 +403,7 @@ const parseRemembered = (raw: string | undefined): RememberedInitiation | undefi
if (!raw) return;
try {
const value = JSON.parse(raw) as Partial<RememberedInitiation>;
- if (!isInitiationReason(value.reason)) return;
+ if (!isWakeInitiationReason(value.reason)) return;
const followup = value.followup;
@@ -687,50 +611,23 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
*/
const initiated = async (
observation: BotWakeObservation,
- reason: BotWakeInitiationReason,
+ initiation: WakeInitiation,
evaluation: Evaluation,
- details: InitiationDetails = {},
- ): Promise<BotWakeInitiation> => {
+ ): Promise<WakeInitiation> => {
keepEvaluation(observation, evaluation);
await state.rememberInitiation?.(
applicationId,
getOriginMessageId(observation.message),
JSON.stringify({
- ...details,
- reason,
+ duty: initiation.duty,
+ followup: initiation.followup,
+ helpful: initiation.helpful,
+ reason: initiation.reason,
verdicts: evaluation.verdicts ?? [],
} satisfies RememberedInitiation),
);
- return initiationFor(reason, details);
- };
-
- /**
- * Asks the duty judge, after everything else declined: does the message, whoever wrote it, fall
- * within the bot's duties ("θ¦ζ˜―ε―Όε‡Ίθƒ½δΏη•™ζ–‡δ»Άε€Ήη»“ζž„ε°±ε₯½δΊ†" for a bot that assesses feature
- * requests)? Adds its verdict to `evaluation` and keeps it for `record()`.
- */
- const judgeDuty = async (
- observation: BotWakeObservation,
- signal: WakeSignal,
- snapshot: WakeStateSnapshot,
- evaluation: Evaluation & { verdicts: SignalDecisionVerdict[] },
- ): Promise<BotWakeInitiation | undefined> => {
- if (!dutyPolicy) return;
-
- const judged = await aggregateWakeVerdictsAsync([dutyPolicy], signal, snapshot);
- evaluation.verdicts.push(...ruleVerdicts(judged));
-
- // 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, {
- duty: record?.matched,
- helpful: record?.tags.includes(DUTY_HELPFUL_TAG),
- });
- }
-
- keepEvaluation(observation, evaluation);
+ return initiation;
};
const persist = async (observation: BotWakeObservation, observedAt: number) => {
@@ -881,9 +778,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
try {
if (!enabled) return;
- const rulePolicies = policies.filter((policy) => policy.id !== CLASSIFIER_POLICY_ID);
- const rulesEnforce = rulePolicies.some((policy) => policy.mode === 'enforce');
- if (!rulesEnforce && !dutyPolicy) return;
+ if (!canInitiateWake({ dutyPolicy, policies })) return;
const signal = signalFor(observation, observedAt);
const [channel, conversation] = await Promise.all([
@@ -905,75 +800,20 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
}
}
- const ruleDecision = await aggregateWakeVerdictsAsync(rulePolicies, signal, snapshot);
- if (!rulesEnforce || ruleDecision.verdict !== 'allow' || ruleDecision.fastPath) {
- // Nothing addressed the bot and no rule allowed it: not named, outside the follow-up
- // window. Only when no rule had an opinion either way, whatever the rules' mode: a deny
- // (a channel list, the silent-wake budget) still keeps the bot out. Owner presence is
- // the exception: it keeps the bot out of chatter the owner can answer, not off its
- // duties. Logging a feature request does not wait for the owner to go quiet.
- const onlyOwnerPresent =
- ruleDecision.verdict === 'deny' &&
- ruleDecision.decidedBy === OWNER_RULES_POLICY_ID &&
- ruleDecision.reason === 'owner-present' &&
- ruleDecision.records.every(
- (record) => record.policyId === OWNER_RULES_POLICY_ID || record.verdict === 'abstain',
- );
- const undecided =
- !ruleDecision.fastPath &&
- (onlyOwnerPresent ||
- ruleDecision.records.every((record) => record.verdict === 'abstain'));
- if (!undecided || !dutyPolicy) {
- // An enforcing deny is what kept the bot quiet: keep its verdicts, so the row names the
- // rule that stopped the wake instead of replaying every policy as if it only watched.
- keepEvaluation(observation, {
- channel,
- conversation,
- verdicts: ruleDecision.verdict === 'deny' ? ruleVerdicts(ruleDecision) : undefined,
- });
- return;
- }
-
- return await judgeDuty(observation, signal, snapshot, {
- channel,
- conversation,
- verdicts: ruleVerdicts(ruleDecision),
- });
- }
-
- const verdicts = ruleVerdicts(ruleDecision);
- const evaluation = { channel, conversation, verdicts };
-
- // Said by name: no need to ask a model whether it was meant for the bot.
- if (ruleDecision.reason === 'named-in-text') {
- return initiated(observation, 'named-in-text', evaluation);
- }
-
- // 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));
+ const outcome = await decideWakeInitiation({
+ dutyPolicy,
+ policies,
+ selfId: applicationId,
+ signal,
+ snapshot,
+ });
+ const evaluation = { channel, conversation, verdicts: outcome.verdicts };
+ if (!outcome.initiation) {
keepEvaluation(observation, evaluation);
-
- // A classifier that failed or ran out of budget passes in `degraded`: when the owner
- // relies on it, no answer is not a yes. Not a follow-up to the bot, the message may still
- // fall within its duties.
- const degraded = classified.records.some((record) => record.tags.includes('degraded'));
- if (classifier.mode === 'enforce' && (classified.verdict !== 'allow' || degraded)) {
- return dutyPolicy
- ? await judgeDuty(observation, signal, snapshot, evaluation)
- : undefined;
- }
- if (!degraded) score = classified.records[0]?.confidence;
+ return;
}
- // 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 },
- });
+ return await initiated(observation, outcome.initiation, evaluation);
} catch (error) {
botWakeFailureCounter.add(1, { stage: 'initiate' });
log('initiate failed: entry=%s %O', observation.entryPoint, error);
diff --git a/apps/server/src/services/bot/agentBotProviderSettings.ts b/apps/server/src/services/bot/agentBotProviderSettings.ts
index 924695c2c91..5c357055d74 100644
--- a/apps/server/src/services/bot/agentBotProviderSettings.ts
+++ b/apps/server/src/services/bot/agentBotProviderSettings.ts
@@ -7,7 +7,7 @@ import {
BOT_WAKE_SETTING_KEYS,
flattenBotWakeSettings,
hasPassiveListeningRule,
-} from '@/server/services/agentSignal/scenarios/botWake/config';
+} from '@/server/services/conversationWake/config';
import { GatewayService } from '@/server/services/gateway';
import { getBotMessageRouter } from './BotMessageRouter';
diff --git a/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
index 71a26196bcc..2d60e5623a7 100644
--- a/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
+++ b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
@@ -9,7 +9,7 @@ import {
MIN_COLLECT_SECONDS,
MIN_COOLDOWN_SECONDS,
parseBotWakeSettings,
-} from '@/server/services/agentSignal/scenarios/botWake/config';
+} from '@/server/services/conversationWake/config';
import agentLocale from '../../../../../../../packages/locales/src/default/agent';
import { botWakeFields, larkBotWakeFields } from '../botWakeFields';
diff --git a/apps/server/src/services/bot/platforms/botWakeFields.test.ts b/apps/server/src/services/bot/platforms/botWakeFields.test.ts
index 8af9d108ad3..b095ae7f810 100644
--- a/apps/server/src/services/bot/platforms/botWakeFields.test.ts
+++ b/apps/server/src/services/bot/platforms/botWakeFields.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
BOT_WAKE_SETTING_KEYS as KEY,
MAX_BOT_WAKE_CHANNEL_LIST,
-} from '@/server/services/agentSignal/scenarios/botWake/config';
+} from '@/server/services/conversationWake/config';
import { botWakeFields } from './botWakeFields';
diff --git a/apps/server/src/services/bot/platforms/botWakeFields.ts b/apps/server/src/services/bot/platforms/botWakeFields.ts
index 13367da4092..72e81bb90cd 100644
--- a/apps/server/src/services/bot/platforms/botWakeFields.ts
+++ b/apps/server/src/services/bot/platforms/botWakeFields.ts
@@ -7,7 +7,7 @@ import {
MAX_DUTIES_LENGTH,
MIN_COLLECT_SECONDS,
MIN_COOLDOWN_SECONDS,
-} from '@/server/services/agentSignal/scenarios/botWake/config';
+} from '@/server/services/conversationWake/config';
import type { FieldSchema } from './types';
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeFacts.test.ts b/apps/server/src/services/bot/wake/__tests__/platformFacts.test.ts
similarity index 70%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakeFacts.test.ts
rename to apps/server/src/services/bot/wake/__tests__/platformFacts.test.ts
index b81b7d7ef17..e54417e2a80 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeFacts.test.ts
+++ b/apps/server/src/services/bot/wake/__tests__/platformFacts.test.ts
@@ -1,13 +1,16 @@
// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { wakeStateKeys } from '@/server/services/conversationWake/facts';
+
import {
+ discordMessageTime,
hasConversationLog,
- isEmptyOrEmojiOnly,
- judgeExplicitMention,
parseDiscordMentions,
resolveChannelKeys,
+ resolveConversationLogKey,
resolveConversationLogKeys,
- wakeStateKeys,
-} from '../botWake/facts';
+} from '../platformFacts';
const BOT = '111';
@@ -82,68 +85,6 @@ describe('parseDiscordMentions', () => {
});
});
-describe('judgeExplicitMention', () => {
- const none = { botMentioned: false, everyone: false, here: false, otherUserIds: [], roleIds: [] };
-
- it.each([
- {
- adapter: true,
- expected: true,
- mentions: undefined,
- name: 'no mentions parsed: trust the adapter',
- },
- {
- adapter: false,
- expected: false,
- mentions: undefined,
- name: 'no mentions parsed, adapter false',
- },
- {
- adapter: true,
- expected: false,
- mentions: { ...none, everyone: true },
- name: 'adapter counted @everyone',
- },
- {
- adapter: true,
- expected: false,
- mentions: { ...none, roleIds: ['9'] },
- name: 'adapter counted a role ping',
- },
- { adapter: true, expected: true, mentions: { ...none, botMentioned: true }, name: 'real @bot' },
- {
- adapter: false,
- expected: true,
- mentions: { ...none, botMentioned: true },
- name: 'real @bot the adapter missed',
- },
- ])('$name', ({ adapter, expected, mentions }) => {
- expect(judgeExplicitMention(adapter, mentions)).toBe(expected);
- });
-});
-
-describe('isEmptyOrEmojiOnly', () => {
- it.each([
- ['', false, true],
- [' \n ', false, true],
- ['πŸ‘', false, true],
- ['πŸ‘πŸ½ πŸŽ‰', false, true],
- ['πŸ‘¨β€πŸ‘©β€πŸ‘§', false, true],
- ['<:pepe:12345>', false, true],
- ['<a:dance:12345> :smile:', false, true],
- ['...', false, true],
- ['?!', false, true],
- ['', true, false],
- ['πŸ‘', true, false],
- ['ok', false, false],
- ['ε₯½ηš„', false, false],
- ['πŸ‘ thanks', false, false],
- ['42', false, false],
- ])('%j (attachments=%s) -> %s', (text, attachments, expected) => {
- expect(isEmptyOrEmojiOnly(text, attachments)).toBe(expected);
- });
-});
-
describe('resolveChannelKeys', () => {
it('files a Discord channel message under the channel only', () => {
const keys = resolveChannelKeys('discord', 'app', 'discord:g1:c1');
@@ -211,3 +152,21 @@ describe('hasConversationLog', () => {
]);
});
});
+
+describe('resolveConversationLogKey', () => {
+ it('is shared by every bot in a channel and keeps a thread apart from its channel', () => {
+ expect(resolveConversationLogKey('discord', 'discord:g1:c1')).toBe('discord:g1:c1');
+ expect(resolveConversationLogKey('discord', 'discord:g1:c1:t1')).toBe('discord:g1:c1:t1');
+ expect(resolveConversationLogKey('telegram', 'telegram:-100123')).toBe('telegram:-100123');
+ });
+});
+
+describe('discordMessageTime', () => {
+ it('dates a Discord message from its id', () => {
+ // 1564248423568380028 was posted on 2026-10-26 (taken from a real decision row).
+ const at = discordMessageTime('1564248423568380028')!;
+
+ expect(new Date(at).toISOString().slice(0, 10)).toBe('2026-10-26');
+ expect(discordMessageTime('not-a-snowflake')).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/facts.ts b/apps/server/src/services/bot/wake/platformFacts.ts
similarity index 75%
rename from apps/server/src/services/agentSignal/scenarios/botWake/facts.ts
rename to apps/server/src/services/bot/wake/platformFacts.ts
index abe1d216226..3afb065b256 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/facts.ts
+++ b/apps/server/src/services/bot/wake/platformFacts.ts
@@ -1,9 +1,13 @@
-import type { WakeChannelKeys, WakeMentions } from './types';
+import type { WakeChannelKeys, WakeMentions } from '@/server/services/conversationWake/types';
+
+/*
+ * How the chat platforms a bot connects to name their conversations, mentions and messages. The
+ * wake pipeline itself reads only the neutral results: `WakeChannelKeys`, `WakeMentions`, log keys.
+ */
const DISCORD_USER_MENTION = /<@!?(\d+)>/g;
const DISCORD_ROLE_MENTION = /<@&(\d+)>/g;
-const DISCORD_CUSTOM_EMOJI = /<a?:\w+:\d+>/g;
-const SHORTCODE_EMOJI = /:[\w+-]+:/g;
+const DISCORD_EPOCH_MS = 1_420_070_400_000;
const LARK_CHAT_TYPES = new Set(['group', 'p2p']);
const isLarkPlatform = (platform: string) => platform === 'feishu' || platform === 'lark';
@@ -32,36 +36,6 @@ export const parseDiscordMentions = (text: string, botUserId: string): WakeMenti
};
};
-/**
- * Whether the platform's "mentioned" flag survives the re-judgement.
- *
- * Returns:
- * - the flag unchanged when mentions could not be re-derived (non-Discord platforms)
- * - otherwise `true` only when the bot itself is @-mentioned. `@everyone`, `@here` and a role
- * ping the adapter counted as a mention do not wake the bot on the explicit path.
- */
-export const judgeExplicitMention = (
- adapterIsMention: boolean,
- mentions: WakeMentions | undefined,
-): boolean => (mentions ? mentions.botMentioned : adapterIsMention);
-
-/**
- * True for a message with nothing to answer: blank, punctuation, or only emoji. A message
- * carrying an attachment is never empty.
- */
-export const isEmptyOrEmojiOnly = (text: string, hasAttachments = false): boolean => {
- if (hasAttachments) return false;
-
- const stripped = text
- .replaceAll(DISCORD_CUSTOM_EMOJI, '')
- .replaceAll(SHORTCODE_EMOJI, '')
- .replaceAll(/[\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}]/gu, '')
- // Marks cover the variation selector and the keycap; format characters cover the ZWJ.
- .replaceAll(/[\p{M}\p{P}\p{S}\p{Z}\p{C}]/gu, '');
-
- return stripped.length === 0;
-};
-
/**
* File keys for a conversation's wake state.
*
@@ -148,6 +122,9 @@ export const resolveConversationLogKeys = (
export const resolveConversationLogKey = (platform: string, platformThreadId: string): string =>
resolveConversationLogKeys(platform, platformThreadId).at(-1)!;
-/** Every key the channel's state is written under (channel first, then thread when there is one). */
-export const wakeStateKeys = (keys: WakeChannelKeys): string[] =>
- keys.threadKey ? [keys.channelKey, keys.threadKey] : [keys.channelKey];
+/** A Discord message id is a snowflake: the time it was sent is in its high bits. */
+export const discordMessageTime = (id: string): number | undefined => {
+ if (!/^\d{15,20}$/.test(id)) return undefined;
+
+ return Number(BigInt(id) >> 22n) + DISCORD_EPOCH_MS;
+};
diff --git a/apps/server/src/services/bot/wake/scheduler.ts b/apps/server/src/services/bot/wake/scheduler.ts
index ec9dbde7f30..87c7b8570f5 100644
--- a/apps/server/src/services/bot/wake/scheduler.ts
+++ b/apps/server/src/services/bot/wake/scheduler.ts
@@ -3,23 +3,23 @@ import { BOT_STAND_DOWN_MINUTES } from '@lobechat/types';
import debug from 'debug';
import { appEnv } from '@/envs/app';
-import { parseBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
-import { toConversationLine } from '@/server/services/agentSignal/scenarios/botWake/conversation';
-import {
- hasConversationLog,
- resolveChannelKeys,
- resolveConversationLogKeys,
- wakeStateKeys,
-} from '@/server/services/agentSignal/scenarios/botWake/facts';
-import { isBotWakeEnabled } from '@/server/services/agentSignal/scenarios/botWake/gate';
-import type { SchedulerOptions } from '@/server/services/agentSignal/scenarios/botWake/scheduler';
-import { WakeScheduler } from '@/server/services/agentSignal/scenarios/botWake/scheduler';
+import { parseBotWakeSettings } from '@/server/services/conversationWake/config';
+import { toConversationLine } from '@/server/services/conversationWake/conversation';
+import { wakeStateKeys } from '@/server/services/conversationWake/facts';
+import { isBotWakeEnabled } from '@/server/services/conversationWake/gate';
+import type { SchedulerOptions } from '@/server/services/conversationWake/scheduler';
+import { WakeScheduler } from '@/server/services/conversationWake/scheduler';
import { QueueService } from '@/server/services/queue';
import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
import { redisService } from '@/server/services/redis';
import { agentSignalScopeFlowControl } from '@/server/workflows/agentSignal';
import { runDeferredReplay } from '../deferredReplay';
+import {
+ hasConversationLog,
+ resolveChannelKeys,
+ resolveConversationLogKeys,
+} from './platformFacts';
const log = debug('lobe-server:bot:wake-scheduler');
diff --git a/apps/server/src/services/bot/wake/signal.ts b/apps/server/src/services/bot/wake/signal.ts
index a4e5ac5e53c..5f9b3956932 100644
--- a/apps/server/src/services/bot/wake/signal.ts
+++ b/apps/server/src/services/bot/wake/signal.ts
@@ -1,8 +1,6 @@
-import {
- parseDiscordMentions,
- resolveChannelKeys,
-} from '@/server/services/agentSignal/scenarios/botWake/facts';
-import type { WakeAuthor, WakeSignal } from '@/server/services/agentSignal/scenarios/botWake/types';
+import type { WakeAuthor, WakeSignal } from '@/server/services/conversationWake/types';
+
+import { parseDiscordMentions, resolveChannelKeys } from './platformFacts';
/** The part of a chat-sdk `Message` the wake pipeline reads. */
export interface WakeMessageLike {
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakePolicyReplay.json b/apps/server/src/services/conversationWake/__tests__/__fixtures__/policyReplay.json
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakePolicyReplay.json
rename to apps/server/src/services/conversationWake/__tests__/__fixtures__/policyReplay.json
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakeSchedulerReplay.json b/apps/server/src/services/conversationWake/__tests__/__fixtures__/schedulerReplay.json
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakeSchedulerReplay.json
rename to apps/server/src/services/conversationWake/__tests__/__fixtures__/schedulerReplay.json
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/aggregator.test.ts b/apps/server/src/services/conversationWake/__tests__/aggregator.test.ts
similarity index 98%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/aggregator.test.ts
rename to apps/server/src/services/conversationWake/__tests__/aggregator.test.ts
index f2725d80662..843bb742833 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/aggregator.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/aggregator.test.ts
@@ -1,12 +1,12 @@
// @vitest-environment node
-import { aggregateWakeVerdicts, isExplicitWake } from '../botWake/aggregator';
+import { aggregateWakeVerdicts, isExplicitWake } from '../aggregator';
import type {
WakePolicy,
WakePolicyMode,
WakeSignal,
WakeStateSnapshot,
WakeVerdict,
-} from '../botWake/types';
+} from '../types';
const signal: WakeSignal = { message: 'hello', timestamp: 1 };
const idle: WakeStateSnapshot = {
diff --git a/apps/server/src/services/bot/wake/__tests__/classify.test.ts b/apps/server/src/services/conversationWake/__tests__/classify.test.ts
similarity index 100%
rename from apps/server/src/services/bot/wake/__tests__/classify.test.ts
rename to apps/server/src/services/conversationWake/__tests__/classify.test.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts b/apps/server/src/services/conversationWake/__tests__/config.test.ts
similarity index 99%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
rename to apps/server/src/services/conversationWake/__tests__/config.test.ts
index d46ae46ac3a..35bc6ac83ff 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/config.test.ts
@@ -7,7 +7,7 @@ import {
MAX_CUSTOM_INSTRUCTIONS_LENGTH,
MAX_DUTIES_LENGTH,
parseBotWakeSettings,
-} from '../botWake/config';
+} from '../config';
describe('parseBotWakeSettings', () => {
it.each([null, undefined, {}, { botWake: null }, { botWake: 'yes' }, { botWake: [] }])(
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/conversation.test.ts b/apps/server/src/services/conversationWake/__tests__/conversation.test.ts
similarity index 79%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/conversation.test.ts
rename to apps/server/src/services/conversationWake/__tests__/conversation.test.ts
index 0d9ddc9f37f..0e8c05232c1 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/conversation.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/conversation.test.ts
@@ -4,13 +4,11 @@ import { describe, expect, it } from 'vitest';
import {
CONVERSATION_LINE_MAX_CHARS,
describeLine,
- discordMessageTime,
matchesBotName,
parseLine,
serializeLine,
toConversationLine,
-} from '../botWake/conversation';
-import { resolveConversationLogKey } from '../botWake/facts';
+} from '../conversation';
describe('conversation lines', () => {
const base = { at: 1_000, authorId: 'u1', authorName: 'Alice', id: 'm1', isBot: false };
@@ -55,14 +53,6 @@ describe('conversation lines', () => {
expect(parseLine(junk)).toBeUndefined();
});
- it('dates a Discord message from its id', () => {
- // 1564248423568380028 was posted on 2026-10-26 (taken from a real decision row).
- const at = discordMessageTime('1564248423568380028')!;
-
- expect(new Date(at).toISOString().slice(0, 10)).toBe('2026-10-26');
- expect(discordMessageTime('not-a-snowflake')).toBeUndefined();
- });
-
it('labels the bot as the assistant and everyone else by name', () => {
const mine = toConversationLine({
...base,
@@ -112,11 +102,3 @@ describe('matchesBotName', () => {
expect(matchesBotName('hello', ['.*'])).toBe(false);
});
});
-
-describe('resolveConversationLogKey', () => {
- it('is shared by every bot in a channel and keeps a thread apart from its channel', () => {
- expect(resolveConversationLogKey('discord', 'discord:g1:c1')).toBe('discord:g1:c1');
- expect(resolveConversationLogKey('discord', 'discord:g1:c1:t1')).toBe('discord:g1:c1:t1');
- expect(resolveConversationLogKey('telegram', 'telegram:-100123')).toBe('telegram:-100123');
- });
-});
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts b/apps/server/src/services/conversationWake/__tests__/duty.test.ts
similarity index 98%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
rename to apps/server/src/services/conversationWake/__tests__/duty.test.ts
index de41cea0b84..ca6e3ab40f4 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/duty.test.ts
@@ -1,8 +1,8 @@
// @vitest-environment node
-import { BOT_WAKE_SETTING_KEYS as K, parseBotWakeSettings } from '../botWake/config';
-import type { WakeDutyJudge } from '../botWake/policies';
-import { createDutyPolicy, DUTY_HELPFUL_TAG, DUTY_POLICY_ID } from '../botWake/policies';
-import type { WakeAuthor, WakeConversationLine, WakeSignal } from '../botWake/types';
+import { BOT_WAKE_SETTING_KEYS as K, parseBotWakeSettings } from '../config';
+import type { WakeDutyJudge } from '../policies';
+import { createDutyPolicy, DUTY_HELPFUL_TAG, DUTY_POLICY_ID } from '../policies';
+import type { WakeAuthor, WakeConversationLine, WakeSignal } from '../types';
const teammate: WakeAuthor = {
id: 'bob',
diff --git a/apps/server/src/services/bot/wake/__tests__/dutyJudge.test.ts b/apps/server/src/services/conversationWake/__tests__/dutyJudge.test.ts
similarity index 100%
rename from apps/server/src/services/bot/wake/__tests__/dutyJudge.test.ts
rename to apps/server/src/services/conversationWake/__tests__/dutyJudge.test.ts
diff --git a/apps/server/src/services/conversationWake/__tests__/facts.test.ts b/apps/server/src/services/conversationWake/__tests__/facts.test.ts
new file mode 100644
index 00000000000..90bdf701cad
--- /dev/null
+++ b/apps/server/src/services/conversationWake/__tests__/facts.test.ts
@@ -0,0 +1,64 @@
+// @vitest-environment node
+import { isEmptyOrEmojiOnly, judgeExplicitMention } from '../facts';
+
+describe('judgeExplicitMention', () => {
+ const none = { botMentioned: false, everyone: false, here: false, otherUserIds: [], roleIds: [] };
+
+ it.each([
+ {
+ adapter: true,
+ expected: true,
+ mentions: undefined,
+ name: 'no mentions parsed: trust the adapter',
+ },
+ {
+ adapter: false,
+ expected: false,
+ mentions: undefined,
+ name: 'no mentions parsed, adapter false',
+ },
+ {
+ adapter: true,
+ expected: false,
+ mentions: { ...none, everyone: true },
+ name: 'adapter counted @everyone',
+ },
+ {
+ adapter: true,
+ expected: false,
+ mentions: { ...none, roleIds: ['9'] },
+ name: 'adapter counted a role ping',
+ },
+ { adapter: true, expected: true, mentions: { ...none, botMentioned: true }, name: 'real @bot' },
+ {
+ adapter: false,
+ expected: true,
+ mentions: { ...none, botMentioned: true },
+ name: 'real @bot the adapter missed',
+ },
+ ])('$name', ({ adapter, expected, mentions }) => {
+ expect(judgeExplicitMention(adapter, mentions)).toBe(expected);
+ });
+});
+
+describe('isEmptyOrEmojiOnly', () => {
+ it.each([
+ ['', false, true],
+ [' \n ', false, true],
+ ['πŸ‘', false, true],
+ ['πŸ‘πŸ½ πŸŽ‰', false, true],
+ ['πŸ‘¨β€πŸ‘©β€πŸ‘§', false, true],
+ ['<:pepe:12345>', false, true],
+ ['<a:dance:12345> :smile:', false, true],
+ ['...', false, true],
+ ['?!', false, true],
+ ['', true, false],
+ ['πŸ‘', true, false],
+ ['ok', false, false],
+ ['ε₯½ηš„', false, false],
+ ['πŸ‘ thanks', false, false],
+ ['42', false, false],
+ ])('%j (attachments=%s) -> %s', (text, attachments, expected) => {
+ expect(isEmptyOrEmojiOnly(text, attachments)).toBe(expected);
+ });
+});
diff --git a/apps/server/src/services/bot/wake/__tests__/identity.test.ts b/apps/server/src/services/conversationWake/__tests__/identity.test.ts
similarity index 100%
rename from apps/server/src/services/bot/wake/__tests__/identity.test.ts
rename to apps/server/src/services/conversationWake/__tests__/identity.test.ts
diff --git a/apps/server/src/services/conversationWake/__tests__/initiation.test.ts b/apps/server/src/services/conversationWake/__tests__/initiation.test.ts
new file mode 100644
index 00000000000..747b2f090ea
--- /dev/null
+++ b/apps/server/src/services/conversationWake/__tests__/initiation.test.ts
@@ -0,0 +1,161 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { canInitiateWake, decideWakeInitiation } from '../initiation';
+import {
+ CLASSIFIER_POLICY_ID,
+ DUTY_HELPFUL_TAG,
+ DUTY_POLICY_ID,
+ INTERNAL_RULES_POLICY_ID,
+ OWNER_RULES_POLICY_ID,
+} from '../policies';
+import type {
+ WakePolicy,
+ WakePolicyMode,
+ WakePolicyResult,
+ WakeSignal,
+ WakeStateSnapshot,
+} from '../types';
+
+const signal: WakeSignal = { message: 'can someone check the export?', timestamp: 1 };
+
+const snapshot: WakeStateSnapshot = {
+ conversation: {
+ botNames: ['Coder'],
+ recent: [
+ { at: 1, authorId: 'self', id: 'm1', isBot: true, text: 'Done.' },
+ { at: 2, authorId: 'u2', authorName: 'Ada', id: 'm2', isBot: false, text: 'thanks' },
+ ],
+ },
+ explicitMention: false,
+ replyToBot: false,
+ threadSubscribed: true,
+};
+
+const result = (verdict: WakePolicyResult['verdict'], reason: string, extra = {}) => ({
+ confidence: verdict === 'abstain' ? 0 : 0.9,
+ reason,
+ tags: [],
+ verdict,
+ ...extra,
+});
+
+const policy = (
+ id: string,
+ outcome: WakePolicyResult,
+ mode: WakePolicyMode = 'enforce',
+): WakePolicy => ({
+ evaluate: () => outcome,
+ id,
+ mode,
+ requires: [],
+ version: 1,
+});
+
+const rules = (outcome: WakePolicyResult) => policy(OWNER_RULES_POLICY_ID, outcome);
+const classifier = (outcome: WakePolicyResult, mode: WakePolicyMode = 'enforce') =>
+ policy(CLASSIFIER_POLICY_ID, outcome, mode);
+const duty = (outcome: WakePolicyResult) => policy(DUTY_POLICY_ID, outcome);
+
+const decide = (policies: WakePolicy[], dutyPolicy?: WakePolicy) =>
+ decideWakeInitiation({ dutyPolicy, policies, selfId: 'self', signal, snapshot });
+
+describe('decideWakeInitiation', () => {
+ it('wakes a participant its text names, without asking the classifier', async () => {
+ const outcome = await decide([
+ policy(INTERNAL_RULES_POLICY_ID, result('allow', 'named-in-text')),
+ classifier(result('deny', 'not-addressed')),
+ ]);
+
+ expect(outcome.initiation).toEqual({ addressed: true, reason: 'named-in-text' });
+ expect(outcome.verdicts?.map((verdict) => verdict.policyId)).toEqual([
+ INTERNAL_RULES_POLICY_ID,
+ ]);
+ });
+
+ it('opens a follow-up with the classifier score and the other participants', async () => {
+ const outcome = await decide([
+ rules(result('allow', 'inside-followup-window')),
+ classifier(result('allow', 'addressed', { confidence: 0.82 })),
+ ]);
+
+ expect(outcome.initiation).toEqual({
+ addressed: false,
+ followup: { participants: [{ isBot: false, isOwner: false, name: 'Ada' }], score: 0.82 },
+ reason: 'followup-window',
+ });
+ });
+
+ it('falls back to the duty judge when an enforcing classifier declines', async () => {
+ const outcome = await decide(
+ [rules(result('allow', 'inside-followup-window')), classifier(result('deny', 'other'))],
+ duty(result('allow', 'in-duty', { matched: 'exports', tags: [DUTY_HELPFUL_TAG] })),
+ );
+
+ expect(outcome.initiation).toEqual({
+ addressed: false,
+ duty: 'exports',
+ helpful: true,
+ reason: 'in-duty',
+ });
+ expect(outcome.verdicts?.map((verdict) => verdict.policyId)).toEqual([
+ OWNER_RULES_POLICY_ID,
+ CLASSIFIER_POLICY_ID,
+ DUTY_POLICY_ID,
+ ]);
+ });
+
+ it('does not count a degraded classifier as a yes', async () => {
+ const outcome = await decide([
+ rules(result('allow', 'inside-followup-window')),
+ classifier(result('allow', 'classifier-timeout', { tags: ['degraded'] })),
+ ]);
+
+ expect(outcome.initiation).toBeUndefined();
+ expect(outcome.verdicts).toHaveLength(2);
+ });
+
+ it('keeps an enforcing deny on the record and never asks the duty judge', async () => {
+ let judged = false;
+ const outcome = await decide([rules(result('deny', 'budget-exhausted'))], {
+ ...duty(result('allow', 'in-duty')),
+ evaluate: () => {
+ judged = true;
+ return result('allow', 'in-duty');
+ },
+ });
+
+ expect(outcome.initiation).toBeUndefined();
+ expect(judged).toBe(false);
+ expect(outcome.verdicts?.[0]).toMatchObject({ reason: 'budget-exhausted', verdict: 'deny' });
+ });
+
+ it('lets the duty judge act when the only objection is the owner being present', async () => {
+ const outcome = await decide(
+ [rules(result('deny', 'owner-present'))],
+ duty(result('allow', 'in-duty', { matched: 'triage' })),
+ );
+
+ expect(outcome.initiation).toMatchObject({ duty: 'triage', reason: 'in-duty' });
+ });
+
+ it('leaves the verdicts for the record to replay when no rule had an opinion', async () => {
+ const outcome = await decide([rules(result('abstain', 'no-rule-hit'))]);
+
+ expect(outcome).toEqual({ verdicts: undefined });
+ });
+});
+
+describe('canInitiateWake', () => {
+ it('needs an enforcing rule or a duty judge', () => {
+ const shadowRules = policy(OWNER_RULES_POLICY_ID, result('abstain', 'x'), 'shadow');
+
+ expect(canInitiateWake({ policies: [shadowRules, classifier(result('allow', 'x'))] })).toBe(
+ false,
+ );
+ expect(canInitiateWake({ policies: [rules(result('abstain', 'x'))] })).toBe(true);
+ expect(
+ canInitiateWake({ dutyPolicy: duty(result('abstain', 'x')), policies: [shadowRules] }),
+ ).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/bot/wake/__tests__/judgeScore.test.ts b/apps/server/src/services/conversationWake/__tests__/judgeScore.test.ts
similarity index 100%
rename from apps/server/src/services/bot/wake/__tests__/judgeScore.test.ts
rename to apps/server/src/services/conversationWake/__tests__/judgeScore.test.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts b/apps/server/src/services/conversationWake/__tests__/policies.test.ts
similarity index 99%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
rename to apps/server/src/services/conversationWake/__tests__/policies.test.ts
index 454e3cb9973..db286827a0c 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/policies.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
-import { aggregateWakeVerdictsAsync } from '../botWake/aggregator';
-import { parseBotWakeSettings } from '../botWake/config';
-import type { WakeClassification, WakeClassify } from '../botWake/policies';
+import { aggregateWakeVerdictsAsync } from '../aggregator';
+import { parseBotWakeSettings } from '../config';
+import type { WakeClassification, WakeClassify } from '../policies';
import {
CLASSIFIER_POLICY_ID,
createClassifierPolicy,
@@ -10,7 +10,7 @@ import {
createWakePolicySet,
INTERNAL_RULES_POLICY_ID,
OWNER_RULES_POLICY_ID,
-} from '../botWake/policies';
+} from '../policies';
import type {
WakeAuthor,
WakeChannelState,
@@ -18,7 +18,7 @@ import type {
WakeRules,
WakeSignal,
WakeStateSnapshot,
-} from '../botWake/types';
+} from '../types';
const NOW = 1_700_000_000_000;
const human: WakeAuthor = { id: 'u1', isBot: false, isMe: false, isOwner: false, isSystem: false };
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicyReplay.test.ts b/apps/server/src/services/conversationWake/__tests__/policyReplay.test.ts
similarity index 92%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicyReplay.test.ts
rename to apps/server/src/services/conversationWake/__tests__/policyReplay.test.ts
index 6d03b802cf2..f8848d5f5d3 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicyReplay.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/policyReplay.test.ts
@@ -1,8 +1,8 @@
// @vitest-environment node
-import { aggregateWakeVerdictsAsync } from '../botWake/aggregator';
-import { createWakePolicySet } from '../botWake/policies';
-import type { WakeChannelState, WakeSignal } from '../botWake/types';
-import replay from './__fixtures__/botWakePolicyReplay.json';
+import { aggregateWakeVerdictsAsync } from '../aggregator';
+import { createWakePolicySet } from '../policies';
+import type { WakeChannelState, WakeSignal } from '../types';
+import replay from './__fixtures__/policyReplay.json';
interface Entry {
channel: Partial<WakeChannelState>;
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerMachine.test.ts b/apps/server/src/services/conversationWake/__tests__/schedulerMachine.test.ts
similarity index 99%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerMachine.test.ts
rename to apps/server/src/services/conversationWake/__tests__/schedulerMachine.test.ts
index d8da7cca12b..8c6049d4d6c 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerMachine.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/schedulerMachine.test.ts
@@ -4,8 +4,8 @@ import type {
SchedulerEvent,
SchedulerOptions,
SchedulerState,
-} from '../botWake/scheduler';
-import { IDLE_STATE, MAX_PENDING_WAKES, transitionScheduler } from '../botWake/scheduler';
+} from '../scheduler';
+import { IDLE_STATE, MAX_PENDING_WAKES, transitionScheduler } from '../scheduler';
const OPTIONS: SchedulerOptions = { collectMs: 20_000, cooldownMs: 60_000, runLeaseMs: 300_000 };
const T0 = 1_000_000;
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerReplay.test.ts b/apps/server/src/services/conversationWake/__tests__/schedulerReplay.test.ts
similarity index 91%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerReplay.test.ts
rename to apps/server/src/services/conversationWake/__tests__/schedulerReplay.test.ts
index f94c97f0547..48e730bd151 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerReplay.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/schedulerReplay.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
-import type { SchedulerEvent, SchedulerOptions, SchedulerState } from '../botWake/scheduler';
-import { transitionScheduler } from '../botWake/scheduler';
-import replay from './__fixtures__/botWakeSchedulerReplay.json';
+import type { SchedulerEvent, SchedulerOptions, SchedulerState } from '../scheduler';
+import { transitionScheduler } from '../scheduler';
+import replay from './__fixtures__/schedulerReplay.json';
interface RecordedStep {
decision?: string;
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerService.test.ts b/apps/server/src/services/conversationWake/__tests__/schedulerService.test.ts
similarity index 98%
rename from apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerService.test.ts
rename to apps/server/src/services/conversationWake/__tests__/schedulerService.test.ts
index 29e30c6de76..40806a73279 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeSchedulerService.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/schedulerService.test.ts
@@ -4,8 +4,8 @@ import type {
SchedulerRunTarget,
SchedulerState,
SchedulerStore,
-} from '../botWake/scheduler';
-import { WakeScheduler } from '../botWake/scheduler';
+} from '../scheduler';
+import { WakeScheduler } from '../scheduler';
/** In-memory store with the same contract as the Redis one: mutations are serialized per key. */
const createStore = () => {
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/aggregator.ts b/apps/server/src/services/conversationWake/aggregator.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/aggregator.ts
rename to apps/server/src/services/conversationWake/aggregator.ts
diff --git a/apps/server/src/services/bot/wake/classify.ts b/apps/server/src/services/conversationWake/classify.ts
similarity index 97%
rename from apps/server/src/services/bot/wake/classify.ts
rename to apps/server/src/services/conversationWake/classify.ts
index 6bf7e873721..b1cf25e8ce6 100644
--- a/apps/server/src/services/bot/wake/classify.ts
+++ b/apps/server/src/services/conversationWake/classify.ts
@@ -21,12 +21,12 @@ import { z } from 'zod';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
-import { describeLine } from '@/server/services/agentSignal/scenarios/botWake/conversation';
+import { describeLine } from '@/server/services/conversationWake/conversation';
import type {
WakeClassification,
WakeClassifierInput,
WakeClassify,
-} from '@/server/services/agentSignal/scenarios/botWake/policies/classifier';
+} from '@/server/services/conversationWake/policies/classifier';
const log = debug('lobe-server:bot:wake-classifier');
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts b/apps/server/src/services/conversationWake/config.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/config.ts
rename to apps/server/src/services/conversationWake/config.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/conversation.ts b/apps/server/src/services/conversationWake/conversation.ts
similarity index 94%
rename from apps/server/src/services/agentSignal/scenarios/botWake/conversation.ts
rename to apps/server/src/services/conversationWake/conversation.ts
index 1c375a9eb00..58fb244e459 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/conversation.ts
+++ b/apps/server/src/services/conversationWake/conversation.ts
@@ -15,8 +15,6 @@ export const MAX_NAMED_PARTICIPANTS = 8;
/** A name shorter than this would match inside ordinary words. */
const MIN_BOT_NAME_LENGTH = 2;
-const DISCORD_EPOCH_MS = 1_420_070_400_000;
-
export interface ConversationLineInput {
at: number;
authorId?: string;
@@ -89,13 +87,6 @@ export const parseLine = (raw: string): WakeConversationLine | undefined => {
}
};
-/** A Discord message id is a snowflake: the time it was sent is in its high bits. */
-export const discordMessageTime = (id: string): number | undefined => {
- if (!/^\d{15,20}$/.test(id)) return undefined;
-
- return Number(BigInt(id) >> 22n) + DISCORD_EPOCH_MS;
-};
-
/**
* One line as the classifier reads it: the bot is "Assistant", the bot's owner is marked, and
* everyone else is named.
diff --git a/apps/server/src/services/bot/wake/dutyJudge.ts b/apps/server/src/services/conversationWake/dutyJudge.ts
similarity index 98%
rename from apps/server/src/services/bot/wake/dutyJudge.ts
rename to apps/server/src/services/conversationWake/dutyJudge.ts
index ffab67081cc..131027ed91a 100644
--- a/apps/server/src/services/bot/wake/dutyJudge.ts
+++ b/apps/server/src/services/conversationWake/dutyJudge.ts
@@ -18,7 +18,7 @@ import { z } from 'zod';
import type {
WakeDutyJudge,
WakeDutyJudgement,
-} from '@/server/services/agentSignal/scenarios/botWake/policies/duty';
+} from '@/server/services/conversationWake/policies/duty';
import type { CreateWakeClassifyOptions } from './classify';
import { createRuntimeCache, ProbabilitySchema, toPromptInput } from './classify';
diff --git a/apps/server/src/services/conversationWake/facts.ts b/apps/server/src/services/conversationWake/facts.ts
new file mode 100644
index 00000000000..3fbaab26850
--- /dev/null
+++ b/apps/server/src/services/conversationWake/facts.ts
@@ -0,0 +1,38 @@
+import type { WakeChannelKeys, WakeMentions } from './types';
+
+const DISCORD_CUSTOM_EMOJI = /<a?:\w+:\d+>/g;
+const SHORTCODE_EMOJI = /:[\w+-]+:/g;
+
+/**
+ * Whether the platform's "mentioned" flag survives the re-judgement.
+ *
+ * Returns:
+ * - the flag unchanged when mentions could not be re-derived (non-Discord platforms)
+ * - otherwise `true` only when the bot itself is @-mentioned. `@everyone`, `@here` and a role
+ * ping the adapter counted as a mention do not wake the bot on the explicit path.
+ */
+export const judgeExplicitMention = (
+ adapterIsMention: boolean,
+ mentions: WakeMentions | undefined,
+): boolean => (mentions ? mentions.botMentioned : adapterIsMention);
+
+/**
+ * True for a message with nothing to answer: blank, punctuation, or only emoji. A message
+ * carrying an attachment is never empty.
+ */
+export const isEmptyOrEmojiOnly = (text: string, hasAttachments = false): boolean => {
+ if (hasAttachments) return false;
+
+ const stripped = text
+ .replaceAll(DISCORD_CUSTOM_EMOJI, '')
+ .replaceAll(SHORTCODE_EMOJI, '')
+ .replaceAll(/[\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}]/gu, '')
+ // Marks cover the variation selector and the keycap; format characters cover the ZWJ.
+ .replaceAll(/[\p{M}\p{P}\p{S}\p{Z}\p{C}]/gu, '');
+
+ return stripped.length === 0;
+};
+
+/** Every key the channel's state is written under (channel first, then thread when there is one). */
+export const wakeStateKeys = (keys: WakeChannelKeys): string[] =>
+ keys.threadKey ? [keys.channelKey, keys.threadKey] : [keys.channelKey];
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/gate.ts b/apps/server/src/services/conversationWake/gate.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/gate.ts
rename to apps/server/src/services/conversationWake/gate.ts
diff --git a/apps/server/src/services/bot/wake/identity.ts b/apps/server/src/services/conversationWake/identity.ts
similarity index 100%
rename from apps/server/src/services/bot/wake/identity.ts
rename to apps/server/src/services/conversationWake/identity.ts
diff --git a/apps/server/src/services/conversationWake/initiation.ts b/apps/server/src/services/conversationWake/initiation.ts
new file mode 100644
index 00000000000..fd6d874404a
--- /dev/null
+++ b/apps/server/src/services/conversationWake/initiation.ts
@@ -0,0 +1,233 @@
+import type { SignalDecisionVerdict } from '@lobechat/types';
+
+import { aggregateWakeVerdictsAsync } from './aggregator';
+import type { WakeParticipant } from './conversation';
+import { conversationParticipants } from './conversation';
+import {
+ CLASSIFIER_POLICY_ID,
+ DUTY_HELPFUL_TAG,
+ DUTY_POLICY_ID,
+ OWNER_RULES_POLICY_ID,
+} from './policies';
+import type { WakeDecision, WakePolicy, WakeSignal, WakeStateSnapshot } from './types';
+
+/** The reasons a participant can be woken for a message nobody addressed to it. */
+export type WakeInitiationReason = 'followup-window' | 'in-duty' | 'named-in-text';
+
+/**
+ * What each way of starting a wake on its own means for how the wake is handled.
+ *
+ * - `addressed`: the message is meant for the participant (it says its name), so it is answered at
+ * once like an @mention. A collect window is for merging a burst of chatter nobody addressed;
+ * making someone who called the participant wait for it only makes it look dead.
+ *
+ * Declared here, where the reason is decided, and read by callers as a fact about the initiation:
+ * a new reason does not compile until it says what it is, and no call site has to remember to
+ * list it.
+ */
+const INITIATION_TRAITS: Record<WakeInitiationReason, { addressed: boolean }> = {
+ 'followup-window': { addressed: false },
+ // Nobody asked: it waits like any other unaddressed wake, and may end in silence.
+ 'in-duty': { addressed: false },
+ '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 conversation.
+ */
+export interface WakeFollowupContext {
+ /** 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 participant. */
+ score?: number;
+}
+
+/** A wake started without anyone addressing the participant: the rule that started it. */
+export interface WakeInitiation {
+ /** 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 WakeFollowupContext}. */
+ followup?: WakeFollowupContext;
+ /**
+ * `in-duty` only: woken because stepping in would help (an open question nobody answered that the
+ * participant can settle), not because the message falls within the duties.
+ */
+ helpful?: boolean;
+ reason: WakeInitiationReason;
+}
+
+/** What a wake carries for the agent besides its reason. */
+export type WakeInitiationDetails = Pick<WakeInitiation, 'duty' | 'followup' | 'helpful'>;
+
+export const isWakeInitiationReason = (value: unknown): value is WakeInitiationReason =>
+ typeof value === 'string' && value in INITIATION_TRAITS;
+
+export const initiationFor = (
+ reason: WakeInitiationReason,
+ { duty, followup, helpful }: WakeInitiationDetails = {},
+): WakeInitiation => ({
+ ...INITIATION_TRAITS[reason],
+ ...(duty && { duty }),
+ ...(followup && { followup }),
+ ...(helpful && { helpful }),
+ reason,
+});
+
+/** A decision's per-policy records in the shape a decision row stores. */
+export const toWakeVerdicts = (decision: WakeDecision): SignalDecisionVerdict[] =>
+ decision.records.map((record) => ({
+ confidence: record.confidence,
+ latencyMs: record.latencyMs,
+ mode: record.mode,
+ policyId: record.policyId,
+ reason: record.reason,
+ verdict: record.verdict,
+ version: record.policyVersion,
+ }));
+
+export interface WakeInitiationPolicies {
+ /**
+ * Model judge for a message within the participant's duties. Absent when it has no duties or
+ * the judge is off.
+ */
+ dutyPolicy?: WakePolicy;
+ /** The rule policies and, optionally, the addressed classifier. */
+ policies: readonly WakePolicy[];
+}
+
+/**
+ * Whether {@link decideWakeInitiation} could ever start a wake with these policies: some rule
+ * enforces, or there is a duty judge. Checked before any state is read.
+ */
+export const canInitiateWake = ({ dutyPolicy, policies }: WakeInitiationPolicies): boolean =>
+ !!dutyPolicy ||
+ policies.some((policy) => policy.id !== CLASSIFIER_POLICY_ID && policy.mode === 'enforce');
+
+export interface DecideWakeInitiationInput extends WakeInitiationPolicies {
+ /** The participant's own id in the conversation, to tell its lines from everyone else's. */
+ selfId: string;
+ signal: WakeSignal;
+ snapshot: WakeStateSnapshot;
+}
+
+export interface WakeInitiationOutcome {
+ /** Set when the participant should be woken. */
+ initiation?: WakeInitiation;
+ /**
+ * The verdicts of the policies that ran, for the decision row. Absent when the rules stopped
+ * short without a deny: the row then replays them as observers.
+ */
+ verdicts?: SignalDecisionVerdict[];
+}
+
+/**
+ * Decides whether to wake a participant for a message nobody addressed to it. Pure apart from
+ * the model calls inside the policies: the caller reads the state, and keeps or persists the
+ * outcome.
+ *
+ * In order:
+ * 1. The rule policies. The text naming the participant (`named-in-text`) wakes it with no model
+ * call; the follow-up window opens the way for step 2. An enforcing deny keeps it quiet.
+ * 2. Inside the window, an enforcing classifier must agree; a degraded one is not a yes, and a
+ * shadow one only scores.
+ * 3. When no rule had an opinion (or only the owner's presence held it back), or the classifier
+ * declined, the duty judge may still wake it for a message within its duties.
+ */
+export const decideWakeInitiation = async ({
+ dutyPolicy,
+ policies,
+ selfId,
+ signal,
+ snapshot,
+}: DecideWakeInitiationInput): Promise<WakeInitiationOutcome> => {
+ /** Asks the duty judge, after everything else declined. Adds its verdict to `verdicts`. */
+ const judgeDuty = async (verdicts: SignalDecisionVerdict[]): Promise<WakeInitiationOutcome> => {
+ if (!dutyPolicy) return { verdicts };
+
+ const judged = await aggregateWakeVerdictsAsync([dutyPolicy], signal, snapshot);
+ verdicts.push(...toWakeVerdicts(judged));
+
+ // 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 {
+ initiation: initiationFor('in-duty', {
+ duty: record?.matched,
+ helpful: record?.tags.includes(DUTY_HELPFUL_TAG),
+ }),
+ verdicts,
+ };
+ }
+
+ return { verdicts };
+ };
+
+ const rulePolicies = policies.filter((policy) => policy.id !== CLASSIFIER_POLICY_ID);
+ const rulesEnforce = rulePolicies.some((policy) => policy.mode === 'enforce');
+ const ruleDecision = await aggregateWakeVerdictsAsync(rulePolicies, signal, snapshot);
+
+ if (!rulesEnforce || ruleDecision.verdict !== 'allow' || ruleDecision.fastPath) {
+ // Nothing addressed the participant and no rule allowed it: not named, outside the follow-up
+ // window. Only when no rule had an opinion either way, whatever the rules' mode: a deny (a
+ // channel list, the silent-wake budget) still keeps it out. Owner presence is the exception:
+ // it keeps the participant out of chatter the owner can answer, not off its duties. Logging a
+ // feature request does not wait for the owner to go quiet.
+ const onlyOwnerPresent =
+ ruleDecision.verdict === 'deny' &&
+ ruleDecision.decidedBy === OWNER_RULES_POLICY_ID &&
+ ruleDecision.reason === 'owner-present' &&
+ ruleDecision.records.every(
+ (record) => record.policyId === OWNER_RULES_POLICY_ID || record.verdict === 'abstain',
+ );
+ const undecided =
+ !ruleDecision.fastPath &&
+ (onlyOwnerPresent || ruleDecision.records.every((record) => record.verdict === 'abstain'));
+
+ if (!undecided || !dutyPolicy) {
+ // An enforcing deny is what kept the participant quiet: keep its verdicts, so the row names
+ // the rule that stopped the wake instead of replaying every policy as if it only watched.
+ return {
+ verdicts: ruleDecision.verdict === 'deny' ? toWakeVerdicts(ruleDecision) : undefined,
+ };
+ }
+
+ return judgeDuty(toWakeVerdicts(ruleDecision));
+ }
+
+ const verdicts = toWakeVerdicts(ruleDecision);
+
+ // Said by name: no need to ask a model whether it was meant for the participant.
+ if (ruleDecision.reason === 'named-in-text') {
+ return { initiation: initiationFor('named-in-text'), verdicts };
+ }
+
+ // 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(...toWakeVerdicts(classified));
+
+ // A classifier that failed or ran out of budget passes in `degraded`: when the owner relies
+ // on it, no answer is not a yes. Not a follow-up to the participant, the message may still
+ // fall within its duties.
+ const degraded = classified.records.some((record) => record.tags.includes('degraded'));
+ if (classifier.mode === 'enforce' && (classified.verdict !== 'allow' || degraded)) {
+ return judgeDuty(verdicts);
+ }
+ if (!degraded) score = classified.records[0]?.confidence;
+ }
+
+ // The agent is told why it woke: how sure the classifier was, and who else is talking.
+ return {
+ initiation: initiationFor('followup-window', {
+ followup: { participants: conversationParticipants(snapshot.conversation, selfId), score },
+ }),
+ verdicts,
+ };
+};
diff --git a/apps/server/src/services/bot/wake/judgeScore.ts b/apps/server/src/services/conversationWake/judgeScore.ts
similarity index 88%
rename from apps/server/src/services/bot/wake/judgeScore.ts
rename to apps/server/src/services/conversationWake/judgeScore.ts
index b728220602d..9f5e64060c8 100644
--- a/apps/server/src/services/bot/wake/judgeScore.ts
+++ b/apps/server/src/services/conversationWake/judgeScore.ts
@@ -1,7 +1,7 @@
import type { BotWakeJudgeKind, BotWakeJudgeScore, SignalDecisionVerdict } from '@lobechat/types';
-import { CLASSIFIER_POLICY_ID } from '@/server/services/agentSignal/scenarios/botWake/policies/classifier';
-import { DUTY_POLICY_ID } from '@/server/services/agentSignal/scenarios/botWake/policies/duty';
+import { CLASSIFIER_POLICY_ID } from '@/server/services/conversationWake/policies/classifier';
+import { DUTY_POLICY_ID } from '@/server/services/conversationWake/policies/duty';
const KIND_BY_POLICY: Record<string, BotWakeJudgeKind> = {
[CLASSIFIER_POLICY_ID]: 'addressed',
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/classifier.ts b/apps/server/src/services/conversationWake/policies/classifier.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/policies/classifier.ts
rename to apps/server/src/services/conversationWake/policies/classifier.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/duty.ts b/apps/server/src/services/conversationWake/policies/duty.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/policies/duty.ts
rename to apps/server/src/services/conversationWake/policies/duty.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/index.ts b/apps/server/src/services/conversationWake/policies/index.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/policies/index.ts
rename to apps/server/src/services/conversationWake/policies/index.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/internalRules.ts b/apps/server/src/services/conversationWake/policies/internalRules.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/policies/internalRules.ts
rename to apps/server/src/services/conversationWake/policies/internalRules.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts b/apps/server/src/services/conversationWake/policies/ownerRules.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts
rename to apps/server/src/services/conversationWake/policies/ownerRules.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/scheduler/index.ts b/apps/server/src/services/conversationWake/scheduler/index.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/scheduler/index.ts
rename to apps/server/src/services/conversationWake/scheduler/index.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/scheduler/machine.ts b/apps/server/src/services/conversationWake/scheduler/machine.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/scheduler/machine.ts
rename to apps/server/src/services/conversationWake/scheduler/machine.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/scheduler/service.ts b/apps/server/src/services/conversationWake/scheduler/service.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/scheduler/service.ts
rename to apps/server/src/services/conversationWake/scheduler/service.ts
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts b/apps/server/src/services/conversationWake/types.ts
similarity index 100%
rename from apps/server/src/services/agentSignal/scenarios/botWake/types.ts
rename to apps/server/src/services/conversationWake/types.ts
diff --git a/apps/server/src/services/gateway/gatewayMapping.ts b/apps/server/src/services/gateway/gatewayMapping.ts
index ed03928e818..45d0de9326b 100644
--- a/apps/server/src/services/gateway/gatewayMapping.ts
+++ b/apps/server/src/services/gateway/gatewayMapping.ts
@@ -6,8 +6,8 @@ import type { DecryptedMessengerAccountLink } from '@/database/models/messengerA
import { gatewayEnv } from '@/envs/gateway';
import type { BotRuntimeStatus } from '@/types/botRuntimeStatus';
-import { hasPassiveListeningRule } from '../agentSignal/scenarios/botWake/config';
import { extractWatchKeywordEntries } from '../bot/platforms';
+import { hasPassiveListeningRule } from '../conversationWake/config';
import type {
MessageGatewayCapabilities,
MessageGatewayConnectionConfig,
diff --git a/apps/server/src/services/redis/botWake.realRedis.test.ts b/apps/server/src/services/redis/botWake.realRedis.test.ts
index 22d242c23ab..cb981fc66ec 100644
--- a/apps/server/src/services/redis/botWake.realRedis.test.ts
+++ b/apps/server/src/services/redis/botWake.realRedis.test.ts
@@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import type {
SchedulerRunTarget,
WakeScheduler as WakeSchedulerClass,
-} from '../agentSignal/scenarios/botWake/scheduler';
+} from '../conversationWake/scheduler';
import type { botWake } from './botWake';
/**
@@ -27,7 +27,7 @@ describe.skipIf(!url)('botWake redis domain (real Redis)', () => {
process.env.REDIS_URL = url;
process.env.REDIS_PREFIX = prefix;
domain = (await import('./botWake')).botWake;
- WakeScheduler = (await import('../agentSignal/scenarios/botWake/scheduler')).WakeScheduler;
+ WakeScheduler = (await import('../conversationWake/scheduler')).WakeScheduler;
const { default: IORedis } = await import('ioredis');
const raw = new IORedis(url!);
cleanup = async () => {
diff --git a/apps/server/src/services/redis/botWake.ts b/apps/server/src/services/redis/botWake.ts
index bde9261e305..8ce46adfd67 100644
--- a/apps/server/src/services/redis/botWake.ts
+++ b/apps/server/src/services/redis/botWake.ts
@@ -8,8 +8,8 @@ import {
CONVERSATION_LOG_MAX_LINES,
parseLine,
serializeLine,
-} from '@/server/services/agentSignal/scenarios/botWake/conversation';
-import type { WakeConversationLine } from '@/server/services/agentSignal/scenarios/botWake/types';
+} from '@/server/services/conversationWake/conversation';
+import type { WakeConversationLine } from '@/server/services/conversationWake/types';
import { getRedisServiceClient } from './client';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
index 80bb27802c5..ed262d4bd01 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
@@ -27,7 +27,6 @@ import { agents } from '@/database/schemas';
import { notTrashed } from '@/database/utils/softDelete';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
-import { flattenBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
import {
assertBotAccessSettings,
assertWatchKeywordsWritable,
@@ -48,6 +47,7 @@ import {
wechatPendingPushKey,
wechatWindowKey,
} from '@/server/services/bot/platforms/wechat/contextWindow';
+import { flattenBotWakeSettings } from '@/server/services/conversationWake/config';
import { GatewayService } from '@/server/services/gateway';
import { BOT_RUNTIME_STATUSES, getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';
import { getMessengerRouter, messengerPlatformRegistry } from '@/server/services/messenger';
diff --git a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
index 81008d943f9..540d4b8ba56 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
@@ -6,10 +6,10 @@ import { fireEvent, render, screen } from '@testing-library/react';
import { useEffect } from 'react';
import { describe, expect, it, vi } from 'vitest';
-import { flattenBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
import { schema as discordSchema } from '@/server/services/bot/platforms/discord/schema';
import { sharedSchema as feishuSchema } from '@/server/services/bot/platforms/feishu/definitions/schema';
import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
+import { flattenBotWakeSettings } from '@/server/services/conversationWake/config';
import agentZh from '../../../../locales/zh-CN/agent.json';
import agentEn from '../../../../packages/locales/src/default/agent';
diff --git a/src/features/AgentChannel/PlatformDetail/formState.test.ts b/src/features/AgentChannel/PlatformDetail/formState.test.ts
index c15258c8322..c771d36cead 100644
--- a/src/features/AgentChannel/PlatformDetail/formState.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/formState.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
-import { BOT_WAKE_SETTING_KEYS } from '@/server/services/agentSignal/scenarios/botWake/config';
import { schema as discordSchema } from '@/server/services/bot/platforms/discord/schema';
import type { FieldSchema } from '@/server/services/bot/platforms/types';
+import { BOT_WAKE_SETTING_KEYS } from '@/server/services/conversationWake/config';
import {
extractSettingsDefaults,
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
index 125a0d30c29..c92e6424f25 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
-import { BOT_WAKE_SETTING_KEYS } from '@/server/services/agentSignal/scenarios/botWake/config';
import { botWakeFields } from '@/server/services/bot/platforms/botWakeFields';
import type { FieldSchema } from '@/server/services/bot/platforms/types';
+import { BOT_WAKE_SETTING_KEYS } from '@/server/services/conversationWake/config';
import {
getSchemaFields,