🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(bot-wake): stop a parked replay from re-parking itself, keep verdicts across a reply thread, stay out of replies to others (#21702)
Arvin Xu7108eddd885f
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.tsindex c3fa5c3c2bf..9c95b6ade6c 100644--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.ts+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.ts@@ -48,6 +48,20 @@ describe('proactive policy', () => {expect(judge).not.toHaveBeenCalled();});+ // "你忘记我上半年让你搞onboarding Bench 那个了么", the owner replying to a teammate: the model+ // read "你" as the assistant and the bot stepped in.+ it('stays out of a reply to someone else, but not of a reply to itself or to the owner', async () => {+ const judge = judgeScoring(1);+ const reply = (replyToAuthorId: string) =>+ run(judge, signal({ applicationId: 'bot-app', replyToAuthorId }));++ expect(await reply('teammate')).toMatchObject({ reason: 'reply-to-other', verdict: 'abstain' });+ expect(judge).not.toHaveBeenCalled();++ expect((await reply('bot-app')).verdict).toBe('allow');+ expect((await reply('o1')).verdict).toBe('allow');+ });+it('does not ask about a message too short to act on', async () => {const judge = judgeScoring(1);diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.ts b/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.tsindex c57a4fd376b..a65e7b05c04 100644--- a/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.ts+++ b/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.ts@@ -48,7 +48,9 @@ const degraded = (reason: string): WakePolicyResult => ({* policy set the other paths evaluate.** Returns:- * - `abstain` without a model call for anyone but the owner, and for a message too short to act on+ * - `abstain` without a model call for anyone but the owner, for a message too short to act on,+ * and for a reply to someone else: the owner is answering that person, and the model, which+ * only sees the text, reads the "你" in it as the assistant* - `abstain` tagged `degraded` when the model errors or answers late: no answer is not a yes* - Otherwise `allow` when the score reaches `rules.proactive.threshold`, else `deny`;* `confidence` is the score@@ -61,6 +63,13 @@ export const createProactivePolicy = (costly: true,evaluate: async ({ signal, state }) => {if (!signal.author?.isOwner) return abstain('not-owner');+ if (+ signal.replyToAuthorId &&+ signal.replyToAuthorId !== signal.applicationId &&+ signal.replyToAuthorId !== signal.author.id+ ) {+ return abstain('reply-to-other');+ }if (isEmptyOrEmojiOnly(signal.message, signal.hasAttachments) ||signal.message.trim().length < MIN_PROACTIVE_MESSAGE_LENGTHdiff --git a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts b/apps/server/src/services/agentSignal/scenarios/botWake/types.tsindex 99b2b72c0b8..21edb8ff0cc 100644--- a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts+++ b/apps/server/src/services/agentSignal/scenarios/botWake/types.ts@@ -21,6 +21,11 @@ export interface WakeSignal {message: string;platform?: string;platformThreadId?: string;+ /**+ * Platform user id of the author of the message this one replies to (Discord replies only).+ * Absent when it is not a reply or the platform does not say.+ */+ replyToAuthorId?: string;timestamp: number;}diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.proactive.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.proactive.test.tsindex 8282b2e16db..535bb4349cc 100644--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.proactive.test.ts+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.proactive.test.ts@@ -146,6 +146,31 @@ describe('bot-wake recorder: offering the owner help nobody asked for', () => {expect(judge).toHaveBeenCalledOnce();});+ // Discord opens the reply thread between `initiate` and `record()`: the wake is recorded under+ // the new thread. The row must keep the verdict that woke the bot, not re-run the policies on+ // the new thread's empty log (a shadow classifier scored 0.88 there for a 0.45 proactive wake).+ it('records the verdict that woke it when the reply moved to a new thread', async () => {+ const judge = proactiveJudge(0.85);+ const classify = classifierAnswer(0.05);+ const recorder = make(PROACTIVE('enforce'), fakeState(), { classify, proactiveJudge: judge });++ await expect(recorder.initiate(musing())).resolves.toMatchObject({ reason: 'proactive-help' });+ const classifierCalls = vi.mocked(classify).mock.calls.length;+ recorder.record(+ observation(+ { outcome: 'wake', reason: 'proactive-help', threadId: 'discord:g1:c1:t-reply' },+ { text: MUSING },+ ),+ );+ await flush();++ const policyIds = recorded()[0].verdicts.map((verdict: any) => verdict.policyId);+ expect(policyIds).toContain('bot-wake:proactive');+ // Nothing was judged again for the row.+ expect(judge).toHaveBeenCalledOnce();+ expect(classify).toHaveBeenCalledTimes(classifierCalls);+ });+it('works while the other rules only watch: the owner can try it on its own', async () => {const recorder = make(PROACTIVE('enforce', { mode: 'shadow' }), fakeState(), {proactiveJudge: proactiveJudge(0.9),diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.tsindex 716401ccd27..724b2521b32 100644--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts@@ -21,6 +21,7 @@ import {} from '@/server/services/agentSignal/scenarios/botWake/conversation';import {judgeExplicitMention,+ resolveChannelKeys,resolveConversationLogKey,wakeStateKeys,} from '@/server/services/agentSignal/scenarios/botWake/facts';@@ -592,8 +593,11 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR};const evaluations = new Map<string, Evaluation>();+ // By channel, not thread: a Discord wake opens its reply thread after `initiate` and before+ // `record()`, so the same message is recorded under the new thread's id. Keyed by thread, the+ // evaluation was missed and the policies ran again on the new thread's empty log.const evaluationKey = (observation: BotWakeObservation) =>- `${observation.threadId}:${observation.message.id}`;+ `${resolveChannelKeys(platform, applicationId, observation.threadId).channelKey}:${observation.message.id}`;const keepEvaluation = (observation: BotWakeObservation, evaluation: Evaluation) => {evaluations.set(evaluationKey(observation), evaluation);// A message that is never recorded must not pile up.diff --git a/apps/server/src/services/bot/__tests__/mergeMessages.test.ts b/apps/server/src/services/bot/__tests__/mergeMessages.test.tsindex b0fbb875e21..9b86acfc219 100644--- a/apps/server/src/services/bot/__tests__/mergeMessages.test.ts+++ b/apps/server/src/services/bot/__tests__/mergeMessages.test.ts@@ -62,6 +62,24 @@ describe('buildReplayMessages', () => {expect(getOriginMessageId(original)).toBe('10');});+ // A replay the scheduler parked again was stored under its replay id; replaying it once more+ // stacked a second suffix, the origin id no longer matched the released batch, and the message+ // was parked again on every run.+ it('does not stack replay suffixes when a replay is parked and replayed again', () => {+ const original = makeMessage('10', 'hi', { item: 'text' });+ const [first] = buildReplayMessages([original.toJSON()]);+ const [second] = buildReplayMessages([first.toJSON()]);++ expect(second.id).toMatch(/^10:replay:\d+:0$/);+ expect(getOriginMessageId(second)).toBe('10');+ });++ it('reports the platform id behind an id that already stacked replay suffixes', () => {+ expect(getOriginMessageId({ id: '10:replay:1793094332657:0:replay:1793094692762:1' })).toBe(+ '10',+ );+ });+it('keeps each original raw through the SDK JSON round-trip before merging', () => {const image = makeMessage('10', '', { item: 'image' }, [{ type: 'image', url: '' }]);const text = makeMessage('11', '参考这个风格', { item: 'text' });diff --git a/apps/server/src/services/bot/mergeMessages.ts b/apps/server/src/services/bot/mergeMessages.tsindex 0b416b780b1..7dab7290c72 100644--- a/apps/server/src/services/bot/mergeMessages.ts+++ b/apps/server/src/services/bot/mergeMessages.ts@@ -65,6 +65,13 @@ export function getSourceMessages(message: Message): Message[] {/** What {@link buildReplayMessages} appends to a replay's id. */const REPLAY_ID_SUFFIX = /:replay:\d+:\d+$/;+/**+ * Every replay suffix on an id. A replay that is parked again used to keep its replay id, so the+ * next replay stacked another suffix on it (`<id>:replay:1:0:replay:2:1`); those are still in the+ * deferred-message store until they expire.+ */+const REPLAY_ID_SUFFIXES = /(?::replay:\d+:\d+)+$/;+/*** The id a message carried before {@link buildReplayMessages} rewrote it.*@@ -73,7 +80,7 @@ const REPLAY_ID_SUFFIX = /:replay:\d+:\d+$/;* it has to match the original id rather than the replay one.*/export const getOriginMessageId = (message: Pick<Message, 'id'>): string =>- message.id.replace(REPLAY_ID_SUFFIX, '');+ message.id.replace(REPLAY_ID_SUFFIXES, '');/** Whether {@link buildReplayMessages} produced this message from a parked one. */export const isReplayMessage = (message: Pick<Message, 'id'>): boolean =>@@ -84,11 +91,16 @@ export const isReplayMessage = (message: Pick<Message, 'id'>): boolean =>** The replayed message gets a fresh id: the Chat SDK dedupes inbound messages* by `<adapter>:<id>` for 10 minutes, and the originals already went through- * `processMessage` once when they were deferred.+ * `processMessage` once when they were deferred. A message parked again by its own replay keeps+ * its replay id, so the fresh id is built from the origin id: suffixes never stack, and the id+ * still matches the one the wake scheduler released.*/export function buildReplayMessages(entries: DeferredBotMessage[]): Message[] {const now = Date.now();return entries.map((entry, index) => {- return Message.fromJSON({ ...entry, id: `${entry.id}:replay:${now}:${index}` });+ return Message.fromJSON({+ ...entry,+ id: `${getOriginMessageId(entry)}:replay:${now}:${index}`,+ });});}diff --git a/apps/server/src/services/bot/wake/__tests__/signal.test.ts b/apps/server/src/services/bot/wake/__tests__/signal.test.tsindex 95285bc5f7b..267e5b6adf2 100644--- a/apps/server/src/services/bot/wake/__tests__/signal.test.ts+++ b/apps/server/src/services/bot/wake/__tests__/signal.test.ts@@ -75,6 +75,16 @@ describe('buildWakeSignal', () => {).toBeUndefined();});+ it('reads who a Discord reply points at, and nothing elsewhere', () => {+ const raw = { referenced_message: { author: { id: 'teammate' } }, type: 19 };++ expect(build({ raw }).replyToAuthorId).toBe('teammate');+ expect(build({ raw: { referenced_message: null, type: 0 } }).replyToAuthorId).toBeUndefined();+ expect(+ build({ raw }, { platform: 'slack', platformThreadId: 'slack:c:1' }).replyToAuthorId,+ ).toBeUndefined();+ });+it('carries channel keys, attachments and the clock', () => {const signal = build({ attachments: [{}] });diff --git a/apps/server/src/services/bot/wake/signal.ts b/apps/server/src/services/bot/wake/signal.tsindex bbbe003e106..7450a3ee965 100644--- a/apps/server/src/services/bot/wake/signal.ts+++ b/apps/server/src/services/bot/wake/signal.ts@@ -49,6 +49,15 @@ const isSystemMessage = (platform: string, raw: unknown): boolean => {return type !== undefined && !DISCORD_USER_MESSAGE_TYPES.has(type);};+/** Who wrote the message a Discord reply points at; the gateway inlines it as `referenced_message`. */+const readReplyToAuthorId = (platform: string, raw: unknown): string | undefined => {+ if (platform !== 'discord' || typeof raw !== 'object' || raw === null) return undefined;+ const id = (raw as { referenced_message?: { author?: { id?: unknown } } | null })+ .referenced_message?.author?.id;++ return typeof id === 'string' && id ? id : undefined;+};+/*** Normalizes a chat message into the fact the wake policies judge.*@@ -86,6 +95,7 @@ export const buildWakeSignal = ({message: text,platform,platformThreadId,+ replyToAuthorId: readReplyToAuthorId(platform, message.raw),timestamp,};};