🤯 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(agent): introduce an agent by its name and title, not the title alone (#21688)
Arvin Xu3573ffaba8c2
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex d4546162a3e..c7d371bb7c1 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -127,6 +127,7 @@ export const buildServerCallLlmContext = async ({agent: {chatConfig: agentConfig.chatConfig,description: agentConfig.description,+ name: agentConfig.name,slug: agentConfig.slug,title: agentConfig.title,},diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex b9fb42ebf52..e6b20f870a7 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -306,6 +306,7 @@ export const createServerContextFactProviders = ({(await new AgentModel(db, userId, ctx.workspaceId).queryAgents({ limit })).map((a) => ({description: a.description,id: a.id,+ name: a.name,title: a.title,})),diff --git a/apps/server/src/services/aiAgent/helpers/__tests__/groupContext.test.ts b/apps/server/src/services/aiAgent/helpers/__tests__/groupContext.test.tsnew file mode 100644index 00000000000..f1dbb10aea6--- /dev/null+++ b/apps/server/src/services/aiAgent/helpers/__tests__/groupContext.test.ts@@ -0,0 +1,40 @@+// @vitest-environment node+import { buildBotConversationGroupContext, buildGroupAgentContext } from '../groupContext';++describe('buildBotConversationGroupContext', () => {+ it('introduces the bot by its name with its title, since it replaces <agent_identity>', () => {+ const group = buildBotConversationGroupContext('agt_1', {+ description: 'Arvin 的分身',+ name: 'Nasa',+ title: 'Shadow Arvin',+ });++ expect(group.currentAgentName).toBe('Nasa (Shadow Arvin)');+ expect(group.members).toEqual([+ { id: 'agt_1', name: 'Nasa (Shadow Arvin)', role: 'participant' },+ ]);+ expect(group.systemPrompt).toBe('Arvin 的分身');+ });++ it('keeps the title for an agent without a name, and a placeholder for neither', () => {+ expect(+ buildBotConversationGroupContext('agt_1', { title: 'Shadow Arvin' }).currentAgentName,+ ).toBe('Shadow Arvin');+ expect(buildBotConversationGroupContext('agt_1', {}).currentAgentName).toBe('Current Agent');+ });+});++describe('buildGroupAgentContext', () => {+ it('names every member by name and role, and marks the responding one', () => {+ const group = buildGroupAgentContext('agt_2', { title: 'Team' }, [+ { agentId: 'agt_1', name: null, role: 'supervisor', title: 'Lead' },+ { agentId: 'agt_2', name: 'Nasa', role: 'participant', title: 'Shadow Arvin' },+ ]);++ expect(group?.members).toEqual([+ { id: 'agt_1', name: 'Lead', role: 'supervisor' },+ { id: 'agt_2', name: 'Nasa (Shadow Arvin)', role: 'participant' },+ ]);+ expect(group?.currentAgentName).toBe('Nasa (Shadow Arvin)');+ });+});diff --git a/apps/server/src/services/aiAgent/helpers/groupContext.ts b/apps/server/src/services/aiAgent/helpers/groupContext.tsindex 0760a597157..d258c1521e1 100644--- a/apps/server/src/services/aiAgent/helpers/groupContext.ts+++ b/apps/server/src/services/aiAgent/helpers/groupContext.ts@@ -1,4 +1,5 @@import type { AgentGroupConfig } from '@lobechat/context-engine';+import { agentIdentityLabel } from '@lobechat/types';/*** Format error for storage in thread metadata@@ -35,7 +36,12 @@ export function formatErrorForMetadata(error: unknown): Record<string, any> | unexport const buildGroupAgentContext = (currentAgentId: string,group: { content?: string | null; title?: string | null } | undefined,- roster: Array<{ agentId: string; role: string | null; title: string | null }>,+ roster: Array<{+ agentId: string;+ name?: string | null;+ role: string | null;+ title: string | null;+ }>,): AgentGroupConfig | undefined => {if (roster.length === 0) return undefined;@@ -46,7 +52,8 @@ export const buildGroupAgentContext = (for (const member of roster) {const role = member.role === 'supervisor' ? 'supervisor' : 'participant';- const name = member.title?.trim() || 'Untitled Agent';+ // "Nasa (Shadow Arvin)": the name people call it by, and its role.+ const name = agentIdentityLabel(member, 'Untitled Agent');agentMap[member.agentId] = { name, role };members.push({ id: member.agentId, name, role });@@ -74,11 +81,16 @@ export const buildGroupAgentContext = (*/export const buildBotConversationGroupContext = (currentAgentId: string,- agentConfig: { description?: unknown; title?: unknown } | undefined,+ agentConfig: { description?: unknown; name?: unknown; title?: unknown } | undefined,): AgentGroupConfig => {- const title = agentConfig?.title;+ const text = (value: unknown) => (typeof value === 'string' ? value : undefined);const description = agentConfig?.description;- const name = typeof title === 'string' && title.trim() ? title.trim() : 'Current Agent';+ // This block replaces `<agent_identity>` (suppressed whenever a group context is set), so it must+ // carry the agent's name, not only its title: people call the bot by its name.+ const name = agentIdentityLabel(+ { name: text(agentConfig?.name), title: text(agentConfig?.title) },+ 'Current Agent',+ );return {agentMap: { [currentAgentId]: { name, role: 'participant' } },diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.tsindex 611e030a16b..7ed92244cdc 100644--- a/packages/builtin-skills/src/lobehub/content.ts+++ b/packages/builtin-skills/src/lobehub/content.ts@@ -9,6 +9,7 @@ Treat them as common knowledge — you never need to call any tool to discover t| Field | Value ||-------|-------|| Agent ID | \`{{agent_id}}\` |+| Agent Name | {{agent_name}} || Agent Title | {{agent_title}} || Agent Description | {{agent_description}} || Topic ID | \`{{topic_id}}\` |diff --git a/packages/context-engine/src/providers/AgentManagementContextInjector.ts b/packages/context-engine/src/providers/AgentManagementContextInjector.tsindex a71f59bd04c..cc172793f63 100644--- a/packages/context-engine/src/providers/AgentManagementContextInjector.ts+++ b/packages/context-engine/src/providers/AgentManagementContextInjector.ts@@ -1,5 +1,5 @@import { escapeXml } from '@lobechat/prompts';-import type { RuntimeMentionedAgent } from '@lobechat/types';+import { agentIdentityLabel, type RuntimeMentionedAgent } from '@lobechat/types';import debug from 'debug';import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';@@ -52,7 +52,9 @@ export interface AvailableAgentInfo {description?: string;/** Agent ID */id: string;- /** Agent display name */+ /** Personal name the agent is addressed by; wins over `title` as its label */+ name?: string;+ /** The role the agent plays */title: string;}@@ -97,7 +99,7 @@ export interface AgentManagementContext {* Exposed so the model can use Agent Management tools (updateAgent, getAgentDetail,* installPlugin, etc.) to manage itself when the user asks to modify the current agent.*/- currentAgent?: { id: string; title?: string };+ currentAgent?: { id: string; name?: string; title?: string };/** Agents @mentioned by the user — supervisor should delegate to these via callAgent */mentionedAgents?: RuntimeMentionedAgent[];}@@ -119,10 +121,11 @@ const defaultFormatContext = (context: AgentManagementContext): string => {// Add current agent identity so the model can self-manageif (context.currentAgent) {- const titleAttr = context.currentAgent.title- ? ` title="${escapeXml(context.currentAgent.title)}"`- : '';- parts.push(`<current_agent id="${escapeXml(context.currentAgent.id)}"${titleAttr} />`);+ // Both fields: `name` is what people call it by, `title` its role. Either may be blank.+ const { id, name, title } = context.currentAgent;+ const nameAttr = name?.trim() ? ` name="${escapeXml(name.trim())}"` : '';+ const titleAttr = title?.trim() ? ` title="${escapeXml(title.trim())}"` : '';+ parts.push(`<current_agent id="${escapeXml(id)}"${nameAttr}${titleAttr} />`);}// Add available models section@@ -155,7 +158,9 @@ const defaultFormatContext = (context: AgentManagementContext): string => {const agentsXml = context.availableAgents.map((agent) => {const desc = agent.description ? ` - ${escapeXml(agent.description)}` : '';- return ` <agent id="${escapeXml(agent.id)}">${escapeXml(agent.title)}${desc}</agent>`;+ // "Nasa (Shadow Arvin)": the name a user would ask for, and the role.+ const label = agentIdentityLabel(agent, agent.title);+ return ` <agent id="${escapeXml(agent.id)}">${escapeXml(label)}${desc}</agent>`;}).join('\n');const hasMoreNote = context.availableAgentsHasMorediff --git a/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.tsindex d5e4f8277ad..f0f2d8d4ae6 100644--- a/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts@@ -66,6 +66,50 @@ describe('AgentManagementContextInjector', () => {expect(result.messages[2].content).toBe('create an agent');expect(result.metadata.agentManagementContextInjected).toBe(true);});++ it('names the current agent and the available ones by name and title', async () => {+ const injector = new AgentManagementContextInjector({+ enabled: true,+ context: {+ availableAgents: [+ { id: 'agt_2', name: 'Tiko', title: 'Design reviewer' },+ { description: 'drafts docs', id: 'agt_3', title: 'Writer' },+ ],+ currentAgent: { id: 'agt_1', name: 'Nasa', title: 'Shadow Arvin' },+ },+ });++ const result = await injector.process(+ createContext([+ { role: 'system', content: 'sys' },+ { role: 'user', content: 'who are you' },+ ]),+ );+ const content = result.messages[1].content as string;++ expect(content).toContain('<current_agent id="agt_1" name="Nasa" title="Shadow Arvin" />');+ expect(content).toContain('<agent id="agt_2">Tiko (Design reviewer)</agent>');+ // An agent without a name keeps its title, as before.+ expect(content).toContain('<agent id="agt_3">Writer - drafts docs</agent>');+ });++ it('leaves out a blank name or title instead of an empty attribute', async () => {+ const injector = new AgentManagementContextInjector({+ enabled: true,+ context: { currentAgent: { id: 'agt_1', name: ' ', title: 'Shadow Arvin' } },+ });++ const result = await injector.process(+ createContext([+ { role: 'system', content: 'sys' },+ { role: 'user', content: 'hi' },+ ]),+ );++ expect(result.messages[1].content).toContain(+ '<current_agent id="agt_1" title="Shadow Arvin" />',+ );+ });});describe('mentionedAgents delegation', () => {diff --git a/packages/database/src/models/chatGroup/index.ts b/packages/database/src/models/chatGroup/index.tsindex 14de5390ab7..968e1d304af 100644--- a/packages/database/src/models/chatGroup/index.ts+++ b/packages/database/src/models/chatGroup/index.ts@@ -545,6 +545,7 @@ export class ChatGroupModel {Array<{agentId: string;description: string | null;+ name: string | null;role: string | null;title: string | null;}>diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.tsindex f38c81ce9e0..a2a3378c0ee 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts@@ -19,6 +19,18 @@ const message = (content: string) =>({ content, createdAt: 0, id: 'm', role: 'user', updatedAt: 0 }) as never;describe('gatherContextFacts', () => {+ it('tells the agent its name, not only its title', async () => {+ const named = await gatherContextFacts(+ request({ agent: { description: '', name: 'Nasa', title: 'Shadow Arvin' } }),+ {},+ );+ const unnamed = await gatherContextFacts(request(), {});++ expect(named.variables).toMatchObject({ agent_name: 'Nasa', agent_title: 'Shadow Arvin' });+ // Without a name the label is the title, the same as the product shows.+ expect(unnamed.variables).toMatchObject({ agent_name: 'Helper', agent_title: 'Helper' });+ });+it('yields no facts and never throws when the host provides nothing', async () => {const facts = await gatherContextFacts(request(), {});@@ -267,6 +279,19 @@ describe('gatherContextFacts', () => {expect(ctx.availablePlugins).toBeUndefined();});+ it('carries each agent’s name beside its title, for itself and the others', async () => {+ const facts = await gatherContextFacts(+ request({ agent: { name: 'Nasa', title: 'Shadow Arvin' } }),+ { listRecentAgents: async () => [{ id: 'agt_2', name: 'Tiko', title: 'Reviewer' }] },+ );++ const ctx = facts.step.agentManagementContext!;+ expect(ctx.currentAgent).toStrictEqual({ id: 'agt_1', name: 'Nasa', title: 'Shadow Arvin' });+ expect(ctx.availableAgents).toStrictEqual([+ { description: undefined, id: 'agt_2', name: 'Tiko', title: 'Reviewer' },+ ]);+ });+it('adds providers and the plugin catalog only when the tool is enabled', async () => {const facts = await gatherContextFacts(request({diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex c9d2f2fe083..546ec4528a8 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -29,6 +29,7 @@ import {type TopicReferenceItem,type WorkspaceContext,} from '@lobechat/context-engine';+import { agentDisplayName } from '@lobechat/types';import debug from 'debug';import pMap from 'p-map';@@ -396,7 +397,11 @@ const gatherAgentManagementContext = async (// Self-management (updateAgent / installPlugin on itself) stays available// inside a sub-agent, so its own id is kept; only the delegation list goes.const currentAgent = request.agentId- ? { id: request.agentId, title: request.agent.title ?? undefined }+ ? {+ id: request.agentId,+ name: request.agent.name ?? undefined,+ title: request.agent.title ?? undefined,+ }: undefined;if (canDelegate) {@@ -410,6 +415,7 @@ const gatherAgentManagementContext = async (availableAgents: others.slice(0, AVAILABLE_AGENTS_LIMIT).map((a) => ({description: a.description ?? undefined,id: a.id,+ name: a.name ?? undefined,title: a.title ?? 'Untitled',})),availableAgentsHasMore: others.length > AVAILABLE_AGENTS_LIMIT,@@ -523,6 +529,7 @@ export const gatherContextFacts = async (CREDS_LIST: credentials ? generateCredsList(credentials) : '',agent_description: request.agent.description ?? '',agent_id: request.agentId ?? '',+ agent_name: agentDisplayName(request.agent) ?? '',agent_title: request.agent.title ?? '',// A credential is reachable whenever the dedicated sandbox tool is// exposed for 'auto' (independent of device routing) or no device isdiff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsindex a82e99d4852..e10d068a9d5 100644--- a/packages/mecha/src/contextEngineering/facts/types.ts+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -81,6 +81,8 @@ export interface ContextFactRequest {agent: {chatConfig?: LobeAgentChatConfig | null;description?: string | null;+ /** Personal name the agent is addressed by; wins over `title` as its label. */+ name?: string | null;slug?: string | null;title?: string | null;};@@ -153,7 +155,10 @@ export interface ContextFactProviders {/** Recently used agents, most recent first. */listRecentAgents?: (limit: number,- ) => Promise<{ description?: string | null; id: string; title?: string | null }[] | undefined>;+ ) => Promise<+ | { description?: string | null; id: string; name?: string | null; title?: string | null }[]+ | undefined+ >;/** Files synced into the topic's sandbox upload dir. */listSandboxFiles?: (topicId: string) => Promise<{ name: string; size?: number }[] | undefined>;/** Messages of a referenced topic, oldest first. */diff --git a/packages/types/src/agent/displayName.test.ts b/packages/types/src/agent/displayName.test.tsindex 9e908c628a9..061a3852fde 100644--- a/packages/types/src/agent/displayName.test.ts+++ b/packages/types/src/agent/displayName.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { agentDisplayName, agentRenameField, agentSecondaryDisplayName } from './displayName';+import {+ agentDisplayName,+ agentIdentityLabel,+ agentRenameField,+ agentSecondaryDisplayName,+} from './displayName';describe('agentDisplayName', () => {it('prefers the personal name over the role', () => {@@ -91,3 +96,26 @@ describe('agentRenameField', () => {expect(agentRenameField({ name: ' ', title: 'Health Assistant' })).toBe('title');});});++describe('agentIdentityLabel', () => {+ it('introduces a named agent by its name, with its role behind it', () => {+ expect(agentIdentityLabel({ name: 'Nasa', title: 'Shadow Arvin' })).toBe('Nasa (Shadow Arvin)');+ });++ it('uses the title alone when there is no name', () => {+ expect(agentIdentityLabel({ name: null, title: 'Shadow Arvin' })).toBe('Shadow Arvin');+ expect(agentIdentityLabel({ name: ' ', title: 'Shadow Arvin' })).toBe('Shadow Arvin');+ });++ it('does not repeat a role the name already spells out', () => {+ expect(agentIdentityLabel({ name: 'Max 的 Kimi Code', title: 'Kimi Code' })).toBe(+ 'Max 的 Kimi Code',+ );+ expect(agentIdentityLabel({ name: 'Nasa', title: 'Nasa' })).toBe('Nasa');+ });++ it('falls back when the agent has neither', () => {+ expect(agentIdentityLabel({}, 'Current Agent')).toBe('Current Agent');+ expect(agentIdentityLabel(null)).toBeUndefined();+ });+});diff --git a/packages/types/src/agent/displayName.ts b/packages/types/src/agent/displayName.tsindex 339cd400cbc..72bd4e5ebbc 100644--- a/packages/types/src/agent/displayName.ts+++ b/packages/types/src/agent/displayName.ts@@ -91,3 +91,28 @@ export const agentSecondaryDisplayName = (return role;};++/**+ * The label an agent is introduced by in a prompt: its name, with the role behind it when there is+ * one worth adding — "Nasa (Shadow Arvin)". A prompt that only carries the title makes a named+ * agent answer "I'm not Nasa, I'm Shadow Arvin" when people call it by name.+ *+ * Built from {@link agentDisplayName} and {@link agentSecondaryDisplayName}, so the agent names+ * itself the way the product labels it.+ */+export function agentIdentityLabel(agent: AgentNameFields | null | undefined): string | undefined;+export function agentIdentityLabel(+ agent: AgentNameFields | null | undefined,+ fallback: string,+): string;+export function agentIdentityLabel(+ agent: AgentNameFields | null | undefined,+ fallback?: string,+): string | undefined {+ const primary = agentDisplayName(agent);+ if (!primary) return fallback;++ const role = agentSecondaryDisplayName(agent);++ return role ? `${primary} (${role})` : primary;+}diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex e1ffb569f11..4a4fa5cea88 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -14,6 +14,7 @@ import { mentionsTopic } from '@lobechat/context-engine';import { type ContextSnapshot, gatherContextFacts, runContextEngineering } from '@lobechat/mecha';import { historySummaryPrompt } from '@lobechat/prompts';import {+ agentIdentityLabel,type OpenAIChatMessage,type RuntimeAdditionalContextFragment,type RuntimeInitialContext,@@ -161,7 +162,8 @@ export const contextEngineering = async ({for (const agent of groupDetail.agents) {const role = agent.isSupervisor ? 'supervisor' : 'participant';- const name = agent.title || 'Untitled Agent';+ // "Nasa (Shadow Arvin)": the name people call it by, and its role.+ const name = agentIdentityLabel(agent, 'Untitled Agent');agentMap[agent.id] = { name, role };members.push({ id: agent.id, name, role });@@ -267,6 +269,7 @@ export const contextEngineering = async ({chatConfig: respondingChatConfig,description: agentMeta?.description,slug: agentItem?.slug,+ name: agentMeta?.name,title: agentMeta?.title,},agentId,