Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(skill): make library skills opt-in per agent (#23188)

AmAzing-ce9b3a6b9266
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 7077e71f583..5662ae1110a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -317,6 +317,7 @@ export class ServerToolTransport implements ToolTransport {
projectId: context.state.origin?.projectId,
projectSkills: resolveRunProjectSkills(context.state.plan),
rootOperationId: operationId,
+ runSkillIds: context.state.plan?.skills?.skills?.map((skill) => skill.identifier),
scope: context.state.origin?.scope,
serverDB,
skipResultTruncation: true,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts
index 5adee6b70dc..ee9cb588a87 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts
@@ -53,6 +53,7 @@ export const buildPreInitState = (
agentConfig,
agentShareVisitor,
appContext,
+ autoSkillIds,
botContext,
botPlatformContext,
deviceAccessPolicy,
@@ -166,6 +167,7 @@ export const buildPreInitState = (
// the context engine reads it on every step.
world: {
agent: agentConfig,
+ ...(autoSkillIds?.length && { autoSkillIds }),
...((botPlatformContext || discordContext) && {
channel: { botPlatform: botPlatformContext, discord: discordContext },
}),
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 6d27cccd6bf..b111e80dc04 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -520,6 +520,8 @@ export interface OperationCreationParams {
*/
userAgent?: string;
};
+ /** Library skills the agent set to `auto`, kept on `state.world` for the skill pool. */
+ autoSkillIds?: string[];
autoStart?: boolean;
/**
* Sender/owner identity for bot-originated runs. Forwarded into
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 e0abda83d19..9526b73612a 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
@@ -1,3 +1,4 @@
+import type { AgentPluginEntry } from '@lobechat/types';
import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -241,7 +242,7 @@ const toolsEngineConfigArg = () =>
const skillById = (identifier: string) =>
operationSkillSetArg()?.skills.find((s) => s.identifier === identifier);
-const createAgentConfig = (plugins: string[]) => ({
+const createAgentConfig = (plugins: AgentPluginEntry[]) => ({
chatConfig: {},
id: 'agent-1',
model: 'gpt-4',
@@ -306,17 +307,29 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('injects a pinned DB skill body into the operation skill set, leaving auto skills content-less', async () => {
- // db-skill-pinned is pinned; db-skill-auto is absent from plugins → auto.
- mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-pinned']));
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig(['db-skill-pinned', { identifier: 'db-skill-auto', mode: 'auto' }]),
+ );
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');
// The auto skill is still listed (activatable) but carries no body.
+ expect(skillById('db-skill-auto')).toBeDefined();
expect(skillById('db-skill-auto')?.content).toBeUndefined();
});
+ it('leaves a library skill the agent never turned on out of the operation skill set', async () => {
+ // db-skill-auto is installed in the library but absent from this agent's plugins.
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-pinned']));
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+
+ expect(skillById('db-skill-pinned')).toBeDefined();
+ expect(skillById('db-skill-auto')).toBeUndefined();
+ });
+
it('fetches bodies only for the pinned subset to keep the op-param payload bounded', async () => {
mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-pinned']));
@@ -394,7 +407,9 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
it('does not eager-inject an auto skill whose identifier collides with a turn-scoped tool id', async () => {
// Nothing pinned — db-skill-auto is in auto mode.
- mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig([{ identifier: 'db-skill-auto', mode: 'auto' }]),
+ );
// db-skill-auto lands in the expanded operation tool list (`agentPlugins`)
// via a turn-scoped @-mention pick, but it is NOT pinned on the agent.
@@ -406,6 +421,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
// Eager injection must gate on the pinned set, not the expanded tool list,
// 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([]);
});
diff --git a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts
index a1ba3d0564d..52c91ca3937 100644
--- a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts
+++ b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts
@@ -109,6 +109,7 @@ const restoreRunContext = async (
viewedGoal: request.viewedGoal,
} as ExecRunContext['appContext'],
assistantMessageId: origin.assistantMessageId,
+ autoSkillIds: state.world?.autoSkillIds ?? [],
botContext: state.principal?.actor?.bot,
botPlatformContext: channel?.botPlatform,
canUseDevice: deviceAccess?.canUseDevice ?? false,
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index f68e0df3c16..8821b292901 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -260,6 +260,7 @@ export const execAgentTurn = async (
agentConfig,
agentSlug,
assistantAgentId,
+ autoSkillIds,
canManageAgent,
conversationAgentId,
disabledPluginIds,
@@ -506,6 +507,7 @@ export const execAgentTurn = async (
}
: appContext,
assistantMessageId: turn.assistantMessageId,
+ autoSkillIds,
botContext,
botPlatformContext,
canUseDevice,
@@ -802,6 +804,7 @@ export const execAgentTurn = async (
approvalClaim,
approvalSourceOperationId,
approvalSourceToolMessageIds,
+ autoSkillIds,
autoStart,
onOperationCreated: params.onOperationCreated,
markTopicRunning: params.markTopicRunning,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index c50658385d5..339c4b4d847 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -848,6 +848,7 @@ export const prepareOperation = async (
activeDeviceId,
agentConfig,
agentPlugins,
+ autoSkillIds: ctx.autoSkillIds,
disabledPluginIds,
executionPlan,
prompt,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
index 2def1dbe740..2f280462a37 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
@@ -32,6 +32,11 @@ export interface OperationSkillSetInput {
activeDeviceId: ToolDiscoveryResult['activeDeviceId'];
agentConfig: ExecRunContext['agentConfig'];
agentPlugins: ToolDiscoveryResult['agentPlugins'];
+ /**
+ * Library skills the agent set to `auto`. A library skill is opt-in per
+ * agent, so one that is neither here nor pinned / selected is not listed.
+ */
+ autoSkillIds: string[];
/** Tri-state disabled plugin identifiers — excluded from the skill pool. */
disabledPluginIds: string[];
executionPlan: ToolDiscoveryResult['executionPlan'];
@@ -92,6 +97,7 @@ export const buildOperationSkillSet = async (
activeDeviceId,
agentConfig,
agentPlugins,
+ autoSkillIds,
disabledPluginIds,
executionPlan,
prompt,
@@ -279,6 +285,11 @@ export const buildOperationSkillSet = async (
project: projectMetas,
},
{
+ // A library skill is opt-in per agent: the ones this agent set to
+ // `auto` are listed, the ones it never turned on are not. A share's
+ // skill grant is the creator opting the visitor in by name, so a
+ // granted skill stays reachable without also being turned on.
+ autoSkillIds: [...autoSkillIds, ...(shareAllowedSkillIds ?? [])],
canExecuteOnDevice: executionPlan ? isDeviceCapablePlan(executionPlan) : false,
disabledIds: disabledPluginIds,
// Selected skills join the enabled set so the resolver auto-activates
diff --git a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts
index c20300f738d..7246af45684 100644
--- a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts
+++ b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts
@@ -4,6 +4,7 @@ import { type AgentConfigSnapshot, resolveAgentConfig } from '@lobechat/mecha';
import type { AgentModelOverride, LobeAgentAgencyConfig, MessageMapScope } from '@lobechat/types';
import {
applyTopicModelToHeterogeneousProvider,
+ getAutoPluginIds,
getDisabledPluginIds,
resolveAgentAgencyConfig,
resolveHeterogeneousModelOverride,
@@ -57,6 +58,8 @@ export interface ResolvedRunAgentConfig {
agentSlug?: string | null;
/** Agent id stamped on the assistant row (conversation-aware). */
assistantAgentId: string;
+ /** Library skills the agent set to `auto`, captured before pinned-id collapse. */
+ autoSkillIds: string[];
canManageAgent: boolean;
/** Agent id stamped on the user row (conversation-aware). */
conversationAgentId: string;
@@ -262,6 +265,9 @@ export const resolveRunAgentConfig = async (
// collapses plugins to pinned ids: they later filter the auto-discovery
// candidate pool so a disabled plugin can't be rediscovered.
const disabledPluginIds = getDisabledPluginIds(row.plugins);
+ // Same for the explicit `auto` entries: a library skill is opt-in per agent,
+ // so the skill pool needs the ones this agent opted into without pinning.
+ const autoSkillIds = getAutoPluginIds(row.plugins);
// One mutable object from here on — later stages append to `systemRole` and
// `createOperation` must see those writes.
@@ -363,6 +369,7 @@ export const resolveRunAgentConfig = async (
agentConfig,
agentSlug: row.slug,
assistantAgentId,
+ autoSkillIds,
canManageAgent,
conversationAgentId,
disabledPluginIds,
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index ffa2b9a587d..348c7deb746 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -45,6 +45,8 @@ export interface StartOperationInput {
approvalClaim: ApprovalClaimState;
approvalSourceOperationId?: string;
approvalSourceToolMessageIds: string[];
+ /** Library skills the agent set to `auto`, kept on the world slot for the skill pool. */
+ autoSkillIds?: string[];
autoStart: boolean;
botContext?: InternalExecAgentParams['botContext'];
botPlatformContext?: InternalExecAgentParams['botPlatformContext'];
@@ -127,6 +129,7 @@ export const startOperation = async (
approvalClaim,
approvalSourceOperationId,
approvalSourceToolMessageIds,
+ autoSkillIds,
autoStart,
botContext,
botPlatformContext,
@@ -280,6 +283,7 @@ export const startOperation = async (
visitorUserId: shareGate.visitorUserId,
}
: undefined,
+ autoSkillIds,
disabledPluginIds,
userTimezone,
appContext: {
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index a19f90b0a7d..218142ffb1e 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -48,6 +48,8 @@ export interface ExecRunContext {
* that re-runs later reads them back from there rather than from the turn's
* request.
*/
+ /** Library skills the agent set to `auto`; mirrored on `world.autoSkillIds`. */
+ autoSkillIds: string[];
botContext?: InternalExecAgentParams['botContext'];
botPlatformContext?: InternalExecAgentParams['botPlatformContext'];
canUseDevice: boolean;
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
index e02e5720825..d706829230a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
@@ -87,7 +87,7 @@ describe('activatorRuntime', () => {
expect(result.success).toBe(false);
}, 20_000);
- it('still activates the skill when it is not disabled', async () => {
+ it('refuses to activate a library skill the agent never turned on', async () => {
mocks.getAgentConfigById.mockResolvedValue({ plugins: [] });
mocks.findByName.mockImplementation(async (name: string) =>
name === 'user-skill' ? userSkillRow() : undefined,
@@ -103,6 +103,27 @@ describe('activatorRuntime', () => {
const result = await runtime.activateSkill({ name: 'user-skill' });
+ expect(result.success).toBe(false);
+ });
+
+ it('still activates the skill when the agent turned it on', async () => {
+ mocks.getAgentConfigById.mockResolvedValue({
+ plugins: [{ identifier: 'user-skill-identifier', mode: 'auto' }],
+ });
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === 'user-skill' ? userSkillRow() : undefined,
+ );
+
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ agentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateSkill({ name: 'user-skill' });
+
expect(result.success).toBe(true);
});
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillStore.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillStore.test.ts
index efcd127ee2a..6fb04ec3f1a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillStore.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillStore.test.ts
@@ -2,11 +2,19 @@ import { RBAC_PERMISSIONS } from '@lobechat/const/rbac';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ getAgentConfigById: vi.fn(),
getSkillDownloadUrl: vi.fn(),
getUserSettings: vi.fn(),
hasAnyPermission: vi.fn(),
importFromUrl: vi.fn(),
SkillImporter: vi.fn(),
+ updateConfig: vi.fn(),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(function () {
+ return { getAgentConfigById: mocks.getAgentConfigById, updateConfig: mocks.updateConfig };
+ }),
}));
vi.mock('@lobechat/builtin-tool-skill-store', () => ({
@@ -170,4 +178,51 @@ describe('skillStoreRuntime', () => {
status: 'unchanged',
});
});
+
+ // A library skill is opt-in per agent, so a skill the model installs mid-run
+ // would otherwise be off for the very agent that installed it.
+ describe('turning an imported skill on for the run agent', () => {
+ const importAs = async (agentId?: string) => {
+ mocks.getSkillDownloadUrl.mockReturnValue('https://market.example/download');
+ mocks.importFromUrl.mockResolvedValue({
+ skill: { id: 'skl_1', identifier: 'excalidraw', name: 'excalidraw' },
+ status: 'created',
+ });
+ const { skillStoreRuntime } = await import('../skillStore');
+ const runtime = (await skillStoreRuntime.factory({
+ agentId,
+ serverDB,
+ toolManifestMap: {},
+ userId: 'user-1',
+ })) as any;
+ await runtime.service.importFromMarket('excalidraw');
+ };
+
+ it('sets the skill to auto for the agent that imported it', async () => {
+ mocks.getAgentConfigById.mockResolvedValue({ plugins: ['lobe-web-browsing'] });
+
+ await importAs('agent-1');
+
+ expect(mocks.updateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: ['lobe-web-browsing', { identifier: 'excalidraw', mode: 'auto' }],
+ });
+ });
+
+ it('leaves an entry the user already chose alone', async () => {
+ mocks.getAgentConfigById.mockResolvedValue({
+ plugins: [{ identifier: 'excalidraw', mode: 'disabled' }],
+ });
+
+ await importAs('agent-1');
+
+ expect(mocks.updateConfig).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when the import has no agent', async () => {
+ await importAs();
+
+ expect(mocks.getAgentConfigById).not.toHaveBeenCalled();
+ expect(mocks.updateConfig).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
index 603f5f0af08..1a0cc64fd41 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -569,29 +569,30 @@ describe('skillsRuntime', () => {
});
describe('disabled skill enforcement', () => {
- it('refuses to activate a DB skill the agent has disabled, even though it exists', async () => {
- mocks.getAgentConfigById.mockResolvedValue({
+ it.each([
+ {
+ expected: false,
plugins: [{ identifier: 'user-skill-identifier', mode: 'disabled' }],
- });
- mocks.findByName.mockImplementation(async (name: string) =>
- name === 'user-skill'
- ? { id: 'user-skill-id', identifier: 'user-skill-identifier', name: 'user-skill' }
- : undefined,
- );
-
- const { skillsRuntime } = await import('../skills');
- const runtime = await skillsRuntime.factory({
- agentId: 'agent-1',
- ...createRuntimeContext(),
- });
-
- const result = await runtime.activateSkill({ name: 'user-skill' });
-
- expect(result.success).toBe(false);
- });
-
- it('still activates the skill when it is not disabled', async () => {
- mocks.getAgentConfigById.mockResolvedValue({ plugins: [] });
+ title: 'refuses to activate a DB skill the agent has disabled, even though it exists',
+ },
+ {
+ expected: false,
+ plugins: [],
+ title: 'refuses to activate a library skill the agent never turned on',
+ },
+ {
+ expected: true,
+ plugins: [{ identifier: 'user-skill-identifier', mode: 'auto' }],
+ title: 'still activates the skill when the agent turned it on',
+ },
+ {
+ expected: true,
+ plugins: [],
+ runSkillIds: ['user-skill-identifier'],
+ title: 'activates a skill the operation pool offers, such as one selected this turn',
+ },
+ ])('$title', async ({ expected, plugins, runSkillIds }) => {
+ mocks.getAgentConfigById.mockResolvedValue({ plugins });
mocks.findByName.mockImplementation(async (name: string) =>
name === 'user-skill'
? {
@@ -606,12 +607,11 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
agentId: 'agent-1',
+ runSkillIds,
...createRuntimeContext(),
});
- const result = await runtime.activateSkill({ name: 'user-skill' });
-
- expect(result.success).toBe(true);
+ expect((await runtime.activateSkill({ name: 'user-skill' })).success).toBe(expected);
});
});
@@ -743,9 +743,9 @@ describe('skillsRuntime', () => {
expect((await runtime.activateSkill({ name: 'secret-bundle' })).success).toBe(false);
});
- it('leaves a non-share run completely unfiltered', async () => {
- // No `agentShareVisitor` means no per-skill allowlist at all: the creator's
- // own run must keep reaching every skill it owns.
+ it('leaves a non-share run to the agent’s own config, with no per-skill allowlist', async () => {
+ // No `agentShareVisitor`, no share allowlist: the run reaches what the agent turned on.
+ mocks.getAgentConfigById.mockResolvedValue({ plugins: ['user-skill-identifier'] });
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
agentId: 'agent-1',
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
index 23241956cec..3132e5041bd 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
@@ -7,9 +7,8 @@ import {
} from '@lobechat/builtin-tool-activator/executionRuntime';
import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';
import { resolveShareAllowedSkillIds } from '@lobechat/const';
-import { describeLockedDevicePicker, getDisabledPluginIds } from '@lobechat/types';
+import { describeLockedDevicePicker } from '@lobechat/types';
-import { AgentModel } from '@/database/models/agent';
import { AgentSkillModel } from '@/database/models/agentSkill';
import { filterBuiltinSkills } from '@/helpers/skillFilters';
import {
@@ -18,6 +17,7 @@ import {
} from '@/server/services/agentSignal/procedure';
import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';
+import { resolveAgentSkillGates } from './librarySkillGate';
import { REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
import { type ServerRuntimeRegistration } from './types';
@@ -80,12 +80,7 @@ export const activatorRuntime: ServerRuntimeRegistration = {
// model that already knows its name (prior turn, or a guess) could
// still activate and use it. Re-derive the disabled set here so this
// independent resolution path enforces the same tri-state.
- let disabledSkillIds = new Set<string>();
- if (context.agentId) {
- const agentModel = new AgentModel(context.serverDB, context.userId, context.workspaceId);
- const agentConfig = await agentModel.getAgentConfigById(context.agentId);
- disabledSkillIds = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));
- }
+ const { disabledSkillIds, isLibrarySkillEnabled } = await resolveAgentSkillGates(context);
// An Agent Share visitor reaches only the skills the creator listed in
// `shareConfig.skillGrants`. `activateTools` falls back to this runtime
@@ -97,6 +92,8 @@ export const activatorRuntime: ServerRuntimeRegistration = {
const isSkillReachable = (identifier: string) =>
!disabledSkillIds.has(identifier) &&
(!shareVisitor || resolveShareAllowedSkillIds([identifier], shareVisitor).length > 0);
+ const isLibrarySkillReachable = (identifier: string) =>
+ isSkillReachable(identifier) && (isLibrarySkillEnabled?.(identifier) ?? true);
skillsRuntime = new SkillsExecutionRuntime({
// Same device gate as the skills runtime: device-only skills are
@@ -108,18 +105,18 @@ export const activatorRuntime: ServerRuntimeRegistration = {
service: {
findAll: async () => {
const result = await skillModel.findAll();
- if (!shareVisitor) return result;
+ if (!shareVisitor && !isLibrarySkillEnabled) return result;
- const data = result.data.filter((skill) => isSkillReachable(skill.identifier));
+ const data = result.data.filter((skill) => isLibrarySkillReachable(skill.identifier));
return { data, total: data.length };
},
findById: async (id) => {
const skill = await skillModel.findById(id);
- return skill && isSkillReachable(skill.identifier) ? skill : undefined;
+ return skill && isLibrarySkillReachable(skill.identifier) ? skill : undefined;
},
findByName: async (name) => {
const skill = await skillModel.findByName(name);
- return skill && isSkillReachable(skill.identifier) ? skill : undefined;
+ return skill && isLibrarySkillReachable(skill.identifier) ? skill : undefined;
},
readResource: async () => {
throw new Error('readResource not available in tools runtime');
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/librarySkillGate.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/librarySkillGate.test.ts
new file mode 100644
index 00000000000..3d3744e765f
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/librarySkillGate.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createLibrarySkillGate, resolveAgentSkillGates } from './librarySkillGate';
+
+const mocks = vi.hoisted(() => ({ getAgentConfigById: vi.fn() }));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(function () {
+ return { getAgentConfigById: mocks.getAgentConfigById };
+ }),
+}));
+
+describe('createLibrarySkillGate', () => {
+ it('refuses a library skill the agent never turned on', () => {
+ const isEnabled = createLibrarySkillGate(['lobe-web-browsing'], []);
+
+ expect(isEnabled('excalidraw')).toBe(false);
+ });
+
+ it('opens a library skill the agent pinned or set to auto', () => {
+ const isEnabled = createLibrarySkillGate(['pinned', { identifier: 'auto', mode: 'auto' }]);
+
+ expect(isEnabled('pinned')).toBe(true);
+ expect(isEnabled('auto')).toBe(true);
+ });
+
+ it('refuses a library skill the agent disabled', () => {
+ const isEnabled = createLibrarySkillGate([{ identifier: 'off', mode: 'disabled' }]);
+
+ expect(isEnabled('off')).toBe(false);
+ });
+
+ it('opens a skill the operation pool already offers, such as one the user selected this turn', () => {
+ const isEnabled = createLibrarySkillGate(undefined, ['selected-this-turn']);
+
+ expect(isEnabled('selected-this-turn')).toBe(true);
+ expect(isEnabled('something-else')).toBe(false);
+ });
+});
+
+describe('resolveAgentSkillGates', () => {
+ const context = { agentId: 'agent-1', serverDB: {} as never, userId: 'user-1' };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getAgentConfigById.mockResolvedValue({
+ plugins: [
+ { identifier: 'off', mode: 'disabled' },
+ { identifier: 'on', mode: 'auto' },
+ ],
+ });
+ });
+
+ it('derives both gates from the run agent’s own config', async () => {
+ const { disabledSkillIds, isLibrarySkillEnabled } = await resolveAgentSkillGates(context);
+
+ expect([...disabledSkillIds]).toEqual(['off']);
+ expect(isLibrarySkillEnabled?.('on')).toBe(true);
+ expect(isLibrarySkillEnabled?.('never-turned-on')).toBe(false);
+ });
+
+ it('lets a skill the operation pool offers through', async () => {
+ const { isLibrarySkillEnabled } = await resolveAgentSkillGates({
+ ...context,
+ runSkillIds: ['selected-this-turn'],
+ });
+
+ expect(isLibrarySkillEnabled?.('selected-this-turn')).toBe(true);
+ });
+
+ it('leaves a share visitor to the creator’s skill grant instead', async () => {
+ const { isLibrarySkillEnabled } = await resolveAgentSkillGates({
+ ...context,
+ agentShareVisitor: { skillGrants: ['granted'] } as never,
+ });
+
+ expect(isLibrarySkillEnabled).toBeUndefined();
+ });
+
+ it('applies no gate when the run has no agent', async () => {
+ const gates = await resolveAgentSkillGates({ serverDB: {} as never, userId: 'user-1' });
+
+ expect(gates.isLibrarySkillEnabled).toBeUndefined();
+ expect(gates.disabledSkillIds.size).toBe(0);
+ expect(mocks.getAgentConfigById).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/librarySkillGate.ts b/apps/server/src/services/toolExecution/serverRuntimes/librarySkillGate.ts
new file mode 100644
index 00000000000..938b714d096
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/librarySkillGate.ts
@@ -0,0 +1,64 @@
+import { type AgentPluginEntry, getDisabledPluginIds, getLibrarySkillMode } from '@lobechat/types';
+
+import { AgentModel } from '@/database/models/agent';
+
+import type { ToolExecutionContext } from '../types';
+
+/**
+ * Answers "may this run open this library (DB) skill". A library skill is
+ * opt-in per agent, so one the agent has no entry for is off, not `auto`.
+ *
+ * `plugins` is the agent's own config, read fresh so a skill turned on (or
+ * installed by the model) mid-run is reachable at once. `runSkillIds` is the
+ * operation's skill pool: a turn's own selection or a share's grant puts a
+ * skill there without the agent having turned it on, and the runtime must not
+ * refuse what the pool already offered.
+ *
+ * `activateSkill` / `readReference` resolve a MODEL-SUPPLIED name fresh from
+ * the DB, so leaving a skill out of `<available_skills>` is not enough on its
+ * own — this is the check on that path.
+ */
+export const createLibrarySkillGate = (
+ plugins: AgentPluginEntry[] | undefined,
+ runSkillIds?: readonly string[],
+): ((identifier: string) => boolean) => {
+ const inRunPool = new Set(runSkillIds ?? []);
+ return (identifier) =>
+ getLibrarySkillMode(plugins, identifier) !== 'disabled' || inRunPool.has(identifier);
+};
+
+/**
+ * The run agent's own skill tri-state, re-derived for a runtime that resolves
+ * skills fresh by name/id.
+ *
+ * Independent of `<available_skills>` (built once, at operation start): a model
+ * that already knows a skill's name (prior turn, or a guess) could otherwise
+ * still activate it. `disabledSkillIds` applies to every skill source;
+ * `isLibrarySkillEnabled` only to library (DB) skills, and is absent when
+ * there is no agent to opt in against, or for a share visitor — there the
+ * creator's skill grant is the opt-in, by name.
+ */
+export const resolveAgentSkillGates = async (
+ context: Pick<
+ ToolExecutionContext,
+ 'agentId' | 'agentShareVisitor' | 'runSkillIds' | 'serverDB' | 'userId' | 'workspaceId'
+ >,
+): Promise<{
+ disabledSkillIds: Set<string>;
+ isLibrarySkillEnabled?: (identifier: string) => boolean;
+}> => {
+ if (!context.agentId || !context.serverDB || !context.userId) {
+ return { disabledSkillIds: new Set() };
+ }
+
+ const agentModel = new AgentModel(context.serverDB, context.userId, context.workspaceId);
+ const agentConfig = await agentModel.getAgentConfigById(context.agentId);
+ const plugins = agentConfig?.plugins ?? undefined;
+
+ return {
+ disabledSkillIds: new Set(getDisabledPluginIds(plugins)),
+ isLibrarySkillEnabled: context.agentShareVisitor
+ ? undefined
+ : createLibrarySkillGate(plugins, context.runSkillIds),
+ };
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skillStore.ts b/apps/server/src/services/toolExecution/serverRuntimes/skillStore.ts
index 198213a90f7..22ba147fbb6 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skillStore.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skillStore.ts
@@ -9,8 +9,10 @@ import {
type SkillStoreRuntimeService,
} from '@lobechat/builtin-tool-skill-store/executionRuntime';
import { RBAC_PERMISSIONS } from '@lobechat/const/rbac';
+import { LIBRARY_SKILL_IMPLICIT_MODE, parsePluginEntry, upsertPluginMode } from '@lobechat/types';
import debug from 'debug';
+import { AgentModel } from '@/database/models/agent';
import { RbacModel } from '@/database/models/rbac';
import { UserModel } from '@/database/models/user';
import {
@@ -31,6 +33,7 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
private messageId?: string;
private importer: SkillImporter;
private marketService: MarketService;
+ private enableImportedSkill?: (identifier: string) => Promise<void>;
private operationId?: string;
private taskId?: string;
private toolCallId?: string;
@@ -43,6 +46,12 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
importer: SkillImporter;
marketService: MarketService;
messageId?: string;
+ /**
+ * Runs after every successful import with the skill's identifier. A library
+ * skill is opt-in per agent, so the run's own agent is opted in here —
+ * otherwise the model could not use the skill it just installed.
+ */
+ enableImportedSkill?: (identifier: string) => Promise<void>;
operationId?: string;
taskId?: string;
toolCallId?: string;
@@ -54,6 +63,7 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
this.messageId = options.messageId;
this.importer = options.importer;
this.marketService = options.marketService;
+ this.enableImportedSkill = options.enableImportedSkill;
this.operationId = options.operationId;
this.taskId = options.taskId;
this.toolCallId = options.toolCallId;
@@ -104,6 +114,7 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
importFromGitHub = async (gitUrl: string): Promise<SkillImportServiceResult> => {
try {
const result = await this.importer.importFromGitHub({ gitUrl });
+ await this.enableImportedSkill?.(result.skill.identifier);
await this.emitSkillOutcome({
apiName: 'importFromGitHub',
intentClass: 'tool_command',
@@ -130,6 +141,7 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
importFromUrl = async (url: string): Promise<SkillImportServiceResult> => {
try {
const result = await this.importer.importFromUrl({ url });
+ await this.enableImportedSkill?.(result.skill.identifier);
await this.emitSkillOutcome({
apiName: 'importFromUrl',
intentClass: 'tool_command',
@@ -159,6 +171,7 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
): Promise<SkillImportServiceResult> => {
try {
const result = await this.importer.importFromUrl({ url }, options);
+ await this.enableImportedSkill?.(result.skill.identifier);
await this.emitSkillOutcome({
apiName: 'importFromZipUrl',
intentClass: 'tool_command',
@@ -305,12 +318,41 @@ export const skillStoreRuntime: ServerRuntimeRegistration = {
userInfo: { userId: context.userId },
});
+ const { agentId, serverDB, userId } = context;
+ const enableForRunAgent = agentId
+ ? async (identifier: string) => {
+ try {
+ const agentModel = new AgentModel(serverDB, userId, context.workspaceId);
+ const agent = await agentModel.getAgentConfigById(agentId);
+ if (!agent) return;
+
+ // Only a skill the agent has no entry for: a pin or an explicit
+ // disable is the user's own choice and a re-import must not undo it.
+ const plugins = agent.plugins ?? undefined;
+ if (plugins?.some((entry) => parsePluginEntry(entry).identifier === identifier)) return;
+
+ await agentModel.updateConfig(agentId, {
+ plugins: upsertPluginMode(
+ plugins,
+ identifier,
+ 'auto',
+ LIBRARY_SKILL_IMPLICIT_MODE,
+ ) as unknown as string[],
+ });
+ } catch (error) {
+ // The import itself succeeded; the skill can still be turned on by hand.
+ log('Failed to turn imported skill %s on for agent %s: %O', identifier, agentId, error);
+ }
+ }
+ : undefined;
+
const service = new SkillStoreServerRuntimeService({
agentId: context.agentId,
emitOutcome: emitToolOutcomeSafely,
importer,
marketService,
messageId: context.messageId,
+ enableImportedSkill: enableForRunAgent,
operationId: context.operationId,
taskId: context.taskId,
toolCallId: context.toolCallId,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 7af968ec398..84d6960080e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -19,7 +19,6 @@ import { BRANDING_NAME } from '@lobechat/business-const';
import { resolveShareAllowedSkillIds } from '@lobechat/const';
import {
type BuiltinSkill,
- getDisabledPluginIds,
type SkillItem,
type SkillListItem,
type SkillResourceContent,
@@ -27,7 +26,6 @@ import {
import { toRecord } from '@lobechat/utils/object';
import debug from 'debug';
-import { AgentModel } from '@/database/models/agent';
import { AgentSkillModel } from '@/database/models/agentSkill';
import { FileModel } from '@/database/models/file';
import { TaskModel } from '@/database/models/task';
@@ -59,6 +57,7 @@ import {
UserSkillService,
} from '@/server/services/userSkill';
+import { resolveAgentSkillGates } from './librarySkillGate';
import { pageSandboxWrapper, type SandboxWrapper } from './pageSandboxSync';
import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { createSandboxMarketService } from './sandboxMarket';
@@ -175,6 +174,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
private sandboxSpecification?: SandboxSessionSpecification;
private device?: SkillDeviceExecution;
private disabledSkillIds: Set<string>;
+ private isLibrarySkillEnabled?: (identifier: string) => boolean;
private resolveUserSkillArchive?: (
name: string,
) => Promise<{ fileHash: string; url: string } | undefined>;
@@ -194,6 +194,8 @@ class SkillServerRuntimeService implements SkillRuntimeService {
disabledSkillIds?: Set<string>;
fileModel: FileModel;
fileService: FileService;
+ /** Library skills are opt-in per agent; see `resolveAgentSkillGates`. */
+ isLibrarySkillEnabled?: (identifier: string) => boolean;
/**
* Agent Share only: answers "may this visitor reach the skill with this
* identifier". Absent on a creator's own run, where the creator reaches
@@ -249,6 +251,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
this.sandboxSpecification = options.sandboxSpecification;
this.device = options.device;
this.disabledSkillIds = options.disabledSkillIds ?? new Set();
+ this.isLibrarySkillEnabled = options.isLibrarySkillEnabled;
this.isSkillGranted = options.isSkillGranted;
this.shareVisitorBlocked = options.shareVisitorBlocked ?? false;
this.wrapSandbox = options.wrapSandbox;
@@ -260,6 +263,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
* together so no lookup path can honor one and miss the other:
*
* - `disabledSkillIds` — the agent's own tri-state (`agents.plugins`);
+ * - `isLibrarySkillEnabled` — a library skill the agent never turned on is off;
* - `isSkillGranted` — an Agent Share visitor's per-skill allowlist
* (`shareConfig.skillGrants`). Absent for a creator's own run.
*
@@ -268,16 +272,18 @@ class SkillServerRuntimeService implements SkillRuntimeService {
* carries the identifier the grant is written against.
*/
private isSkillReachable = (identifier: string): boolean =>
- !this.disabledSkillIds.has(identifier) && (this.isSkillGranted?.(identifier) ?? true);
+ !this.disabledSkillIds.has(identifier) &&
+ (this.isLibrarySkillEnabled?.(identifier) ?? true) &&
+ (this.isSkillGranted?.(identifier) ?? true);
findAll = async (): Promise<{ data: SkillListItem[]; total: number }> => {
const result = await this.skillModel.findAll();
- if (!this.isSkillGranted) return result;
+ if (!this.isSkillGranted && !this.isLibrarySkillEnabled) return result;
- // A share visitor must not learn the creator's catalog. This list is not
- // just an internal lookup: `activateSkill` echoes it back in its
- // not-found message ("Available skills: ..."), so an unfiltered read here
- // hands every skill name and description to anyone with the link.
+ // A share visitor must not learn the creator's catalog, and no run should be
+ // offered a skill its agent never turned on. This list is not just an
+ // internal lookup: `activateSkill` echoes it back in its not-found message
+ // ("Available skills: ..."), handing every name and description to the model.
const data = result.data.filter((skill) => this.isSkillReachable(skill.identifier));
return { data, total: data.length };
};
@@ -906,17 +912,9 @@ export const skillsRuntime: ServerRuntimeRegistration = {
log('Failed to fetch market accessToken for user %s: %O', context.userId, error);
}
- // Independent of `<available_skills>` (built once, earlier, in
- // aiAgent/index.ts) — this runtime resolves skills fresh by name/id, so a
- // model that already knows a disabled skill's name (prior turn, or a
- // guess) could otherwise still activate/run it. Re-derive the disabled
- // set here so this path enforces the same tri-state.
- let disabledSkillIds = new Set<string>();
- if (context.agentId) {
- const agentModel = new AgentModel(context.serverDB, context.userId, context.workspaceId);
- const agentConfig = await agentModel.getAgentConfigById(context.agentId);
- disabledSkillIds = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));
- }
+ // This runtime resolves skills fresh by name/id, so the agent's own
+ // tri-state is enforced here too (see `resolveAgentSkillGates`).
+ const { disabledSkillIds, isLibrarySkillEnabled } = await resolveAgentSkillGates(context);
// The share's own opt-out, for the same reason: the creator named the
// skills a visitor may load (`shareConfig.skillGrants`), and the
@@ -1051,6 +1049,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {
disabledSkillIds,
fileModel,
fileService,
+ isLibrarySkillEnabled,
isSkillGranted,
marketService,
// The run this runtime belongs to, so an `lh agent run` it preprocesses in
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 941b38ec7e0..dc365fddfe0 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -347,6 +347,12 @@ export interface ToolExecutionContext {
projectSkills?: { location: string; name: string; source?: 'device' | 'project' }[];
/** Root AI runtime operation ID used to aggregate artifacts produced by one run. */
rootOperationId?: string;
+ /**
+ * Identifiers of the skills in this operation's pool. A library skill is
+ * opt-in per agent, and the pool is where a turn's selection or a share's
+ * grant opted one in without it being turned on in the agent's own config.
+ */
+ runSkillIds?: string[];
/** Conversation scope captured when the operation was created */
scope?: string | null;
/** Server database for LobeHub Skills execution */
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 63f385ee1a0..8de3d71a363 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -309,6 +309,12 @@ export interface RunAgentSnapshot extends Partial<LobeAgentConfig> {
export interface AgentWorldSnapshot {
/** Agent definition snapshot: systemRole, chatConfig, agencyConfig … */
agent?: RunAgentSnapshot;
+ /**
+ * Library skills the agent set to `auto` (explicit tri-state entries). A
+ * library skill is opt-in per agent and `agent.plugins` is already collapsed
+ * to pinned ids, so the skill pool reads the opted-in ones from here.
+ */
+ autoSkillIds?: string[];
/** Channel-specific facts the model should know (bot platform, Discord …). */
channel?: {
botPlatform?: BotPlatformContext;
diff --git a/packages/mecha/src/toolSet/skillPool.test.ts b/packages/mecha/src/toolSet/skillPool.test.ts
index 159a3a8f4bf..ec2bd65eb13 100644
--- a/packages/mecha/src/toolSet/skillPool.test.ts
+++ b/packages/mecha/src/toolSet/skillPool.test.ts
@@ -20,29 +20,38 @@ describe('isBuiltinSkillEnabled', () => {
describe('assembleSkillPool', () => {
it('resolves a name collision as project > db > agent-skills > builtin', () => {
- const pool = assembleSkillPool({
- agentSkills: [skill('agent-skills:review', 'review')],
- builtin: [skill('builtin-review', 'review')],
- db: [skill('db-review', 'review')],
- project: [skill('project:review', 'review')],
- });
+ const pool = assembleSkillPool(
+ {
+ agentSkills: [skill('agent-skills:review', 'review')],
+ builtin: [skill('builtin-review', 'review')],
+ db: [skill('db-review', 'review')],
+ project: [skill('project:review', 'review')],
+ },
+ { autoSkillIds: ['db-review'] },
+ );
expect(pool.skills.map((s) => s.identifier)).toEqual(['project:review']);
- const withoutProject = assembleSkillPool({
- agentSkills: [skill('agent-skills:review', 'review')],
- builtin: [skill('builtin-review', 'review')],
- db: [skill('db-review', 'review')],
- });
+ const withoutProject = assembleSkillPool(
+ {
+ agentSkills: [skill('agent-skills:review', 'review')],
+ builtin: [skill('builtin-review', 'review')],
+ db: [skill('db-review', 'review')],
+ },
+ { autoSkillIds: ['db-review'] },
+ );
expect(withoutProject.skills.map((s) => s.identifier)).toEqual(['db-review']);
});
it('keeps distinct names from every source, in precedence order', () => {
- const pool = assembleSkillPool({
- agentSkills: [skill('agent-skills:notes', 'agent-skills:notes')],
- builtin: [skill('artifacts')],
- db: [skill('my-skill')],
- project: [skill('project:deploy', 'deploy')],
- });
+ const pool = assembleSkillPool(
+ {
+ agentSkills: [skill('agent-skills:notes', 'agent-skills:notes')],
+ builtin: [skill('artifacts')],
+ db: [skill('my-skill')],
+ project: [skill('project:deploy', 'deploy')],
+ },
+ { autoSkillIds: ['my-skill'] },
+ );
expect(pool.skills.map((s) => s.identifier)).toEqual([
'project:deploy',
'my-skill',
@@ -54,19 +63,51 @@ describe('assembleSkillPool', () => {
it('drops disabled skills from the pool, so they are neither listed nor activatable', () => {
const pool = assembleSkillPool(
{ builtin: [skill('artifacts')], db: [skill('gone'), skill('kept')] },
- { disabledIds: ['gone'] },
+ { autoSkillIds: ['gone', 'kept'], disabledIds: ['gone'] },
);
expect(pool.skills.map((s) => s.identifier)).toEqual(['kept', 'artifacts']);
});
+ it('leaves out a library skill the agent never turned on, while builtin skills stay listed', () => {
+ const sources = {
+ agentSkills: [skill('agent-skills:notes')],
+ builtin: [skill('artifacts')],
+ db: [skill('pinned'), skill('auto'), skill('untouched')],
+ project: [skill('project:deploy', 'deploy')],
+ };
+ const pool = assembleSkillPool(sources, {
+ autoSkillIds: ['auto'],
+ enabledPluginIds: ['pinned'],
+ });
+ expect(pool.skills.map((s) => s.identifier)).toEqual([
+ 'project:deploy',
+ 'pinned',
+ 'auto',
+ 'agent-skills:notes',
+ 'artifacts',
+ ]);
+
+ // Manual mode is still "only what the user picked": an `auto` library skill goes too.
+ expect(
+ assembleSkillPool(sources, {
+ autoSkillIds: ['auto'],
+ enabledPluginIds: ['pinned'],
+ skillActivateMode: 'manual',
+ }).skills.map((s) => s.identifier),
+ ).toEqual(['project:deploy', 'pinned']);
+ });
+
it('withholds everything a share configuration does not allow', () => {
const sources = { builtin: [skill('artifacts')], db: [skill('shared'), skill('private')] };
+ const autoSkillIds = ['shared', 'private'];
expect(
- assembleSkillPool(sources, { shareAllowedIds: ['shared'] }).skills.map((s) => s.identifier),
+ assembleSkillPool(sources, { autoSkillIds, shareAllowedIds: ['shared'] }).skills.map(
+ (s) => s.identifier,
+ ),
).toEqual(['shared']);
// An empty allowlist collapses the pool; no allowlist means no gate.
- expect(assembleSkillPool(sources, { shareAllowedIds: [] }).skills).toEqual([]);
- expect(assembleSkillPool(sources).skills).toHaveLength(3);
+ expect(assembleSkillPool(sources, { autoSkillIds, shareAllowedIds: [] }).skills).toEqual([]);
+ expect(assembleSkillPool(sources, { autoSkillIds }).skills).toHaveLength(3);
});
it('gates the device-only builtin on the run, not on the host', () => {
@@ -116,10 +157,11 @@ describe('assembleSkillPool', () => {
enabledPluginIds: ['picked'],
skillActivateMode: 'auto',
});
+ // Auto mode brings back the sources the agent does not opt into one by one;
+ // a library skill it never turned on stays out either way.
expect(auto.skills.map((s) => s.identifier)).toEqual([
'project:deploy',
'picked',
- 'not-picked',
'agent-skills:notes',
'artifacts',
]);
@@ -128,7 +170,7 @@ describe('assembleSkillPool', () => {
it('pairs the pool with the run’s enabled plugin ids for the resolver', () => {
const pool = assembleSkillPool(
{ db: [skill('pinned'), skill('listed')] },
- { enabledPluginIds: ['pinned'] },
+ { autoSkillIds: ['listed'], enabledPluginIds: ['pinned'] },
);
expect(pool.enabledPluginIds).toEqual(['pinned']);
expect(pool.skills.map((s) => s.identifier)).toEqual(['pinned', 'listed']);
diff --git a/packages/mecha/src/toolSet/skillPool.ts b/packages/mecha/src/toolSet/skillPool.ts
index 5ed0bf2786d..0ebac8a9475 100644
--- a/packages/mecha/src/toolSet/skillPool.ts
+++ b/packages/mecha/src/toolSet/skillPool.ts
@@ -24,6 +24,13 @@ 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.
+ */
+ autoSkillIds?: readonly string[];
/** Gates the device-only builtin skills. */
canExecuteOnDevice?: boolean;
/** Skills the agent explicitly disabled; neither listed nor activatable. */
@@ -79,9 +86,19 @@ 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),
+ );
+
const ordered = [
...(sources.project ?? []),
- ...selectable(sources.db),
+ ...selectable(optedIn),
...selectable(sources.agentSkills),
...selectable(sources.builtin),
];
diff --git a/packages/types/src/agent/pluginConfig.test.ts b/packages/types/src/agent/pluginConfig.test.ts
index a451a09d865..7b89da3dbca 100644
--- a/packages/types/src/agent/pluginConfig.test.ts
+++ b/packages/types/src/agent/pluginConfig.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest';
import {
getActivePluginIds,
+ getAutoPluginIds,
getDisabledPluginIds,
+ getLibrarySkillMode,
getPinnedPluginIds,
getPluginMode,
parsePluginEntry,
@@ -148,3 +150,38 @@ describe('upsertPluginMode', () => {
expect(upsertPluginMode(['a'], 'not-there', 'auto')).toEqual(['a']);
});
});
+
+describe('library skills', () => {
+ it('resolves a library skill the agent has no entry for as disabled', () => {
+ expect(getLibrarySkillMode(undefined, 'excalidraw')).toBe('disabled');
+ expect(getLibrarySkillMode(['other'], 'excalidraw')).toBe('disabled');
+ });
+
+ it('resolves the explicit mode of a library skill the agent has an entry for', () => {
+ expect(getLibrarySkillMode(['excalidraw'], 'excalidraw')).toBe('pinned');
+ expect(getLibrarySkillMode([{ identifier: 'excalidraw', mode: 'auto' }], 'excalidraw')).toBe(
+ 'auto',
+ );
+ });
+
+ it('collects only explicit auto entries', () => {
+ expect(getAutoPluginIds(['a', { identifier: 'b', mode: 'auto' }, { identifier: 'c' }])).toEqual(
+ ['b'],
+ );
+ });
+
+ it('persists auto and removes disabled when disabled is the implicit mode', () => {
+ expect(upsertPluginMode(['a'], 'skill', 'auto', 'disabled')).toEqual([
+ 'a',
+ { identifier: 'skill', mode: 'auto' },
+ ]);
+ expect(
+ upsertPluginMode(
+ [{ identifier: 'skill', mode: 'auto' }, 'a'],
+ 'skill',
+ 'disabled',
+ 'disabled',
+ ),
+ ).toEqual(['a']);
+ });
+});
diff --git a/packages/types/src/agent/pluginConfig.ts b/packages/types/src/agent/pluginConfig.ts
index d880ec7b567..806ddc71385 100644
--- a/packages/types/src/agent/pluginConfig.ts
+++ b/packages/types/src/agent/pluginConfig.ts
@@ -62,6 +62,24 @@ 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';
+
+/** A library skill's mode for this agent; see {@link LIBRARY_SKILL_IMPLICIT_MODE}. */
+export const getLibrarySkillMode = (
+ plugins: AgentPluginEntry[] | undefined,
+ identifier: string,
+): AgentPluginMode => {
+ const entry = plugins?.find((item) => parsePluginEntry(item).identifier === identifier);
+ return entry ? parsePluginEntry(entry).mode : LIBRARY_SKILL_IMPLICIT_MODE;
+};
+
const getPluginIdsByMode = (
plugins: AgentPluginEntry[] | undefined,
mode: AgentPluginMode,
@@ -74,6 +92,14 @@ const getPluginIdsByMode = (
export const getPinnedPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
getPluginIdsByMode(plugins, 'pinned');
+/**
+ * Identifiers carrying an explicit `{ mode: 'auto' }` entry. Only library
+ * skills persist one (see {@link LIBRARY_SKILL_IMPLICIT_MODE}); for everything
+ * else `'auto'` is the absence of an entry.
+ */
+export const getAutoPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
+ getPluginIdsByMode(plugins, 'auto');
+
export const getDisabledPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
getPluginIdsByMode(plugins, 'disabled');
@@ -90,20 +116,24 @@ export const getActivePluginIds = (plugins: AgentPluginEntry[] | undefined): str
* Sets `identifier`'s mode, upgrading only that one entry. Every other entry
* — including untouched legacy strings — is returned unchanged.
*
- * `'auto'` is the implicit default for an identifier absent from `plugins`
- * altogether, so setting it explicitly removes any existing entry instead of
- * persisting a redundant `{ identifier, mode: 'auto' }` record — this mirrors
- * the pre-tri-state behavior where unpinning spliced the id out of the array.
+ * `implicitMode` is what an identifier absent from `plugins` resolves to —
+ * `'auto'` for everything but a library skill
+ * ({@link LIBRARY_SKILL_IMPLICIT_MODE}). Setting that mode removes any existing
+ * entry instead of persisting a redundant record, which mirrors the
+ * pre-tri-state behavior where unpinning spliced the id out of the array. Every
+ * other mode is written explicitly, so a library skill set to `'auto'` keeps a
+ * `{ identifier, mode: 'auto' }` entry.
*/
export const upsertPluginMode = (
plugins: AgentPluginEntry[] | undefined,
identifier: string,
mode: AgentPluginMode,
+ implicitMode: AgentPluginMode = 'auto',
): AgentPluginEntry[] => {
const list = plugins ? [...plugins] : [];
const index = list.findIndex((item) => parsePluginEntry(item).identifier === identifier);
- if (mode === 'auto') {
+ if (mode === implicitMode) {
if (index !== -1) list.splice(index, 1);
return list;
}
diff --git a/src/features/ChatInput/ActionBar/Tools/librarySkillPolicy.test.ts b/src/features/ChatInput/ActionBar/Tools/librarySkillPolicy.test.ts
new file mode 100644
index 00000000000..b729bce308d
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/librarySkillPolicy.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveDisabledIds, resolveImplicitMode } from './librarySkillPolicy';
+
+describe('resolveDisabledIds', () => {
+ it('lists a library skill the agent never turned on as disabled', () => {
+ expect(resolveDisabledIds([], ['excalidraw', 'posthog'])).toEqual(['excalidraw', 'posthog']);
+ expect(resolveDisabledIds(undefined, ['excalidraw'])).toEqual(['excalidraw']);
+ });
+
+ it('keeps a library skill the agent pinned or set to auto out of the disabled list', () => {
+ expect(
+ resolveDisabledIds(
+ ['pinned-skill', { identifier: 'auto-skill', mode: 'auto' }],
+ ['pinned-skill', 'auto-skill', 'untouched-skill'],
+ ),
+ ).toEqual(['untouched-skill']);
+ });
+
+ it('leaves tools and builtin skills on the explicit disabled entries only', () => {
+ // `lobe-web-browsing` and `artifacts` are not library skills: no entry is Auto.
+ expect(
+ resolveDisabledIds([{ identifier: 'github', mode: 'disabled' }], ['excalidraw']),
+ ).toEqual(['github', 'excalidraw']);
+ });
+
+ it('does not repeat a library skill that is also explicitly disabled', () => {
+ expect(
+ resolveDisabledIds([{ identifier: 'excalidraw', mode: 'disabled' }], ['excalidraw']),
+ ).toEqual(['excalidraw']);
+ });
+});
+
+describe('resolveImplicitMode', () => {
+ it('is disabled for a library skill and auto for everything else', () => {
+ const librarySkillIds = new Set(['excalidraw']);
+
+ expect(resolveImplicitMode('excalidraw', librarySkillIds)).toBe('disabled');
+ expect(resolveImplicitMode('artifacts', librarySkillIds)).toBe('auto');
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Tools/librarySkillPolicy.ts b/src/features/ChatInput/ActionBar/Tools/librarySkillPolicy.ts
new file mode 100644
index 00000000000..b50022e7b40
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/librarySkillPolicy.ts
@@ -0,0 +1,33 @@
+import {
+ type AgentPluginEntry,
+ type AgentPluginMode,
+ getDisabledPluginIds,
+ getLibrarySkillMode,
+ LIBRARY_SKILL_IMPLICIT_MODE,
+} from '@lobechat/types';
+
+/**
+ * Identifiers the Tools popover lists under Disabled: everything the agent
+ * explicitly disabled, plus every library skill it has not turned on. A library
+ * skill is opt-in per agent — the profile is where one is turned on — so having
+ * no entry means off for it, where it means Auto for a tool or a builtin skill.
+ */
+export const resolveDisabledIds = (
+ plugins: AgentPluginEntry[] | undefined,
+ librarySkillIds: Iterable<string>,
+): string[] => [
+ ...new Set([
+ ...getDisabledPluginIds(plugins),
+ ...[...librarySkillIds].filter((id) => getLibrarySkillMode(plugins, id) === 'disabled'),
+ ]),
+];
+
+/**
+ * What `id` resolves to with no entry in the agent's plugins. Passed along with
+ * a mode change so choosing Auto on a library skill writes an explicit entry
+ * instead of removing it, which would turn the skill back off.
+ */
+export const resolveImplicitMode = (
+ id: string,
+ librarySkillIds: ReadonlySet<string>,
+): AgentPluginMode => (librarySkillIds.has(id) ? LIBRARY_SKILL_IMPLICIT_MODE : 'auto');
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 02af59d20c3..822f2bcfe2e 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -1,7 +1,7 @@
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { getConnectorCatalog, RECOMMENDED_SKILLS, RecommendedSkillType } from '@lobechat/const';
-import { type AgentPluginMode, getDisabledPluginIds } from '@lobechat/types';
+import { type AgentPluginMode } from '@lobechat/types';
import type { ItemType } from '@lobehub/ui';
import {
Avatar,
@@ -74,6 +74,7 @@ import {
import ComposioServerItem from './ComposioServerItem';
import ComposioSkillIcon from './ComposioSkillIcon';
import { SKILL_ICON_SIZE } from './constants';
+import { resolveDisabledIds, resolveImplicitMode } from './librarySkillPolicy';
import LobehubSkillIcon from './LobehubSkillIcon';
import LobehubSkillServerItem from './LobehubSkillServerItem';
import MarketAgentSkillPopoverContent from './MarketAgentSkillPopoverContent';
@@ -178,8 +179,17 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const rawPlugins = useAgentStore(
(s) => agentByIdSelectors.getAgentConfigById(agentId)(s)?.plugins,
);
- const disabledIds = useMemo(() => getDisabledPluginIds(rawPlugins), [rawPlugins]);
- const disabledIdSet = useMemo(() => new Set(disabledIds), [disabledIds]);
+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
+ // Library skills are opt-in per agent: one this agent never turned on is Disabled.
+ const librarySkillIds = useMemo(
+ () => new Set([...marketAgentSkills, ...userAgentSkills].map((skill) => skill.identifier)),
+ [marketAgentSkills, userAgentSkills],
+ );
+ const disabledIdSet = useMemo(
+ () => new Set(resolveDisabledIds(rawPlugins, librarySkillIds)),
+ [rawPlugins, librarySkillIds],
+ );
// In manual skill-activate mode, surface hidden builtin tools (web-browsing,
// cloud-sandbox, knowledge-base, etc.) so users can explicitly enable/disable them.
// In auto mode the activator handles those tools transparently, so they remain hidden.
@@ -233,24 +243,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
async (id: string, mode: SkillPolicyMode) => {
if (!canEdit) return;
- // A capability has two homes. chatConfig carries the on/off state the engine
- // reads (`resolveToolRules`), so the row, the injection and the wiring can never
- // disagree; `agents.plugins` carries the explicit Pinned/Disabled choice, which
- // is what puts the row in the Pinned or Disabled group.
- if (isCapabilityTool(id)) {
- const currentMode: SkillPolicyMode = checkedSet.has(id)
- ? 'pinned'
- : disabledIdSet.has(id)
- ? 'disabled'
- : 'auto';
- if (currentMode === mode) return;
-
- const patch = resolveCapabilityConfigPatch(id, mode);
- if (patch) await updateAgentChatConfig(patch);
- await setPluginMode(id, mode);
- return;
- }
-
const currentMode: SkillPolicyMode = checkedSet.has(id)
? 'pinned'
: disabledIdSet.has(id)
@@ -258,9 +250,15 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
: 'auto';
if (currentMode === mode) return;
- await setPluginMode(id, mode);
+ // A capability has two homes. chatConfig carries the on/off state the engine
+ // reads (`resolveToolRules`), so the row, the injection and the wiring can never
+ // disagree; `agents.plugins` carries the explicit Pinned/Disabled choice, which
+ // is what puts the row in the Pinned or Disabled group.
+ const patch = isCapabilityTool(id) ? resolveCapabilityConfigPatch(id, mode) : undefined;
+ if (patch) await updateAgentChatConfig(patch);
+ await setPluginMode(id, mode, resolveImplicitMode(id, librarySkillIds));
},
- [canEdit, checkedSet, disabledIdSet, setPluginMode, updateAgentChatConfig],
+ [canEdit, checkedSet, disabledIdSet, librarySkillIds, setPluginMode, updateAgentChatConfig],
);
const openSkillPolicyMenu = useCallback((id: string) => {
@@ -562,8 +560,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// Agent Skills related state
const installedBuiltinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);
- const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
- const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
// MCP connectors the user added: custom ones and marketplace installs
const customConnectors = useToolStore(connectorSelectors.userMcpConnectors, isEqual);
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsx
index 8625c9d21ff..83578fe8fc1 100644
--- a/src/features/ProfileEditor/AgentTool.tsx
+++ b/src/features/ProfileEditor/AgentTool.tsx
@@ -134,6 +134,18 @@ const AgentTool = memo<AgentToolProps>(
// is a distinct, valid config state; this component has no tri-state UI
// and treats it as "not enabled", matching pre-tri-state semantics).
const plugins = getActivePluginIds(config?.plugins);
+ // Everything switched on for this agent: pinned entries, plus a library skill set to Auto
+ // from the chat input — the only kind of entry that carries an explicit `auto`.
+ const enabledIds = useMemo(
+ () =>
+ new Set(
+ (config?.plugins ?? [])
+ .map((entry) => parsePluginEntry(entry))
+ .filter((entry) => entry.mode !== 'disabled')
+ .map((entry) => entry.identifier),
+ ),
+ [config?.plugins],
+ );
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
@@ -237,7 +249,7 @@ const AgentTool = memo<AgentToolProps>(
async (pluginId: string, state?: boolean) => {
if (!canEdit) return;
if (!effectiveAgentId) return;
- const hasPlugin = plugins.includes(pluginId);
+ const hasPlugin = enabledIds.has(pluginId);
const shouldEnable = state !== undefined ? state : !hasPlugin;
// Taking an item out must also work on one that is switched off: it is not pinned, but
// it still has an entry to remove.
@@ -253,13 +265,13 @@ const AgentTool = memo<AgentToolProps>(
plugins: upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),
});
},
- [canEdit, effectiveAgentId, plugins, config?.plugins, updateAgentConfigById],
+ [canEdit, effectiveAgentId, enabledIds, config?.plugins, updateAgentConfigById],
);
- // Check if a profile-managed tool is pinned.
+ // Check if a profile-managed tool is on for this agent.
const isToolEnabled = useCallback(
- (identifier: string) => plugins.includes(identifier),
- [plugins],
+ (identifier: string) => enabledIds.has(identifier),
+ [enabledIds],
);
// Toggle a profile-managed tool.
@@ -856,11 +868,10 @@ const AgentTool = memo<AgentToolProps>(
]);
// A list shows what is turned off as well, so it can be turned back on; the chips show only
- // what is on.
+ // what is on. Every entry is listed: one that is merely Auto has no entry at all, except a
+ // library skill, where an explicit Auto is what turns it on.
const listedTools = useMemo(() => {
- const entries = (config?.plugins ?? [])
- .map((entry) => parsePluginEntry(entry))
- .filter((entry) => entry.mode !== 'auto');
+ const entries = (config?.plugins ?? []).map((entry) => parsePluginEntry(entry));
const visible = getVisibleProfileToolIds(
entries.map((entry) => entry.identifier),
{
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 870466c79f9..c573f68d678 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -13,6 +13,7 @@ import { AgentRuntimeError } from '@lobechat/model-runtime/utils/createError';
import {
ChatErrorType,
type ChatMessageError,
+ getAutoPluginIds,
getDisabledPluginIds,
type RequestTrigger,
type RuntimeAdditionalContextFragment,
@@ -229,6 +230,7 @@ class ChatService {
agentId: targetAgentId,
// `agentConfig.plugins` is the raw (pre-filter) field — `plugins` below
// is already pinned-only (resolved upstream in agentConfigResolver).
+ autoSkillIds: getAutoPluginIds(agentConfig.plugins),
disabledPluginIds: getDisabledPluginIds(agentConfig.plugins),
// The stored mode passes through: a model without function calling is
// not demoted to chat mode here, matching the server runtime.
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index e7ea573d007..d668531c04b 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -68,6 +68,12 @@ interface ContextEngineeringContext {
* budget is spent (planned by `shouldCompress`).
*/
attachmentPreviewFileIds?: string[];
+ /**
+ * Library skills the agent set to `auto` (`agents.plugins` tri-state). A
+ * library skill is opt-in per agent, so one that is neither here nor in
+ * `plugins` (pinned) is left out of the client skill pool.
+ */
+ autoSkillIds?: string[];
/**
* Identifiers the agent has explicitly disabled (`agents.plugins` tri-state).
* Excluded from the client skill candidate pool entirely — not just left
@@ -135,6 +141,7 @@ export const contextEngineering = async ({
historyCount,
historySummary,
agentId,
+ autoSkillIds,
disabledPluginIds,
enableAgentMode,
groupId,
@@ -307,6 +314,7 @@ export const contextEngineering = async ({
// Reading another topic (`<refer_topic>` or a raw `tpc_` id) goes through `lh topic view`,
// which the lobehub skill teaches.
mentionsTopic(messages) ? [LobeHubIdentifier] : undefined,
+ autoSkillIds,
)
).skills;
}
diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.ts
index 822ed3645c5..c6d98274b87 100644
--- a/src/services/chat/mecha/skillEngineering.test.ts
+++ b/src/services/chat/mecha/skillEngineering.test.ts
@@ -134,15 +134,32 @@ describe('resolveClientSkills', () => {
],
});
- // pluginIds empty => skill is exposed (available list) but not pinned
- const result = await resolveClientSkills([]);
+ // set to auto, not pinned => skill is exposed (available list) without its body
+ const result = await resolveClientSkills([], undefined, 'auto', undefined, ['my-skill']);
expect(mockedGetById).not.toHaveBeenCalled();
const skill = findSkill(result.skills, 'my-skill');
+ expect(skill).toBeDefined();
expect(skill?.content).toBeUndefined();
expect(skill?.activated).toBeFalsy();
});
+ it('leaves out a library skill the agent never turned on, keeping builtin skills', async () => {
+ setToolState({
+ agentSkills: [
+ { description: 'A user skill', id: 'db-1', identifier: 'my-skill', name: 'My Skill' },
+ ],
+ builtinSkills: [
+ { content: 'guide', description: 'd', identifier: 'artifacts', name: 'Artifacts' },
+ ],
+ });
+
+ const result = await resolveClientSkills([]);
+
+ expect(findSkill(result.skills, 'my-skill')).toBeUndefined();
+ expect(findSkill(result.skills, 'artifacts')).toBeDefined();
+ });
+
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.
@@ -226,7 +243,7 @@ describe('resolveClientSkills', () => {
});
mockedGetToolStoreState.mockReturnValue(state);
- const result = await resolveClientSkills();
+ const result = await resolveClientSkills([], undefined, 'auto', undefined, ['bound-skill']);
expect(state.ensureAgentSkillsLoaded).toHaveBeenCalledTimes(1);
expect(findSkill(result.skills, 'bound-skill')).toMatchObject({ name: 'Bound' });
@@ -287,7 +304,9 @@ describe('resolveClientSkills', () => {
],
});
- const result = await resolveClientSkills([], ['disabled-skill']);
+ const result = await resolveClientSkills([], ['disabled-skill'], 'auto', undefined, [
+ 'enabled-skill',
+ ]);
expect(findSkill(result.skills, 'disabled-skill')).toBeUndefined();
expect(findSkill(result.skills, 'enabled-skill')).toBeDefined();
diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.ts
index eb6dcb0ebd6..fda42e89fad 100644
--- a/src/services/chat/mecha/skillEngineering.ts
+++ b/src/services/chat/mecha/skillEngineering.ts
@@ -30,7 +30,8 @@ const buildDbSkillContent = (detail: SkillItem): string | undefined => {
*
* Sources:
* 1. Builtin skills (e.g., Artifacts) - from toolStore.builtinSkills
- * 2. DB skills (user/market) - from the `agentSkillList` replica
+ * 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
@@ -48,6 +49,11 @@ export const resolveClientSkills = async (
skillActivateMode?: 'auto' | 'manual',
/** Selectable for this turn even in manual mode, without being pinned. */
turnSkillIds?: string[],
+ /**
+ * Library skills the agent set to `auto`. A library skill is opt-in per
+ * agent: one that is neither here nor pinned is not listed at all.
+ */
+ autoSkillIds?: string[],
): Promise<OperationSkillSet> => {
// The list is only fetched by mounted views (tool popover, side panel), so a
// send right after a page load would otherwise see no DB skills. A failed
@@ -123,6 +129,7 @@ export const resolveClientSkills = async (
return assembleSkillPool(
{ builtin: builtinMetas, db: dbMetas },
{
+ autoSkillIds,
// The desktop app is itself the execution device.
canExecuteOnDevice: isDesktop,
enabledPluginIds: pluginIds,
diff --git a/src/store/agent/slices/plugin/action.test.ts b/src/store/agent/slices/plugin/action.test.ts
index 4427f46dd1b..fba140aa319 100644
--- a/src/store/agent/slices/plugin/action.test.ts
+++ b/src/store/agent/slices/plugin/action.test.ts
@@ -361,5 +361,34 @@ describe('PluginSlice Actions', () => {
undefined,
);
});
+
+ it('keeps an explicit auto entry for a library skill, whose absence means disabled', async () => {
+ const { result } = renderHook(() => useAgentStore());
+
+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({
+ agent: {} as any,
+ success: true,
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': { plugins: ['plugin-2'] } as any },
+ });
+ });
+
+ await act(async () => {
+ await result.current.setPluginMode('excalidraw', 'auto', 'disabled');
+ });
+
+ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ plugins: ['plugin-2', { identifier: 'excalidraw', mode: 'auto' }],
+ }),
+ expect.any(AbortSignal),
+ undefined,
+ );
+ });
});
});
diff --git a/src/store/agent/slices/plugin/action.ts b/src/store/agent/slices/plugin/action.ts
index 66c62fea316..a772d7c9bff 100644
--- a/src/store/agent/slices/plugin/action.ts
+++ b/src/store/agent/slices/plugin/action.ts
@@ -49,8 +49,17 @@ export class PluginSliceActionImpl {
* Sets one identifier's explicit mode (pinned / auto / disabled). Only the
* touched entry is upgraded to object shape — every other entry, including
* untouched legacy strings, is left exactly as-is (lazy per-item upgrade).
+ *
+ * `implicitMode` is what the identifier resolves to with no entry at all:
+ * `'auto'` for tools and builtin skills, `'disabled'` for a library skill
+ * (`LIBRARY_SKILL_IMPLICIT_MODE`). Setting that mode drops the entry; any
+ * other is written explicitly, so a library skill set to `'auto'` is kept.
*/
- setPluginMode = async (id: string, mode: AgentPluginMode): Promise<void> => {
+ setPluginMode = async (
+ id: string,
+ mode: AgentPluginMode,
+ implicitMode: AgentPluginMode = 'auto',
+ ): Promise<void> => {
const originConfig = agentSelectors.currentAgentConfig(this.#get());
if (!originConfig) return;
@@ -61,7 +70,12 @@ export class PluginSliceActionImpl {
// runtime value legitimately becomes mixed-shape here (JSONB has no
// schema enforcement), so this cast is the one deliberate boundary
// where that mismatch is intentional.
- draft.plugins = upsertPluginMode(draft.plugins, id, mode) as unknown as string[];
+ draft.plugins = upsertPluginMode(
+ draft.plugins,
+ id,
+ mode,
+ implicitMode,
+ ) as unknown as string[];
});
await this.#get().updateAgentConfig(config);
diff --git a/src/store/tool/slices/builtin/executors/lobe-skill-store.ts b/src/store/tool/slices/builtin/executors/lobe-skill-store.ts
index cf7ceeba689..d22f7575545 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skill-store.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skill-store.ts
@@ -6,31 +6,53 @@
*/
import { SkillStoreExecutionRuntime } from '@lobechat/builtin-tool-skill-store/executionRuntime';
import { SkillStoreExecutor } from '@lobechat/builtin-tool-skill-store/executor';
+import { LIBRARY_SKILL_IMPLICIT_MODE, parsePluginEntry } from '@lobechat/types';
import { marketApiService } from '@/services/marketApi';
import { agentSkillService } from '@/services/skill';
+/**
+ * A library skill is opt-in per agent, so a skill the model installs mid-run
+ * would be off for the very agent that installed it. Set it to Auto there,
+ * unless the agent already has an entry: a pin or an explicit disable is the
+ * user's own choice and a re-import must not undo it.
+ */
+const turnOnForActiveAgent = async (skill: { identifier: string }) => {
+ // Dynamic import to avoid circular dependency (this file is inside the tool store)
+ const { getAgentStoreState } = await import('@/store/agent/store');
+ const { agentSelectors } = await import('@/store/agent/selectors');
+ const agentState = getAgentStoreState();
+ const plugins = agentSelectors.currentAgentConfig(agentState)?.plugins ?? [];
+ if (plugins.some((entry) => parsePluginEntry(entry).identifier === skill.identifier)) return;
+
+ await agentState.setPluginMode(skill.identifier, 'auto', LIBRARY_SKILL_IMPLICIT_MODE);
+};
+
// Create runtime with client-side service
const runtime = new SkillStoreExecutionRuntime({
service: {
importFromGitHub: async (gitUrl) => {
const result = await agentSkillService.importFromGitHub({ gitUrl });
if (!result) throw new Error('Import failed');
+ await turnOnForActiveAgent(result.skill);
return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
},
importFromMarket: async (identifier) => {
const result = await agentSkillService.importFromMarket(identifier);
if (!result) throw new Error('Import failed');
+ await turnOnForActiveAgent(result.skill);
return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
},
importFromUrl: async (url) => {
const result = await agentSkillService.importFromUrl({ url });
if (!result) throw new Error('Import failed');
+ await turnOnForActiveAgent(result.skill);
return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
},
importFromZipUrl: async (url) => {
const result = await agentSkillService.importFromUrl({ url });
if (!result) throw new Error('Import failed');
+ await turnOnForActiveAgent(result.skill);
return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
},
onSkillImported: async () => {