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.

🐛 fix(skills): inject pinned skill content into the system prompt (#15568)

LiJiandfb70c1e87f0
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 1414dc8c599..286af5a678d 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -29,6 +29,7 @@ import type {
LobeToolManifest,
MemoryContext,
OnboardingContext,
+ OperationSkillSet,
PlanTodoConfig,
ToolDiscoveryConfig,
UserMemoryData,
@@ -643,6 +644,20 @@ export const contextEngineering = async ({
}
}
+ // Resolve enabled skills (await: pinned DB skills fetch their content on demand).
+ // In auto mode: expose all installed skills so the AI can discover and activate them.
+ // In manual mode: only expose user-selected skills (filtered by pluginIds).
+ let enabledSkills: OperationSkillSet['skills'] | undefined;
+ if (plugins) {
+ const skillSet = await resolveClientSkills(plugins);
+ if (isInAutoSkillMode) {
+ enabledSkills = skillSet.skills;
+ } else {
+ const selectedIds = new Set(plugins);
+ enabledSkills = skillSet.skills.filter((s) => selectedIds.has(s.identifier));
+ }
+ }
+
// Create MessagesEngine with injected dependencies
const engine = new MessagesEngine({
// Agent configuration
@@ -689,20 +704,9 @@ export const contextEngineering = async ({
// agent-document injectors when this is `false` (chat mode).
enableAgentMode: agentChatConfigSelectors.currentChatConfig(agentStoreState).enableAgentMode,
- // Skills configuration
- // In auto mode: expose all installed skills so the AI can discover and activate them
- // In manual mode: only expose user-selected skills (filtered by pluginIds)
+ // Skills configuration (resolved above)
skillsConfig: {
- enabledSkills: plugins
- ? (() => {
- const skillSet = resolveClientSkills(plugins);
- if (!isInAutoSkillMode) {
- const selectedIds = new Set(plugins);
- return skillSet.skills.filter((s) => selectedIds.has(s.identifier));
- }
- return skillSet.skills;
- })()
- : undefined,
+ enabledSkills,
},
// Tool Discovery configuration
diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.ts
new file mode 100644
index 00000000000..f4749a4ab77
--- /dev/null
+++ b/src/services/chat/mecha/skillEngineering.test.ts
@@ -0,0 +1,184 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentSkillService } from '@/services/skill';
+import { getToolStoreState } from '@/store/tool';
+
+import { resolveClientSkills } from './skillEngineering';
+
+vi.mock('@/store/tool', () => ({
+ getToolStoreState: vi.fn(),
+}));
+
+vi.mock('@/services/skill', () => ({
+ agentSkillService: {
+ getById: vi.fn(),
+ },
+}));
+
+// Keep all skills available in the test environment.
+vi.mock('@/helpers/toolAvailability', () => ({
+ isBuiltinSkillAvailableInCurrentEnv: () => true,
+}));
+
+const mockedGetToolStoreState = vi.mocked(getToolStoreState);
+const mockedGetById = vi.mocked(agentSkillService.getById);
+
+const setToolState = (state: any) => {
+ mockedGetToolStoreState.mockReturnValue({
+ agentSkillDetailMap: {},
+ agentSkills: [],
+ builtinSkills: [],
+ ...state,
+ } as any);
+};
+
+const findSkill = (
+ skills: { activated?: boolean; content?: string; identifier: string }[],
+ identifier: string,
+) => skills.find((s) => s.identifier === identifier);
+
+describe('resolveClientSkills', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('carries builtin skill content so pinned builtin skills can be injected', async () => {
+ setToolState({
+ builtinSkills: [
+ {
+ content: '<artifacts_guide>build UI</artifacts_guide>',
+ description: 'Generate interactive UI',
+ identifier: 'artifacts',
+ name: 'Artifacts',
+ source: 'builtin',
+ },
+ ],
+ });
+
+ const result = await resolveClientSkills(['artifacts']);
+
+ expect(result.enabledPluginIds).toEqual(['artifacts']);
+ // activated must be set so SkillContextProvider injects content directly
+ // (the MessagesEngine path consumes these metas without running SkillResolver).
+ expect(findSkill(result.skills, 'artifacts')).toMatchObject({
+ activated: true,
+ content: '<artifacts_guide>build UI</artifacts_guide>',
+ identifier: 'artifacts',
+ });
+ });
+
+ it('fetches DB skill content for pinned skills', async () => {
+ setToolState({
+ agentSkills: [
+ { description: 'A user skill', id: 'db-1', identifier: 'my-skill', name: 'My Skill' },
+ ],
+ });
+ mockedGetById.mockResolvedValue({
+ content: 'full skill body',
+ id: 'db-1',
+ identifier: 'my-skill',
+ name: 'My Skill',
+ } as any);
+
+ const result = await resolveClientSkills(['my-skill']);
+
+ expect(mockedGetById).toHaveBeenCalledWith('db-1');
+ expect(findSkill(result.skills, 'my-skill')).toMatchObject({
+ activated: true,
+ content: 'full skill body',
+ identifier: 'my-skill',
+ });
+ });
+
+ it('appends the resource tree to pinned DB skill content', async () => {
+ setToolState({
+ agentSkills: [{ description: '', id: 'db-1', identifier: 'my-skill', name: 'My Skill' }],
+ });
+ mockedGetById.mockResolvedValue({
+ content: 'body',
+ id: 'db-1',
+ identifier: 'my-skill',
+ name: 'My Skill',
+ resources: { 'kb/readme.md': { fileHash: 'h', size: 1 } },
+ } as any);
+
+ const result = await resolveClientSkills(['my-skill']);
+
+ const skill = findSkill(result.skills, 'my-skill');
+ expect(skill?.content).toContain('body');
+ // resourcesTreePrompt output references the resource tree
+ expect(skill?.content).toContain('Available Resources');
+ expect(skill?.content).toContain('readme.md');
+ });
+
+ it('does NOT fetch content for non-pinned DB skills (auto mode bulk exposure)', async () => {
+ setToolState({
+ agentSkills: [
+ { description: 'A user skill', id: 'db-1', identifier: 'my-skill', name: 'My Skill' },
+ ],
+ });
+
+ // pluginIds empty => skill is exposed (available list) but not pinned
+ const result = await resolveClientSkills([]);
+
+ expect(mockedGetById).not.toHaveBeenCalled();
+ const skill = findSkill(result.skills, 'my-skill');
+ expect(skill?.content).toBeUndefined();
+ expect(skill?.activated).toBeFalsy();
+ });
+
+ it('does NOT pre-activate a pinned DB skill bundled as a ZIP', async () => {
+ // Bundled skills must go through activateSkill so the server mounts the bundle;
+ // pre-injecting content here would reference scripts/resources that are not mounted.
+ setToolState({
+ agentSkills: [
+ {
+ description: 'bundled',
+ id: 'db-1',
+ identifier: 'zip-skill',
+ name: 'Zip Skill',
+ zipFileHash: 'hash-abc',
+ },
+ ],
+ });
+
+ const result = await resolveClientSkills(['zip-skill']);
+
+ expect(mockedGetById).not.toHaveBeenCalled();
+ const skill = findSkill(result.skills, 'zip-skill');
+ expect(skill?.content).toBeUndefined();
+ expect(skill?.activated).toBeFalsy();
+ });
+
+ it('prefers the cached skill detail over a network fetch', async () => {
+ setToolState({
+ agentSkillDetailMap: {
+ 'db-1': { content: 'cached body', id: 'db-1', identifier: 'my-skill', name: 'My Skill' },
+ },
+ agentSkills: [{ description: '', id: 'db-1', identifier: 'my-skill', name: 'My Skill' }],
+ });
+
+ const result = await resolveClientSkills(['my-skill']);
+
+ expect(mockedGetById).not.toHaveBeenCalled();
+ expect(findSkill(result.skills, 'my-skill')).toMatchObject({
+ activated: true,
+ content: 'cached body',
+ });
+ });
+
+ it('degrades gracefully when a pinned DB skill content fetch fails', async () => {
+ setToolState({
+ agentSkills: [{ description: '', id: 'db-1', identifier: 'my-skill', name: 'My Skill' }],
+ });
+ mockedGetById.mockRejectedValue(new Error('network down'));
+
+ const result = await resolveClientSkills(['my-skill']);
+
+ // No throw; skill still listed (available, not activated), just without content.
+ const skill = findSkill(result.skills, 'my-skill');
+ expect(skill).toMatchObject({ identifier: 'my-skill' });
+ expect(skill?.content).toBeUndefined();
+ expect(skill?.activated).toBeFalsy();
+ });
+});
diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.ts
index 79f44fba8b5..10c76110fd3 100644
--- a/src/services/chat/mecha/skillEngineering.ts
+++ b/src/services/chat/mecha/skillEngineering.ts
@@ -1,9 +1,28 @@
import type { OperationSkillSet } from '@lobechat/context-engine';
import { SkillEngine } from '@lobechat/context-engine';
+import { resourcesTreePrompt } from '@lobechat/prompts';
+import type { SkillItem } from '@lobechat/types';
+import debug from 'debug';
import { isBuiltinSkillAvailableInCurrentEnv } from '@/helpers/toolAvailability';
+import { agentSkillService } from '@/services/skill';
import { getToolStoreState } from '@/store/tool';
+const log = debug('context-engine:resolveClientSkills');
+
+/**
+ * Build the full content payload for a DB skill detail, appending its resource
+ * tree when present (mirrors the activateSkill executor output).
+ */
+const buildDbSkillContent = (detail: SkillItem): string | undefined => {
+ if (!detail.content) return undefined;
+
+ const hasResources = !!(detail.resources && Object.keys(detail.resources).length > 0);
+ return hasResources
+ ? detail.content + '\n\n' + resourcesTreePrompt(detail.name, detail.resources!)
+ : detail.content;
+};
+
/**
* Build a client-side OperationSkillSet via SkillEngine.
*
@@ -11,23 +30,65 @@ import { getToolStoreState } from '@/store/tool';
* 1. Builtin skills (e.g., Artifacts) - from toolStore.builtinSkills
* 2. DB skills (user/market) - from toolStore.agentSkills
*
+ * Pinned skills (ids in `pluginIds`) carry their full `content` so the
+ * SkillContextProvider can inject it directly into the system prompt instead of
+ * only listing them under `<available_skills>`. Builtin content is already in
+ * memory; DB content is fetched on demand (store cache first) and only for the
+ * pinned skills, to avoid bulk network calls when auto mode exposes every skill.
+ *
* Uses isBuiltinSkillAvailableInCurrentEnv as the enableChecker to
* filter platform-specific skills (e.g., agent-browser on desktop only).
*/
-export const resolveClientSkills = (pluginIds?: string[]): OperationSkillSet => {
+export const resolveClientSkills = async (pluginIds?: string[]): Promise<OperationSkillSet> => {
const toolState = getToolStoreState();
+ const pinnedIds = new Set(pluginIds ?? []);
+ // Builtin skills keep their full content in the store, so it is always cheap
+ // to carry along. Pinned skills are marked `activated` so SkillContextProvider
+ // injects their content directly; non-pinned ones stay in <available_skills>.
const builtinMetas = (toolState.builtinSkills || []).map((s) => ({
+ activated: pinnedIds.has(s.identifier) && !!s.content,
+ content: s.content,
description: s.description,
identifier: s.identifier,
name: s.name,
}));
- const dbMetas = (toolState.agentSkills || []).map((s) => ({
- description: s.description ?? '',
- identifier: s.identifier,
- name: s.name,
- }));
+ const dbMetas = await Promise.all(
+ (toolState.agentSkills || []).map(async (s) => {
+ const meta = {
+ description: s.description ?? '',
+ identifier: s.identifier,
+ name: s.name,
+ };
+
+ // Only pinned DB skills need full content for direct injection; the list
+ // query (SkillListItem) does not carry content, so fetch it on demand.
+ if (!pinnedIds.has(s.identifier)) return meta;
+
+ // Skills bundled as a ZIP (scripts/resources) must be activated via the
+ // activateSkill tool so the server mounts their bundle for execScript /
+ // readReference — that runtime mount is keyed off stepContext.activatedSkills,
+ // which operation-level pinning does not populate. Pre-injecting their
+ // content would instruct the model to run scripts from an unmounted bundle,
+ // so leave bundled skills in <available_skills> and let the model activate them.
+ if (s.zipFileHash) return meta;
+
+ try {
+ const detail =
+ toolState.agentSkillDetailMap?.[s.id] ?? (await agentSkillService.getById(s.id));
+ const content = detail && buildDbSkillContent(detail);
+ // Mark activated only when content is available, otherwise the skill would
+ // be excluded from both the activated and the <available_skills> lists.
+ return content ? { ...meta, activated: true, content } : meta;
+ } catch (error) {
+ // A single skill's content fetch must never break the whole request;
+ // degrade gracefully by listing the skill without injected content.
+ log('Failed to load content for pinned skill %s: %O', s.identifier, error);
+ return meta;
+ }
+ }),
+ );
const skillEngine = new SkillEngine({
enableChecker: (skill) => isBuiltinSkillAvailableInCurrentEnv(skill.identifier),