π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(skills): align Skills prompts and activation fallback with runtime contract (#23649)
AmAzing-c45b8e68c938
diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts b/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.tsindex d968c44c455..2495a928ecf 100644--- a/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts+++ b/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts@@ -6,13 +6,16 @@* batch path silently dropped these fields once already.*/export const resolveRunProjectSkills = (plan?: {- skills?: { skills?: { location?: string; name: string; source?: string }[] };-}): { location: string; name: string; source: 'device' | 'project' }[] =>+ skills?: {+ skills?: { description?: string; location?: string; name: string; source?: string }[];+ };+}): { description?: string; location: string; name: string; source: 'device' | 'project' }[] =>(plan?.skills?.skills ?? []).filter((skill) => (skill.source === 'project' || skill.source === 'device') && !!skill.location,).map((skill) => ({+ ...(skill.description ? { description: skill.description } : {}),location: skill.location as string,name: skill.name,source: skill.source === 'device' ? ('device' as const) : ('project' as const),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.tsindex 5c45d210b6c..9c97b06f375 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts@@ -1,10 +1,16 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({+ executeToolCall: vi.fn(),findAll: vi.fn(),findById: vi.fn(),findByName: vi.fn(),getAgentConfigById: vi.fn(),+ getAgentSkills: vi.fn(),+ listCatalog: vi.fn(),+ loadRuntimeSkills: vi.fn(),+ resolveContentWorkspaceId: vi.fn(),+ resolveRunWorkspaceId: vi.fn(),}));vi.mock('@lobechat/builtin-skills', () => ({@@ -35,6 +41,38 @@ vi.mock('@/helpers/skillFilters', () => ({}),}));+vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: vi.fn(function () {+ return {+ getAgentSkills: mocks.getAgentSkills,+ };+ }),+}));++vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>+ mocks.executeToolCall(...args),+}));++vi.mock('@/server/services/userSkill', async () => {+ const actual = await vi.importActual('@/server/services/userSkill');++ return {+ ...(actual as Record<string, unknown>),+ UserSkillService: vi.fn(function () {+ return {+ listCatalog: mocks.listCatalog,+ loadRuntimeSkills: mocks.loadRuntimeSkills,+ };+ }),+ };+});++vi.mock('../resolveWorkspaceScope', () => ({+ resolveContentWorkspaceId: mocks.resolveContentWorkspaceId,+ resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,+}));+vi.mock('@/server/services/agentSignal/procedure', () => ({emitToolOutcomeSafely: vi.fn().mockResolvedValue(undefined),resolveToolOutcomeScope: vi.fn(function () {@@ -57,9 +95,16 @@ describe('activatorRuntime', () => {beforeEach(() => {vi.clearAllMocks();mocks.getAgentConfigById.mockResolvedValue({ plugins: [] });+ mocks.getAgentSkills.mockResolvedValue([]);mocks.findAll.mockResolvedValue({ data: [], total: 0 });mocks.findById.mockResolvedValue(undefined);mocks.findByName.mockResolvedValue(undefined);+ mocks.listCatalog.mockResolvedValue([]);+ mocks.loadRuntimeSkills.mockResolvedValue([]);+ mocks.resolveContentWorkspaceId.mockImplementation(+ async (ctx?: { workspaceId?: string }) => ctx?.workspaceId,+ );+ mocks.resolveRunWorkspaceId.mockResolvedValue(undefined);});describe('activateSkill β disabled skill enforcement', () => {@@ -229,6 +274,42 @@ describe('activatorRuntime', () => {expect(outcome.domainKey).toBeUndefined();}, 20_000);+ it('activates a tool without opening the skill sources', async () => {+ // The factory runs for every tool call. Opening the skill runtime there+ // read the agent config, its workspace and all its skill documents for+ // a call that names only tools.+ const { activatorRuntime } = await import('../activator');+ const runtime = await activatorRuntime.factory({+ agentId: 'agent-1',+ serverDB: {} as never,+ toolManifestMap: { 'lobe-web-browsing': webBrowsingManifest },+ userId: 'user-1',+ });++ const result = await runtime.activateTools({ identifiers: ['lobe-web-browsing'] });++ expect(result.state.activatedTools).toHaveLength(1);+ expect(mocks.getAgentConfigById).not.toHaveBeenCalled();+ expect(mocks.resolveContentWorkspaceId).not.toHaveBeenCalled();+ expect(mocks.getAgentSkills).not.toHaveBeenCalled();+ }, 20_000);++ it('opens the skill sources once for several identifiers that are not tools', async () => {+ const { activatorRuntime } = await import('../activator');+ const runtime = await activatorRuntime.factory({+ agentId: 'agent-1',+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ });++ const result = await runtime.activateTools({ identifiers: ['no-such-a', 'no-such-b'] });++ expect(result.state.notFound).toEqual(['no-such-a', 'no-such-b']);+ expect(mocks.getAgentSkills).toHaveBeenCalledTimes(1);+ expect(mocks.resolveContentWorkspaceId).toHaveBeenCalledTimes(1);+ }, 20_000);+it('still reports a skill opened through the activateTools fallback as a skill', async () => {mocks.findByName.mockImplementation(async (name: string) =>name === 'user-skill' ? userSkillRow() : undefined,@@ -509,4 +590,114 @@ describe('activatorRuntime', () => {expect(result.content).not.toContain('Successfully activated');}, 20_000);});++ describe('activateTools β full skill source parity with lobe-skills', () => {+ it('resolves agent-document, project filesystem, and user-library skills via fallback', async () => {+ mocks.getAgentSkills.mockResolvedValue([+ {+ content: '# Agent workflow body',+ description: 'Agent workflow',+ identifier: 'agent-skills:workflow',+ name: 'agent-skills:workflow',+ title: 'Workflow',+ },+ ]);+ mocks.executeToolCall.mockResolvedValue({+ content: '# Deploy skill body',+ success: true,+ });+ mocks.loadRuntimeSkills.mockResolvedValue([+ {+ body: '# Saved plan body',+ content: '# Saved plan body',+ description: 'Saved plan',+ identifier: 'user-skills:saved-plan',+ name: 'user-skills:saved-plan',+ title: 'Saved Plan',+ },+ ]);++ const { activatorRuntime } = await import('../activator');+ const runtime = await activatorRuntime.factory({+ activeDeviceId: 'device-1',+ agentId: 'agent-1',+ projectSkills: [+ {+ description: 'Project deploy',+ location: '/repo/.agents/skills/deploy/SKILL.md',+ name: 'deploy',+ source: 'project',+ },+ ],+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ });++ const result = await runtime.activateTools({+ identifiers: ['agent-skills:workflow', 'deploy', 'user-skills:saved-plan'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('# Agent workflow body');+ expect(result.content).toContain('# Deploy skill body');+ expect(result.content).toContain('# Saved plan body');+ expect(result.state?.notFound).toEqual([]);+ expect(result.state?.activatedSkills).toHaveLength(3);+ }, 20_000);++ it('still blocks ungranted agent/project/user skills for share visitors', async () => {+ mocks.getAgentSkills.mockResolvedValue([+ {+ content: '# Secret agent skill',+ description: 'Secret',+ identifier: 'agent-skills:secret',+ name: 'agent-skills:secret',+ },+ ]);+ mocks.loadRuntimeSkills.mockResolvedValue([+ {+ body: '# Secret user skill',+ content: '# Secret user skill',+ description: 'Secret',+ identifier: 'user-skills:secret',+ name: 'user-skills:secret',+ title: 'Secret',+ },+ ]);++ const { activatorRuntime } = await import('../activator');+ const runtime = await activatorRuntime.factory({+ activeDeviceId: 'device-1',+ agentId: 'agent-1',+ agentShareVisitor: {+ skillGrants: ['allowed-skill'],+ toolGrants: [{ identifier: 'lobe-calculator' }],+ } as never,+ projectSkills: [+ {+ location: '/repo/.agents/skills/secret-proj/SKILL.md',+ name: 'secret-proj',+ source: 'project',+ },+ ],+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'creator-1',+ });++ const result = await runtime.activateTools({+ identifiers: ['agent-skills:secret', 'secret-proj', 'user-skills:secret'],+ });++ expect(result.state?.activatedSkills).toEqual([]);+ expect(result.state?.notFound).toEqual([+ 'agent-skills:secret',+ 'secret-proj',+ 'user-skills:secret',+ ]);+ expect(mocks.executeToolCall).not.toHaveBeenCalled();+ expect(mocks.loadRuntimeSkills).not.toHaveBeenCalled();+ }, 20_000);+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.activationConsistency.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.activationConsistency.test.tsnew file mode 100644index 00000000000..ca24d1b8024--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.activationConsistency.test.ts@@ -0,0 +1,234 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ agentDocumentsCtor: vi.fn(),+ executeToolCall: vi.fn(),+ findAll: vi.fn(),+ findById: vi.fn(),+ findByName: vi.fn(),+ getAgentConfigById: vi.fn(),+ getAgentSkills: vi.fn(),+ getUserSettings: vi.fn(),+ listCatalog: vi.fn(),+ loadRuntimeSkills: vi.fn(),+ resolveContentWorkspaceId: vi.fn(),+ resolveRunWorkspaceId: vi.fn(),+}));++vi.mock('@lobechat/builtin-skills', () => ({+ builtinSkills: [+ {+ content: '# Artifacts body',+ description: 'Render artifacts',+ identifier: 'artifacts',+ name: 'Artifacts',+ source: 'builtin',+ },+ ],+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn(function () {+ return {+ getAgentConfigById: mocks.getAgentConfigById,+ };+ }),+}));++vi.mock('@/database/models/agentSkill', () => ({+ AgentSkillModel: vi.fn(function () {+ return {+ findAll: mocks.findAll,+ findById: mocks.findById,+ findByName: mocks.findByName,+ };+ }),+}));++vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn(function () {+ return { checkHash: vi.fn() };+ }),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(function () {+ return {+ getUserSettings: mocks.getUserSettings,+ };+ }),+}));++vi.mock('@/helpers/skillFilters', () => ({+ filterBuiltinSkills: vi.fn(function (skills: unknown) {+ return skills;+ }),+}));++vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: vi.fn(function (...args: unknown[]) {+ mocks.agentDocumentsCtor(...args);+ return {+ getAgentSkills: mocks.getAgentSkills,+ };+ }),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return { getFullFileUrl: vi.fn() };+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/server/services/sandbox', async () => {+ const actual = await vi.importActual('@/server/services/sandbox');+ return {+ ...(actual as Record<string, unknown>),+ createSandboxService: vi.fn(),+ resolveSandboxSessionConfig: vi.fn().mockResolvedValue({}),+ };+});++vi.mock('@/server/services/skill/resource', () => ({+ SkillResourceService: vi.fn(function () {+ return { readResource: vi.fn() };+ }),+}));++vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>+ mocks.executeToolCall(...args),+}));++vi.mock('@/server/services/userSkill', async () => {+ const actual = await vi.importActual('@/server/services/userSkill');+ return {+ ...(actual as Record<string, unknown>),+ UserSkillService: vi.fn(function () {+ return {+ listCatalog: mocks.listCatalog,+ loadRuntimeSkills: mocks.loadRuntimeSkills,+ };+ }),+ };+});++vi.mock('../resolveWorkspaceScope', () => ({+ resolveContentWorkspaceId: mocks.resolveContentWorkspaceId,+ resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,+}));++describe('skillsRuntime prompt/runtime consistency', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findAll.mockResolvedValue({ data: [], total: 0 });+ mocks.findById.mockResolvedValue(undefined);+ mocks.findByName.mockResolvedValue(undefined);+ mocks.getAgentConfigById.mockResolvedValue({+ plugins: [+ { identifier: 'artifacts', mode: 'auto' },+ { identifier: 'db-skill-id', mode: 'auto' },+ ],+ });+ mocks.getAgentSkills.mockResolvedValue([]);+ mocks.getUserSettings.mockResolvedValue({});+ mocks.listCatalog.mockResolvedValue([]);+ mocks.loadRuntimeSkills.mockResolvedValue([]);+ mocks.resolveContentWorkspaceId.mockResolvedValue('ws-recovered');+ mocks.resolveRunWorkspaceId.mockResolvedValue(undefined);+ });++ it('uses the recovered workspaceId when loading agent-document skills', async () => {+ mocks.getAgentSkills.mockResolvedValue([+ {+ content: '# Agent skill body',+ description: 'Agent doc skill',+ identifier: 'agent-skills:guide',+ name: 'agent-skills:guide',+ },+ ]);++ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ agentId: 'agent-1',+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ // Deliberately omitted to mirror dispatch/resume paths+ });++ const result = await runtime.activateSkill({ name: 'agent-skills:guide' });++ expect(mocks.agentDocumentsCtor).toHaveBeenCalledWith(+ expect.anything(),+ 'user-1',+ 'ws-recovered',+ );+ expect(result.success).toBe(true);+ expect(result.content).toContain('# Agent skill body');+ }, 20_000);++ it('returns project, DB, builtin, agent-document, and user-library skills on activateSkill miss', async () => {+ mocks.findAll.mockResolvedValue({+ data: [{ description: 'DB helper', id: '1', identifier: 'db-skill-id', name: 'db-helper' }],+ total: 1,+ });+ mocks.getAgentSkills.mockResolvedValue([+ {+ content: '# Agent doc',+ description: 'Agent doc',+ identifier: 'agent-skills:doc',+ name: 'agent-skills:doc',+ },+ ]);+ mocks.listCatalog.mockResolvedValue([+ {+ description: 'Saved user plan',+ generated: false,+ identifier: 'user-skills:plan',+ name: 'user-skills:plan',+ title: 'Plan',+ },+ ]);++ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ activeDeviceId: 'device-1',+ agentId: 'agent-1',+ projectSkills: [+ {+ description: 'Project deploy',+ location: '/repo/.agents/skills/deploy/SKILL.md',+ name: 'deploy',+ source: 'project',+ },+ ],+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });++ const result = await runtime.activateSkill({ name: 'typo-skill' });++ expect(result.success).toBe(false);+ const candidates = JSON.parse(result.content.slice(result.content.indexOf('['))) as Array<{+ description?: string;+ name: string;+ }>;+ expect(candidates).toEqual([+ { description: 'Project deploy', name: 'deploy' },+ { description: 'DB helper', name: 'db-helper' },+ { description: 'Render artifacts', name: 'Artifacts' },+ { description: 'Agent doc', name: 'agent-skills:doc' },+ { description: 'Saved user plan', name: 'user-skills:plan' },+ ]);+ }, 20_000);+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.tsindex 9dd4a0a316c..50f5edd9ef6 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts@@ -1,24 +1,20 @@-import { builtinSkills } from '@lobechat/builtin-skills';import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import {ActivatorExecutionRuntime,type ActivatorRuntimeService,type ToolManifestInfo,} from '@lobechat/builtin-tool-activator/executionRuntime';-import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';-import { resolveShareAllowedSkillIds } from '@lobechat/const';+import { type SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';import { describeLockedDevicePicker } from '@lobechat/types';-import { AgentSkillModel } from '@/database/models/agentSkill';-import { filterBuiltinSkills } from '@/helpers/skillFilters';import {emitToolOutcomeSafely,resolveToolOutcomeScope,} 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 { createSkillActivationRuntime } from './skillActivation';import { type ServerRuntimeRegistration } from './types';/**@@ -87,65 +83,23 @@ export const activatorRuntime: ServerRuntimeRegistration = {});};- // Create SkillsExecutionRuntime for activateSkill delegation- let skillsRuntime: SkillsExecutionRuntime | undefined;- if (context.serverDB && context.userId) {- const skillModel = new AgentSkillModel(context.serverDB, context.userId, context.workspaceId);-- // `activateSkill` resolves independently of `operationSkillSet`/- // `<available_skills>` (built once, earlier, in aiAgent/index.ts) β it- // queries builtins/DB directly by name. Without this guard, a skill- // the agent has explicitly disabled would no longer be *listed*, but a- // 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.- 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- // for any identifier that is not a tool, so without this check a- // model-supplied name would open a skill the share never granted β- // the same model-supplied-name hole the skills runtime closes with its- // own `isSkillGranted` predicate (`skills.ts`).- const shareVisitor = context.agentShareVisitor;- 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- // activatable in device-capable runs (matching <available_skills>),- // with `activeDeviceId` as the fallback for callers without a plan.- builtinSkills: filterBuiltinSkills(builtinSkills, {- canExecuteOnDevice: context.deviceCapable ?? !!context.activeDeviceId,- }).filter((skill) => isLibrarySkillReachable(skill.identifier)),- service: {- findAll: async () => {- const result = await skillModel.findAll();- if (!shareVisitor && !isLibrarySkillEnabled) return result;-- 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 && isLibrarySkillReachable(skill.identifier) ? skill : undefined;- },- findByName: async (name) => {- const skill = await skillModel.findByName(name);- return skill && isLibrarySkillReachable(skill.identifier) ? skill : undefined;- },- readResource: async () => {- throw new Error('readResource not available in tools runtime');- },- },- });- }+ // Share the full skill-activation runtime with `lobe-skills` so the+ // `activateTools` skill fallback resolves agent-document, filesystem+ // (project/device), and user-library skills under the exact same gates.+ //+ // Opened on the first skill activation, not here: this factory runs for+ // every tool call, and most `activateTools` calls name only tools. Opening+ // it reads the agent's config, its workspace and every skill document it+ // owns, none of which a tool activation uses.+ const { serverDB, userId } = context;+ let skillsRuntime: Promise<SkillsExecutionRuntime> | undefined;+ const getSkillsRuntime =+ serverDB && userId+ ? () => (skillsRuntime ??= createSkillActivationRuntime({ ...context, serverDB, userId }))+ : undefined;const service: ActivatorRuntimeService = {- activateSkill: skillsRuntime+ activateSkill: getSkillsRuntime? async (args, options) => {const reportFailure = (errorReason: string) =>emitActivationOutcome({@@ -158,7 +112,7 @@ export const activatorRuntime: ServerRuntimeRegistration = {let result: Awaited<ReturnType<SkillsExecutionRuntime['activateSkill']>>;try {- result = await skillsRuntime!.activateSkill(args);+ result = await (await getSkillsRuntime()).activateSkill(args);} catch (error) {await reportFailure((error as Error).message);throw error;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skillActivation.ts b/apps/server/src/services/toolExecution/serverRuntimes/skillActivation.tsnew file mode 100644index 00000000000..02945b7c89e--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/skillActivation.ts@@ -0,0 +1,362 @@+import { builtinSkills } from '@lobechat/builtin-skills';+import { LocalSystemApiName, LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';+import {+ type DeviceFileAccess,+ type ProjectSkillRuntimeItem,+ SkillsExecutionRuntime,+} from '@lobechat/builtin-tool-skills/executionRuntime';+import { resolveShareAllowedSkillIds } from '@lobechat/const';+import type { BuiltinSkill } from '@lobechat/types';+import debug from 'debug';++import { AgentSkillModel } from '@/database/models/agentSkill';+import { TaskModel } from '@/database/models/task';+import type { LobeChatDatabase } from '@/database/type';+import { filterBuiltinSkills } from '@/helpers/skillFilters';+import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';+import {+ canonicalUserSkillIdentifier,+ readTaskSkillIds,+ type UserRuntimeSkill,+ UserSkillService,+} from '@/server/services/userSkill';++import type { ToolExecutionContext } from '../types';+import { type readSkillUserSettings, resolveAgentSkillGates } from './librarySkillGate';+import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';++const log = debug('lobe-server:skill-activation');++export type SkillActivationContext = ToolExecutionContext & {+ serverDB: LobeChatDatabase;+ userId: string;+};++export interface ResolvedSkillActivationResources {+ builtinSkills: BuiltinSkill[];+ deviceFileAccess?: DeviceFileAccess;+ disabledSkillIds: Set<string>;+ isLibrarySkillEnabled?: (identifier: string) => boolean;+ isLibrarySkillReachable: (identifier: string) => boolean;+ isSkillGranted?: (identifier: string) => boolean;+ isSkillReachable: (identifier: string) => boolean;+ listAvailableSkills: () => Promise<Array<{ description?: string; name: string }>>;+ loadUserSkill: (requested: string) => Promise<UserRuntimeSkill | undefined>;+ projectSkills?: ProjectSkillRuntimeItem[];+ resolveDeviceWorkspaceId: () => Promise<string | undefined>;+ resolveSkill: (requested: string) => Promise<BuiltinSkill | undefined>;+ workspaceId?: string;+}++/**+ * Shared skill-source resolution for both `lobe-skills` (`skills.ts`) and the+ * `lobe-activator` skill fallback (`activator.ts`).+ *+ * Keeping one assembly path ensures agent-document bundles (`agent-skills:*`),+ * project/device filesystem skills, user-library skills (`user-skills:*`),+ * workspace recovery, agent tri-state gates, and Agent Share grants behave+ * identically regardless of which tool activated the skill.+ */+export const resolveSkillActivationResources = async (+ context: SkillActivationContext,+ options?: {+ userSettings?: Awaited<ReturnType<typeof readSkillUserSettings>>;+ },+): Promise<ResolvedSkillActivationResources> => {+ // 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,+ options?.userSettings,+ );++ // The share's own opt-out, for the same reason: the creator named the+ // skills a visitor may load (`shareConfig.skillGrants`), and the+ // operation's skill pool was already intersected with that grant at+ // assembly (`filterSkillsByShareGate`) β but `activateSkill` /+ // `readReference` / `execScript` all resolve a MODEL-SUPPLIED name, so a+ // name the pool never offered still arrives here. This predicate is that+ // second, authoritative check.+ //+ // `resolveShareAllowedSkillIds` intersects candidates with the grant, so+ // passing the single id under test makes each call exactly the membership+ // question this predicate asks.+ const shareVisitor = context.agentShareVisitor;+ const isSkillGranted = shareVisitor+ ? (identifier: string) => resolveShareAllowedSkillIds([identifier], shareVisitor).length > 0+ : undefined;++ /**+ * The two opt-outs applied to non-library sources (agent documents, user+ * skill library, filesystem skills) β filtering at assembly closes the+ * fall-through where a refused DB lookup would otherwise match a later branch.+ */+ const isSkillReachable = (identifier: string) =>+ !disabledSkillIds.has(identifier) && (isSkillGranted?.(identifier) ?? true);++ /** Library (DB & builtin) skills additionally require opt-in per agent. */+ const isLibrarySkillReachable = (identifier: string) =>+ isSkillReachable(identifier) && (isLibrarySkillEnabled?.(identifier) ?? true);++ /**+ * The workspace everything this runtime touches belongs to β the skills it+ * can see, the files it writes, and the sandbox session it reaches.+ *+ * Recovered rather than read off the context: the dispatch and resume paths+ * do not carry it, and there a workspace topic resolved in the personal+ * scope, came back "no such topic", and ran ephemeral β `pwd` answered+ * `/workspace` while the conversation showed a persistent instance.+ */+ const workspaceId = await resolveContentWorkspaceId(context);++ let runWorkspaceIdPromise: Promise<string | undefined> | undefined;+ const resolveDeviceWorkspaceId = () => (runWorkspaceIdPromise ??= resolveRunWorkspaceId(context));++ // The user's own skill library is read per call, for the one name asked+ // for β it grows with every goal batch, and this factory runs per tool+ // call. Read under the recovered workspace (a dispatched or resumed run may+ // not carry it on the context).+ const loadUserSkill = async (requested: string): Promise<UserRuntimeSkill | undefined> => {+ // Models vary the casing of a name, as the preloaded lookup tolerates.+ const name = canonicalUserSkillIdentifier(requested);+ if (!name || !isSkillReachable(name)) return undefined;++ try {+ const trustedGenerated = context.taskId+ ? readTaskSkillIds(+ (+ await new TaskModel(context.serverDB, context.userId, workspaceId).findById(+ context.taskId,+ )+ )?.config,+ )+ : [];+ const [skill] = await new UserSkillService(+ context.serverDB,+ context.userId,+ workspaceId,+ context.agentVisibility,+ ).loadRuntimeSkills([name], {+ // Only the generated skills this run's own Task names are trusted+ // past a public agent's visibility β never a name the model chose.+ trustedGenerated,+ });+ return skill;+ } catch (error) {+ log('failed to load user skill %s: %O', name, error);+ return undefined;+ }+ };++ // Surface this agent's skill-bundle documents as `BuiltinSkill`-shaped+ // entries so `activateSkill('agent-skills:<filename>')` resolves on the+ // existing no-DB-lookup path β no `SkillRuntimeService` extension needed.+ // `AgentDocumentsService.getAgentSkills` is the single source of truth for+ // the identifier prefix and the bundle β index-child content resolution+ // (also used by `operationSkillSet.ts` when building `<available_skills>`).+ // `source: 'builtin'` is the type-system carrier shape required by+ // `BuiltinSkill`; the runtime re-tags `source: 'agent'` in the activateSkill+ // result based on the identifier prefix so the inspector can show+ // "Activate Agent Skill" + the friendly `title`.+ const agentSkillBuiltins: BuiltinSkill[] = context.agentId+ ? await new AgentDocumentsService(context.serverDB, context.userId, workspaceId)+ .getAgentSkills(context.agentId)+ .then((skills) =>+ skills+ .filter((skill) => isSkillReachable(skill.identifier))+ .map((skill) => ({+ content: skill.content,+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ source: 'builtin' as const,+ ...(skill.title && { title: skill.title }),+ })),+ )+ .catch((error) => {+ log('failed to load agent skills for agent %s: %O', context.agentId, error);+ return [];+ })+ : [];++ // Project/device skills live on the execution device filesystem. Read them+ // through the device gateway by reusing the local-system tools β no special+ // file-read primitive, just the existing capabilities over deviceGateway.+ // - `readFile` loads SKILL.md and validated reference files.+ // - `globFiles` enumerates the skill directory so `readReference` can+ // reject paths the model guessed (e.g. `.env`) instead of trusting+ // the raw string.+ const { activeDeviceId, projectSkills } = context;+ let deviceFileAccess: DeviceFileAccess | undefined;+ if (activeDeviceId) {+ const userId = context.userId;+ deviceFileAccess = {+ listFiles: async (dir: string) => {+ const result = await executeAuthorizedDeviceToolCall(+ context.serverDB,+ {+ deviceId: activeDeviceId,+ userId,+ workspaceId: await resolveDeviceWorkspaceId(),+ },+ {+ apiName: LocalSystemApiName.globFiles,+ // `**/*` matches every regular file recursively under `dir`.+ // The device-side enumerator already skips hidden files; the+ // runtime re-checks segments as defense in depth.+ arguments: JSON.stringify({ pattern: '**/*', scope: dir }),+ identifier: LocalSystemIdentifier,+ },+ );+ if (!result.success) {+ throw new Error(result.error || result.content || `globFiles failed: ${dir}`);+ }+ let payload: { files?: unknown };+ try {+ payload = JSON.parse(result.content) as { files?: unknown };+ } catch {+ throw new Error(`globFiles returned a non-JSON payload for ${dir}`);+ }+ if (!Array.isArray(payload.files)) return [];+ // Files come back as paths relative to `scope` (POSIX). Strip any+ // absolute path the engine may have emitted so the runtime can+ // compare against normalized user-supplied relative paths.+ return payload.files+ .filter((f): f is string => typeof f === 'string')+ .map((f) => (f.startsWith(dir) ? f.slice(dir.length).replace(/^[/\\]+/, '') : f));+ },+ readFile: async (filePath: string) => {+ const result = await executeAuthorizedDeviceToolCall(+ context.serverDB,+ {+ deviceId: activeDeviceId,+ userId,+ workspaceId: await resolveDeviceWorkspaceId(),+ },+ {+ apiName: LocalSystemApiName.readFile,+ // Read the whole file; SKILL.md and references are small.+ arguments: JSON.stringify({ loc: [0, 5000], path: filePath }),+ identifier: LocalSystemIdentifier,+ },+ );+ if (!result.success) {+ throw new Error(result.error || result.content || `readFile failed: ${filePath}`);+ }+ return result.content;+ },+ };+ }++ const resolveSkill = async (requested: string): Promise<BuiltinSkill | undefined> => {+ const skill = await loadUserSkill(requested);+ return (+ skill && {+ content: skill.body,+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ resources: skill.resources,+ source: 'builtin' as const,+ title: skill.title,+ }+ );+ };++ // Called only on an `activateSkill` miss so the not-found recovery list+ // includes the user's skill library without paying a catalog query on hits.+ const listAvailableSkills = async (): Promise<Array<{ description?: string; name: string }>> => {+ try {+ const userSkillService = new UserSkillService(+ context.serverDB,+ context.userId,+ workspaceId,+ context.agentVisibility,+ );+ const catalog = await userSkillService.listCatalog({ includeGenerated: false });+ return catalog+ .filter((skill) => isSkillReachable(skill.identifier))+ .map((skill) => ({ description: skill.description, name: skill.name }));+ } catch (error) {+ log('failed to list user skills catalog: %O', error);+ return [];+ }+ };++ return {+ builtinSkills: [+ // Match the device and opt-in gates of the operation's skill catalog.+ ...filterBuiltinSkills(builtinSkills, {+ canExecuteOnDevice: context.deviceCapable ?? !!activeDeviceId,+ }).filter((skill) => isLibrarySkillReachable(skill.identifier)),+ ...agentSkillBuiltins,+ ],+ deviceFileAccess,+ disabledSkillIds,+ isLibrarySkillEnabled,+ isLibrarySkillReachable,+ isSkillGranted,+ isSkillReachable,+ listAvailableSkills,+ loadUserSkill,+ // Filesystem skills carry no identifier of their own; the skill pool+ // derives one as `<source>:<name>` (see `operationSkillSet`'s `projectMetas`)+ // and that is what a `skillGrants` entry names, so rebuild it the same+ // way rather than matching on the bare name.+ projectSkills: projectSkills?.filter((skill) =>+ isSkillReachable(`${skill.source ?? 'project'}:${skill.name}`),+ ),+ resolveDeviceWorkspaceId,+ resolveSkill,+ workspaceId,+ };+};++/**+ * Create a read-only `SkillsExecutionRuntime` for `lobe-activator`'s+ * `activateSkill` / `activateTools` skill fallback, wired to the exact same+ * sources and gates as `lobe-skills`.+ */+export const createSkillActivationRuntime = async (+ context: SkillActivationContext,+): Promise<SkillsExecutionRuntime> => {+ const resources = await resolveSkillActivationResources(context);+ const skillModel = new AgentSkillModel(context.serverDB, context.userId, resources.workspaceId);++ return new SkillsExecutionRuntime({+ builtinSkills: resources.builtinSkills,+ deviceFileAccess: resources.deviceFileAccess,+ listAvailableSkills: resources.listAvailableSkills,+ projectSkills: resources.projectSkills,+ resolveSkill: resources.resolveSkill,+ service: {+ findAll: async () => {+ const result = await skillModel.findAll();+ if (+ !resources.isSkillGranted &&+ !resources.isLibrarySkillEnabled &&+ resources.disabledSkillIds.size === 0+ ) {+ return result;+ }++ const data = result.data.filter((skill) =>+ resources.isLibrarySkillReachable(skill.identifier),+ );+ return { data, total: data.length };+ },+ findById: async (id) => {+ const skill = await skillModel.findById(id);+ return skill && resources.isLibrarySkillReachable(skill.identifier) ? skill : undefined;+ },+ findByName: async (name) => {+ const skill = await skillModel.findByName(name);+ return skill && resources.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/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex e74a09e3db7..10875ce70d7 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -1,38 +1,25 @@-import { builtinSkills } from '@lobechat/builtin-skills';import type { SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';import { LocalSystemApiName, LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';-// Note: only `readFile` is wired through deviceGateway. Directory enumeration is-// left to the model via `local-system.globFiles` so we don't double-fetch.import {type CommandResult,type ExecScriptActivatedSkill,SkillsIdentifier,} from '@lobechat/builtin-tool-skills';import {- type DeviceFileAccess,type ExportFileResult,getDirname,type SkillRuntimeService,SkillsExecutionRuntime,} from '@lobechat/builtin-tool-skills/executionRuntime';import { BRANDING_NAME } from '@lobechat/business-const';-import { resolveShareAllowedSkillIds } from '@lobechat/const';-import {- type BuiltinSkill,- type SkillItem,- type SkillListItem,- type SkillResourceContent,-} from '@lobechat/types';+import { type SkillItem, type SkillListItem, type SkillResourceContent } from '@lobechat/types';import { toRecord } from '@lobechat/utils/object';import debug from 'debug';import { AgentSkillModel } from '@/database/models/agentSkill';import { FileModel } from '@/database/models/file';-import { TaskModel } from '@/database/models/task';import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';-import { filterBuiltinSkills } from '@/helpers/skillFilters';-import { AgentDocumentsService } from '@/server/services/agentDocuments';import { deviceGateway } from '@/server/services/deviceGateway';import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';import { FileService } from '@/server/services/file';@@ -51,16 +38,13 @@ import {isLhCommand,preprocessLhCommand,} from '@/server/services/toolExecution/preprocessLhCommand';-import {- canonicalUserSkillIdentifier,- readTaskSkillIds,- UserSkillService,-} from '@/server/services/userSkill';+import { canonicalUserSkillIdentifier } from '@/server/services/userSkill';-import { readSkillUserSettings, resolveAgentSkillGates } from './librarySkillGate';+import { readSkillUserSettings } from './librarySkillGate';import { pageSandboxWrapper, type SandboxWrapper } from './pageSandboxSync';-import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';+import { resolveContentWorkspaceId } from './resolveWorkspaceScope';import { createSandboxMarketService } from './sandboxMarket';+import { resolveSkillActivationResources } from './skillActivation';import { type ServerRuntimeRegistration } from './types';const log = debug('lobe-server:skills-runtime');@@ -272,12 +256,15 @@ class SkillServerRuntimeService implements SkillRuntimeService {findAll = async (): Promise<{ data: SkillListItem[]; total: number }> => {const result = await this.skillModel.findAll();- if (!this.isSkillGranted && !this.isLibrarySkillEnabled) return result;+ if (!this.isSkillGranted && !this.isLibrarySkillEnabled && this.disabledSkillIds.size === 0) {+ return result;+ }// 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.+ // offered a skill its agent never turned on or explicitly disabled. 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 };};@@ -896,53 +883,23 @@ export const skillsRuntime: ServerRuntimeRegistration = {);const marketAccessToken = userSettings?.market?.accessToken;- // 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,- userSettings,+ const activation = await resolveSkillActivationResources(+ { ...context, serverDB: context.serverDB, userId: context.userId },+ { userSettings },);-- // The share's own opt-out, for the same reason: the creator named the- // skills a visitor may load (`shareConfig.skillGrants`), and the- // operation's skill pool was already intersected with that grant at- // assembly (`filterSkillsByShareGate`) β but `activateSkill` /- // `readReference` / `execScript` all resolve a MODEL-SUPPLIED name, so a- // name the pool never offered still arrives here. This predicate is that- // second, authoritative check.- //- // `resolveShareAllowedSkillIds` intersects candidates with the grant, so- // passing the single id under test makes each call exactly the membership- // question this predicate asks.- const shareVisitor = context.agentShareVisitor;- const isSkillGranted = shareVisitor- ? (identifier: string) => resolveShareAllowedSkillIds([identifier], shareVisitor).length > 0- : undefined;-- /**- * The same two opt-outs `SkillServerRuntimeService.isSkillReachable`- * applies to DB lookups, for the sources that reach the runtime as plain- * LISTS instead of being resolved through the service.- *- * Filtering here β not inside a per-call check β is what closes the- * fall-through: `activateSkill` tries the DB first and, on a miss, walks on- * to the builtin / agent-document / filesystem branches, which do no lookup- * at all. A skill refused by the service would otherwise simply be found- * one branch later.- */- const isSkillReachable = (identifier: string) =>- !disabledSkillIds.has(identifier) && (isSkillGranted?.(identifier) ?? true);-- /**- * The workspace everything this runtime touches belongs to β the skills it- * can see, the files it writes, and the sandbox session it reaches.- *- * Recovered rather than read off the context: the dispatch and resume paths- * do not carry it, and there a workspace topic resolved in the personal- * scope, came back "no such topic", and ran ephemeral β `pwd` answered- * `/workspace` while the conversation showed a persistent instance.- */- const workspaceId = await resolveContentWorkspaceId(context);+ const {+ builtinSkills: resolvedBuiltinSkills,+ deviceFileAccess,+ disabledSkillIds,+ isLibrarySkillEnabled,+ isSkillGranted,+ listAvailableSkills,+ loadUserSkill,+ projectSkills: resolvedProjectSkills,+ resolveDeviceWorkspaceId,+ resolveSkill,+ workspaceId,+ } = activation;const skillModel = new AgentSkillModel(context.serverDB, context.userId, workspaceId);const resourceService = new SkillResourceService(context.serverDB, context.userId, workspaceId);@@ -979,7 +936,6 @@ export const skillsRuntime: ServerRuntimeRegistration = {// route execution onto a device the resolved plan didn't authorize;// `device-unrouted` runs keep the sandbox path (with the unrouted// disclosure in the manifest).- let workspaceIdPromise: Promise<string | undefined> | undefined;const device: SkillDeviceExecution | undefined = context.activeDeviceId? {deviceId: context.activeDeviceId,@@ -987,48 +943,14 @@ export const skillsRuntime: ServerRuntimeRegistration = {localSandbox: context.localSandbox,localSandboxNetwork: context.localSandboxNetwork,operationId: context.operationId,- projectSkills: context.projectSkills,+ projectSkills: resolvedProjectSkills,// Same lazy workspace-principal recovery as the local-system runtime,// so workspace devices are addressed under the right gateway pool.- resolveWorkspaceId: () => (workspaceIdPromise ??= resolveRunWorkspaceId(context)),+ resolveWorkspaceId: resolveDeviceWorkspaceId,workingDirectory: context.workingDirectory,}: undefined;- // The user's own skill library is read per call, for the one name asked- // for β it grows with every goal batch, and this factory runs per tool- // call. Read under the recovered workspace (a dispatched or resumed run may- // not carry it on the context).- const loadUserSkill = async (requested: string) => {- // Models vary the casing of a name, as the preloaded lookup tolerates.- const name = canonicalUserSkillIdentifier(requested);- if (!name || !isSkillReachable(name)) return undefined;- const [skill] = await new UserSkillService(- context.serverDB!,- context.userId!,- workspaceId,- context.agentVisibility,- )- .loadRuntimeSkills([name], {- // Only the generated skills this run's own Task names are trusted- // past a public agent's visibility β never a name the model chose.- trustedGenerated: context.taskId- ? readTaskSkillIds(- (- await new TaskModel(context.serverDB!, context.userId!, workspaceId).findById(- context.taskId,- )- )?.config,- )- : [],- })- .catch((error) => {- log('failed to load user skill %s: %O', name, error);- return [];- });- return skill;- };-const service = new SkillServerRuntimeService({wrapSandbox: pageSandboxWrapper(context, workspaceId),agentId: context.agentId,@@ -1054,7 +976,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {sandboxSpecification: sandbox.specification,sandboxWorkingDir: sandbox.workingDir,serverDB: context.serverDB,- shareVisitorBlocked: !!shareVisitor,+ shareVisitorBlocked: !!context.agentShareVisitor,skillModel,topicId: context.topicId,userId: context.userId,@@ -1063,149 +985,16 @@ export const skillsRuntime: ServerRuntimeRegistration = {workspaceId,});- // Surface this agent's skill-bundle documents as `BuiltinSkill`-shaped- // entries so `activateSkill('agent-skills:<filename>')` resolves on the- // existing no-DB-lookup path β no `SkillRuntimeService` extension needed.- // `AgentDocumentsService.getAgentSkills` is the single source of truth for- // the identifier prefix and the bundle β index-child content resolution- // (also used by `aiAgent/index.ts` when building `<available_skills>`).- // `source: 'builtin'` is the type-system carrier shape required by- // `BuiltinSkill`; the runtime re-tags `source: 'agent'` in the activateSkill- // result based on the identifier prefix so the inspector can show- // "Activate Agent Skill" + the friendly `title`.- const agentSkillBuiltins: BuiltinSkill[] = context.agentId- ? await new AgentDocumentsService(context.serverDB, context.userId, context.workspaceId)- .getAgentSkills(context.agentId)- .then((skills) =>- skills- .filter((skill) => isSkillReachable(skill.identifier))- .map((skill) => ({- content: skill.content,- description: skill.description,- identifier: skill.identifier,- name: skill.name,- source: 'builtin' as const,- ...(skill.title && { title: skill.title }),- })),- )- .catch((error) => {- log('failed to load agent skills for agent %s: %O', context.agentId, error);- return [];- })- : [];-- // Project/device skills live on the execution device filesystem. Read them through the- // device gateway by reusing the local-system tools β no special- // file-read primitive, just the existing capabilities over deviceGateway.- // - `readFile` loads SKILL.md and validated reference files.- // - `globFiles` enumerates the skill directory so `readReference` can- // reject paths the model guessed (e.g. `.env`) instead of trusting- // the raw string. The discovery payload no longer carries the file- // tree (see commit 8e8f3aed14), so we enumerate live at read time.- const { activeDeviceId, projectSkills } = context;- let deviceFileAccess: DeviceFileAccess | undefined;- if (activeDeviceId && context.userId) {- const userId = context.userId;- deviceFileAccess = {- listFiles: async (dir: string) => {- const result = await executeAuthorizedDeviceToolCall(- context.serverDB,- {- deviceId: activeDeviceId,- userId,- workspaceId: await resolveRunWorkspaceId(context),- },- {- apiName: LocalSystemApiName.globFiles,- // `**/*` matches every regular file recursively under `dir`.- // The device-side enumerator already skips hidden files; the- // runtime re-checks segments as defense in depth.- arguments: JSON.stringify({ pattern: '**/*', scope: dir }),- identifier: LocalSystemIdentifier,- },- );- if (!result.success) {- throw new Error(result.error || result.content || `globFiles failed: ${dir}`);- }- let payload: { files?: unknown };- try {- payload = JSON.parse(result.content) as { files?: unknown };- } catch {- throw new Error(`globFiles returned a non-JSON payload for ${dir}`);- }- if (!Array.isArray(payload.files)) return [];- // Files come back as paths relative to `scope` (POSIX). Strip any- // absolute path the engine may have emitted so the runtime can- // compare against normalized user-supplied relative paths.- return payload.files- .filter((f): f is string => typeof f === 'string')- .map((f) => (f.startsWith(dir) ? f.slice(dir.length).replace(/^[/\\]+/, '') : f));- },- readFile: async (filePath: string) => {- const result = await executeAuthorizedDeviceToolCall(- context.serverDB,- {- deviceId: activeDeviceId,- userId,- workspaceId: await resolveRunWorkspaceId(context),- },- {- apiName: LocalSystemApiName.readFile,- // Read the whole file; SKILL.md and references are small.- arguments: JSON.stringify({ loc: [0, 5000], path: filePath }),- identifier: LocalSystemIdentifier,- },- );- if (!result.success) {- throw new Error(result.error || result.content || `readFile failed: ${filePath}`);- }- return result.content;- },- };- }-return new SkillsExecutionRuntime({// Resolved by the runtime executors from the operation's message// history (the server-side stepContext equivalent); execScript falls// back to these because the raw LLM args never carry activatedSkills.activatedSkills: context.activatedSkills,- builtinSkills: [- // Match the device and opt-in gates of the operation's skill catalog.- ...filterBuiltinSkills(builtinSkills, {- canExecuteOnDevice: context.deviceCapable ?? !!activeDeviceId,- }).filter(- (skill) =>- isSkillReachable(skill.identifier) &&- (isLibrarySkillEnabled?.(skill.identifier) ?? true),- ),- ...agentSkillBuiltins,- ],+ builtinSkills: resolvedBuiltinSkills,deviceFileAccess,- // Filesystem skills carry no identifier of their own; the skill pool- // derives one as `<source>:<name>` (see `operationPrep`'s `projectMetas`)- // and that is what a `skillGrants` entry names, so rebuild it the same- // way rather than matching on the bare name.- projectSkills: projectSkills?.filter((skill) =>- isSkillReachable(`${skill.source ?? 'project'}:${skill.name}`),- ),- // The user's own skill library is read per call, for the one name asked- // for β it grows with every goal batch, and this factory runs per tool- // call. Same carrier shape as above, under the recovered workspace (a- // dispatched or resumed run may not carry it on the context).- resolveSkill: async (requested) => {- const skill = await loadUserSkill(requested);- return (- skill && {- content: skill.body,- description: skill.description,- identifier: skill.identifier,- name: skill.name,- resources: skill.resources,- source: 'builtin' as const,- title: skill.title,- }- );- },+ listAvailableSkills,+ projectSkills: resolvedProjectSkills,+ resolveSkill,service,});},diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex dc365fddfe0..875dbdbcf96 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -344,7 +344,12 @@ export interface ToolExecutionContext {* execution device. Used by the Skills runtime to load them on demand via the* device gateway. Derived from the operation's skill set.*/- projectSkills?: { location: string; name: string; source?: 'device' | 'project' }[];+ projectSkills?: {+ description?: string;+ location: string;+ name: string;+ source?: 'device' | 'project';+ }[];/** Root AI runtime operation ID used to aggregate artifacts produced by one run. */rootOperationId?: string;/**diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.tsindex bb11b7aa84c..cc6e74e20fd 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts@@ -246,6 +246,73 @@ describe('SkillsExecutionRuntime', () => {size: 14,});});++ it('returns a clear validation error instead of crashing when id is missing (e.g. model passed skillName)', async () => {+ const runtime = new SkillsExecutionRuntime({ service: createMockService() });++ const result = await runtime.readReference({+ path: 'guide.md',+ ...({ skillName: 'demo-skill' } as object),+ } as never);++ expect(result.success).toBe(false);+ expect(result.content).toContain('"id"');+ expect(result.content).not.toContain('toLowerCase');+ });++ it('falls back to findById when id is a DB skill id and normalizes leading ./ in resource paths', async () => {+ const readResource = vi.fn().mockResolvedValue({+ content: '# Guide',+ encoding: 'utf8',+ fileHash: 'h1',+ fileType: 'text/markdown',+ path: 'references/guide.md',+ size: 7,+ });+ const service = createMockService({+ findById: vi.fn().mockResolvedValue({+ id: 'skl_123',+ name: 'demo-skill',+ resources: { 'references/guide.md': { fileHash: 'h1', size: 7 } },+ }),+ findByName: vi.fn().mockResolvedValue(undefined),+ readResource,+ });+ const runtime = new SkillsExecutionRuntime({ service });++ const result = await runtime.readReference({+ id: 'skl_123',+ path: './references/guide.md',+ });++ expect(result.success).toBe(true);+ expect(readResource).toHaveBeenCalledWith('skl_123', 'references/guide.md');+ expect(result.content).toBe('# Guide');+ });++ it('matches builtin skills by identifier and normalizes leading ./ in resource paths', async () => {+ const runtime = new SkillsExecutionRuntime({+ builtinSkills: [+ {+ content: 'main',+ description: 'desc',+ identifier: 'lobe-lobehub',+ name: 'LobeHub',+ resources: { 'references/kb.md': { content: 'kb body', fileHash: 'h', size: 7 } },+ source: 'builtin',+ },+ ],+ service: createMockService(),+ });++ const result = await runtime.readReference({+ id: 'lobe-lobehub',+ path: './references/kb.md',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('kb body');+ });});describe('project skills', () => {@@ -269,9 +336,12 @@ describe('SkillsExecutionRuntime', () => {expect(result.success).toBe(true);expect(result.content).toContain('Run the deploy steps.');// The hint points at the skill's directory and instructs the model to- // call `local-system.globFiles` itself rather than pre-enumerating here.+ // call `local-system.globFiles` itself rather than pre-enumerating here,+ // and uses the real `id` parameter name for `readReference`.expect(result.content).toContain('/repo/.agents/skills/deploy');expect(result.content).toContain('globFiles');+ expect(result.content).toContain('id="deploy"');+ expect(result.content).not.toContain('skillName=');expect(result.state).toMatchObject({ name: 'deploy', source: 'project' });});@@ -519,4 +589,144 @@ describe('SkillsExecutionRuntime', () => {expect(resolveSkill).toHaveBeenCalledTimes(1);});});++ describe('activateSkill not-found candidates', () => {+ it('lists project, DB, builtin/agent, and lazy user-library skills without duplicates', async () => {+ const runtime = new SkillsExecutionRuntime({+ builtinSkills: [+ {+ content: 'builtin body',+ description: 'Builtin artifacts',+ identifier: 'artifacts',+ name: 'artifacts',+ source: 'builtin',+ },+ {+ content: 'shadowed builtin',+ description: 'Old overlap',+ identifier: 'overlap',+ name: 'Overlap',+ source: 'builtin',+ },+ {+ content: 'agent doc body',+ description: 'Agent workflow',+ identifier: 'agent-skills:workflow',+ name: 'agent-skills:workflow',+ source: 'builtin',+ },+ ],+ listAvailableSkills: vi+ .fn()+ .mockResolvedValue([{ description: 'Saved plan', name: 'user-skills:plan' }]),+ projectSkills: [+ {+ description: 'Deploy helper',+ location: '/repo/.agents/skills/deploy/SKILL.md',+ name: 'deploy',+ source: 'project',+ },+ ],+ service: createMockService({+ findAll: vi.fn().mockResolvedValue({+ data: [+ { description: 'User override', id: 'db-1', name: 'overlap' },+ { description: 'PDF helper', id: 'db-2', name: 'pdf' },+ ],+ total: 2,+ }),+ }),+ });++ const result = await runtime.activateSkill({ name: 'nonexistent' });++ expect(result.success).toBe(false);+ expect(result.content).toContain('Skill not found: "nonexistent"');+ const jsonStart = result.content.indexOf('[');+ const candidates = JSON.parse(result.content.slice(jsonStart)) as Array<{+ description?: string;+ name: string;+ }>;+ expect(candidates).toEqual([+ { description: 'Deploy helper', name: 'deploy' },+ { description: 'User override', name: 'overlap' },+ { description: 'PDF helper', name: 'pdf' },+ { description: 'Builtin artifacts', name: 'artifacts' },+ { description: 'Agent workflow', name: 'agent-skills:workflow' },+ { description: 'Saved plan', name: 'user-skills:plan' },+ ]);+ });++ it('caps the list and says how many skills it left out', async () => {+ const runtime = new SkillsExecutionRuntime({+ listAvailableSkills: vi.fn().mockResolvedValue(+ Array.from({ length: 45 }, (_, index) => ({+ description: 'd'.repeat(400),+ name: `user-skills:plan-${index}`,+ })),+ ),+ service: createMockService(),+ });++ const result = await runtime.activateSkill({ name: 'nonexistent' });++ expect(result.content).toMatch(/ \(15 more not listed\)$/);+ const candidates = JSON.parse(+ result.content.slice(result.content.indexOf('['), result.content.lastIndexOf(']') + 1),+ ) as Array<{ description: string; name: string }>;+ expect(candidates).toHaveLength(30);+ expect(candidates[0].name).toBe('user-skills:plan-0');+ expect(candidates[0].description).toHaveLength(160);+ });++ it('lists the skills that resemble the request first, so the cap cannot drop them', async () => {+ const runtime = new SkillsExecutionRuntime({+ listAvailableSkills: vi+ .fn()+ .mockResolvedValue([+ ...Array.from({ length: 40 }, (_, index) => ({ name: `user-skills:plan-${index}` })),+ { name: 'user-skills:weekly-report' },+ ]),+ service: createMockService(),+ });++ const result = await runtime.activateSkill({ name: 'weekly-report' });++ const candidates = JSON.parse(+ result.content.slice(result.content.indexOf('['), result.content.lastIndexOf(']') + 1),+ ) as Array<{ name: string }>;+ expect(candidates[0].name).toBe('user-skills:weekly-report');+ expect(candidates[1].name).toBe('user-skills:plan-0');+ });++ it('does not treat a source prefix or the word "skill" as a resemblance', async () => {+ const runtime = new SkillsExecutionRuntime({+ listAvailableSkills: vi+ .fn()+ .mockResolvedValue([{ name: 'user-skills:plan' }, { name: 'user-skills:report' }]),+ projectSkills: [{ location: '/repo/.agents/skills/deploy/SKILL.md', name: 'deploy' }],+ service: createMockService(),+ });++ const result = await runtime.activateSkill({ name: 'user-skills:typo-skill' });++ const candidates = JSON.parse(result.content.slice(result.content.indexOf('['))) as Array<{+ name: string;+ }>;+ expect(candidates.map((skill) => skill.name)).toEqual([+ 'deploy',+ 'user-skills:plan',+ 'user-skills:report',+ ]);+ });++ it('returns a clear validation error when name is missing', async () => {+ const runtime = new SkillsExecutionRuntime({ service: createMockService() });++ const result = await runtime.activateSkill({} as never);++ expect(result.success).toBe(false);+ expect(result.content).toContain('"name"');+ });+ });});diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.tsindex f7ed2d901b5..b0fbef07c6c 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts@@ -89,6 +89,7 @@ export interface SkillRuntimeService {* `DeviceFileAccess.listFiles` β keeping it out of the op param payload.*/export interface ProjectSkillRuntimeItem {+ description?: string;/** Absolute path to the skill's SKILL.md on the device. */location: string;name: string;@@ -124,6 +125,12 @@ export interface SkillsExecutionRuntimeOptions {builtinSkills?: BuiltinSkill[];/** Reads project skill files from the device (local-system over the gateway). */deviceFileAccess?: DeviceFileAccess;+ /**+ * Lists metadata for skills resolved lazily via `resolveSkill` (e.g. the+ * user's skill library). Invoked only when `activateSkill` misses, so the+ * not-found candidate list stays complete without loading the library up front.+ */+ listAvailableSkills?: () => Promise<Array<{ description?: string; name: string }>>;/** Filesystem skills discovered on the execution device. */projectSkills?: ProjectSkillRuntimeItem[];/**@@ -178,6 +185,36 @@ const findByNameCI = <T extends { name: string }>(items: T[], target: string): Treturn items.find((s) => s.name.toLowerCase() === lower);};+/** How many skills an `activateSkill` miss lists, and how much of each description. */+const MAX_MISS_CANDIDATES = 30;+const MAX_MISS_DESCRIPTION_LENGTH = 160;++const truncate = (text: string, max: number): string =>+ text.length > max ? `${text.slice(0, max - 1)}β¦` : text;++/** A skill name without its source prefix (`user-skills:`, `agent-skills:`). */+const bareName = (name: string): string => name.toLowerCase().slice(name.lastIndexOf(':') + 1);++/**+ * Skills whose name shares a word with the requested one, then the rest, each+ * group keeping its order. A missed name is usually a near miss: a dropped+ * prefix (`weekly-report` for `user-skills:weekly-report`) or a reworded one.+ * Prefixes and the word "skill" say nothing about which skill was meant, so+ * neither counts as a shared word.+ */+const rankByResemblance = <T extends { name: string }>(items: T[], requested: string): T[] => {+ const words = bareName(requested)+ .split(/[^\da-z]+/)+ .filter((word) => word.length > 2 && word !== 'skill' && word !== 'skills');+ if (words.length === 0) return items;++ const resembles = (item: T) => {+ const bare = bareName(item.name);+ return words.some((word) => bare.includes(word));+ };+ return [...items.filter((item) => resembles(item)), ...items.filter((item) => !resembles(item))];+};+/*** Hint appended to activated filesystem-skill content so the model knows how to* discover the rest of the skill's directory. We deliberately don't enumerate@@ -187,13 +224,14 @@ const findByNameCI = <T extends { name: string }>(items: T[], target: string): Tconst buildProjectDirectoryHint = (skillName: string, skillDir: string): string =>`## Skill resources-This filesystem skill lives in \`${skillDir}\`. Use \`local-system.globFiles\` with scope="${skillDir}" and pattern="**/*" to discover reference files, then \`readReference\` with skillName="${skillName}" + the relative path to load any of them.`;+This filesystem skill lives in \`${skillDir}\`. Use \`local-system.globFiles\` with scope="${skillDir}" and pattern="**/*" to discover reference files, then \`readReference\` with id="${skillName}" + the relative path to load any of them.`;export class SkillsExecutionRuntime {private activatedSkills?: ExecScriptActivatedSkill[];private builtinSkills: BuiltinSkill[];private projectSkills: ProjectSkillRuntimeItem[];private deviceFileAccess?: DeviceFileAccess;+ private listAvailableSkills?: () => Promise<Array<{ description?: string; name: string }>>;private resolveSkill?: (name: string) => Promise<BuiltinSkill | undefined>;private service: SkillRuntimeService;@@ -203,14 +241,18 @@ export class SkillsExecutionRuntime {this.builtinSkills = options.builtinSkills || [];this.projectSkills = options.projectSkills || [];this.deviceFileAccess = options.deviceFileAccess;+ this.listAvailableSkills = options.listAvailableSkills;this.resolveSkill = options.resolveSkill;}- /** A preloaded builtin-shaped skill, else one the resolver reads on demand. */- private findBuiltinSkill = async (name: string): Promise<BuiltinSkill | undefined> => {- const preloaded = findByNameCI(this.builtinSkills, name);+ /** A preloaded builtin-shaped skill (by name or identifier), else one the resolver reads on demand. */+ private findBuiltinSkill = async (target: string): Promise<BuiltinSkill | undefined> => {+ const lower = target.toLowerCase();+ const preloaded = this.builtinSkills.find(+ (s) => s.name.toLowerCase() === lower || s.identifier.toLowerCase() === lower,+ );if (preloaded || !this.resolveSkill) return preloaded;- const resolved = await this.resolveSkill(name);+ const resolved = await this.resolveSkill(target);if (resolved) this.builtinSkills = [...this.builtinSkills, resolved];return resolved;};@@ -323,7 +365,21 @@ export class SkillsExecutionRuntime {}async readReference(args: ReadReferenceParams): Promise<BuiltinServerRuntimeOutput> {- const { id, path } = args;+ const { id, path } = args ?? {};++ if (!id || typeof id !== 'string') {+ return {+ content: 'Invalid arguments: "id" (the skill ID or name) is required.',+ success: false,+ };+ }++ if (!path || typeof path !== 'string') {+ return {+ content: 'Invalid arguments: "path" (the reference file path) is required.',+ success: false,+ };+ }try {// Project/device skills resolve references relative to the SKILL.md@@ -384,14 +440,21 @@ export class SkillsExecutionRuntime {};}+ const normalizedPath = normalizeRelativePath(path);+// DB (user-level) skills win over builtins on name collision β matches// the `<available_skills>` dedupe precedence (project > user > agent >// builtin) in `aiAgent/index.ts`. Without this, the model would see a// user skill in the list but `readReference` would silently read the- // shadowed builtin's resources.- const skill = await this.service.findByName(id);+ // shadowed builtin's resources. Accept either skill name or DB id to+ // match the manifest contract ("The skill ID or name returned by activateSkill").+ const skill = (await this.service.findByName(id)) ?? (await this.service.findById(id));if (skill) {- const resource = await this.service.readResource(skill.id, path);+ const resourcePath =+ skill.resources && !(path in skill.resources) && normalizedPath in skill.resources+ ? normalizedPath+ : path;+ const resource = await this.service.readResource(skill.id, resourcePath);return {content: resource.content,state: {@@ -408,15 +471,21 @@ export class SkillsExecutionRuntime {// Fall back to builtin skills (includes agent-document skill bundles// via the `agent-skills:` identifier prefix).const builtinSkill = await this.findBuiltinSkill(id);- if (builtinSkill?.resources) {- const meta = builtinSkill.resources[path];+ if (builtinSkill) {+ const resolvedPath =+ builtinSkill.resources &&+ !(path in builtinSkill.resources) &&+ normalizedPath in builtinSkill.resources+ ? normalizedPath+ : path;+ const meta = builtinSkill.resources?.[resolvedPath];if (meta?.content !== undefined) {return {content: meta.content,state: {encoding: 'utf8',fileType: 'text/plain',- path,+ path: resolvedPath,size: meta.size,},success: true,@@ -441,7 +510,14 @@ export class SkillsExecutionRuntime {}async activateSkill(args: ActivateSkillParams): Promise<BuiltinServerRuntimeOutput> {- const { name } = args;+ const { name } = args ?? {};++ if (!name || typeof name !== 'string') {+ return {+ content: 'Invalid arguments: "name" (the skill name) is required.',+ success: false,+ };+ }// Filesystem skills (project/device SKILL.md) take precedence over db/builtin.const projectSkill = findByNameCI(this.projectSkills, name);@@ -545,14 +621,44 @@ export class SkillsExecutionRuntime {};}- const { data: allSkills } = await this.service.findAll();- const availableSkills = allSkills.map((s) => ({- description: s.description,- name: s.name,- }));+ const [{ data: dbSkills }, extraSkills] = await Promise.all([+ this.service.findAll(),+ this.listAvailableSkills ? this.listAvailableSkills() : Promise.resolve([]),+ ]);++ // Aggregate every skill source in activation-precedence order+ // (project/device > DB > builtin/agent > lazy user-skill library),+ // deduplicating by case-insensitive name so the model can recover from a+ // miss regardless of where the skill lives.+ const seen = new Set<string>();+ const availableSkills: Array<{ description?: string; name: string }> = [];+ const addCandidate = (candidate: { description?: string | null; name: string }) => {+ const key = candidate.name.toLowerCase();+ if (seen.has(key)) return;+ seen.add(key);+ availableSkills.push({+ ...(candidate.description+ ? { description: truncate(candidate.description, MAX_MISS_DESCRIPTION_LENGTH) }+ : {}),+ name: candidate.name,+ });+ };++ for (const projectSkill of this.projectSkills) addCandidate(projectSkill);+ for (const dbSkill of dbSkills) addCandidate(dbSkill);+ for (const builtin of this.builtinSkills) addCandidate(builtin);+ for (const extra of extraSkills) addCandidate(extra);++ // A skill library has no size limit and a miss is paid for in tokens, so+ // the list is capped. Names that resemble the request go first: a cap in+ // source order alone could cut off the very skill a typo was aiming at.+ const listed = rankByResemblance(availableSkills, name).slice(0, MAX_MISS_CANDIDATES);+ const omitted = availableSkills.length - listed.length;return {- content: `Skill not found: "${name}". Available skills: ${JSON.stringify(availableSkills)}`,+ content:+ `Skill not found: "${name}". Available skills: ${JSON.stringify(listed)}` ++ (omitted > 0 ? ` (${omitted} more not listed)` : ''),success: false,};}diff --git a/packages/builtin-tool-skills/src/resolveRestrictedManifest.test.ts b/packages/builtin-tool-skills/src/resolveRestrictedManifest.test.tsnew file mode 100644index 00000000000..0abe0824261--- /dev/null+++ b/packages/builtin-tool-skills/src/resolveRestrictedManifest.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import {+ agentShareSystemPrompt,+ resolveSkillsRestrictedManifest,+} from './resolveRestrictedManifest';+import { sharedSkillGuidelines } from './systemRole';+import { AGENT_SHARE_SKILL_API_NAMES, SkillsApiName } from './types';++describe('resolveSkillsRestrictedManifest', () => {+ it('returns the read-only manifest with the concise agentShareSystemPrompt', () => {+ const manifest = resolveSkillsRestrictedManifest({+ allowedApiNames: [...AGENT_SHARE_SKILL_API_NAMES],+ restriction: 'agentShare',+ });++ expect(manifest).toBeDefined();+ expect(manifest?.api.map((api) => api.name).sort()).toEqual(+ [SkillsApiName.activateSkill, SkillsApiName.readReference].sort(),+ );+ expect(manifest?.systemRole).toBe(agentShareSystemPrompt);+ expect(agentShareSystemPrompt).toContain(sharedSkillGuidelines);+ expect(agentShareSystemPrompt).toContain('<selected_skill_context>');+ expect(agentShareSystemPrompt).toContain('cannot run commands or scripts');+ for (const forbidden of [+ SkillsApiName.execScript,+ SkillsApiName.runCommand,+ SkillsApiName.exportFile,+ '{{sandbox_workspace}}',+ '<core_capabilities>',+ ]) {+ expect(agentShareSystemPrompt).not.toContain(forbidden);+ }+ });++ it('returns undefined for unsupported restrictions or API subsets (fail-closed)', () => {+ expect(+ resolveSkillsRestrictedManifest({+ allowedApiNames: [...AGENT_SHARE_SKILL_API_NAMES],+ restriction: 'unknown' as never,+ }),+ ).toBeUndefined();++ expect(+ resolveSkillsRestrictedManifest({+ allowedApiNames: [SkillsApiName.readReference],+ restriction: 'agentShare',+ }),+ ).toBeUndefined();++ expect(+ resolveSkillsRestrictedManifest({+ allowedApiNames: [...AGENT_SHARE_SKILL_API_NAMES, SkillsApiName.execScript],+ restriction: 'agentShare',+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/builtin-tool-skills/src/resolveRestrictedManifest.ts b/packages/builtin-tool-skills/src/resolveRestrictedManifest.tsindex 493a73e89a5..3a637e2b793 100644--- a/packages/builtin-tool-skills/src/resolveRestrictedManifest.ts+++ b/packages/builtin-tool-skills/src/resolveRestrictedManifest.ts@@ -1,6 +1,7 @@import type { BuiltinRestrictedManifestResolver } from '@lobechat/types';import { SkillsManifest } from './manifest';+import { sharedSkillGuidelines } from './systemRole';import { AGENT_SHARE_SKILL_API_NAMES } from './types';/**@@ -16,35 +17,10 @@ import { AGENT_SHARE_SKILL_API_NAMES } from './types';*/export const agentShareSystemPrompt = `You have access to a Skills tool that loads skills β reusable instruction packages that extend your capabilities.-<core_capabilities>-1. Activate a skill by name to load its instructions (activateSkill)-2. Read reference files attached to an activated skill (readReference)-</core_capabilities>--<workflow>-1. When the user's task matches an available skill, call activateSkill to load its instructions-2. Follow the skill's instructions to complete the task-3. If the skill content references additional files, use readReference to load them-</workflow>--<tool_selection_guidelines>-- **activateSkill**: Call this when the user's task matches one of the available skills- - Provide the exact skill name- - Returns the skill content (instructions, templates, guidelines) that you should follow- - **IMPORTANT**: If a skill's content is already provided in \`<selected_skill_context>\` within the user message, do NOT call activateSkill for that skill β its instructions are already loaded and ready to use--- **readReference**: Call this to read reference files mentioned in a skill's content- - Requires the id (returned by activateSkill) and the file path- - Returns the file content for you to use as context- - Only use paths that are referenced in the skill content-</tool_selection_guidelines>--<best_practices>-- Only activate skills when the user's task clearly matches the skill's purpose-- Follow the skill's instructions carefully once loaded-- Use readReference only for files explicitly mentioned in the skill content-- This tool cannot run commands or scripts in this conversation. If a skill's instructions call for executing a script, do as much as you can from the written instructions and tell the user which step needs execution instead of pretending it ran-</best_practices>+<guidelines>+${sharedSkillGuidelines}+- This tool cannot run commands or scripts in this conversation. If a skill's instructions call for executing a script, do as much as you can from the written instructions and tell the user which step needs execution instead of pretending it ran.+</guidelines>`;/**diff --git a/packages/builtin-tool-skills/src/systemRole.desktop.ts b/packages/builtin-tool-skills/src/systemRole.desktop.tsindex 8f2771b4dd3..d29f85ea0ce 100644--- a/packages/builtin-tool-skills/src/systemRole.desktop.ts+++ b/packages/builtin-tool-skills/src/systemRole.desktop.ts@@ -1 +1,5 @@-export { deviceSystemPrompt, deviceSystemPrompt as systemPrompt } from './systemRole';+export {+ deviceSystemPrompt,+ sharedSkillGuidelines,+ deviceSystemPrompt as systemPrompt,+} from './systemRole';diff --git a/packages/builtin-tool-skills/src/systemRole.ts b/packages/builtin-tool-skills/src/systemRole.tsindex 82bc4fe3b46..98eaa08fc6b 100644--- a/packages/builtin-tool-skills/src/systemRole.ts+++ b/packages/builtin-tool-skills/src/systemRole.ts@@ -1,6 +1,6 @@const intro = `You have access to a Skills tool that loads and executes skills β reusable instruction packages that extend your capabilities.`;-const sharedSkillGuidelines = `- **activateSkill**: Call when the user's task matches an available skill to load and follow its instructions. Do NOT call \`activateSkill\` if the skill's content is already provided in \`<selected_skill_context>\` within the user message.+export const sharedSkillGuidelines = `- **activateSkill**: Call when the user's task matches an available skill to load and follow its instructions. Do NOT call \`activateSkill\` if the skill's content is already provided in \`<selected_skill_context>\` within the user message.- **readReference**: Load reference files explicitly mentioned in an activated skill's instructions.`;export const systemPrompt = `${intro}diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex ee1f42103af..b83e4928ad9 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -93,6 +93,7 @@ const log = debug('context-engine:MessagesEngine');/** `AttachmentsIdentifier` from `@lobechat/builtin-tool-attachments`, inlined to avoid a package cycle */const ATTACHMENTS_TOOL_ID = 'lobe-attachments';const AGENT_DOCUMENTS_TOOL_ID = 'lobe-agent-documents';+const SKILLS_TOOL_ID = 'lobe-skills';/*** MessagesEngine - High-level message processing engine@@ -267,6 +268,9 @@ export class MessagesEngine {// Same gate for referenced agent documents: only point at `readDocument` when it is sent.const canReadDocuments =toolIds.includes(AGENT_DOCUMENTS_TOOL_ID) && !!canUseFC(model, provider);+ // Same gate for filesystem skills: only require `activateSkill` when it is sent. A Custom-mode+ // agent or a goal turn that did not pin Skills still reaches them through readFile.+ const canActivateSkill = toolIds.includes(SKILLS_TOOL_ID) && !!canUseFC(model, provider);const injectedActivatedSkills =isAgentMode && (skillsConfig?.enabledSkills?.length ?? 0) > 0? selectActivatedSkills(skillsConfig?.enabledSkills)@@ -371,6 +375,7 @@ export class MessagesEngine {// Disabled in chat mode β pairs with the tools-engine gate so the LLM// sees neither the manifests nor the discovery prompt.new SkillContextProvider({+ canActivateSkill,enabled:isAgentMode && !!(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0),enabledSkills: skillsConfig?.enabledSkills,diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.filesystemSkillLoading.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.filesystemSkillLoading.test.tsnew file mode 100644index 00000000000..8adfb6fdbcc--- /dev/null+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.filesystemSkillLoading.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import type { UIChatMessage } from '@/types/index';++import { MessagesEngine } from '../MessagesEngine';+import type { MessagesEngineParams } from '../types';++const createParams = (tools: string[]): MessagesEngineParams => ({+ messages: [+ {+ content: 'Deploy the project',+ createdAt: 1_700_000_000_000,+ id: 'msg-1',+ role: 'user',+ updatedAt: 1_700_000_000_000,+ } as UIChatMessage,+ ],+ model: 'gemini-4-neon',+ provider: 'lobehub',+ skillsConfig: {+ enabledSkills: [+ {+ description: 'Deploy helper',+ identifier: 'project:deploy',+ location: '/repo/.agents/skills/deploy/SKILL.md',+ name: 'deploy',+ source: 'project',+ },+ ],+ },+ systemRole: 'You are a helpful assistant.',+ toolsConfig: { manifests: [], tools },+});++const systemPromptFor = async (tools: string[]) => {+ const result = await new MessagesEngine(createParams(tools)).process();+ return result.messages[0].content as string;+};++describe('MessagesEngine filesystem skill loading instruction', () => {+ it('routes a filesystem skill through activateSkill when the run was sent Skills', async () => {+ const system = await systemPromptFor(['lobe-skills', 'lobe-local-system']);++ expect(system).toContain('load it with activateSkill by name');+ expect(system).not.toContain('calling the readFile tool');+ });++ it('keeps the readFile route when the run was not sent Skills', async () => {+ // A Custom-mode agent or a goal turn gets exactly its pinned tools. With+ // local-system pinned and Skills not, requiring `activateSkill` and+ // forbidding readFile left the advertised skill with no way to be opened.+ const system = await systemPromptFor(['lobe-local-system']);++ expect(system).toContain('calling the readFile tool on its `location` path');+ expect(system).not.toContain('do not bypass activation with readFile');+ });+});diff --git a/packages/context-engine/src/providers/SkillContextProvider.ts b/packages/context-engine/src/providers/SkillContextProvider.tsindex 61ae58f22db..2a11a7d9d70 100644--- a/packages/context-engine/src/providers/SkillContextProvider.ts+++ b/packages/context-engine/src/providers/SkillContextProvider.ts@@ -35,8 +35,9 @@ export interface SkillMeta {location?: string;name: string;/**- * Skill origin. `project` skills are discovered on the device filesystem and- * loaded on demand via the readFile tool (see `location`).+ * Skill origin. `project` and `device` skills are discovered on the device+ * filesystem and loaded on demand via `activateSkill` (`location` gives their+ * absolute SKILL.md path).*/source?: SkillSource;}@@ -45,6 +46,11 @@ export interface SkillMeta {* Skill Context Provider Configuration*/export interface SkillContextProviderConfig {+ /**+ * Whether the run was sent the `activateSkill` tool. Without it the prompt+ * keeps the readFile route into filesystem skills. Defaults to true.+ */+ canActivateSkill?: boolean;enabled?: boolean;enabledSkills?: SkillMeta[];}@@ -107,7 +113,9 @@ export class SkillContextProvider extends BaseSystemRoleProvider {source: skill.source,}));- const availableSkillsContent = skillsPrompts(skills);+ const availableSkillsContent = skillsPrompts(skills, {+ canActivateSkill: this.config.canActivateSkill,+ });if (availableSkillsContent) {contentParts.push(availableSkillsContent);}diff --git a/packages/prompts/src/prompts/skills/index.test.ts b/packages/prompts/src/prompts/skills/index.test.tsindex 6e59eb9b226..3de3897c979 100644--- a/packages/prompts/src/prompts/skills/index.test.ts+++ b/packages/prompts/src/prompts/skills/index.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { type SkillItem, skillPrompt, skillsPrompts } from './index';+import { resourcesTreePrompt, type SkillItem, skillPrompt, skillsPrompts } from './index';describe('skillPrompt', () => {it('should generate skill tag with location', () => {@@ -81,7 +81,7 @@ Use the activateSkill tool to load a skill when the user's task matches its descexpect(skillsPrompts(skills)).toBe(expected);});- it('should include filesystem skill loading and relative-path resolution instructions for project/device skills', () => {+ it('should direct project/device skills through activateSkill with relative-path guidance', () => {const skills: SkillItem[] = [{description: 'Device writing guidance',@@ -95,7 +95,7 @@ Use the activateSkill tool to load a skill when the user's task matches its descexpect(skillsPrompts(skills)).toBe(`The following skills provide specialized instructions for specific tasks.Use the activateSkill tool to load a skill when the user's task matches its description.-For a skill with source="project" or source="device", load it by calling the readFile tool on its \`location\` path and resolve relative paths against its parent directory (parent of SKILL.md).+For a skill with source="project" or source="device", load it with activateSkill by name (do not bypass activation with readFile) and resolve relative paths against the parent directory of its \`location\` (parent of SKILL.md).<available_skills><skill name="writing" source="device" location="/Users/dev/.agents/skills/writing/SKILL.md">Device writing guidance</skill>@@ -103,7 +103,38 @@ For a skill with source="project" or source="device", load it by calling the rea);});+ it('should keep the readFile route for project/device skills when activateSkill was not sent', () => {+ const skills: SkillItem[] = [+ {+ description: 'Device writing guidance',+ identifier: 'device:writing',+ location: '/Users/dev/.agents/skills/writing/SKILL.md',+ name: 'writing',+ source: 'device',+ },+ ];++ const prompt = skillsPrompts(skills, { canActivateSkill: false });++ expect(prompt).toContain(+ 'For a skill with source="project" or source="device", load it by calling the readFile tool on its `location` path and resolve relative paths against its parent directory (parent of SKILL.md).',+ );+ expect(prompt).not.toContain('do not bypass activation with readFile');+ });+it('should return empty string for empty skills array', () => {expect(skillsPrompts([])).toBe('');});});++describe('resourcesTreePrompt', () => {+ it('instructs readReference with the manifest parameter name `id` rather than `skillName`', () => {+ const prompt = resourcesTreePrompt('pdf-tools', {+ 'references/guide.md': { fileHash: 'h1', size: 120 },+ });++ expect(prompt).toContain('Use `readReference` with id="pdf-tools"');+ expect(prompt).not.toContain('skillName=');+ expect(prompt).toContain('guide.md');+ });+});diff --git a/packages/prompts/src/prompts/skills/index.ts b/packages/prompts/src/prompts/skills/index.tsindex 248d413c83a..11d111b86c7 100644--- a/packages/prompts/src/prompts/skills/index.ts+++ b/packages/prompts/src/prompts/skills/index.ts@@ -9,8 +9,9 @@ export interface SkillItem {name: string;/*** Where the skill comes from. `project` and `device` skills live on the- * execution device filesystem and `location` carries their absolute path so- * the model can load them via the readFile tool.+ * execution device filesystem; `activateSkill` loads them by name and+ * `location` gives their absolute path for resolving relative paths, and+ * for reading SKILL.md directly in a run that has no `activateSkill`.*/source?: SkillSource;}@@ -22,17 +23,33 @@ export const skillPrompt = (skill: SkillItem) => {return ` <skill ${attrs.join(' ')}>${skill.description}</skill>`;};-export const skillsPrompts = (skills: SkillItem[]) => {+export interface SkillsPromptOptions {+ /**+ * Whether this run was sent the `activateSkill` tool. A run without it (a+ * Custom-mode agent or a goal turn that did not pin Skills) can still open a+ * filesystem skill by reading its SKILL.md. Defaults to true.+ */+ canActivateSkill?: boolean;+}++export const skillsPrompts = (skills: SkillItem[], options: SkillsPromptOptions = {}) => {if (skills.length === 0) return '';+ const { canActivateSkill = true } = options;+const skillTags = skills.map((skill) => skillPrompt(skill)).join('\n');const hasFilesystemSkill = skills.some((skill) => skill.source === 'project' || skill.source === 'device',);- const filesystemHint = hasFilesystemSkill- ? `\nFor a skill with source="project" or source="device", load it by calling the readFile tool on its \`location\` path and resolve relative paths against its parent directory (parent of SKILL.md).`- : '';+ // Activation records the skill for the run, which is how `execScript` finds+ // its directory, so it is the way in whenever the tool was sent. Reading the+ // file is the only way left when it was not.+ const filesystemHint = !hasFilesystemSkill+ ? ''+ : canActivateSkill+ ? `\nFor a skill with source="project" or source="device", load it with activateSkill by name (do not bypass activation with readFile) and resolve relative paths against the parent directory of its \`location\` (parent of SKILL.md).`+ : `\nFor a skill with source="project" or source="device", load it by calling the readFile tool on its \`location\` path and resolve relative paths against its parent directory (parent of SKILL.md).`;return `The following skills provide specialized instructions for specific tasks.Use the activateSkill tool to load a skill when the user's task matches its description.${filesystemHint}diff --git a/packages/prompts/src/prompts/skills/resourcesTree.ts b/packages/prompts/src/prompts/skills/resourcesTree.tsindex 79568db6003..82ea4c115e3 100644--- a/packages/prompts/src/prompts/skills/resourcesTree.ts+++ b/packages/prompts/src/prompts/skills/resourcesTree.ts@@ -82,7 +82,7 @@ export const resourcesTreePrompt = (return `## Available Resources-Use \`readReference\` with skillName="${skillName}" and the file path to read these files.+Use \`readReference\` with id="${skillName}" and the file path to read these files.\`\`\`${treeText}