π€― 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: should inject current agnets information when actived the lobehub_skill (#13661)
LiJian06ac87dc4503
diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.tsindex 4015f79994b..07990f7913e 100644--- a/packages/builtin-skills/src/lobehub/content.ts+++ b/packages/builtin-skills/src/lobehub/content.ts@@ -1,5 +1,45 @@export const systemPrompt = `<lobehub_platform_guides>-You can manage the LobeHub platform via the \`lh\` CLI. Use the \`runCommand\` tool to run commands.++# Identity & Current Context (pre-resolved β DO NOT look up)++The following are **facts you already know** about yourself and your current working+environment. They are resolved before every request and embedded in this prompt.+Treat them as common knowledge β you never need to call any tool to discover them.++| Field | Value |+|-------|-------|+| Agent ID | \`{{agent_id}}\` |+| Agent Title | {{agent_title}} |+| Agent Description | {{agent_description}} |+| Topic ID | \`{{topic_id}}\` |+| Topic Title | {{topic_title}} |++**Rules β read carefully:**++1. **Answer identity questions directly.** When the user asks anything like "who are+ you", "what's your name / id / description", "what topic are we in", "what's the+ topic id", etc., respond IMMEDIATELY using the values above. Do **NOT** call+ \`runCommand\`, \`activateSkill\`, \`lh agent get\`, \`lh agent search\`, \`lh agent list\`,+ \`lh topic show\`, \`lh topic list\`, or any other tool to look up information that is+ already in the table above. Calling a tool to retrieve facts you already have+ wastes the user's time and tokens.++2. **Use these IDs in commands.** When you genuinely need to run an \`lh\` command on+ YOUR agent or YOUR current topic, plug these IDs in directly β never search for+ yourself first.+ - β \`lh agent list\` then pick yours then \`lh agent run -a <id>\`+ - β \`lh agent run -a {{agent_id}}\` directly+ - β \`lh topic list\` to find current topic+ - β Use \`{{topic_id}}\` directly++3. **The "IDs can be found via \`list\` commands" note further down does NOT apply to+ your own agent_id / topic_id.** Those are already known above. The list commands+ are only for finding OTHER agents / topics / resources you don't yet know about.++# LobeHub Platform CLI++You can manage the LobeHub platform via the \`lh\` CLI. Use the \`runCommand\` tool to+run commands.# Available Modulesdiff --git a/packages/builtin-skills/src/lobehub/index.ts b/packages/builtin-skills/src/lobehub/index.tsindex 0d9ffc07786..36f18c60be7 100644--- a/packages/builtin-skills/src/lobehub/index.ts+++ b/packages/builtin-skills/src/lobehub/index.ts@@ -29,7 +29,7 @@ export const LobeHubSkill: BuiltinSkill = {avatar: LOBEHUB_AVATAR,content: systemPrompt,description:- 'Manage the LobeHub platform via CLI β knowledge bases, memory, agents, files, search, generation, and more.',+ "Manage the LobeHub platform via the `lh` CLI β INCLUDING modifying THIS agent's own configuration. ACTIVATE this skill whenever the user asks you to: change your system prompt / instructions / persona, enable or disable tools / plugins / skills, switch model or provider, attach knowledge bases or files, edit the opening message, rename the topic, OR operate on any other platform resource (agents, topics, memory, documents, search, content generation, model/provider/plugin management, bot integrations, evals, usage stats). Without activation you cannot persist any change β you can only describe what you would do.",identifier: LobeHubIdentifier,name: 'LobeHub',resources: toResourceMeta({diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex c217f6dc963..5812fd588e8 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -368,8 +368,6 @@ export class MessagesEngine {// Input template processingnew InputTemplateProcessor({ inputTemplate }),- // Placeholder variables processing- new PlaceholderVariablesProcessor({ variableGenerators: variableGenerators || {} }),// AgentCouncil message flattennew AgentCouncilFlattenProcessor(),// Group message flatten@@ -403,6 +401,16 @@ export class MessagesEngine {}),]: []),+ // Placeholder variables processing β MUST run AFTER all flatten / role+ // transform steps. AssistantGroup / Supervisor messages keep their real+ // content (including any `{{...}}` placeholders inside tool results)+ // nested under `children[].tools[].result.content`. The flatten processors+ // hoist that nested content into top-level `role: 'tool'` messages.+ // PlaceholderVariablesProcessor only walks `message.content`, so it MUST+ // run after the hoist or it would silently miss every placeholder buried+ // inside an assistantGroup. (Regression discovered while wiring lobehub+ // skill identity placeholders β see LOBE-6882.)+ new PlaceholderVariablesProcessor({ variableGenerators: variableGenerators || {} }),// =============================================// Phase 6: Content Processingdiff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolMessage.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolMessage.test.tsnew file mode 100644index 00000000000..37568b988e4--- /dev/null+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolMessage.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { PlaceholderVariablesProcessor } from '../PlaceholderVariables';++/**+ * Regression for LOBE-6882 placeholder approach.+ *+ * Confirms that PlaceholderVariablesProcessor does substitute `{{...}}` tokens+ * inside `role: 'tool'` messages. If this test ever fails, it means the+ * processor is silently skipping tool messages and the lobehub skill identity+ * placeholders won't be filled in after the model calls+ * `lobe-activator.activateSkill('lobehub')`.+ */+describe('PlaceholderVariablesProcessor β tool message substitution', () => {+ const buildContext = (messages: any[]): PipelineContext => ({+ initialState: { messages: [] },+ isAborted: false,+ messages,+ metadata: {},+ });++ it('substitutes placeholders inside a string-content tool message', async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: {+ agent_id: () => 'agt_xyz',+ agent_title: () => 'Test Agent',+ topic_id: () => 'tpc_abc',+ },+ });++ const ctx = buildContext([+ { role: 'system', content: 'sys' },+ { role: 'user', content: 'hi' },+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ id: 'toolu_1',+ type: 'function',+ function: { name: 'lobe-activator____activateSkill____builtin', arguments: '{}' },+ },+ ],+ },+ {+ role: 'tool',+ tool_call_id: 'toolu_1',+ name: 'lobe-activator____activateSkill____builtin',+ content:+ '<lobehub_platform_guides>\n| Agent ID | `{{agent_id}}` |\n| Agent Title | {{agent_title}} |\n| Topic ID | `{{topic_id}}` |\n</lobehub_platform_guides>',+ },+ ]);++ const result = await processor.process(ctx);++ const toolMessage = result.messages[3];+ expect(toolMessage.role).toBe('tool');+ expect(toolMessage.content).toContain('agt_xyz');+ expect(toolMessage.content).toContain('Test Agent');+ expect(toolMessage.content).toContain('tpc_abc');+ expect(toolMessage.content).not.toContain('{{agent_id}}');+ expect(toolMessage.content).not.toContain('{{agent_title}}');+ expect(toolMessage.content).not.toContain('{{topic_id}}');+ });++ it('preserves placeholder when matching generator is missing', async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: {+ // intentionally NO agent_id+ },+ });++ const ctx = buildContext([+ { role: 'tool', tool_call_id: 't1', name: 'foo', content: 'agent={{agent_id}}' },+ ]);++ const result = await processor.process(ctx);+ expect(result.messages[0].content).toBe('agent={{agent_id}}');+ });++ it('substitutes generator returning empty string to empty (NOT raw)', async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: {+ agent_id: () => '',+ },+ });++ const ctx = buildContext([+ { role: 'tool', tool_call_id: 't1', name: 'foo', content: 'agent=[{{agent_id}}]' },+ ]);++ const result = await processor.process(ctx);+ // Empty string is a valid replacement value β must NOT preserve `{{agent_id}}`+ expect(result.messages[0].content).toBe('agent=[]');+ });+});diff --git a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts b/packages/context-engine/src/providers/AgentBuilderContextInjector.tsindex 2dab4f78c50..050eef15b2a 100644--- a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts+++ b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts@@ -1,7 +1,7 @@import { escapeXml } from '@lobechat/prompts';import debug from 'debug';-import { BaseProvider } from '../base/BaseProvider';+import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';import type { PipelineContext, ProcessorOptions } from '../types';declare module '../types' {@@ -197,9 +197,14 @@ ${parts.join('\n')}/*** Agent Builder Context Injector- * Responsible for injecting current agent context when Agent Builder tool is enabled+ * Responsible for injecting current agent context when Agent Builder tool is enabled.+ *+ * Extends BaseFirstUserContentProvider so the injected XML is consolidated+ * into the shared `systemInjection` message together with other before-first-user+ * providers (UserMemory, Knowledge, AgentManagement, ...). This keeps Phase 3+ * ordering intact and preserves prefix-cache friendliness.*/-export class AgentBuilderContextInjector extends BaseProvider {+export class AgentBuilderContextInjector extends BaseFirstUserContentProvider {readonly name = 'AgentBuilderContextInjector';constructor(@@ -209,56 +214,34 @@ export class AgentBuilderContextInjector extends BaseProvider {super(options);}- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {- const clonedContext = this.cloneContext(context);-- // Skip if Agent Builder is not enabled+ protected buildContent(_context: PipelineContext): string | null {if (!this.config.enabled) {log('Agent Builder not enabled, skipping injection');- return this.markAsExecuted(clonedContext);+ return null;}- // Skip if no agent contextif (!this.config.agentContext) {log('No agent context provided, skipping injection');- return this.markAsExecuted(clonedContext);+ return null;}- // Format agent contextconst formatFn = this.config.formatAgentContext || defaultFormatAgentContext;const formattedContent = formatFn(this.config.agentContext);- // Skip if no content to injectif (!formattedContent) {log('No content to inject after formatting');- return this.markAsExecuted(clonedContext);+ return null;}- // Find the first user message index- const firstUserIndex = clonedContext.messages.findIndex((msg) => msg.role === 'user');+ log('Agent Builder context prepared');+ return formattedContent;+ }- if (firstUserIndex === -1) {- log('No user messages found, skipping injection');- return this.markAsExecuted(clonedContext);+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ const result = await super.doProcess(context);+ if (this.config.enabled && this.config.agentContext) {+ result.metadata.agentBuilderContextInjected = true;}-- // Insert a new user message with agent context before the first user message- const agentContextMessage = {- content: formattedContent,- createdAt: Date.now(),- id: `agent-builder-context-${Date.now()}`,- meta: { injectType: 'agent-builder-context', systemInjection: true },- role: 'user' as const,- updatedAt: Date.now(),- };-- clonedContext.messages.splice(firstUserIndex, 0, agentContextMessage);-- // Update metadata- clonedContext.metadata.agentBuilderContextInjected = true;-- log('Agent Builder context injected as new user message');-- return this.markAsExecuted(clonedContext);+ return result;}}diff --git a/packages/context-engine/src/providers/AgentManagementContextInjector.ts b/packages/context-engine/src/providers/AgentManagementContextInjector.tsindex 19e56a6dd6c..7c599ca64f8 100644--- a/packages/context-engine/src/providers/AgentManagementContextInjector.ts+++ b/packages/context-engine/src/providers/AgentManagementContextInjector.ts@@ -2,7 +2,7 @@ import { escapeXml } from '@lobechat/prompts';import type { RuntimeMentionedAgent } from '@lobechat/types';import debug from 'debug';-import { BaseProvider } from '../base/BaseProvider';+import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';import type { PipelineContext, ProcessorOptions } from '../types';declare module '../types' {@@ -237,9 +237,22 @@ ${agentsXml}/*** Agent Management Context Injector- * Responsible for injecting available models and plugins when Agent Management tool is enabled+ *+ * Has two injection points:+ *+ * 1. **Before first user message** β providers/plugins/availableAgents XML.+ * Goes through `BaseFirstUserContentProvider` so it merges with other+ * `systemInjection: true` providers (UserMemory, Knowledge, AgentBuilder,+ * ...) into a single consolidated message, preserving Phase 3 ordering+ * and prefix-cache friendliness.+ *+ * 2. **After last user message** β `<mentioned_agents>` delegation hint.+ * Always its own standalone message because position matters for model+ * salience (delegation instructions need to be the last thing the model+ * sees before responding). Handled by overriding `doProcess` to splice+ * after `super.doProcess()` returns.*/-export class AgentManagementContextInjector extends BaseProvider {+export class AgentManagementContextInjector extends BaseFirstUserContentProvider {readonly name = 'AgentManagementContextInjector';constructor(@@ -249,82 +262,100 @@ export class AgentManagementContextInjector extends BaseProvider {super(options);}- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {- const clonedContext = this.cloneContext(context);-- // Skip if Agent Management is not enabled+ /**+ * Build the providers/plugins/availableAgents context block for the+ * before-first-user merged injection. Excludes `mentionedAgents` β those+ * have a different injection position and are handled in `doProcess`.+ */+ protected buildContent(_context: PipelineContext): string | null {if (!this.config.enabled) {- log('Agent Management not enabled, skipping injection');- return this.markAsExecuted(clonedContext);+ log('Agent Management not enabled, skipping before-first-user injection');+ return null;}- // Skip if no context dataif (!this.config.context) {- log('No Agent Management context provided, skipping injection');- return this.markAsExecuted(clonedContext);+ log('No Agent Management context provided, skipping before-first-user injection');+ return null;}- const hasMentionedAgents =- this.config.context.mentionedAgents && this.config.context.mentionedAgents.length > 0;-- // Format context (excluding mentionedAgents β those are injected separately- // after the last user message). Use a destructure-rest copy so future fields- // (e.g. currentAgent) don't silently get dropped here.+ // Use a destructure-rest copy so future fields (e.g. currentAgent) don't+ // silently get dropped here.const { mentionedAgents: _mentioned, ...contextWithoutMentions } = this.config.context;const formatFn = this.config.formatContext || defaultFormatContext;const formattedContent = formatFn(contextWithoutMentions);- // Inject agent-management context (providers/plugins) before the first user message- if (formattedContent) {- const firstUserIndex = clonedContext.messages.findIndex((msg) => msg.role === 'user');-- if (firstUserIndex !== -1) {- const contextMessage = {- content: formattedContent,- createdAt: Date.now(),- id: `agent-management-context-${Date.now()}`,- meta: { injectType: 'agent-management-context', systemInjection: true },- role: 'user' as const,- updatedAt: Date.now(),- };-- clonedContext.messages.splice(firstUserIndex, 0, contextMessage);- clonedContext.metadata.agentManagementContextInjected = true;- log('Agent Management context injected before first user message');- }+ if (!formattedContent) {+ log('No agent-management content to inject after formatting');+ return null;}- // Inject mentionedAgents delegation context AFTER the last user message- // This position makes the delegation instruction most salient to the model- if (hasMentionedAgents) {- const mentionedContent = formatMentionedAgentsContext(this.config.context.mentionedAgents!);-- // Find the last user message index- let lastUserIndex = -1;- for (let i = clonedContext.messages.length - 1; i >= 0; i--) {- if (clonedContext.messages[i].role === 'user') {- lastUserIndex = i;- break;- }+ log('Agent Management context prepared for before-first-user merge');+ return formattedContent;+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ // 1) Let BaseFirstUserContentProvider handle the before-first-user merge+ let result = await super.doProcess(context);++ // Track metadata when we actually injected content+ if (this.config.enabled && this.config.context) {+ const { mentionedAgents: _m, ...rest } = this.config.context;+ const formatFn = this.config.formatContext || defaultFormatContext;+ if (formatFn(rest)) {+ result.metadata.agentManagementContextInjected = true;}+ }- if (lastUserIndex !== -1) {- const mentionMessage = {- content: mentionedContent,- createdAt: Date.now(),- id: `agent-mention-delegation-${Date.now()}`,- meta: { injectType: 'agent-mention-delegation', systemInjection: true },- role: 'user' as const,- updatedAt: Date.now(),- };-- // Insert after the last user message- clonedContext.messages.splice(lastUserIndex + 1, 0, mentionMessage);- log('Mentioned agents delegation context injected after last user message');+ // 2) Handle mentionedAgents β separate standalone message after last user+ if (!this.config.enabled || !this.config.context) {+ return result;+ }++ const hasMentionedAgents =+ this.config.context.mentionedAgents && this.config.context.mentionedAgents.length > 0;++ if (!hasMentionedAgents) {+ return result;+ }++ // Clone again only if super.doProcess didn't already (i.e. when buildContent+ // returned null). cloneContext is cheap and idempotent at this granularity.+ result = this.cloneContext(result);++ const mentionedContent = formatMentionedAgentsContext(this.config.context.mentionedAgents!);++ // Find the last user message index β but skip the synthetic systemInjection+ // wrapper messages so we anchor to a real user turn.+ let lastUserIndex = -1;+ for (let i = result.messages.length - 1; i >= 0; i--) {+ const msg = result.messages[i];+ if (msg.role === 'user' && !msg.meta?.systemInjection) {+ lastUserIndex = i;+ break;}}- return this.markAsExecuted(clonedContext);+ if (lastUserIndex !== -1) {+ // NOTE: deliberately NOT tagging this with `systemInjection: true`.+ // The delegation hint is a standalone instruction anchored after the+ // last user message β it must NOT be picked up as the "consolidated+ // system context" by subsequent BaseFirstUserContentProvider injectors+ // (which would mistakenly append identity / memory / etc. into the+ // delegation block).+ const mentionMessage = {+ content: mentionedContent,+ createdAt: Date.now(),+ id: `agent-mention-delegation-${Date.now()}`,+ meta: { injectType: 'agent-mention-delegation' },+ role: 'user' as const,+ updatedAt: Date.now(),+ };++ result.messages.splice(lastUserIndex + 1, 0, mentionMessage);+ log('Mentioned agents delegation context injected after last user message');+ }++ return result;}}diff --git a/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.tsindex b06a1997ef6..b34c4c11e90 100644--- a/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts@@ -1,7 +1,9 @@import { describe, expect, it } from 'vitest';import type { PipelineContext } from '../../types';+import { AgentBuilderContextInjector } from '../AgentBuilderContextInjector';import { AgentManagementContextInjector } from '../AgentManagementContextInjector';+import { UserMemoryInjector } from '../UserMemoryInjector';describe('AgentManagementContextInjector', () => {const createContext = (messages: any[]): PipelineContext => ({@@ -181,6 +183,127 @@ describe('AgentManagementContextInjector', () => {});});+ describe('multi-injector merge β fixes split systemInjection bug', () => {+ /**+ * Regression for the bug where AgentManagementContextInjector created its+ * own systemInjection message via splice(firstUserIndex, 0, ...) instead+ * of merging into the existing one. After UserMemory ran first, the+ * "first user" became the memory wrapper, so AgentManagement inserted+ * its message BEFORE the memory wrapper, splitting the consolidated+ * context into two messages with reversed order.+ *+ * Now that AgentManagement / AgentBuilder both extend+ * BaseFirstUserContentProvider, all three should merge into ONE message+ * in the order their injectors run.+ */+ it('should merge UserMemory + AgentBuilder + AgentManagement into ONE message', async () => {+ const memory = new UserMemoryInjector({+ enabled: true,+ memories: {+ contexts: [],+ experiences: [],+ preferences: [],+ persona: { tagline: 'tag', narrative: 'narr' },+ } as any,+ });+ const builder = new AgentBuilderContextInjector({+ enabled: true,+ agentContext: { meta: { title: 'Builder Agent' } },+ });+ const mgmt = new AgentManagementContextInjector({+ enabled: true,+ context: {+ availableProviders: [+ { id: 'openai', name: 'OpenAI', models: [{ id: 'gpt-4', name: 'GPT-4' }] },+ ],+ },+ });++ let ctx: PipelineContext = {+ initialState: { messages: [] },+ isAborted: false,+ messages: [+ { role: 'system', content: 'sys' },+ { role: 'user', content: 'hi' },+ ],+ metadata: {},+ };++ // Run them in the same order MessagesEngine.buildProcessors uses+ ctx = await memory.process(ctx);+ ctx = await builder.process(ctx);+ ctx = await mgmt.process(ctx);++ // Expect exactly: [system, merged systemInjection, original user]+ expect(ctx.messages).toHaveLength(3);+ expect(ctx.messages[0].role).toBe('system');+ expect(ctx.messages[2].content).toBe('hi');++ const merged = ctx.messages[1];+ expect(merged.role).toBe('user');+ expect(merged.meta?.systemInjection).toBe(true);+ const content = merged.content as string;++ // All three context blocks present in the SAME message+ expect(content).toContain('<user_memory>');+ expect(content).toContain('<current_agent_context>');+ expect(content).toContain('Builder Agent');+ expect(content).toContain('<agent_management_context>');+ expect(content).toContain('gpt-4');++ // And in injector-run order: memory < builder < management+ expect(content.indexOf('<user_memory>')).toBeLessThan(+ content.indexOf('<current_agent_context>'),+ );+ expect(content.indexOf('<current_agent_context>')).toBeLessThan(+ content.indexOf('<agent_management_context>'),+ );+ });++ it('should still anchor mentionedAgents AFTER the real last user, not after merged systemInjection', async () => {+ const memory = new UserMemoryInjector({+ enabled: true,+ memories: {+ contexts: [],+ experiences: [],+ preferences: [],+ persona: { tagline: 'test tagline', narrative: 'test narrative' },+ } as any,+ });+ const mgmt = new AgentManagementContextInjector({+ enabled: true,+ context: {+ availableProviders: [{ id: 'openai', name: 'OpenAI', models: [] }],+ mentionedAgents: [{ id: 'agt_x', name: 'X' }],+ },+ });++ let ctx: PipelineContext = {+ initialState: { messages: [] },+ isAborted: false,+ messages: [+ { role: 'system', content: 'sys' },+ { role: 'user', content: 'real user msg' },+ ],+ metadata: {},+ };++ ctx = await memory.process(ctx);+ ctx = await mgmt.process(ctx);++ // [system, merged context, real user, delegation]+ expect(ctx.messages).toHaveLength(4);+ expect(ctx.messages[1].content).toContain('<user_memory>');+ expect(ctx.messages[1].content).toContain('<agent_management_context>');+ expect(ctx.messages[2].content).toBe('real user msg');+ expect(ctx.messages[3].content).toContain('<mentioned_agents>');+ expect(ctx.messages[3].content).toContain('agt_x');+ // Delegation message must NOT be tagged systemInjection (otherwise+ // subsequent BFUCP injectors would try to append into it)+ expect(ctx.messages[3].meta?.systemInjection).toBeFalsy();+ });+ });+describe('only mentionedAgents (no providers/plugins)', () => {it('should NOT inject empty agent-management context but SHOULD inject delegation', async () => {const injector = new AgentManagementContextInjector({diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex d0749a814c0..31ebc9ac852 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -465,9 +465,50 @@ export const createRuntimeExecutors = (}}+ // Build additional placeholder variables for the lobehub builtin skill+ // (`packages/builtin-skills/src/lobehub/content.ts`) so it can render+ // `{{agent_id}}` / `{{agent_title}}` / `{{topic_id}}` etc. into the+ // model's prompt without needing a separate context injector.+ //+ // - agent_title / agent_description: read directly from agentConfig,+ // which is the result of AgentModel.getAgentConfig() and already+ // contains the full enriched agent record (title, description, ...).+ // No extra query needed.+ // - topic_title: requires a single primary-key lookup against the+ // topics table. Skipped when topicId is missing or the lookup fails+ // (best-effort, falls back to empty string so the template still+ // renders cleanly).+ const lobehubSkillAgentId = state.metadata?.agentId;+ const lobehubSkillTopicId = state.metadata?.topicId;+ const lobehubSkillAgentMeta = state.metadata?.agentConfig as+ | { description?: string | null; title?: string | null }+ | undefined;++ let lobehubSkillTopicTitle = '';+ if (lobehubSkillTopicId && ctx.serverDB && ctx.userId) {+ try {+ const topicModelForLobehub = new TopicModel(ctx.serverDB, ctx.userId);+ const topicRecord = await topicModelForLobehub.findById(lobehubSkillTopicId);+ lobehubSkillTopicTitle = topicRecord?.title ?? '';+ } catch (error) {+ log('Failed to load topic title for lobehub skill placeholders: %O', error);+ }+ }++ const lobehubSkillVariables: Record<string, string> = {+ agent_id: lobehubSkillAgentId ?? '',+ agent_title: lobehubSkillAgentMeta?.title ?? '',+ agent_description: lobehubSkillAgentMeta?.description ?? '',+ topic_id: lobehubSkillTopicId ?? '',+ topic_title: lobehubSkillTopicTitle,+ };+const contextEngineInput = {agentDocuments,- additionalVariables: state.metadata?.deviceSystemInfo,+ additionalVariables: {+ ...state.metadata?.deviceSystemInfo,+ ...lobehubSkillVariables,+ },userTimezone: ctx.userTimezone,capabilities: {isCanUseFC: (m: string, p: string) => {diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex e9f2a271b32..ad8f681768e 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -679,6 +679,24 @@ export const contextEngineering = async ({CREDS_LIST: () => (credsList ? generateCredsList(credsList) : ''),// NOTICE(@nekomeowww): required by builtin-tool-memory/src/systemRole.tsmemory_effort: () => (userMemoryConfig ? (memoryContext?.effort ?? '') : ''),+ // Current agent + topic identity β referenced by the LobeHub builtin+ // skill (packages/builtin-skills/src/lobehub/content.ts) so the model+ // can run `lh agent run -a {{agent_id}}` etc without first having to+ // search for itself. Read lazily from stores so we only pay the cost+ // when the placeholder actually appears in a rendered message.+ agent_id: () => agentId ?? '',+ agent_title: () =>+ agentId ? (agentSelectors.getAgentMetaById(agentId)(agentStoreState)?.title ?? '') : '',+ agent_description: () =>+ agentId+ ? (agentSelectors.getAgentMetaById(agentId)(agentStoreState)?.description ?? '')+ : '',+ topic_id: () => topicId ?? '',+ topic_title: () => {+ if (!topicId) return '';+ const topic = topicSelectors.getTopicById(topicId)(getChatStoreState());+ return topic?.title ?? '';+ },},// Extended contexts - only pass when enableddiff --git a/src/services/chat/mecha/lobehubSkillPlaceholders.test.ts b/src/services/chat/mecha/lobehubSkillPlaceholders.test.tsnew file mode 100644index 00000000000..b8a66799e88--- /dev/null+++ b/src/services/chat/mecha/lobehubSkillPlaceholders.test.ts@@ -0,0 +1,91 @@+import { builtinSkills, LobeHubIdentifier } from '@lobechat/builtin-skills';+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import { describe, expect, it } from 'vitest';++const LobeHubSkill = builtinSkills.find((s) => s.identifier === LobeHubIdentifier);+if (!LobeHubSkill) {+ throw new Error(`LobeHubSkill not found in builtinSkills (looking for "${LobeHubIdentifier}")`);+}+const lobeHubContent = LobeHubSkill.content;++/**+ * Regression for LOBE-6882.+ *+ * Instead of building a dedicated AgentIdentityContextInjector, we wire current+ * agent / topic identity through the existing PlaceholderVariablesProcessor β+ * the LobeHub builtin skill content references `{{agent_id}}`, `{{topic_id}}`,+ * etc., and `contextEngineering.ts` provides the matching variable generators.+ *+ * This test pins the contract from BOTH ends:+ * 1. `lobehub/content.ts` actually contains the expected `{{...}}` tokens.+ * 2. The placeholder engine substitutes them with caller-provided values.+ *+ * If anyone renames a token in content.ts without updating the generators (or+ * vice versa), this test fails before users see a broken `lh agent run -a {{agent_id}}`+ * literal in their prompts.+ */+describe('LobeHub skill identity placeholders (LOBE-6882)', () => {+ const PLACEHOLDER_KEYS = [+ 'agent_id',+ 'agent_title',+ 'agent_description',+ 'topic_id',+ 'topic_title',+ ] as const;++ it('lobeHubContent references all expected placeholder tokens', () => {+ const content = lobeHubContent;+ for (const key of PLACEHOLDER_KEYS) {+ expect(content).toContain(`{{${key}}}`);+ }+ });++ it('renderPlaceholderTemplate substitutes all identity placeholders', () => {+ const rendered = renderPlaceholderTemplate(lobeHubContent, {+ agent_id: 'agt_xyz',+ agent_title: 'Test Agent',+ agent_description: 'A test assistant',+ topic_id: 'tpc_abc',+ topic_title: 'Hello topic',+ });++ // All raw `{{...}}` tokens for our keys must be gone after substitution+ for (const key of PLACEHOLDER_KEYS) {+ expect(rendered).not.toContain(`{{${key}}}`);+ }+ // And the substituted values must be present+ expect(rendered).toContain('agt_xyz');+ expect(rendered).toContain('Test Agent');+ expect(rendered).toContain('A test assistant');+ expect(rendered).toContain('tpc_abc');+ expect(rendered).toContain('Hello topic');+ });++ it('falls back to empty string when an identity field is missing', () => {+ const rendered = renderPlaceholderTemplate(lobeHubContent, {+ agent_id: 'agt_only',+ agent_title: '',+ agent_description: '',+ topic_id: 'tpc_only',+ topic_title: '',+ });++ // ID rows still render their values+ expect(rendered).toContain('agt_only');+ expect(rendered).toContain('tpc_only');+ // Empty values do NOT leave a literal `{{...}}` behind+ for (const key of PLACEHOLDER_KEYS) {+ expect(rendered).not.toContain(`{{${key}}}`);+ }+ });++ it('leaves unrelated placeholder tokens untouched', () => {+ // Sanity check: if someone adds an unsupported `{{foo}}` token to content.ts,+ // renderPlaceholderTemplate should preserve it rather than dropping it.+ // We synthesize a tiny template here so the test stays narrow.+ const result = renderPlaceholderTemplate('agent={{agent_id}}; unknown={{not_a_real_var}}', {+ agent_id: 'agt_xyz',+ });+ expect(result).toBe('agent=agt_xyz; unknown={{not_a_real_var}}');+ });+});