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.

✨ feat(channel): acknowledge a request that only names the Agent, and commit to answer it (#22926)

Lobehub Coder19f5d680cdf5
diff --git a/apps/server/src/services/bot/wake/__tests__/opener.test.ts b/apps/server/src/services/bot/wake/__tests__/opener.test.ts
index 958bdd96dc4..a5cf6b9c8f3 100644
--- a/apps/server/src/services/bot/wake/__tests__/opener.test.ts
+++ b/apps/server/src/services/bot/wake/__tests__/opener.test.ts
@@ -33,7 +33,7 @@ describe('createReplyOpener', () => {
const [payload, options] = mockGenerateObject.mock.calls[0];
expect(options.tracing).toMatchObject({
agentId: 'agt',
- promptVersion: 'v4',
+ promptVersion: 'v5',
scenario: 'bot_reply_opener',
schemaName: 'bot_reply_opener',
});
diff --git a/apps/server/src/services/channel/replyOpening.test.ts b/apps/server/src/services/channel/replyOpening.test.ts
index 533f14de498..56791df2d4f 100644
--- a/apps/server/src/services/channel/replyOpening.test.ts
+++ b/apps/server/src/services/channel/replyOpening.test.ts
@@ -16,6 +16,7 @@ vi.mock('@/database/repositories/channel', () => ({
vi.mock('@/server/services/bot/wake/opener', () => ({ createReplyOpener: vi.fn() }));
const candidate = {
+ addressed: true,
agent: { id: 'agt-coder', name: 'Coder', title: 'Engineer' },
canOpenThread: true,
coAddressed: [],
@@ -90,6 +91,18 @@ describe('openChannelReply', () => {
);
});
+ it('tells the opener when the Agent was woken without being addressed', async () => {
+ executions.openingCandidate.mockResolvedValue({ ...candidate, addressed: false });
+ const opener = vi.fn().mockResolvedValue({ placement: 'channel' });
+
+ await openChannelReply({} as never, 'channel', 'job', { createOpener: () => opener });
+
+ expect(opener).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'Why?', notAddressed: true }),
+ expect.any(AbortSignal),
+ );
+ });
+
it('calls an Agent without a name by its title', async () => {
executions.openingCandidate.mockResolvedValue({
...candidate,
diff --git a/apps/server/src/services/channel/replyOpening.ts b/apps/server/src/services/channel/replyOpening.ts
index 0f54334a6e8..3ec2498e550 100644
--- a/apps/server/src/services/channel/replyOpening.ts
+++ b/apps/server/src/services/channel/replyOpening.ts
@@ -53,6 +53,8 @@ const decide = async (
title: agent.title ?? undefined,
})),
message: candidate.request.content,
+ // Woken by its own rules, not asked: it acknowledges only a clear request for work.
+ ...(!candidate.addressed && { notAddressed: true }),
recentMessages: candidate.recent.map((message) => describe(message, candidate.agent.id)),
},
controller.signal,
@@ -69,7 +71,8 @@ const decide = async (
/**
* Opens an Agent member's reply before its run, as an IM bot does: a one-sentence
* acknowledgement when the work takes a while, and a Thread under the request when the answer
- * runs long. Only an owed answer opens; a wake that may stay silent never does. Runs once per
+ * runs long. An owed answer opens; so does a follow-up leading the message, whose acknowledgement
+ * commits it to answer. A follow-up deferred behind another member never does. Runs once per
* job, before the claim, so the run's topic, branch and worktree follow the Thread.
*
* Never throws. A failed or slow opener is recorded as an opening that changed nothing, and the
diff --git a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts b/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts
index 4f0e1151d37..f19a9e2bec6 100644
--- a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts
@@ -43,6 +43,7 @@ describe('Channel reply opening', () => {
const candidate = await execution.openingCandidate(channel.id, job.id);
expect(candidate).toMatchObject({
+ addressed: true,
agent: { id: agent.agentId, name: 'Coder' },
canOpenThread: true,
recent: [],
@@ -421,14 +422,71 @@ describe('Channel reply opening', () => {
expect(await execution.claim(channel.id, job.id, lease)).not.toBeNull();
});
- it('never opens a wake that may stay silent', async () => {
- const { channel, job } = await mentionAgent();
- await db
+ const asFollowup = async (jobId: string, wake: Record<string, unknown>) =>
+ db
.update(channelJobs)
- .set({ wake: { kind: 'followup', reason: 'followup-window' } as never })
- .where(eq(channelJobs.id, job.id));
+ .set({ wake: { kind: 'followup', ...wake } as never })
+ .where(eq(channelJobs.id, jobId));
- expect(await execution.openingCandidate(channel.id, job.id)).toBeUndefined();
+ it('opens a follow-up that leads the message, telling the opener it was not addressed', async () => {
+ const { channel, job } = await mentionAgent();
+ await asFollowup(job.id, { named: true, reason: 'named-in-text' });
+
+ expect(await execution.openingCandidate(channel.id, job.id)).toMatchObject({
+ addressed: false,
+ });
+ });
+
+ it('commits a follow-up that acknowledges to answer', async () => {
+ const { channel, job } = await mentionAgent();
+ await asFollowup(job.id, { named: true, reason: 'named-in-text' });
+
+ await execution.open(channel.id, job.id, {
+ ack: 'Got it, I will read the doc first.',
+ threadTitle: 'Doc review',
+ });
+
+ // The acknowledgement said it will answer: no longer a wake that may stay silent.
+ const opened = await jobById(db, job.id);
+ expect(opened.wake).toMatchObject({ kind: 'mention', named: true, reason: 'named-in-text' });
+ expect(opened.threadId).not.toBeNull();
+ expect(await execution.openingReply(channel.id, job.id)).toBe(
+ 'Got it, I will read the doc first.',
+ );
+ await execution.claim(channel.id, job.id, lease);
+ expect(await execution.silence(channel.id, job.id, 'NO_REPLY')).toBe(false);
+ });
+
+ it('keeps a follow-up that does not acknowledge optional, and in place', async () => {
+ const { channel, job } = await mentionAgent();
+ await asFollowup(job.id, { reason: 'followup-window' });
+
+ expect(await execution.open(channel.id, job.id, { threadTitle: 'Doc review' })).toBe(true);
+
+ const opened = await jobById(db, job.id);
+ expect(opened.wake).toMatchObject({ kind: 'followup' });
+ expect(opened.threadId).toBeNull();
+ expect(
+ await db.select().from(channelThreads).where(eq(channelThreads.channelId, channel.id)),
+ ).toEqual([]);
+ await execution.claim(channel.id, job.id, lease);
+ expect(await execution.silence(channel.id, job.id, 'NO_REPLY')).toBe(true);
+ });
+
+ it('never opens a follow-up deferred behind another member’s answer', async () => {
+ const { channel, coder, reviewerJob } = await mentionTwoAgents();
+ await asFollowup(reviewerJob.id, { afterMemberId: coder.id, reason: 'routing-deferred' });
+
+ expect(await execution.openingCandidate(channel.id, reviewerJob.id)).toBeUndefined();
+ });
+
+ it('does not count a follow-up that leads the message as asked together with the others', async () => {
+ const { channel, coderJob, reviewerJob } = await mentionTwoAgents();
+ await asFollowup(reviewerJob.id, { reason: 'routing-uncertain' });
+
+ expect(await execution.openingCandidate(channel.id, coderJob.id)).toMatchObject({
+ coAddressed: [],
+ });
});
it('records an opening that changed nothing, so the opener is not asked again', async () => {
diff --git a/packages/database/src/repositories/channel/opening.ts b/packages/database/src/repositories/channel/opening.ts
index 620c9915bdb..945f35b9d0b 100644
--- a/packages/database/src/repositories/channel/opening.ts
+++ b/packages/database/src/repositories/channel/opening.ts
@@ -40,6 +40,11 @@ export interface ChannelCoAddressedAgent {
/** A queued job that may still open its reply, with what the opener needs to decide. */
export interface ChannelOpeningCandidate {
+ /**
+ * Whether someone addressed the Agent (owed answer). False for a follow-up its own rules woke:
+ * the opener then acknowledges only a clear request for work.
+ */
+ addressed: boolean;
agent: { id: string; name: string | null; title: string | null };
/**
* Whether the reply may move into a new Thread: only a request on the main timeline can, in a
@@ -72,10 +77,17 @@ const isOpened = async (db: LobeChatDatabase | Transaction, jobId: string) => {
};
/**
- * Whether a job opens its reply before the run: an owed answer only. A follow-up nobody asked
- * for, or one deferred behind another member's answer, may stay silent and never acknowledges.
+ * Whether a job opens its reply before the run. An owed answer always does. So does a follow-up
+ * that leads the message (its name in the text, a follow-up window, its duties): its opener
+ * acknowledges only a clear request, and acknowledging commits it to answer (see
+ * {@link applyOpening}). A follow-up deferred behind another member's answer never opens: it
+ * reads that answer first, and most often stays silent.
*/
export const opensReply = (job: { wake: { afterMemberId?: string; kind: string } | null }) =>
+ !job.wake?.afterMemberId;
+
+/** Whether someone addressed the job's Agent, so it owes an answer and may not stay silent. */
+const owesAnswer = (job: { wake: { afterMemberId?: string; kind: string } | null }) =>
!job.wake || (job.wake.kind !== 'followup' && !job.wake.afterMemberId);
/**
@@ -101,7 +113,7 @@ const coAddressedJobs = async (
),
);
return rows
- .filter(opensReply)
+ .filter(owesAnswer)
.map(({ name, title }): ChannelCoAddressedAgent => ({ name, title }));
};
@@ -189,6 +201,7 @@ export const findOpeningCandidate = async (
if (!requestMessage) return;
return {
+ addressed: owesAnswer(job),
agent: { id: row.agentId, name: row.agentName, title: row.agentTitle },
canOpenThread: !job.threadId,
coAddressed: await coAddressedJobs(db, job),
@@ -230,8 +243,18 @@ export const applyOpening = async (
if (!member?.agentId) return false;
const ack = decision.ack?.trim();
+ // A follow-up that acknowledges has said it will answer: it owes the answer now, and may no
+ // longer end in silence. One that does not stays optional, where it was asked.
+ const optional = job.wake?.kind === 'followup';
+ if (optional && ack)
+ await tx
+ .update(channelJobs)
+ .set({ wake: { ...job.wake!, kind: 'mention' } })
+ .where(eq(channelJobs.id, job.id));
const title = decision.threadTitle?.trim().slice(0, THREAD_TITLE_LENGTH) ?? '';
- const layout = await planOpening(tx, channelId, job, { ack, title });
+ // An optional reply never opens or joins a Thread on its own: it may yet stay silent in it.
+ const layout: OpeningLayout =
+ optional && !ack ? 'inline' : await planOpening(tx, channelId, job, { ack, title });
let threadId = job.threadId;
if (layout === 'underRequest') threadId = await openReplyThread(tx, job, job.messageId, title);
@@ -255,6 +278,7 @@ export const applyOpening = async (
await audit(tx, channelId, REPLY_OPENED_EVENT, job.id, {
...(posted && { messageId: posted.id }),
+ ...(optional && posted && { committed: true }),
...(threadId !== job.threadId && { threadId }),
});
diff --git a/packages/prompts/src/chains/botReplyOpener.ts b/packages/prompts/src/chains/botReplyOpener.ts
index 2c75374a736..6b006a3a4bc 100644
--- a/packages/prompts/src/chains/botReplyOpener.ts
+++ b/packages/prompts/src/chains/botReplyOpener.ts
@@ -1,6 +1,6 @@
import type { OpenAIChatMessage } from '@lobechat/types';
-export const BOT_REPLY_OPENER_PROMPT_VERSION = 'v4';
+export const BOT_REPLY_OPENER_PROMPT_VERSION = 'v5';
export const BOT_REPLY_PLACEMENTS = ['channel', 'thread'] as const;
export type BotReplyPlacement = (typeof BOT_REPLY_PLACEMENTS)[number];
@@ -60,6 +60,14 @@ const coAddressedSection = (agents: NonNullable<BotReplyOpenerInput['coAddressed
return `The same message also asked ${names.join(', ')} to answer. You answer in parallel, in one shared thread where each of you sees the others. Do not plan to cover the whole request alone: your acknowledgement names only the slice your role is best placed for (for a data role, say, the metrics or attribution; for an engineering role, the tracking or the systems), so the person sees the work divided rather than the same opening twice.`;
};
+/**
+ * When nobody addressed the assistant, the acknowledgement is also its commitment to answer, so it
+ * is posted only for a message that clearly asks it to work.
+ */
+const NOT_ADDRESSED = `You were not @-mentioned or replied to. You were woken because the message may concern you: it says your name, follows up on something you said, or falls within your duties. People also talk about you without asking you anything.
+- Set "acknowledge" true only when the message clearly asks you to do something that takes real work. Acknowledging commits you to answer.
+- When it only talks about you, is meant for someone else, or you are unsure: "acknowledge" false, "ack" empty, "placement" "channel", "title" empty. You decide later whether to speak at all.`;
+
export interface BotReplyOpenerInput {
/**
* Where the acknowledgement lands: `before-thread` posts it in the conversation the person is
@@ -77,6 +85,11 @@ export interface BotReplyOpenerInput {
/** Other assistants the same message asked to answer, in parallel with this one. */
coAddressed?: { name?: string; title?: string }[];
message: string;
+ /**
+ * The assistant was woken without being addressed (its name in the text, a follow-up, its
+ * duties): acknowledge only a clear request for work. Absent: the message was addressed to it.
+ */
+ notAddressed?: boolean;
/** Short transcript of the messages just before this one, oldest first. */
recentMessages?: string[];
}
@@ -101,10 +114,13 @@ const buildState = (input: BotReplyOpenerInput): string => {
if (input.ackPlacement === 'before-thread') sections.push(ACK_BEFORE_THREAD);
const coAddressed = input.coAddressed?.length ? coAddressedSection(input.coAddressed) : undefined;
if (coAddressed) sections.push(coAddressed);
+ if (input.notAddressed) sections.push(NOT_ADDRESSED);
if (input.recentMessages?.length) {
sections.push(`Earlier messages (oldest first):\n${input.recentMessages.join('\n')}`);
}
- sections.push(`Message to you:\n"""\n${input.message.trim()}\n"""`);
+ sections.push(
+ `${input.notAddressed ? 'Message' : 'Message to you'}:\n"""\n${input.message.trim()}\n"""`,
+ );
return sections.join('\n\n');
};
diff --git a/packages/prompts/src/chains/generationContracts.test.ts b/packages/prompts/src/chains/generationContracts.test.ts
index 9a983275eb0..44efab221fb 100644
--- a/packages/prompts/src/chains/generationContracts.test.ts
+++ b/packages/prompts/src/chains/generationContracts.test.ts
@@ -91,7 +91,7 @@ describe('application generation chains', () => {
recentMessages: ['alice: deploy failed again'],
});
- expect(BOT_REPLY_OPENER_PROMPT_VERSION).toBe('v4');
+ expect(BOT_REPLY_OPENER_PROMPT_VERSION).toBe('v5');
expect(BOT_REPLY_OPENER_JSON_SCHEMA.name).toBe('bot_reply_opener');
expect(BOT_REPLY_OPENER_JSON_SCHEMA.schema.required).toEqual([
'acknowledge',
@@ -121,6 +121,21 @@ describe('application generation chains', () => {
expect(messages[1].content).not.toContain('may move the conversation');
});
+ it('tells an opener woken without being addressed to acknowledge only a clear request', () => {
+ const woken = chainBotReplyOpener({
+ canOpenThread: true,
+ message: 'Cook 昨天那个 PR 合了吗',
+ notAddressed: true,
+ });
+ expect(woken.messages[1].content).toContain('You were not @-mentioned or replied to');
+ expect(woken.messages[1].content).toContain('Acknowledging commits you to answer');
+ expect(woken.messages[1].content).not.toContain('Message to you');
+
+ const asked = chainBotReplyOpener({ canOpenThread: true, message: 'Cook 帮我看下这个 PR' });
+ expect(asked.messages[1].content).not.toContain('You were not @-mentioned');
+ expect(asked.messages[1].content).toContain('Message to you');
+ });
+
it('tells a Channel opener to say where it starts, not to announce the thread or restate the question', () => {
const channel = chainBotReplyOpener({
ackPlacement: 'before-thread',