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): make agent skills opt-in and load their content on demand (#23412)

AmAzing-3bc9577537c7
diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.ts
index ad1a0d0e279..0df5f96afb5 100644
--- a/apps/server/src/routers/lambda/agentShare.ts
+++ b/apps/server/src/routers/lambda/agentShare.ts
@@ -5,7 +5,7 @@ import {
AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT,
} from '@lobechat/const';
import { assembleSkillPool } from '@lobechat/mecha';
-import { getActivePluginIds, getDisabledPluginIds } from '@lobechat/types';
+import { getActivePluginIds, getAutoPluginIds, getDisabledPluginIds } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { eq } from 'drizzle-orm';
import pMap from 'p-map';
@@ -451,6 +451,7 @@ export const agentShareRouter = router({
})),
},
{
+ autoSkillIds: getAutoPluginIds(agentConfig?.plugins ?? undefined),
canExecuteOnDevice: false,
disabledIds: getDisabledPluginIds(agentConfig?.plugins ?? undefined),
enabledPluginIds: getActivePluginIds(agentConfig?.plugins ?? undefined),
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
index 9526b73612a..8a0b3f31b1e 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
@@ -4,11 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
-// Verifies that a PINNED skill (DB `agent_skills` row or agent-document bundle)
-// has its SKILL.md body eagerly injected into the operation's skill set β€” so
-// downstream SkillResolver/SkillContextProvider inject the content directly
-// instead of requiring the model to call `activateSkill`. Non-pinned (auto)
-// skills stay content-less here and remain lazily activatable.
+// Agent preferences expose skill metadata; only a topic selection requests its body.
const {
mockConnectorResolveByIdentifiers,
mockConnectorToolQueryAll,
@@ -306,7 +302,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
service = new AiAgentService({} as any, 'test-user-id');
});
- it('injects a pinned DB skill body into the operation skill set, leaving auto skills content-less', async () => {
+ it('treats legacy pinned and auto skills as metadata-only', async () => {
mockGetAgentConfig.mockResolvedValue(
createAgentConfig(['db-skill-pinned', { identifier: 'db-skill-auto', mode: 'auto' }]),
);
@@ -314,7 +310,8 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
expect(operationSkillSetArg()?.enabledPluginIds).toContain('db-skill-pinned');
- expect(skillById('db-skill-pinned')?.content).toBe('PINNED SKILL BODY');
+ expect(skillById('db-skill-pinned')).toBeDefined();
+ expect(skillById('db-skill-pinned')?.content).toBeUndefined();
// The auto skill is still listed (activatable) but carries no body.
expect(skillById('db-skill-auto')).toBeDefined();
expect(skillById('db-skill-auto')?.content).toBeUndefined();
@@ -330,16 +327,15 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
expect(skillById('db-skill-auto')).toBeUndefined();
});
- it('fetches bodies only for the pinned subset to keep the op-param payload bounded', async () => {
+ it('does not fetch bodies for legacy pins', async () => {
mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-pinned']));
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
- // Only the pinned skill's row id is fetched β€” not the auto skill (sk-2).
- expect(mockSkillFindByIds).toHaveBeenCalledWith(['sk-1']);
+ expect(mockSkillFindByIds).not.toHaveBeenCalled();
});
- it('injects a pinned agent-document skill body without an extra fetch', async () => {
+ it('advertises a legacy pinned agent-document without its body', async () => {
mockGetAgentSkills.mockResolvedValue([
{
content: 'AGENT DOC SKILL BODY',
@@ -354,11 +350,27 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
- expect(skillById('agent-skills:foo')?.content).toBe('AGENT DOC SKILL BODY');
+ expect(skillById('agent-skills:foo')).toBeDefined();
+ expect(skillById('agent-skills:foo')?.content).toBeUndefined();
// Agent-document bodies come from `getAgentSkills`, never the DB skill fetch.
- expect(mockSkillFindByIds).toHaveBeenCalledWith([]);
+ expect(mockSkillFindByIds).not.toHaveBeenCalled();
});
+ it.each([
+ { plugins: [], offered: false },
+ { plugins: [{ identifier: 'lobe-artifacts', mode: 'auto' as const }], offered: true },
+ { plugins: ['lobe-artifacts'], offered: true },
+ ])(
+ 'advertises only opted-in builtin metadata for a greeting: $plugins',
+ async ({ plugins, offered }) => {
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig(plugins));
+ await service.execAgent({ agentId: 'agent-1', prompt: 'δ½ ε₯½' } as any);
+ expect(!!skillById('lobe-artifacts')).toBe(offered);
+ expect(skillById('lobe-artifacts')?.content).toBeUndefined();
+ expect(skillById('lobehub')).toBeUndefined();
+ },
+ );
+
it('does not attach content when no skill is pinned', async () => {
mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
@@ -366,7 +378,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
expect(skillById('db-skill-pinned')?.content).toBeUndefined();
expect(skillById('db-skill-auto')?.content).toBeUndefined();
- expect(mockSkillFindByIds).toHaveBeenCalledWith([]);
+ expect(mockSkillFindByIds).not.toHaveBeenCalled();
});
it('enables the goal tool for a direct server /goal prompt', async () => {
@@ -423,7 +435,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
// so the colliding auto skill stays content-less (lazily activatable).
expect(skillById('db-skill-auto')).toBeDefined();
expect(skillById('db-skill-auto')?.content).toBeUndefined();
- expect(mockSkillFindByIds).toHaveBeenCalledWith([]);
+ expect(mockSkillFindByIds).not.toHaveBeenCalled();
});
it('lists the user skill library to every run, content-less until a run names a skill', async () => {
@@ -455,10 +467,14 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
expect(skillById('user-skills:goal-plan-x')?.content).toBe('PLAN BODY + FILES');
});
- it('appends the resource tree to a pinned skill body, mirroring activateSkill', async () => {
- mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-with-resources']));
+ it('appends the resource tree to a topic-selected skill body, mirroring activateSkill', async () => {
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
- await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Hello',
+ selectedSkillIds: ['db-skill-with-resources'],
+ } as any);
const injected = skillById('db-skill-with-resources')?.content;
// Body plus the readReference resource tree β€” so a pinned ZIP/GitHub skill
diff --git a/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
index 2f280462a37..74e4eb9600f 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
@@ -110,7 +110,7 @@ export const buildOperationSkillSet = async (
try {
const builtinMetas = builtinSkills.map((s) => ({
- content: s.content,
+ content: selectedSkillIds.includes(s.identifier) ? s.content : undefined,
description: s.description,
identifier: s.identifier,
name: s.name,
@@ -118,28 +118,15 @@ export const buildOperationSkillSet = async (
const skillModel = new AgentSkillModel(deps.db, deps.userId, deps.workspaceId);
const { data: dbSkills } = await skillModel.findAll();
- // Pinned skills need their SKILL.md body injected into context directly,
- // not lazily via the `activateSkill` tool. Gate on the agent's genuinely
- // pinned entries (`getActivePluginIds(agentConfig.plugins)`), NOT the
- // fully-expanded `agentPlugins`: the latter also carries turn-scoped tool
- // ids (mentions, selected tools, `lobe-message`, …), which would
- // eager-activate an auto-mode skill whose identifier merely collides with
- // one of them. `findAll` uses `skillListColumns` (no `content`), so fetch
- // bodies only for the pinned subset to keep the op-param payload bounded.
- // Non-pinned skills stay content-less here and remain lazily activatable.
- // Content lives in the DB `content` column already (SKILL.md body), so no
- // zip unpack is needed; mirror `activateSkill` by appending the resource
- // tree so pinned ZIP/GitHub skills keep their `readReference` paths.
- //
- // Skills the user explicitly selected in this topic are injected the same
- // way: the selection names them directly, so no tool id can collide into it.
+ // Only a topic selection requests a body up front. A saved (legacy)
+ // pin, like auto, advertises the skill for on-demand activation.
const pinnedSkillIds = new Set(getActivePluginIds(agentConfig.plugins));
- const injectedSkillIds = new Set([...pinnedSkillIds, ...selectedSkillIds]);
+ const injectedSkillIds = new Set(selectedSkillIds);
const pinnedDbSkillIds = dbSkills
.filter((s) => injectedSkillIds.has(s.identifier))
.map((s) => s.id);
const pinnedDbContent = new Map(
- (await skillModel.findByIds(pinnedDbSkillIds)).map((s) => {
+ (pinnedDbSkillIds.length ? await skillModel.findByIds(pinnedDbSkillIds) : []).map((s) => {
const hasResources = !!(s.resources && Object.keys(s.resources).length > 0);
const content =
hasResources && s.resources
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
index 197914b588d..e6a5f018955 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
@@ -114,7 +114,7 @@ export const activatorRuntime: ServerRuntimeRegistration = {
// with `activeDeviceId` as the fallback for callers without a plan.
builtinSkills: filterBuiltinSkills(builtinSkills, {
canExecuteOnDevice: context.deviceCapable ?? !!context.activeDeviceId,
- }).filter((skill) => isSkillReachable(skill.identifier)),
+ }).filter((skill) => isLibrarySkillReachable(skill.identifier)),
service: {
findAll: async () => {
const result = await skillModel.findAll();
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 84d6960080e..5ac09b0bce2 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -1183,14 +1183,14 @@ export const skillsRuntime: ServerRuntimeRegistration = {
// back to these because the raw LLM args never carry activatedSkills.
activatedSkills: context.activatedSkills,
builtinSkills: [
- // Device-only skills resolve in device-capable runs β€” mirrors the
- // SkillEngine gate in aiAgent that builds <available_skills>, so a
- // `device-unrouted` run can activate/read them before the model routes
- // a device. `activeDeviceId` is the fallback for callers without an
- // execution plan.
+ // Match the device and opt-in gates of the operation's skill catalog.
...filterBuiltinSkills(builtinSkills, {
canExecuteOnDevice: context.deviceCapable ?? !!activeDeviceId,
- }).filter((skill) => isSkillReachable(skill.identifier)),
+ }).filter(
+ (skill) =>
+ isSkillReachable(skill.identifier) &&
+ (isLibrarySkillEnabled?.(skill.identifier) ?? true),
+ ),
...agentSkillBuiltins,
],
deviceFileAccess,
diff --git a/packages/builtin-tool-activator/src/executor/index.ts b/packages/builtin-tool-activator/src/executor/index.ts
index 3117da60c02..61db5976b60 100644
--- a/packages/builtin-tool-activator/src/executor/index.ts
+++ b/packages/builtin-tool-activator/src/executor/index.ts
@@ -12,11 +12,13 @@ class ActivatorExecutor extends BaseExecutor<typeof ActivatorApiName> {
readonly identifier = LobeActivatorIdentifier;
protected readonly apiEnum = ActivatorApiName;
- private runtime: ActivatorExecutionRuntime;
+ private getRuntime: (ctx: BuiltinToolContext) => ActivatorExecutionRuntime;
- constructor(runtime: ActivatorExecutionRuntime) {
+ constructor(
+ runtime: ActivatorExecutionRuntime | ((ctx: BuiltinToolContext) => ActivatorExecutionRuntime),
+ ) {
super();
- this.runtime = runtime;
+ this.getRuntime = typeof runtime === 'function' ? runtime : () => runtime;
}
activateSkill = async (
@@ -28,7 +30,7 @@ class ActivatorExecutor extends BaseExecutor<typeof ActivatorApiName> {
return { stop: true, success: false };
}
- const result = await this.runtime.activateSkill(params);
+ const result = await this.getRuntime(ctx).activateSkill(params);
if (result.success) {
return { content: result.content, state: result.state, success: true };
@@ -57,7 +59,7 @@ class ActivatorExecutor extends BaseExecutor<typeof ActivatorApiName> {
return { stop: true, success: false };
}
- const result = await this.runtime.activateTools(params);
+ const result = await this.getRuntime(ctx).activateTools(params);
if (result.success) {
return { content: result.content, state: result.state, success: true };
diff --git a/packages/builtin-tool-skills/src/executor/index.ts b/packages/builtin-tool-skills/src/executor/index.ts
index 760eb01c8cd..b9306c396db 100644
--- a/packages/builtin-tool-skills/src/executor/index.ts
+++ b/packages/builtin-tool-skills/src/executor/index.ts
@@ -15,11 +15,13 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
readonly identifier = SkillsIdentifier;
protected readonly apiEnum = SkillsApiName;
- private runtime: SkillsExecutionRuntime;
+ private getRuntime: (ctx: BuiltinToolContext) => SkillsExecutionRuntime;
- constructor(runtime: SkillsExecutionRuntime) {
+ constructor(
+ runtime: SkillsExecutionRuntime | ((ctx: BuiltinToolContext) => SkillsExecutionRuntime),
+ ) {
super();
- this.runtime = runtime;
+ this.getRuntime = typeof runtime === 'function' ? runtime : () => runtime;
}
execScript = async (
@@ -35,7 +37,7 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
// Server will resolve zipUrls for all activated skills
const activatedSkills = ctx.stepContext?.activatedSkills;
- const result = await this.runtime.execScript(
+ const result = await this.getRuntime(ctx).execScript(
{
...params,
activatedSkills: activatedSkills?.map((s) => ({
@@ -82,7 +84,7 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
return { stop: true, success: false };
}
- const result = await this.runtime.activateSkill(params);
+ const result = await this.getRuntime(ctx).activateSkill(params);
if (result.success) {
return { content: result.content, state: result.state, success: true };
@@ -111,7 +113,7 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
return { stop: true, success: false };
}
- const result = await this.runtime.readReference(params);
+ const result = await this.getRuntime(ctx).readReference(params);
if (result.success) {
return { content: result.content, state: result.state, success: true };
@@ -140,7 +142,7 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
return { stop: true, success: false };
}
- const result = await this.runtime.runCommand(params);
+ const result = await this.getRuntime(ctx).runCommand(params);
if (result.success) {
return { content: result.content, state: result.state, success: true };
@@ -169,7 +171,7 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
return { stop: true, success: false };
}
- const result = await this.runtime.exportFile(params);
+ const result = await this.getRuntime(ctx).exportFile(params);
if (result.success) {
return { content: result.content, state: result.state, success: true };
diff --git a/packages/mecha/src/toolSet/skillPool.test.ts b/packages/mecha/src/toolSet/skillPool.test.ts
index 083709ed9a3..d0daaf8d58f 100644
--- a/packages/mecha/src/toolSet/skillPool.test.ts
+++ b/packages/mecha/src/toolSet/skillPool.test.ts
@@ -49,7 +49,7 @@ describe('assembleSkillPool', () => {
db: [skill('my-skill')],
project: [skill('project:deploy', 'deploy')],
},
- { autoSkillIds: ['my-skill'] },
+ { autoSkillIds: ['my-skill', 'artifacts'] },
);
expect(pool.skills.map((s) => s.identifier)).toEqual([
'project:deploy',
@@ -64,10 +64,10 @@ describe('assembleSkillPool', () => {
{ builtin: [skill('artifacts')], db: [skill('gone'), skill('kept')] },
{ autoSkillIds: ['gone', 'kept'], disabledIds: ['gone'] },
);
- expect(pool.skills.map((s) => s.identifier)).toEqual(['kept', 'artifacts']);
+ expect(pool.skills.map((s) => s.identifier)).toEqual(['kept']);
});
- it('leaves out a library skill the agent never turned on, while builtin skills stay listed', () => {
+ it('leaves out a library skill the agent never turned on, including unselected builtin skills', () => {
const sources = {
agentSkills: [skill('agent-skills:notes')],
builtin: [skill('artifacts')],
@@ -83,17 +83,16 @@ describe('assembleSkillPool', () => {
'pinned',
'auto',
'agent-skills:notes',
- 'artifacts',
]);
- // Manual mode is still "only what the user picked": an `auto` library skill goes too.
+ // A saved auto entry is a user choice, including on legacy manual agents.
expect(
assembleSkillPool(sources, {
autoSkillIds: ['auto'],
enabledPluginIds: ['pinned'],
skillActivateMode: 'manual',
}).skills.map((s) => s.identifier),
- ).toEqual(['project:deploy', 'pinned']);
+ ).toEqual(['project:deploy', 'pinned', 'auto']);
});
it('withholds everything a share configuration does not allow', () => {
@@ -106,14 +105,20 @@ describe('assembleSkillPool', () => {
).toEqual(['shared']);
// An empty allowlist collapses the pool; no allowlist means no gate.
expect(assembleSkillPool(sources, { autoSkillIds, shareAllowedIds: [] }).skills).toEqual([]);
- expect(assembleSkillPool(sources, { autoSkillIds }).skills).toHaveLength(3);
+ expect(assembleSkillPool(sources, { autoSkillIds }).skills).toHaveLength(2);
});
it('gates the device-only builtin on the run, not on the host', () => {
const sources = { builtin: [skill(AgentBrowserIdentifier), skill('artifacts')] };
- expect(assembleSkillPool(sources).skills.map((s) => s.identifier)).toEqual(['artifacts']);
+ const autoSkillIds = [AgentBrowserIdentifier, 'artifacts'];
+ expect(assembleSkillPool(sources).skills).toEqual([]);
+ expect(assembleSkillPool(sources, { autoSkillIds }).skills.map((s) => s.identifier)).toEqual([
+ 'artifacts',
+ ]);
expect(
- assembleSkillPool(sources, { canExecuteOnDevice: true }).skills.map((s) => s.identifier),
+ assembleSkillPool(sources, { autoSkillIds, canExecuteOnDevice: true }).skills.map(
+ (s) => s.identifier,
+ ),
).toEqual([AgentBrowserIdentifier, 'artifacts']);
});
@@ -162,7 +167,6 @@ describe('assembleSkillPool', () => {
'project:deploy',
'picked',
'agent-skills:notes',
- 'artifacts',
]);
});
diff --git a/packages/mecha/src/toolSet/skillPool.ts b/packages/mecha/src/toolSet/skillPool.ts
index 7c6c64bc56b..ebd56187b98 100644
--- a/packages/mecha/src/toolSet/skillPool.ts
+++ b/packages/mecha/src/toolSet/skillPool.ts
@@ -24,12 +24,7 @@ export interface SkillPoolSources {
}
export interface AssembleSkillPoolOptions {
- /**
- * Library (`db`) skills the agent set to `auto`. A library skill is opt-in
- * per agent β€” the profile is where one is turned on β€” so unlike every other
- * source it is listed only when named here, in `enabledPluginIds` or in
- * `turnSkillIds`. `manual` mode still narrows it to the latter two.
- */
+ /** Builtin and library skills explicitly enabled for on-demand loading. */
autoSkillIds?: readonly string[];
/** Gates the device-only builtin skills. */
canExecuteOnDevice?: boolean;
@@ -86,21 +81,17 @@ export const assembleSkillPool = (
)
: (skills: readonly SkillMeta[] = []) => skills;
- // A library skill the agent never turned on is disabled for it, whatever the
- // mode: installing a skill into the library does not hand it to every agent.
- const autoSkillIds = new Set(options.autoSkillIds ?? []);
- const optedIn = (sources.db ?? []).filter(
- (skill) =>
- enabledPluginIds.has(skill.identifier) ||
- autoSkillIds.has(skill.identifier) ||
- turnSkillIds.has(skill.identifier),
- );
+ // Profile-managed skills are opt-in. A legacy pin and explicit auto both
+ // make a skill discoverable, even on agents with the old manual setting.
+ const on = new Set([...enabledPluginIds, ...turnSkillIds, ...(options.autoSkillIds ?? [])]);
+ const offered = (skills: readonly SkillMeta[] = []) =>
+ skills.filter((skill) => on.has(skill.identifier));
const ordered = [
...(sources.project ?? []),
- ...selectable(optedIn),
+ ...offered(sources.db),
...selectable(sources.agentSkills),
- ...selectable(sources.builtin),
+ ...offered(sources.builtin),
];
const disabled = new Set(options.disabledIds ?? []);
const shareAllowed = options.shareAllowedIds ? new Set(options.shareAllowedIds) : undefined;
diff --git a/packages/types/src/agent/pluginConfig.test.ts b/packages/types/src/agent/pluginConfig.test.ts
index d338291f15c..820f8a2b6da 100644
--- a/packages/types/src/agent/pluginConfig.test.ts
+++ b/packages/types/src/agent/pluginConfig.test.ts
@@ -161,7 +161,7 @@ describe('library skills', () => {
});
it('resolves the explicit mode of a library skill the agent has an entry for', () => {
- expect(getLibrarySkillMode(['excalidraw'], 'excalidraw')).toBe('pinned');
+ expect(getLibrarySkillMode(['excalidraw'], 'excalidraw')).toBe('auto');
expect(getLibrarySkillMode([{ identifier: 'excalidraw', mode: 'auto' }], 'excalidraw')).toBe(
'auto',
);
diff --git a/packages/types/src/agent/pluginConfig.ts b/packages/types/src/agent/pluginConfig.ts
index 2be0a1a1a7f..d09184e2d6b 100644
--- a/packages/types/src/agent/pluginConfig.ts
+++ b/packages/types/src/agent/pluginConfig.ts
@@ -62,22 +62,15 @@ export const getPluginMode = (
return entry ? parsePluginEntry(entry).mode : 'auto';
};
-/**
- * Library skills β€” the ones a user installs from the market or authors
- * themselves β€” are opt-in per agent. The agent's profile is where one is
- * turned on, so a library skill the agent has no entry for is `'disabled'`
- * there, not the implicit `'auto'` every other plugin kind resolves to.
- * Builtin skills, tools and connectors keep {@link getPluginMode}.
- */
-export const LIBRARY_SKILL_IMPLICIT_MODE: AgentPluginMode = 'disabled';
+/** Profile-managed skills are off without an entry and loaded on demand when on. */
+export const LIBRARY_SKILL_IMPLICIT_MODE = 'disabled' as const;
-/** A library skill's mode for this agent; see {@link LIBRARY_SKILL_IMPLICIT_MODE}. */
export const getLibrarySkillMode = (
plugins: AgentPluginEntry[] | undefined,
identifier: string,
-): AgentPluginMode => {
+): 'auto' | 'disabled' => {
const entry = plugins?.find((item) => parsePluginEntry(item).identifier === identifier);
- return entry ? parsePluginEntry(entry).mode : LIBRARY_SKILL_IMPLICIT_MODE;
+ return entry && parsePluginEntry(entry).mode !== 'disabled' ? 'auto' : 'disabled';
};
/**
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index db867816c7a..bbbca8a51c5 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -736,6 +736,9 @@ export interface BuiltinToolContext {
*/
subAgent?: SubAgentCallbacks;
+ /** Agent whose profile is used for this run when it differs from the conversation owner. */
+ subAgentId?: string;
+
/**
* Current task identifier or database id when the conversation is scoped to a task detail page.
*/
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsx
index b1b76795192..6effe48d222 100644
--- a/src/features/ProfileEditor/AgentTool.tsx
+++ b/src/features/ProfileEditor/AgentTool.tsx
@@ -245,6 +245,15 @@ const AgentTool = memo<AgentToolProps>(
if (!isConnectorsInit) fetchConnectors();
}, [isConnectorsInit, fetchConnectors]);
+ // Get all skill identifiers (used to filter the builtin list)
+ const allSkillIdentifiers = useMemo(() => {
+ const ids = new Set<string>();
+ for (const s of installedBuiltinSkills) ids.add(s.identifier);
+ for (const s of marketAgentSkills) ids.add(s.identifier);
+ for (const s of userAgentSkills) ids.add(s.identifier);
+ return ids;
+ }, [installedBuiltinSkills, marketAgentSkills, userAgentSkills]);
+
// Toggle a plugin - use byId action
const togglePlugin = useCallback(
async (pluginId: string, state?: boolean) => {
@@ -264,12 +273,23 @@ const AgentTool = memo<AgentToolProps>(
// dropped from the array.
await updateAgentConfigById(effectiveAgentId, {
plugins:
- shouldEnable && (connectorIds.has(pluginId) || isOnDemandBuiltinTool(pluginId))
+ shouldEnable &&
+ (allSkillIdentifiers.has(pluginId) ||
+ connectorIds.has(pluginId) ||
+ isOnDemandBuiltinTool(pluginId))
? upsertConnectorEnabled(config?.plugins, pluginId, true)
: upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),
});
},
- [canEdit, effectiveAgentId, enabledIds, connectorIds, config?.plugins, updateAgentConfigById],
+ [
+ canEdit,
+ effectiveAgentId,
+ enabledIds,
+ connectorIds,
+ allSkillIdentifiers,
+ config?.plugins,
+ updateAgentConfigById,
+ ],
);
// Check if a profile-managed tool is on for this agent.
@@ -316,15 +336,6 @@ const AgentTool = memo<AgentToolProps>(
[connectorCatalog],
);
- // Get all skill identifiers (used to filter the builtin list)
- const allSkillIdentifiers = useMemo(() => {
- const ids = new Set<string>();
- for (const s of installedBuiltinSkills) ids.add(s.identifier);
- for (const s of marketAgentSkills) ids.add(s.identifier);
- for (const s of userAgentSkills) ids.add(s.identifier);
- return ids;
- }, [installedBuiltinSkills, marketAgentSkills, userAgentSkills]);
-
// Filter out Composio tools and skills from profileBuiltinList (they are displayed separately)
// Optionally filter out tools with availableInWeb: false based on config (e.g., LocalSystem is desktop-only)
const filteredBuiltinList = useMemo(() => {
@@ -912,7 +923,9 @@ const AgentTool = memo<AgentToolProps>(
if (!canEdit || !effectiveAgentId) return;
return updateAgentConfigById(effectiveAgentId, {
plugins:
- connectorIds.has(pluginId) || isOnDemandBuiltinTool(pluginId)
+ allSkillIdentifiers.has(pluginId) ||
+ connectorIds.has(pluginId) ||
+ isOnDemandBuiltinTool(pluginId)
? upsertConnectorEnabled(config?.plugins, pluginId, enabled)
: upsertPluginMode(config?.plugins, pluginId, enabled ? 'pinned' : 'disabled'),
});
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 59474ec5393..ffa0b276d38 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -1258,8 +1258,8 @@ describe('ChatService', () => {
role: 'system',
}),
);
- expect(requestMessages[0].content).toContain('<available_skills>');
- expect(requestMessages[0].content).toContain(
+ expect(requestMessages[0].content).not.toContain('<available_skills>');
+ expect(requestMessages[0].content).not.toContain(
'Use the activateSkill tool to activate a skill when needed.',
);
expect(requestMessages[0].content).toContain('<tool name="SEO">');
@@ -1342,7 +1342,7 @@ describe('ChatService', () => {
role: 'system',
}),
);
- expect(requestMessages[0].content).toContain('<available_skills>');
+ expect(requestMessages[0].content).not.toContain('<available_skills>');
expect(requestMessages[0].content).toContain('<tool name="SEO">');
expect(requestMessages[1]).toEqual(
expect.objectContaining({
@@ -1394,7 +1394,7 @@ describe('ChatService', () => {
role: 'system',
}),
);
- expect(requestMessages[0].content).toContain('<available_skills>');
+ expect(requestMessages[0].content).not.toContain('<available_skills>');
expect(requestMessages[0].content).not.toContain('<tool name="SEO">');
expect(requestMessages[1]).toEqual(
expect.objectContaining({
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index c805425fe44..ee4a5a8a0a0 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -306,9 +306,7 @@ export const contextEngineering = async ({
createBrowserContextFactProviders({ agentId, groupId, shareVisitor }),
);
- // 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).
+ // Profile skill choices contribute discovery metadata only.
let enabledSkills: OperationSkillSet['skills'] | undefined;
if (plugins) {
// Manual mode narrows the pool itself, so an unselected skill is neither
diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.ts
index c6d98274b87..e40b6a1b9c7 100644
--- a/src/services/chat/mecha/skillEngineering.test.ts
+++ b/src/services/chat/mecha/skillEngineering.test.ts
@@ -58,74 +58,33 @@ describe('resolveClientSkills', () => {
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.each(['legacy pin', 'auto'])(
+ 'lists an enabled %s without loading either body',
+ async (mode) => {
+ setToolState({
+ agentSkills: [
+ { description: 'installed', id: 'db-1', identifier: 'my-skill', name: 'Mine' },
+ ],
+ builtinSkills: [
+ { content: 'guide', description: 'builtin', identifier: 'artifacts', name: 'Artifacts' },
+ ],
+ });
+ const ids = ['my-skill', 'artifacts'];
+ const result = await resolveClientSkills(
+ mode === 'legacy pin' ? ids : [],
+ [],
+ 'auto',
+ [],
+ mode === 'auto' ? ids : [],
+ );
+ expect(result.skills.map((s) => [s.name, s.description])).toEqual([
+ ['Mine', 'installed'],
+ ['Artifacts', 'builtin'],
+ ]);
+ expect(result.skills.every((s) => !s.content && !s.activated)).toBe(true);
+ expect(mockedGetById).not.toHaveBeenCalled();
+ },
+ );
it('does NOT fetch content for non-pinned DB skills (auto mode bulk exposure)', async () => {
setToolState({
@@ -144,7 +103,7 @@ describe('resolveClientSkills', () => {
expect(skill?.activated).toBeFalsy();
});
- it('leaves out a library skill the agent never turned on, keeping builtin skills', async () => {
+ it('leaves out a library skill the agent never turned on, including builtin skills', async () => {
setToolState({
agentSkills: [
{ description: 'A user skill', id: 'db-1', identifier: 'my-skill', name: 'My Skill' },
@@ -157,7 +116,7 @@ describe('resolveClientSkills', () => {
const result = await resolveClientSkills([]);
expect(findSkill(result.skills, 'my-skill')).toBeUndefined();
- expect(findSkill(result.skills, 'artifacts')).toBeDefined();
+ expect(findSkill(result.skills, 'artifacts')).toBeUndefined();
});
it('does NOT pre-activate a pinned DB skill bundled as a ZIP', async () => {
@@ -183,38 +142,6 @@ describe('resolveClientSkills', () => {
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();
- });
-
it('keeps a turn skill selectable in manual mode without pinning it', async () => {
setToolState({
builtinSkills: [
@@ -230,7 +157,7 @@ describe('resolveClientSkills', () => {
const result = await resolveClientSkills([], [], 'manual', ['lobehub']);
expect(result.enabledPluginIds).toEqual([]);
- expect(findSkill(result.skills, 'lobehub')).toMatchObject({ activated: false });
+ expect(findSkill(result.skills, 'lobehub')).toMatchObject({ name: 'lobehub' });
});
describe('agent skill list loading', () => {
@@ -257,7 +184,7 @@ describe('resolveClientSkills', () => {
ensureAgentSkillsLoaded: vi.fn().mockRejectedValue(new Error('network down')),
});
- const result = await resolveClientSkills();
+ const result = await resolveClientSkills(['artifacts']);
expect(findSkill(result.skills, 'artifacts')).toBeDefined();
});
diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.ts
index fda42e89fad..6af1a2ac8df 100644
--- a/src/services/chat/mecha/skillEngineering.ts
+++ b/src/services/chat/mecha/skillEngineering.ts
@@ -1,48 +1,15 @@
import { isDesktop } from '@lobechat/const';
import type { OperationSkillSet } from '@lobechat/context-engine';
import { assembleSkillPool } from '@lobechat/mecha';
-import { resourcesTreePrompt } from '@lobechat/prompts';
-import type { SkillItem } from '@lobechat/types';
import debug from 'debug';
-import { agentSkillService } from '@/services/skill';
import { getToolStoreState } from '@/store/tool';
import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';
import { loadBuiltinSkills } from '@/store/tool/slices/builtin/loadBuiltinSkills';
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.
- *
- * Sources:
- * 1. Builtin skills (e.g., Artifacts) - from toolStore.builtinSkills
- * 2. DB skills (user/market) - from the `agentSkillList` replica; opt-in per
- * agent, so only the ones it pinned or set to `auto` make the pool
- *
- * 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.
- *
- * Platform-specific skills (e.g. agent-browser on desktop only) are filtered
- * by the shared rule, which the desktop client satisfies by being the
- * execution device itself.
- */
+/** Build the discoverable catalog without fetching any skill bodies. */
export const resolveClientSkills = async (
pluginIds?: string[],
disabledIds?: string[],
@@ -65,63 +32,16 @@ export const resolveClientSkills = async (
}
const toolState = getToolStoreState();
- const pinnedIds = new Set(pluginIds ?? []);
- const disabledIdSet = new Set(disabledIds ?? []);
-
- // Pinned skills are marked `activated` so SkillContextProvider injects their
- // content directly; non-pinned ones stay in <available_skills>. Disabled
- // skills are dropped from the candidate pool entirely β€” not just left
- // unpinned β€” so a disabled skill is neither listed nor resolvable by name via
- // `activateSkill`.
- const builtinMetas = (await loadBuiltinSkills())
- .filter((s) => !disabledIdSet.has(s.identifier))
- .map((s) => ({
- activated: pinnedIds.has(s.identifier) && !!s.content,
- content: s.content,
- description: s.description,
- identifier: s.identifier,
- name: s.name,
- }));
-
- const dbMetas = await Promise.all(
- agentSkillsSelectors
- .getAgentSkills(toolState)
- .filter((s) => !disabledIdSet.has(s.identifier))
- .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 =
- agentSkillsSelectors.getAgentSkillDetail(s.id)(toolState) ??
- (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 builtinMetas = (await loadBuiltinSkills()).map(({ description, identifier, name }) => ({
+ description,
+ identifier,
+ name,
+ }));
+ const dbMetas = agentSkillsSelectors.getAgentSkills(toolState).map((skill) => ({
+ description: skill.description ?? '',
+ identifier: skill.identifier,
+ name: skill.name,
+ }));
// Precedence, name dedupe and the device-only builtin gate are the shared
// rules; the browser scans no project directory and mounts no
@@ -130,6 +50,7 @@ export const resolveClientSkills = async (
{ builtin: builtinMetas, db: dbMetas },
{
autoSkillIds,
+ disabledIds,
// The desktop app is itself the execution device.
canExecuteOnDevice: isDesktop,
enabledPluginIds: pluginIds,
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 1f30b2e55b6..d0c6ba891ab 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -218,6 +218,7 @@ export class PluginTypesActionImpl {
rootRuntimeOperationContext?.messageId,
stepContext,
subAgent,
+ subAgentId: operation?.context?.subAgentId ?? rootRuntimeOperationContext?.subAgentId,
taskId,
threadId,
toolCallId: payload.id,
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.test.ts
index 41a27c9fb24..d1cc3ec79e8 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.test.ts
@@ -7,11 +7,78 @@ import { skillsExecutor } from '../lobe-skills';
vi.mock('@lobechat/builtin-skills', () => ({ builtinSkills: [] }));
vi.mock('@/helpers/skillFilters', () => ({ filterBuiltinSkills: () => [] }));
vi.mock('@/services/cloudSandbox', () => ({ cloudSandboxService: { callTool: vi.fn() } }));
-vi.mock('@/services/skill', () => ({ agentSkillService: {} }));
+vi.mock('@/services/skill', () => ({
+ agentSkillService: {
+ getByName: async (name: string) => ({ id: name, identifier: name }),
+ readResource: async (id: string) => ({ content: `Reference for ${id}` }),
+ },
+}));
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => ({
+ agentMap: {
+ member: { plugins: ['member-skill'] },
+ supervisor: { plugins: ['supervisor-skill'] },
+ },
+ }),
+}));
vi.mock('@/store/chat', () => ({
+ getChatStoreState: () => ({
+ dbMessagesMap: {
+ group_agent_group_topic_member: [
+ { metadata: { selectedSkillIds: ['selected-skill'] }, role: 'user' },
+ ],
+ main_agent_topic: [{ metadata: { selectedSkillIds: ['main-skill'] }, role: 'user' }],
+ page_agent_doc: [
+ {
+ editorData: {
+ root: {
+ children: [{ actionCategory: 'skill', actionType: 'page-skill', type: 'action-tag' }],
+ },
+ },
+ role: 'user',
+ },
+ ],
+ task_agent_topic: [{ metadata: { selectedSkillIds: ['task-skill'] }, role: 'user' }],
+ },
+ }),
useChatStore: { getState: () => ({ activeTopicId: 'test-topic' }) },
}));
+describe('Web Skills conversation selection', () => {
+ it('uses the group member profile and selections from its conversation', async () => {
+ const context = {
+ agentId: 'supervisor',
+ groupId: 'group',
+ messageId: 'message',
+ scope: 'group_agent',
+ subAgentId: 'member',
+ topicId: 'topic',
+ };
+ const read = (id: string) =>
+ skillsExecutor.invoke('readReference', { id, path: 'guide.md' }, context);
+
+ expect(await read('member-skill')).toMatchObject({ success: true });
+ expect(await read('supervisor-skill')).toMatchObject({ success: false });
+ expect(await read('selected-skill')).toMatchObject({ success: true });
+ });
+
+ it.each([
+ { scope: 'task', topicId: 'topic' },
+ { documentId: 'doc', scope: 'page' },
+ ])('reads a reference selected in the $scope conversation', async (context) => {
+ const id = `${context.scope}-skill`;
+ const read = (skill: string) =>
+ skillsExecutor.invoke(
+ 'readReference',
+ { id: skill, path: 'guide.md' },
+ { ...context, agentId: 'agent', messageId: 'message' },
+ );
+
+ expect(await read(id)).toMatchObject({ content: `Reference for ${id}`, success: true });
+ expect(await read('main-skill')).toMatchObject({ success: false });
+ });
+});
+
describe.each(['runCommand', 'execScript'] as const)('Web Skills %s recreation', (api) => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/src/store/tool/slices/builtin/executors/clientSkillCatalog.ts b/src/store/tool/slices/builtin/executors/clientSkillCatalog.ts
new file mode 100644
index 00000000000..4fb4a04828c
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/clientSkillCatalog.ts
@@ -0,0 +1,74 @@
+import { builtinSkills } from '@lobechat/builtin-skills';
+import { LobeHubIdentifier } from '@lobechat/builtin-skills/manifests';
+import type { SkillRuntimeService } from '@lobechat/builtin-tool-skills/executionRuntime';
+import { mentionsTopic } from '@lobechat/context-engine';
+import {
+ type BuiltinToolContext,
+ getDisabledPluginIds,
+ getLibrarySkillMode,
+ type MessageMapScope,
+} from '@lobechat/types';
+
+import { filterBuiltinSkills } from '@/helpers/skillFilters';
+import { agentSkillService } from '@/services/skill';
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { getChatStoreState } from '@/store/chat';
+import { parseSelectedSkillsFromEditorData } from '@/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+/** Bind both name lookup and the fallback catalog to the calling agent, not the active tab. */
+export const clientSkillCatalog = (ctx: BuiltinToolContext) => {
+ const { agentId, subAgentId } = ctx;
+ const profileAgentId = subAgentId ?? agentId;
+ const plugins = profileAgentId
+ ? agentSelectors.getAgentConfigById(profileAgentId)(getAgentStoreState())?.plugins
+ : undefined;
+ const messages = agentId
+ ? (getChatStoreState().dbMessagesMap[
+ messageMapKey({
+ agentId,
+ documentId: ctx.documentId ?? undefined,
+ groupId: ctx.groupId,
+ scope: (ctx.scope ?? undefined) as MessageMapScope | undefined,
+ subAgentId,
+ threadId: ctx.threadId ?? undefined,
+ topicId: ctx.topicId,
+ })
+ ] ?? [])
+ : [];
+ const userTurns = messages.filter((message) => message.role === 'user');
+ const selected = new Set(
+ userTurns.flatMap(
+ (message) =>
+ message.metadata?.selectedSkillIds ??
+ parseSelectedSkillsFromEditorData(message.editorData ?? undefined).map(
+ (skill) => skill.identifier,
+ ),
+ ),
+ );
+ if (mentionsTopic(userTurns)) selected.add(LobeHubIdentifier);
+ const disabled = new Set(getDisabledPluginIds(plugins));
+ const offered = (id: string) =>
+ !disabled.has(id) && (selected.has(id) || getLibrarySkillMode(plugins, id) !== 'disabled');
+ const lookup: Pick<SkillRuntimeService, 'findAll' | 'findById' | 'findByName'> = {
+ findAll: async () => {
+ const { data } = await agentSkillService.list();
+ const skills = data.filter((skill) => offered(skill.identifier));
+ return { data: skills, total: skills.length };
+ },
+ findById: async (id) => {
+ const skill = await agentSkillService.getById(id);
+ return skill && offered(skill.identifier) ? skill : undefined;
+ },
+ findByName: async (name) => {
+ const skill = await agentSkillService.getByName(name);
+ return skill && offered(skill.identifier) ? skill : undefined;
+ },
+ };
+
+ return {
+ builtinSkills: filterBuiltinSkills(builtinSkills).filter((skill) => offered(skill.identifier)),
+ lookup,
+ };
+};
diff --git a/src/store/tool/slices/builtin/executors/lobe-activator.ts b/src/store/tool/slices/builtin/executors/lobe-activator.ts
index b2ceb4a58bd..88a08b046c7 100644
--- a/src/store/tool/slices/builtin/executors/lobe-activator.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-activator.ts
@@ -9,7 +9,6 @@
* because the activated state is persisted in message pluginState and accumulated
* by selectActivatedToolIdsFromMessages at each agentic loop step.
*/
-import { builtinSkills } from '@lobechat/builtin-skills';
import {
ActivatorExecutionRuntime,
type ActivatorRuntimeService,
@@ -17,8 +16,8 @@ import {
} from '@lobechat/builtin-tool-activator/executionRuntime';
import { ActivatorExecutor } from '@lobechat/builtin-tool-activator/executor';
import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';
+import type { BuiltinToolContext } from '@lobechat/types';
-import { filterBuiltinSkills } from '@/helpers/skillFilters';
import { agentSkillService } from '@/services/skill';
import { getToolStoreState } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/selectors';
@@ -26,18 +25,9 @@ import { toolSelectors } from '@/store/tool/selectors/tool';
import { composioStoreSelectors } from '@/store/tool/slices/composioStore/selectors';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore';
-const skillsRuntime = new SkillsExecutionRuntime({
- builtinSkills: filterBuiltinSkills(builtinSkills),
- service: {
- findAll: () => agentSkillService.list(),
- findById: (id) => agentSkillService.getById(id),
- findByName: (name) => agentSkillService.getByName(name),
- readResource: (id, path) => agentSkillService.readResource(id, path),
- },
-});
+import { clientSkillCatalog } from './clientSkillCatalog';
const service: ActivatorRuntimeService = {
- activateSkill: (args) => skillsRuntime.activateSkill(args),
getActivatedToolIds: () => [],
getToolManifests: async (identifiers: string[]): Promise<ToolManifestInfo[]> => {
const s = getToolStoreState();
@@ -169,6 +159,21 @@ const service: ActivatorRuntimeService = {
markActivated: () => {},
};
-const runtime = new ActivatorExecutionRuntime({ service });
+const runtime = (ctx: BuiltinToolContext) =>
+ new ActivatorExecutionRuntime({
+ service: {
+ ...service,
+ activateSkill: (args) => {
+ const { builtinSkills, lookup } = clientSkillCatalog(ctx);
+ return new SkillsExecutionRuntime({
+ builtinSkills,
+ service: {
+ ...lookup,
+ readResource: (id, path) => agentSkillService.readResource(id, path),
+ },
+ }).activateSkill(args);
+ },
+ },
+ });
export const activatorExecutor = new ActivatorExecutor(runtime);
diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
index 7ec38e68ecc..6b4a622ca36 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
@@ -4,75 +4,77 @@
* Desktop version: all commands run locally via localFileService.
* No cloud sandbox, no exportFile.
*/
-import { builtinSkills } from '@lobechat/builtin-skills';
import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';
import { SkillsExecutor } from '@lobechat/builtin-tool-skills/executor';
+import type { BuiltinToolContext } from '@lobechat/types';
-import { filterBuiltinSkills } from '@/helpers/skillFilters';
import { desktopSkillRuntimeService } from '@/services/electron/desktopSkillRuntime';
import { localFileService } from '@/services/electron/localFileService';
import { agentSkillService } from '@/services/skill';
-const runtime = new SkillsExecutionRuntime({
- builtinSkills: filterBuiltinSkills(builtinSkills),
- service: {
- execScript: async (command, options) => {
- const skillDir = await desktopSkillRuntimeService.resolveExecutionDirectory(
- options.activatedSkills,
- );
- // A Local Sandbox run is fenced to the agent's working directory, never
- // to the skill directory: that is the device's shared skill cache, and a
- // writable cache would let a fenced run plant code a later unfenced run
- // executes. The script still starts in its skill directory (reads are not
- // fenced). Unfenced runs keep the historical skill-directory-only cwd.
- if (options.localSandbox && !options.workingDirectory) {
+import { clientSkillCatalog } from './clientSkillCatalog';
+
+const runtime = (ctx: BuiltinToolContext) => {
+ const { builtinSkills, lookup } = clientSkillCatalog(ctx);
+ return new SkillsExecutionRuntime({
+ builtinSkills,
+ service: {
+ execScript: async (command, options) => {
+ const skillDir = await desktopSkillRuntimeService.resolveExecutionDirectory(
+ options.activatedSkills,
+ );
+ // A Local Sandbox run is fenced to the agent's working directory, never
+ // to the skill directory: that is the device's shared skill cache, and a
+ // writable cache would let a fenced run plant code a later unfenced run
+ // executes. The script still starts in its skill directory (reads are not
+ // fenced). Unfenced runs keep the historical skill-directory-only cwd.
+ if (options.localSandbox && !options.workingDirectory) {
+ return {
+ executionEnv: 'device' as const,
+ exitCode: 1,
+ output: '',
+ stderr:
+ 'Local Sandbox requires a working directory. Set one for this agent (or topic) and run the command again.',
+ success: false,
+ };
+ }
+ const result = await localFileService.runCommand({
+ command,
+ cwd: options.localSandbox ? (skillDir ?? options.workingDirectory) : skillDir,
+ description: options.description,
+ ...(options.localSandbox && {
+ sandbox: true,
+ sandboxNetwork: options.localSandboxNetwork === true,
+ sandboxRoot: options.workingDirectory,
+ }),
+ timeout: undefined,
+ });
return {
+ // Desktop commands run on the user's machine β€” stamp the execution env
+ // so the file-edit scanner treats produced files as device-local (the
+ // server runtime stamps the same field for gateway-dispatched runs).
executionEnv: 'device' as const,
- exitCode: 1,
- output: '',
- stderr:
- 'Local Sandbox requires a working directory. Set one for this agent (or topic) and run the command again.',
- success: false,
+ exitCode: result.exit_code ?? 1,
+ output: result.stdout || result.output || '',
+ stderr: result.stderr,
+ success: result.success,
};
- }
- const result = await localFileService.runCommand({
- command,
- cwd: options.localSandbox ? (skillDir ?? options.workingDirectory) : skillDir,
- description: options.description,
- ...(options.localSandbox && {
- sandbox: true,
- sandboxNetwork: options.localSandboxNetwork === true,
- sandboxRoot: options.workingDirectory,
- }),
- timeout: undefined,
- });
- return {
- // Desktop commands run on the user's machine β€” stamp the execution env
- // so the file-edit scanner treats produced files as device-local (the
- // server runtime stamps the same field for gateway-dispatched runs).
- executionEnv: 'device' as const,
- exitCode: result.exit_code ?? 1,
- output: result.stdout || result.output || '',
- stderr: result.stderr,
- success: result.success,
- };
- },
- findAll: () => agentSkillService.list(),
- findById: (id) => agentSkillService.getById(id),
- findByName: (name) => agentSkillService.getByName(name),
- readResource: async (id, path) => {
- const resource = await agentSkillService.readResource(id, path);
- const fullPath = await desktopSkillRuntimeService.resolveReferenceFullPath({
- path,
- skillId: id,
- });
+ },
+ ...lookup,
+ readResource: async (id, path) => {
+ const resource = await agentSkillService.readResource(id, path);
+ const fullPath = await desktopSkillRuntimeService.resolveReferenceFullPath({
+ path,
+ skillId: id,
+ });
- return {
- ...resource,
- fullPath,
- };
+ return {
+ ...resource,
+ fullPath,
+ };
+ },
},
- },
-});
+ });
+};
export const skillsExecutor = new SkillsExecutor(runtime);
diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.ts b/src/store/tool/slices/builtin/executors/lobe-skills.ts
index 4a7e83d6218..b55500c6ff3 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skills.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skills.ts
@@ -4,159 +4,161 @@
* Creates and exports the SkillsExecutor instance for registration.
* Injects agentSkillService as dependency.
*/
-import { builtinSkills } from '@lobechat/builtin-skills';
import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';
import { SkillsExecutor } from '@lobechat/builtin-tool-skills/executor';
+import type { BuiltinToolContext } from '@lobechat/types';
-import { filterBuiltinSkills } from '@/helpers/skillFilters';
import { cloudSandboxService } from '@/services/cloudSandbox';
import { agentSkillService } from '@/services/skill';
import { useChatStore } from '@/store/chat';
+import { clientSkillCatalog } from './clientSkillCatalog';
+
// Create runtime with client-side service
-const runtime = new SkillsExecutionRuntime({
- builtinSkills: filterBuiltinSkills(builtinSkills),
- service: {
- execScript: async (command, options) => {
- const { activatedSkills, description } = options;
+const runtime = (ctx: BuiltinToolContext) => {
+ const { builtinSkills, lookup } = clientSkillCatalog(ctx);
+ return new SkillsExecutionRuntime({
+ builtinSkills,
+ service: {
+ execScript: async (command, options) => {
+ const { activatedSkills, description } = options;
+
+ // Cloud: execute via Cloud Sandbox with execScript tool
+ // Server will resolve zipUrls for all activatedSkills
+ const chatState = useChatStore.getState();
+ const topicId = chatState.activeTopicId || 'default';
+
+ try {
+ // Call cloud sandbox execScript tool
+ const result = await cloudSandboxService.callTool(
+ 'execScript',
+ {
+ activatedSkills,
+ command,
+ description,
+ },
+ { topicId },
+ );
- // Cloud: execute via Cloud Sandbox with execScript tool
- // Server will resolve zipUrls for all activatedSkills
- const chatState = useChatStore.getState();
- const topicId = chatState.activeTopicId || 'default';
+ if (!result.success) {
+ return {
+ executionEnv: 'sandbox' as const,
+ exitCode: 1,
+ output: '',
+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
+ stderr: result.error?.message || 'Command execution failed',
+ success: false,
+ };
+ }
- try {
- // Call cloud sandbox execScript tool
- const result = await cloudSandboxService.callTool(
- 'execScript',
- {
- activatedSkills,
- command,
- description,
- },
- { topicId },
- );
+ const sandboxResult = result.result || {};
- if (!result.success) {
+ return {
+ // Web-client commands execute in the cloud sandbox β€” stamp the
+ // execution env so the file-edit scanner excludes these rows
+ // (sandbox delivery goes through exportFile, not the card), matching
+ // the server runtime's stamping.
+ executionEnv: 'sandbox' as const,
+ exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
+ output: sandboxResult.stdout || sandboxResult.output || '',
+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
+ stderr: sandboxResult.stderr || '',
+ success:
+ result.success &&
+ (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),
+ };
+ } catch (error) {
return {
executionEnv: 'sandbox' as const,
exitCode: 1,
output: '',
- ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
- stderr: result.error?.message || 'Command execution failed',
+ stderr: (error as Error).message || 'Command execution failed',
success: false,
};
}
+ },
+ exportFile: async (path, filename) => {
+ // Get current session context
+ const chatState = useChatStore.getState();
+ const topicId = chatState.activeTopicId || 'default';
- const sandboxResult = result.result || {};
+ try {
+ // Call cloud sandbox exportAndUploadFile
+ const result = await cloudSandboxService.exportAndUploadFile(path, filename, topicId);
- return {
- // Web-client commands execute in the cloud sandbox β€” stamp the
- // execution env so the file-edit scanner excludes these rows
- // (sandbox delivery goes through exportFile, not the card), matching
- // the server runtime's stamping.
- executionEnv: 'sandbox' as const,
- exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
- output: sandboxResult.stdout || sandboxResult.output || '',
- ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
- stderr: sandboxResult.stderr || '',
- success:
- result.success &&
- (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),
- };
- } catch (error) {
- return {
- executionEnv: 'sandbox' as const,
- exitCode: 1,
- output: '',
- stderr: (error as Error).message || 'Command execution failed',
- success: false,
- };
- }
- },
- exportFile: async (path, filename) => {
- // Get current session context
- const chatState = useChatStore.getState();
- const topicId = chatState.activeTopicId || 'default';
+ return {
+ fileId: result.fileId,
+ filename: result.filename,
+ mimeType: result.mimeType,
+ size: result.size,
+ success: result.success,
+ url: result.url,
+ };
+ } catch {
+ return {
+ filename,
+ success: false,
+ };
+ }
+ },
+ ...lookup,
+ readResource: (id, path) => agentSkillService.readResource(id, path),
+ runCommand: async ({ command, timeout }) => {
+ // Cloud: execute via Cloud Sandbox
+ // Get current session context for sandbox isolation
+ const chatState = useChatStore.getState();
+ const topicId = chatState.activeTopicId || 'default';
- try {
- // Call cloud sandbox exportAndUploadFile
- const result = await cloudSandboxService.exportAndUploadFile(path, filename, topicId);
+ try {
+ // Call cloud sandbox via TRPC
+ // Note: userId is automatically set by server from authenticated context
+ const result = await cloudSandboxService.callTool(
+ 'runCommand',
+ {
+ command,
+ description: `Execute skill command: ${command.slice(0, 100)}${command.length > 100 ? '...' : ''}`,
+ timeout,
+ },
+ { topicId },
+ );
- return {
- fileId: result.fileId,
- filename: result.filename,
- mimeType: result.mimeType,
- size: result.size,
- success: result.success,
- url: result.url,
- };
- } catch {
- return {
- filename,
- success: false,
- };
- }
- },
- findAll: () => agentSkillService.list(),
- findById: (id) => agentSkillService.getById(id),
- findByName: (name) => agentSkillService.getByName(name),
- readResource: (id, path) => agentSkillService.readResource(id, path),
- runCommand: async ({ command, timeout }) => {
- // Cloud: execute via Cloud Sandbox
- // Get current session context for sandbox isolation
- const chatState = useChatStore.getState();
- const topicId = chatState.activeTopicId || 'default';
+ if (!result.success) {
+ return {
+ executionEnv: 'sandbox' as const,
+ exitCode: 1,
+ output: '',
+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
+ stderr: result.error?.message || 'Command execution failed',
+ success: false,
+ };
+ }
- try {
- // Call cloud sandbox via TRPC
- // Note: userId is automatically set by server from authenticated context
- const result = await cloudSandboxService.callTool(
- 'runCommand',
- {
- command,
- description: `Execute skill command: ${command.slice(0, 100)}${command.length > 100 ? '...' : ''}`,
- timeout,
- },
- { topicId },
- );
+ // Parse cloud sandbox result
+ const sandboxResult = result.result || {};
- if (!result.success) {
+ return {
+ executionEnv: 'sandbox' as const,
+ exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
+ output: sandboxResult.stdout || sandboxResult.output || '',
+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
+ stderr: sandboxResult.stderr || '',
+ success:
+ result.success &&
+ (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),
+ };
+ } catch (error) {
return {
executionEnv: 'sandbox' as const,
exitCode: 1,
output: '',
- ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
- stderr: result.error?.message || 'Command execution failed',
+ stderr: (error as Error).message || 'Command execution failed',
success: false,
};
}
-
- // Parse cloud sandbox result
- const sandboxResult = result.result || {};
-
- return {
- executionEnv: 'sandbox' as const,
- exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
- output: sandboxResult.stdout || sandboxResult.output || '',
- ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
- stderr: sandboxResult.stderr || '',
- success:
- result.success &&
- (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),
- };
- } catch (error) {
- return {
- executionEnv: 'sandbox' as const,
- exitCode: 1,
- output: '',
- stderr: (error as Error).message || 'Command execution failed',
- success: false,
- };
- }
+ },
},
- },
-});
+ });
+};
// Create executor instance with the runtime
export const skillsExecutor = new SkillsExecutor(runtime);