🤯 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
âš¡ perf(agent): defer the skill APIs of lobe-skills when no skills are available (#23771)
AmAzing-88a88dbb07ef
diff --git a/.agents/skills/builtin-tool/references/architecture.md b/.agents/skills/builtin-tool/references/architecture.mdindex 989be33c669..a2aa62a2197 100644--- a/.agents/skills/builtin-tool/references/architecture.md+++ b/.agents/skills/builtin-tool/references/architecture.md@@ -270,7 +270,7 @@ Five core files plus optional ones. Miss any and you'll see "tool not found", aLists in the same file you may need to touch:- `defaultToolIds` — added to the agent's tool list by default-- `alwaysOnToolIds` — forced on regardless of user selection (use sparingly)+- `alwaysOnToolIds` — forced on regardless of user selection (use sparingly). `lobe-skills` is the one exception to "always in full": a run with no skill to offer keeps only its sandbox shell (`runCommand` / `exportFile`), and the full manifest waits in `OperationToolSet.deferredManifestMap` until a skill is installed mid-run (`planSkillsToolDeferral` in `packages/mecha/src/toolSet/deferSkillsTool.ts`)- `runtimeManagedToolIds` — enable state controlled by runtime, not user UI; **must mirror the rules map** in `apps/server/src/modules/Mecha/AgentToolsEngine/index.ts` and `src/helpers/toolEngineering/index.ts`---diff --git a/apps/server/src/modules/AgentRuntime/__tests__/slimAgentState.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/slimAgentState.test.tsindex 0fb609865e0..00b2f2a238b 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/slimAgentState.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/slimAgentState.test.ts@@ -141,4 +141,24 @@ describe('restoreSlimState', () => {expect(JSON.stringify(state)).toBe(before);});++ it('restores a promoted tool from the deferred manifest it was copied from', () => {+ const fullManifest = { api: [{ name: 'a' }, { name: 'a2' }], identifier: 'a' };+ const state = {+ ...buildState(),+ activatedStepTools: [+ {+ activatedAtStep: 1,+ id: 'a',+ manifest: structuredClone(fullManifest),+ source: 'discovery',+ },+ ],+ operationToolSet: { ...toolSet, deferredManifestMap: { a: fullManifest } },+ };++ const slim = slimStateForPersist(state) as any;+ expect(slim.activatedStepTools[0].manifest).toBeUndefined();+ expect(roundTrip(state)).toEqual(state);+ });});diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.tsindex db9b8ca1284..15e0cec0a6a 100644--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts@@ -246,4 +246,64 @@ describe('resolveServerCallLlmTooling', () => {expect(result.activeDeviceId).toBeUndefined();});++ it('keeps the shell of a deferred lobe-skills and restores its skill APIs once activated', () => {+ const api = (name: string) => ({ description: name, name, parameters: {} });+ const shellManifest = {+ api: [api('runCommand'), api('exportFile')],+ identifier: 'lobe-skills',+ meta: { title: 'Skills' },+ systemRole: 'shell only',+ type: 'builtin' as const,+ };+ const fullManifest = {+ ...shellManifest,+ api: [api('activateSkill'), ...shellManifest.api],+ systemRole: 'full',+ };+ const ctx = { operationId: 'op-1', stepIndex: 0 };+ const state = buildState({+ operationToolSet: {+ deferredManifestMap: { 'lobe-skills': fullManifest },+ enabledToolIds: [LobeActivatorManifest.identifier, 'lobe-skills'],+ manifestMap: {+ [LobeActivatorManifest.identifier]: LobeActivatorManifest,+ [CredsIdentifier]: CredsManifest,+ 'lobe-skills': shellManifest,+ },+ sourceMap: { 'lobe-skills': 'builtin' },+ tools: [+ { function: { name: 'lobe-skills____runCommand' }, type: 'function' },+ { function: { name: 'lobe-skills____exportFile' }, type: 'function' },+ ] as unknown as NonNullable<AgentState['tools']>,+ },+ });++ const before = resolveServerCallLlmTooling(ctx, state);+ expect(before.tools?.map((tool) => tool.function.name)).toEqual([+ 'lobe-skills____runCommand',+ 'lobe-skills____exportFile',+ ]);+ expect(before.resolved.promptManifestMap['lobe-skills']).toEqual(shellManifest);+ // A deferred tool is promoted by the runtime, never offered for activation.+ expect(before.toolDiscoveryConfig?.availableTools.map((tool) => tool.identifier)).toEqual([+ CredsIdentifier,+ ]);++ const after = resolveServerCallLlmTooling(+ { ...ctx, stepIndex: 1 },+ {+ ...state,+ activatedStepTools: [+ { activatedAtStep: 0, id: 'lobe-skills', manifest: fullManifest, source: 'discovery' },+ ],+ },+ );+ expect(after.resolved.promptManifestMap['lobe-skills']).toEqual(fullManifest);+ expect(after.tools?.map((tool) => tool.function.name)).toEqual([+ 'lobe-skills____runCommand',+ 'lobe-skills____exportFile',+ 'lobe-skills____activateSkill',+ ]);+ });});diff --git a/apps/server/src/modules/AgentRuntime/slimAgentState.ts b/apps/server/src/modules/AgentRuntime/slimAgentState.tsindex ab649203678..6227545f02d 100644--- a/apps/server/src/modules/AgentRuntime/slimAgentState.ts+++ b/apps/server/src/modules/AgentRuntime/slimAgentState.ts@@ -8,7 +8,8 @@* - `initialContext.payload.tools` is the same array as `operationToolSet.tools`* (`operationPrep` hands both the discovery result);* - each `activatedStepTools[i].manifest` is copied from- * `operationToolSet.manifestMap[id]` when the tool is activated;+ * `operationToolSet.manifestMap[id]` when the tool is activated, or from+ * `operationToolSet.deferredManifestMap[id]` for a tool the run deferred;* - the deprecated top-level `expertise` mirrors `world.expertise`.** {@link slimStateForPersist} drops a copy only when it is equal to its source,@@ -33,6 +34,10 @@ interface SlimMarker {type LooseState = Record<string, any>;+/** Where an activation's manifest was copied from: a deferred tool is promoted to its full manifest. */+const activationSource = (toolSet: LooseState | undefined, id: string) =>+ toolSet?.deferredManifestMap?.[id] ?? toolSet?.manifestMap?.[id];+const sameJson = (a: unknown, b: unknown) =>a !== undefined && b !== undefined && JSON.stringify(a) === JSON.stringify(b);@@ -58,7 +63,7 @@ export const slimStateForPersist = <T extends object>(state: T): T => {if (Array.isArray(activated) && toolSet?.manifestMap) {const indices: number[] = [];const slimmed = activated.map((entry: LooseState, index: number) => {- if (!entry?.manifest || !sameJson(entry.manifest, toolSet.manifestMap[entry.id])) {+ if (!entry?.manifest || !sameJson(entry.manifest, activationSource(toolSet, entry.id))) {return entry;}indices.push(index);@@ -103,7 +108,7 @@ export const restoreSlimState = (state: object): void => {if (marker.activatedManifests && Array.isArray(target.activatedStepTools)) {for (const index of marker.activatedManifests) {const entry = target.activatedStepTools[index];- const manifest = entry && toolSet?.manifestMap?.[entry.id];+ const manifest = entry && activationSource(toolSet, entry.id);if (manifest) entry.manifest = structuredClone(manifest);}}diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex a0620eb4abb..ec06a184b32 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -41,6 +41,8 @@ import { type AgentHook } from './hooks/types';export interface OperationToolSet {/** Tool IDs that may be restored from historical explicit activations for this run. */activatableToolIds?: string[];+ /** Full manifests of tools this run starts narrowed; see the context-engine `OperationToolSet`. */+ deferredManifestMap?: Record<string, LobeToolManifest>;enabledToolIds?: string[];executorMap?: Record<string, ToolExecutor>;manifestMap: Record<string, LobeToolManifest>;diff --git a/apps/server/src/services/aiAgent/pipeline/deferUnusedSkillsTool.test.ts b/apps/server/src/services/aiAgent/pipeline/deferUnusedSkillsTool.test.tsnew file mode 100644index 00000000000..eabaee0e528--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/deferUnusedSkillsTool.test.ts@@ -0,0 +1,285 @@+import {+ getSystemPrompt as getActivatorSystemPrompt,+ getSystemPromptForShareVisitor as getActivatorSystemPromptForShareVisitor,+ LobeActivatorIdentifier,+ LobeActivatorManifest,+} from '@lobechat/builtin-tool-activator';+import {+ resolveSkillsManifest,+ SkillsApiName,+ SkillsIdentifier,+ SkillsManifest,+} from '@lobechat/builtin-tool-skills';+import {+ generateToolsFromManifest,+ type LobeToolManifest,+ type UniformTool,+} from '@lobechat/context-engine';+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { deferUnusedSkillsTool, type DeferUnusedSkillsToolParams } from './deferUnusedSkillsTool';++const webBrowsingManifest: LobeToolManifest = {+ api: [{ description: 'Search the web', name: 'search', parameters: {} }],+ identifier: 'lobe-web-browsing',+ meta: { description: 'Web search', title: 'Web Browsing' },+ type: 'builtin',+};++const skillStoreManifest: LobeToolManifest = {+ api: [{ description: 'Import a skill', name: 'importFromMarket', parameters: {} }],+ identifier: 'lobe-skill-store',+ meta: { description: 'Skill Store', title: 'Skill Store' },+ type: 'builtin',+};++type ToolSet = DeferUnusedSkillsToolParams['toolSet'] & {+ enabledToolIds: string[];+ tools: UniformTool[];+};++const buildToolSet = (+ skillsManifest: LobeToolManifest = { ...SkillsManifest } as LobeToolManifest,+): ToolSet => {+ const manifestMap: Record<string, LobeToolManifest> = {+ [LobeActivatorIdentifier]: { ...LobeActivatorManifest },+ [SkillsIdentifier]: skillsManifest,+ 'lobe-skill-store': { ...skillStoreManifest },+ 'lobe-web-browsing': { ...webBrowsingManifest },+ };++ return {+ activatableToolIds: [],+ enabledToolIds: [LobeActivatorIdentifier, SkillsIdentifier, 'lobe-web-browsing'],+ executorMap: {},+ manifestMap,+ sourceMap: {+ [LobeActivatorIdentifier]: 'builtin',+ [SkillsIdentifier]: 'builtin',+ 'lobe-skill-store': 'builtin',+ 'lobe-web-browsing': 'builtin',+ },+ tools: [+ ...generateToolsFromManifest(manifestMap[LobeActivatorIdentifier]),+ ...generateToolsFromManifest(manifestMap[SkillsIdentifier]),+ ...generateToolsFromManifest(manifestMap['lobe-web-browsing']),+ ],+ };+};++const buildParams = (+ overrides: Partial<DeferUnusedSkillsToolParams> = {},+): DeferUnusedSkillsToolParams & { toolSet: ToolSet } => ({+ agentChatConfig: {},+ allMessages: [{ content: 'Hello', id: 'u-1', role: 'user' } as UIChatMessage],+ operationSkillSet: { enabledSkillIds: [], skills: [] },+ toolSet: buildToolSet(),+ ...overrides,+});++const skillsToolNames = (toolSet: ToolSet) =>+ toolSet.tools+ .map((tool) => tool.function.name)+ .filter((name) => name.startsWith(`${SkillsIdentifier}____`));++const skillsTool = (apiName: string) => `${SkillsIdentifier}____${apiName}`;++const expectUntouched = (params: DeferUnusedSkillsToolParams & { toolSet: ToolSet }) => {+ expect(deferUnusedSkillsTool(params)).toBe(false);+ expect(params.toolSet.enabledToolIds).toContain(SkillsIdentifier);+ expect(params.toolSet.manifestMap[SkillsIdentifier].api).toHaveLength(SkillsManifest.api.length);+ expect(skillsToolNames(params.toolSet)).toHaveLength(SkillsManifest.api.length);+ expect(params.toolSet.deferredManifestMap).toBeUndefined();+};++describe('deferUnusedSkillsTool', () => {+ it('keeps the sandbox shell and exportFile while deferring the skill APIs', () => {+ const params = buildParams();+ const { toolSet } = params;+ const fullManifest = toolSet.manifestMap[SkillsIdentifier];++ expect(deferUnusedSkillsTool(params)).toBe(true);++ // The always-on shell is still enabled and callable.+ expect(toolSet.enabledToolIds).toEqual([+ LobeActivatorIdentifier,+ SkillsIdentifier,+ 'lobe-web-browsing',+ ]);+ expect(skillsToolNames(toolSet)).toEqual([+ skillsTool(SkillsApiName.runCommand),+ skillsTool(SkillsApiName.exportFile),+ ]);+ expect(toolSet.manifestMap[SkillsIdentifier].api.map((api) => api.name)).toEqual([+ SkillsApiName.runCommand,+ SkillsApiName.exportFile,+ ]);+ expect(toolSet.manifestMap[SkillsIdentifier].systemRole).toContain('{{sandbox_workspace}}');+ expect(toolSet.manifestMap[SkillsIdentifier].systemRole).not.toContain('activateSkill');++ // The full manifest waits for a mid-run skill install.+ expect(toolSet.deferredManifestMap).toEqual({ [SkillsIdentifier]: fullManifest });++ // Other tools are untouched.+ expect(toolSet.tools.some((t) => t.function.name.startsWith('lobe-web-browsing____'))).toBe(+ true,+ );++ // The activator stops pointing at `activateSkill` but keeps skill store discovery.+ const activatorRole = toolSet.manifestMap[LobeActivatorIdentifier].systemRole;+ expect(activatorRole).toBe(getActivatorSystemPrompt({ withSkills: false }));+ expect(activatorRole).toContain('<skill_store_discovery>');+ expect(activatorRole).not.toContain('activateSkill');+ });++ it('removes the tool entirely on a routed device, where it offers no sandbox shell', () => {+ const deviceManifest = resolveSkillsManifest({ executionEnv: 'device' }) as LobeToolManifest;+ const params = buildParams({ toolSet: buildToolSet(deviceManifest) });+ const { toolSet } = params;++ expect(deferUnusedSkillsTool(params)).toBe(true);++ expect(toolSet.enabledToolIds).toEqual([LobeActivatorIdentifier, 'lobe-web-browsing']);+ expect(skillsToolNames(toolSet)).toEqual([]);+ // Out of `manifestMap`, so the activator never lists it in <available_tools>.+ expect(toolSet.manifestMap[SkillsIdentifier]).toBeUndefined();+ expect(toolSet.deferredManifestMap).toEqual({ [SkillsIdentifier]: deviceManifest });+ // Routing stays in place for the promotion.+ expect(toolSet.sourceMap[SkillsIdentifier]).toBe('builtin');+ });++ it('leaves the tool alone when at least one skill is available', () => {+ expectUntouched(+ buildParams({+ operationSkillSet: {+ enabledSkillIds: ['lobehub'],+ skills: [{ description: 'CLI', identifier: 'lobehub', name: 'LobeHub' }],+ },+ }),+ );+ });++ it('leaves the tool alone when the skill set could not be built', () => {+ expectUntouched(buildParams({ operationSkillSet: undefined }));+ });++ it('does nothing when the tools engine reported no enabled tool ids', () => {+ const params = buildParams();+ const toolSet = { ...params.toolSet, enabledToolIds: undefined };++ expect(deferUnusedSkillsTool({ ...params, toolSet })).toBe(false);+ expect(toolSet.deferredManifestMap).toBeUndefined();+ });++ it('leaves the tool alone when history already called lobe-skills', () => {+ expectUntouched(+ buildParams({+ allMessages: [+ { content: 'Run my skill', id: 'u-1', role: 'user' } as UIChatMessage,+ {+ content: 'Loaded',+ id: 't-1',+ plugin: { apiName: 'activateSkill', identifier: SkillsIdentifier },+ role: 'tool',+ } as unknown as UIChatMessage,+ { content: 'Continue', id: 'u-2', role: 'user' } as UIChatMessage,+ ],+ }),+ );+ });++ it('still defers the skill APIs after earlier turns used the sandbox shell', () => {+ const params = buildParams({+ allMessages: [+ {+ content: 'done',+ id: 't-1',+ plugin: { apiName: SkillsApiName.runCommand, identifier: SkillsIdentifier },+ role: 'tool',+ } as unknown as UIChatMessage,+ { content: 'Run another', id: 'u-2', role: 'user' } as UIChatMessage,+ ],+ });++ expect(deferUnusedSkillsTool(params)).toBe(true);+ expect(skillsToolNames(params.toolSet)).toEqual([+ skillsTool(SkillsApiName.runCommand),+ skillsTool(SkillsApiName.exportFile),+ ]);+ });++ it('leaves the tool alone when history has grouped lobe-skills tool calls', () => {+ expectUntouched(+ buildParams({+ allMessages: [+ {+ children: [+ {+ tools: [{ apiName: 'execScript', id: 'call_1', identifier: SkillsIdentifier }],+ },+ ],+ content: '',+ id: 'grp-1',+ role: 'assistantGroup',+ } as unknown as UIChatMessage,+ ],+ }),+ );+ });++ it('leaves the tool alone when a skill was loaded through the activator fallback', () => {+ expectUntouched(+ buildParams({+ allMessages: [+ {+ content: 'Skill loaded',+ id: 't-1',+ plugin: { apiName: 'activateTools', identifier: LobeActivatorIdentifier },+ pluginState: { activatedSkills: [{ id: 'skl_1', name: 'pptx' }], activatedTools: [] },+ role: 'tool',+ } as unknown as UIChatMessage,+ { content: 'Now read its reference', id: 'u-2', role: 'user' } as UIChatMessage,+ ],+ }),+ );+ });++ it('leaves the tool alone in custom mode, goal turns, exclusivePluginIds, or evalAllowedTools', () => {+ expectUntouched(buildParams({ agentChatConfig: { toolMode: 'custom' } }));+ expectUntouched(buildParams({ isGoalTurn: true }));+ expectUntouched(buildParams({ exclusivePluginIds: [SkillsIdentifier] }));+ expectUntouched(buildParams({ evalAllowedTools: [skillsTool(SkillsApiName.activateSkill)] }));+ });++ it('drops lobe-skills completely on share runs with 0 surviving skills and updates activator', () => {+ const params = buildParams({ isShareRun: true });+ const { toolSet } = params;+ toolSet.manifestMap[LobeActivatorIdentifier] = {+ ...LobeActivatorManifest,+ systemRole: getActivatorSystemPromptForShareVisitor({ withSkills: true }),+ };++ expect(deferUnusedSkillsTool(params)).toBe(true);+ expect(toolSet.enabledToolIds).not.toContain(SkillsIdentifier);+ expect(skillsToolNames(toolSet)).toEqual([]);+ expect(toolSet.manifestMap[SkillsIdentifier]).toBeUndefined();+ expect(toolSet.sourceMap[SkillsIdentifier]).toBeUndefined();+ // A visitor cannot install skills, so nothing is kept for later.+ expect(toolSet.deferredManifestMap).toBeUndefined();+ expect(toolSet.manifestMap[LobeActivatorIdentifier].systemRole).toBe(+ getActivatorSystemPromptForShareVisitor({ withSkills: false }),+ );+ });++ it('also drops lobe-activator on share runs when no other activatable tools remain', () => {+ const params = buildParams({ isShareRun: true });+ const { toolSet } = params;+ delete toolSet.manifestMap['lobe-skill-store'];++ expect(deferUnusedSkillsTool(params)).toBe(true);+ expect(toolSet.manifestMap[SkillsIdentifier]).toBeUndefined();+ expect(toolSet.manifestMap[LobeActivatorIdentifier]).toBeUndefined();+ expect(toolSet.enabledToolIds).not.toContain(LobeActivatorIdentifier);+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/deferUnusedSkillsTool.ts b/apps/server/src/services/aiAgent/pipeline/deferUnusedSkillsTool.tsnew file mode 100644index 00000000000..e84473b669c--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/deferUnusedSkillsTool.ts@@ -0,0 +1,98 @@+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';+import { PLUGIN_SCHEMA_SEPARATOR } from '@lobechat/const';+import type { LobeToolManifest, OperationSkillSet } from '@lobechat/context-engine';+import {+ applySkillsToolDeferral,+ canDeferSkillsTool,+ planSkillsToolDeferral,+} from '@lobechat/mecha';+import type { LobeAgentChatConfig, UIChatMessage } from '@lobechat/types';++import { applyShareGateToActivator } from '../shareGate/toolSet';+import { dropToolFromSet } from '../shareGate/toolSetMutation';+import type { ShareGateToolSet } from '../shareGate/types';++export interface DeferUnusedSkillsToolParams {+ agentChatConfig?: Pick<LobeAgentChatConfig, 'enableAgentMode' | 'toolMode'> | null;+ allMessages: UIChatMessage[];+ evalAllowedTools?: readonly string[];+ exclusivePluginIds?: readonly string[];+ isGoalTurn?: boolean;+ isShareRun?: boolean;+ /** `undefined` when the skill set could not be built, which never defers. */+ operationSkillSet?: OperationSkillSet;+ /**+ * The operation's tool set. `enabledToolIds` is optional because the tools+ * engine is not obliged to report it; a run without it is left untouched.+ */+ toolSet: Omit<ShareGateToolSet, 'enabledToolIds'> & {+ deferredManifestMap?: Record<string, LobeToolManifest>;+ enabledToolIds?: string[];+ };+}++const isExplicitlyAllowedByEval = (evalAllowedTools?: readonly string[]): boolean =>+ !!evalAllowedTools?.some(+ (entry) =>+ entry === SkillsIdentifier ||+ entry.startsWith(`${SkillsIdentifier}${PLUGIN_SCHEMA_SEPARATOR}`),+ );++/**+ * Start an Agent-mode run without the skill APIs of `lobe-skills` when it has+ * no skill to offer and the conversation never used one.+ *+ * The sandbox shell and `exportFile` stay enabled: they are the run's always-on+ * shell and do not depend on skills. Only `activateSkill` / `readReference` /+ * `execScript` leave, and the full manifest moves to `deferredManifestMap` so+ * installing a skill mid-run (`lobe-skill-store`) restores them on the next+ * step. On a routed device the tool has no shell to keep and leaves entirely.+ * Share runs cannot install skills, so there the tool is dropped outright.+ *+ * Mutates the tool set in place so `initialContext.payload.tools` and+ * `resolveOperationInitSlots` observe the same narrowed surface.+ */+export const deferUnusedSkillsTool = (params: DeferUnusedSkillsToolParams): boolean => {+ const {+ agentChatConfig,+ allMessages,+ evalAllowedTools,+ exclusivePluginIds,+ isGoalTurn = false,+ isShareRun = false,+ operationSkillSet,+ toolSet,+ } = params;+ const { enabledToolIds } = toolSet;++ if (!enabledToolIds?.includes(SkillsIdentifier)) return false;+ if (isGoalTurn) return false;+ if (exclusivePluginIds?.includes(SkillsIdentifier)) return false;+ if (isExplicitlyAllowedByEval(evalAllowedTools)) return false;+ if (toolSet.activatableToolIds.includes(SkillsIdentifier)) return false;+ if (+ !canDeferSkillsTool({+ chatConfig: agentChatConfig,+ hasSkills: operationSkillSet ? operationSkillSet.skills.length > 0 : undefined,+ messages: allMessages,+ })+ ) {+ return false;+ }++ const gatedToolSet = { ...toolSet, enabledToolIds };++ if (isShareRun) {+ dropToolFromSet(gatedToolSet, SkillsIdentifier);+ applyShareGateToActivator(gatedToolSet);+ return true;+ }++ const deferral = planSkillsToolDeferral(toolSet.manifestMap);+ if (!deferral) return false;++ applySkillsToolDeferral(gatedToolSet, deferral);+ toolSet.deferredManifestMap = gatedToolSet.deferredManifestMap;++ return true;+};diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.tsindex 10fd8b42616..ecc405cd36d 100644--- a/apps/server/src/services/aiAgent/pipeline/operationInit.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts@@ -221,6 +221,7 @@ export const runOperationInit = async (ephemeralUserMessage: request.ephemeralUserMessage,evalAllowedTools: request.evalAllowedTools,evalMemory: request.evalMemory,+ exclusivePluginIds: request.exclusivePluginIds,globalMemoryEnabled: request.globalMemoryEnabled,hasMentionedAgents: request.hasMentionedAgents,loadHistoryMessages: deps.loadHistoryMessages,diff --git a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.tsindex 4192fd98322..4a41a3fbf72 100644--- a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts@@ -61,6 +61,7 @@ export const resolveOperationInitSlots = async ({searchDecision: discovery.searchDecision,toolSet: {activatableToolIds: prep.activatableToolIds,+ deferredManifestMap: prep.deferredManifestMap,enabledToolIds: discovery.toolsResult.enabledToolIds,executorMap: discovery.toolExecutorMap,manifestMap: discovery.toolManifestMap,diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex d8a1cb339d6..efc37f86432 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -2,9 +2,14 @@ import type { AgentRuntimeContext } from '@lobechat/agent-runtime';import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';import { ChannelIdentifier } from '@lobechat/builtin-tool-channel';+import { isGoalPrompt } from '@lobechat/builtin-tool-goal';import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';import { TaskIdentifier } from '@lobechat/builtin-tool-task';-import type { OperationSkillSet, ProjectInstructionFile } from '@lobechat/context-engine';+import type {+ LobeToolManifest,+ OperationSkillSet,+ ProjectInstructionFile,+} from '@lobechat/context-engine';import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';import type { LobeChatDatabase } from '@lobechat/database';import type {@@ -41,6 +46,7 @@ import type {} from '../types';import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCache';import { buildArtboardCommentsPrompt } from './artboardContext';+import { deferUnusedSkillsTool, type DeferUnusedSkillsToolParams } from './deferUnusedSkillsTool';import { buildOperationSkillSet, collectSelectedSkillIds } from './operationSkillSet';import { buildRunProjectContextPrompt } from './projectContext';import type { ToolDiscoveryResult } from './toolDiscovery';@@ -196,6 +202,8 @@ export interface OperationPrepInput {evalAllowedTools?: string[];/** Isolated Memory scope of an eval trial; persona is read from it, never the caller. */evalMemory?: EvalMemoryReference;+ /** Exact toolset requested by the caller (e.g. verify agent, goal supervisor). */+ exclusivePluginIds?: string[];globalMemoryEnabled: boolean;hasMentionedAgents: boolean;loadHistoryMessages: () => Promise<any[]>;@@ -214,6 +222,8 @@ export interface OperationPrepInput {export interface OperationPrepResult {activatableToolIds: string[];allMessages: any[];+ /** Full manifests of tools this run starts narrowed (`OperationToolSet.deferredManifestMap`). */+ deferredManifestMap?: Record<string, LobeToolManifest>;deviceSystemInfo: Record<string, string>;expertise?: Awaited<ReturnType<typeof buildExpertiseContextSnapshot>>;initialContext: AgentRuntimeContext;@@ -867,6 +877,32 @@ export const prepareOperation = async (workspaceInit,});+ // 18b. A run with no skill to offer starts without the skill APIs of+ // `lobe-skills`; its sandbox shell and `exportFile` stay. The full manifest+ // waits in `deferredManifestMap` until a skill is installed mid-run.+ const skillsToolSet: DeferUnusedSkillsToolParams['toolSet'] = {+ activatableToolIds,+ enabledToolIds: toolsResult.enabledToolIds,+ executorMap: discovery.toolExecutorMap,+ manifestMap: discovery.toolManifestMap,+ sourceMap: discovery.toolSourceMap,+ tools,+ };+ if (+ deferUnusedSkillsTool({+ agentChatConfig: agentConfig.chatConfig,+ allMessages,+ evalAllowedTools: input.evalAllowedTools,+ exclusivePluginIds: input.exclusivePluginIds,+ isGoalTurn: isGoalPrompt(prompt),+ isShareRun: Boolean(shareGate),+ operationSkillSet,+ toolSet: skillsToolSet,+ })+ ) {+ log('execAgent: deferred the skill APIs of lobe-skills (no skill available or used)');+ }+// Resolve learned expertise once so every step in this operation uses the exact same snapshot.// ContextEngine owns the Lab-controlled injection decision via enableExpertise.const expertiseAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;@@ -886,6 +922,7 @@ export const prepareOperation = async (return {activatableToolIds,allMessages,+ deferredManifestMap: skillsToolSet.deferredManifestMap,deviceSystemInfo,expertise,initialContext,diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.tsindex 45802c0be6d..8af8e3ba7d1 100644--- a/apps/server/src/services/aiAgent/shareGate/toolSet.ts+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.ts@@ -208,7 +208,7 @@ const applyShareGateToCloudSandbox = (toolSet: ShareGateToolSet): void => {* never in a visitor's set, and its `activateSkill` lines stay only while* `lobe-skills` itself survived the gate (a share with `skillGrants`).*/-const applyShareGateToActivator = (toolSet: ShareGateToolSet): void => {+export const applyShareGateToActivator = (toolSet: ShareGateToolSet): void => {const manifest = toolSet.manifestMap[LobeActivatorIdentifier];if (!manifest) return;diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex c6a9c4d1a62..5ab33c287b8 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -659,4 +659,176 @@ describe('single tool executors', () => {expect.not.objectContaining({ toolMessageIds: expect.anything() }),);});++ it('auto-activates deferred lobe-skills after lobe-skill-store imports a skill in the same operation', async () => {+ const skillsManifest = {+ api: [{ description: 'Activate skill', name: 'activateSkill', parameters: {} }],+ identifier: 'lobe-skills',+ meta: { title: 'Skills' },+ type: 'builtin',+ };+ runTool.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'Skill "pptx" created successfully from market.',+ state: { name: 'pptx', skillId: 'skl_1', status: 'created', success: true },+ success: true,+ },+ });++ // The run started without skills: `lobe-skills` is enabled with its shell+ // surface only, and the full manifest waits in `deferredManifestMap`.+ const shellManifest = {+ ...skillsManifest,+ api: [{ description: 'Run a command', name: 'runCommand', parameters: {} }],+ };+ const state = createState({+ operationToolSet: {+ deferredManifestMap: { 'lobe-skills': skillsManifest },+ enabledToolIds: ['lobe-activator', 'lobe-skill-store', 'lobe-skills'],+ manifestMap: { 'lobe-skills': shellManifest },+ sourceMap: { 'lobe-skills': 'builtin' },+ tools: [],+ },+ } as any);++ const result = await callTool(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: {+ ...createToolCall('import-call-1', 'lobe-skill-store'),+ apiName: 'importFromMarket',+ },+ },+ type: 'call_tool',+ },+ state,+ );++ expect(result.newState.activatedStepTools).toEqual([+ expect.objectContaining({+ afterToolCallId: 'import-call-1',+ id: 'lobe-skills',+ manifest: skillsManifest,+ source: 'discovery',+ }),+ ]);+ });++ it('does not auto-activate lobe-skills when skill import fails or when the run did not defer it', async () => {+ runTool.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'Failed to import skill',+ success: false,+ },+ });++ const failed = await callTool(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: {+ ...createToolCall('import-fail', 'lobe-skill-store'),+ apiName: 'importSkill',+ },+ },+ type: 'call_tool',+ },+ createState({+ operationToolSet: {+ deferredManifestMap: { 'lobe-skills': { api: [], identifier: 'lobe-skills' } },+ enabledToolIds: ['lobe-activator', 'lobe-skill-store'],+ manifestMap: {},+ sourceMap: {},+ tools: [],+ },+ } as any),+ );+ expect(failed.newState.activatedStepTools).toBeUndefined();++ runTool.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'Skill "pptx" created successfully.',+ state: { name: 'pptx', skillId: 'skl_1', status: 'created', success: true },+ success: true,+ },+ });+ const notDeferred = await callTool(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: {+ ...createToolCall('import-no-manifest', 'lobe-skill-store'),+ apiName: 'importSkill',+ },+ },+ type: 'call_tool',+ },+ // `lobe-skills` is enabled in full here, so there is nothing to promote.+ createState({+ operationToolSet: {+ enabledToolIds: ['lobe-activator', 'lobe-skills'],+ manifestMap: { 'lobe-skills': { api: [], identifier: 'lobe-skills' } },+ sourceMap: {},+ tools: [],+ },+ } as any),+ );+ expect(notDeferred.newState.activatedStepTools).toBeUndefined();+ });++ it('auto-activates deferred lobe-skills when lobe-activator activates a skill via fallback', async () => {+ const skillsManifest = {+ api: [{ description: 'Activate skill', name: 'activateSkill', parameters: {} }],+ identifier: 'lobe-skills',+ meta: { title: 'Skills' },+ type: 'builtin',+ };+ runTool.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'Activated skill content',+ state: {+ activatedSkills: [{ id: 'skl_1', name: 'pptx' }],+ activatedTools: [],+ },+ success: true,+ },+ });++ const result = await callTool(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: {+ ...createToolCall('activate-skill-fallback', 'lobe-activator'),+ apiName: 'activateTools',+ },+ },+ type: 'call_tool',+ },+ createState({+ // A device run: nothing of `lobe-skills` is enabled at start.+ operationToolSet: {+ deferredManifestMap: { 'lobe-skills': skillsManifest },+ enabledToolIds: ['lobe-activator'],+ manifestMap: {},+ sourceMap: {},+ tools: [],+ },+ } as any),+ );++ expect(result.newState.activatedStepTools).toEqual([+ expect.objectContaining({+ afterToolCallId: 'activate-skill-fallback',+ id: 'lobe-skills',+ manifest: skillsManifest,+ source: 'discovery',+ }),+ ]);+ });});diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 6705ebc9941..76158f3727e 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -410,6 +410,28 @@ const pauseForTools = async ({};};+const SKILLS_IDENTIFIER = 'lobe-skills';+const SKILL_STORE_IDENTIFIER = 'lobe-skill-store';+const ACTIVATOR_IDENTIFIER = 'lobe-activator';+const SKILL_STORE_IMPORT_APIS = new Set(['importFromMarket', 'importSkill']);++const shouldAutoActivateSkillsTool = (result: ToolResultEntry): boolean => {+ if (!result.isSuccess) return false;+ if (+ result.toolCall.identifier === SKILL_STORE_IDENTIFIER &&+ SKILL_STORE_IMPORT_APIS.has(result.toolCall.apiName)+ ) {+ return true;+ }++ return (+ result.toolCall.identifier === ACTIVATOR_IDENTIFIER &&+ result.toolCall.apiName === 'activateTools' &&+ Array.isArray(result.data.state?.activatedSkills) &&+ result.data.state.activatedSkills.length > 0+ );+};+const persistActivatedTools = ({effectiveManifestMap,newState,@@ -422,26 +444,38 @@ const persistActivatedTools = ({stepCount: number;}) => {const existingIds = new Set((newState.activatedStepTools ?? []).map((tool) => tool.id));+ const deferredManifestMap = newState.operationToolSet?.deferredManifestMap ?? {};for (const result of results) {- const discoveredTools = result.data.state?.activatedTools as- Array<{ identifier: string }> | undefined;- if (!discoveredTools?.length) continue;+ const discoveredTools = (+ (result.data.state?.activatedTools as Array<{ identifier: string }> | undefined) ?? []+ ).map((tool) => tool.identifier);++ // A run that starts without skills defers the skill APIs of `lobe-skills`+ // (`operationToolSet.deferredManifestMap`). Once this operation installs a+ // skill, or activates one through the activator's skill fallback, promote+ // the tool so the next LLM call can invoke `activateSkill` /+ // `readReference` / `execScript`.+ if (shouldAutoActivateSkillsTool(result) && deferredManifestMap[SKILLS_IDENTIFIER]) {+ discoveredTools.push(SKILLS_IDENTIFIER);+ }++ if (discoveredTools.length === 0) continue;// The set is updated inside the filter, not after mapping the batch: two// results in the same step (or one result listing the same tool twice)// would otherwise both pass and be appended twice.const newActivations = discoveredTools- .filter((tool) => {- if (existingIds.has(tool.identifier)) return false;- existingIds.add(tool.identifier);+ .filter((identifier) => {+ if (existingIds.has(identifier)) return false;+ existingIds.add(identifier);return true;})- .map((tool) => ({+ .map((identifier) => ({activatedAtStep: stepCount,afterToolCallId: result.toolCallId,- id: tool.identifier,- manifest: effectiveManifestMap[tool.identifier],+ id: identifier,+ manifest: effectiveManifestMap[identifier],source: 'discovery' as const,}));diff --git a/packages/agent-runtime/src/utils/messageSelectors.test.ts b/packages/agent-runtime/src/utils/messageSelectors.test.tsindex cad588f80c9..bbc12fd3e11 100644--- a/packages/agent-runtime/src/utils/messageSelectors.test.ts+++ b/packages/agent-runtime/src/utils/messageSelectors.test.ts@@ -8,6 +8,7 @@ import {extractTodosFromMessages,extractToolActivationsFromMessages,findInMessages,+ hasHistoricalToolInvocation,normalizeTodosState,} from './messageSelectors';@@ -581,3 +582,124 @@ describe('flat tool rows inside compressedGroup compressedMessages', () => {expect(extractTodosFromMessages(messages)).toEqual(todos);});});++describe('hasHistoricalToolInvocation', () => {+ it('returns false when messages contain no matching tool invocations', () => {+ const messages = [+ createMessage({ content: 'hello', role: 'user' }),+ createToolMessage({+ plugin: { apiName: 'search', identifier: 'lobe-web-browsing' },+ } as any),+ ];++ expect(hasHistoricalToolInvocation(messages, 'lobe-skills')).toBe(false);+ });++ it('detects flat tool messages, assistant tools/tool_calls, assistantGroup children, and compressedGroup entries', () => {+ expect(+ hasHistoricalToolInvocation(+ [+ createToolMessage({+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },+ } as any),+ ],+ 'lobe-skills',+ ),+ ).toBe(true);++ expect(+ hasHistoricalToolInvocation(+ [+ createMessage({+ role: 'assistant',+ tools: [{ apiName: 'execScript', id: 'tc-1', identifier: 'lobe-skills' }],+ } as any),+ ],+ 'lobe-skills',+ ),+ ).toBe(true);++ expect(+ hasHistoricalToolInvocation(+ [+ createMessage({+ role: 'assistant',+ tool_calls: [{ function: { name: 'lobe-skills____runCommand' }, id: 'tc-2' }],+ } as any),+ ],+ 'lobe-skills',+ ),+ ).toBe(true);++ expect(+ hasHistoricalToolInvocation(+ [+ createMessage({+ children: [+ { tools: [{ apiName: 'readReference', id: 'tc-3', identifier: 'lobe-skills' }] },+ ],+ role: 'assistantGroup',+ } as any),+ ],+ 'lobe-skills',+ ),+ ).toBe(true);++ expect(+ hasHistoricalToolInvocation(+ [+ createMessage({+ compressedMessages: [+ createMessage({+ role: 'assistant',+ tools: [{ apiName: 'activateSkill', id: 'tc-4', identifier: 'lobe-skills' }],+ } as any),+ ],+ role: 'compressedGroup',+ } as any),+ ],+ 'lobe-skills',+ ),+ ).toBe(true);+ });++ it('limits the match to the given API names', () => {+ const skillApis = new Set(['activateSkill', 'execScript', 'readReference']);+ const shellOnly = [+ createToolMessage({+ plugin: { apiName: 'runCommand', identifier: 'lobe-skills' },+ } as any),+ createMessage({+ role: 'assistant',+ tool_calls: [{ function: { name: 'lobe-skills____exportFile' }, id: 'tc-1' }],+ tools: [{ apiName: 'runCommand', id: 'tc-2', identifier: 'lobe-skills' }],+ } as any),+ ];++ expect(hasHistoricalToolInvocation(shellOnly, 'lobe-skills')).toBe(true);+ expect(hasHistoricalToolInvocation(shellOnly, 'lobe-skills', skillApis)).toBe(false);++ expect(+ hasHistoricalToolInvocation(+ [+ ...shellOnly,+ createMessage({+ role: 'assistant',+ tool_calls: [{ function: { name: 'lobe-skills____execScript' }, id: 'tc-3' }],+ } as any),+ ],+ 'lobe-skills',+ skillApis,+ ),+ ).toBe(true);++ // A row that did not record its API cannot be ruled out.+ expect(+ hasHistoricalToolInvocation(+ [createToolMessage({ plugin: { identifier: 'lobe-skills' } } as any)],+ 'lobe-skills',+ skillApis,+ ),+ ).toBe(true);+ });+});diff --git a/packages/agent-runtime/src/utils/messageSelectors.ts b/packages/agent-runtime/src/utils/messageSelectors.tsindex 450a3395871..79e3513e80e 100644--- a/packages/agent-runtime/src/utils/messageSelectors.ts+++ b/packages/agent-runtime/src/utils/messageSelectors.ts@@ -317,3 +317,77 @@ export const extractToolActivationsFromMessages = (export const extractActivatedToolIdsFromMessages = (messages: UIChatMessage[],): string[] | undefined => extractToolActivationsFromMessages(messages)?.map(({ id }) => id);++const TOOL_NAME_SEPARATOR = '____';++const messageHasToolInvocation = (+ msg: UIChatMessage,+ identifier: string,+ prefix: string,+ apiNames?: ReadonlySet<string>,+): boolean => {+ // A call whose API name was not recorded counts: it cannot be ruled out.+ const matchesApi = (apiName: string | undefined) =>+ !apiNames || !apiName || apiNames.has(apiName);++ if (+ collectToolInvocations(msg).some(+ (invocation) => invocation.identifier === identifier && matchesApi(invocation.apiName),+ )+ ) {+ return true;+ }++ if (msg.role === 'assistant') {+ if (+ Array.isArray(msg.tools) &&+ msg.tools.some((tool) => tool?.identifier === identifier && matchesApi(tool?.apiName))+ ) {+ return true;+ }++ const toolCalls = (msg as { tool_calls?: Array<{ function?: { name?: string } }> }).tool_calls;+ if (+ Array.isArray(toolCalls) &&+ toolCalls.some((call) => {+ const name = call?.function?.name;+ if (name === identifier) return true;+ return (+ typeof name === 'string' &&+ name.startsWith(prefix) &&+ matchesApi(name.slice(prefix.length))+ );+ })+ ) {+ return true;+ }+ }++ if (Array.isArray(msg.compressedMessages)) {+ return msg.compressedMessages.some((compressed) =>+ messageHasToolInvocation(compressed, identifier, prefix, apiNames),+ );+ }++ return false;+};++/**+ * Whether the conversation history contains a tool invocation for `identifier`,+ * optionally limited to the given API names.+ *+ * Covers flat DB rows (`role='tool'` and `role='assistant'` with `tools` /+ * `tool_calls`), grouped `assistantGroup` / `supervisor` nodes, and nested+ * `compressedGroup` entries. Used to keep the APIs of a deferred tool (such as+ * the skill APIs of `lobe-skills`) declared when earlier turns already called+ * them: a provider rejects a history that calls a function the request no+ * longer declares.+ */+export const hasHistoricalToolInvocation = (+ messages: UIChatMessage[],+ identifier: string,+ apiNames?: ReadonlySet<string>,+): boolean => {+ const prefix = `${identifier}${TOOL_NAME_SEPARATOR}`;+ return messages.some((msg) => messageHasToolInvocation(msg, identifier, prefix, apiNames));+};diff --git a/packages/agent-runtime/src/utils/operationToolSet.test.ts b/packages/agent-runtime/src/utils/operationToolSet.test.tsnew file mode 100644index 00000000000..87c2eebc031--- /dev/null+++ b/packages/agent-runtime/src/utils/operationToolSet.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { selectEffectiveToolManifestMap } from './operationToolSet';++const shellManifest = { api: [{ name: 'runCommand' }], identifier: 'lobe-skills' };+const fullManifest = {+ api: [{ name: 'runCommand' }, { humanIntervention: 'required', name: 'execScript' }],+ identifier: 'lobe-skills',+};+const searchManifest = { api: [{ name: 'search' }], identifier: 'web-search' };++const toolSet = (extra: object = {}) =>+ ({+ enabledToolIds: ['lobe-skills'],+ manifestMap: { 'lobe-skills': shellManifest },+ sourceMap: {},+ tools: [],+ ...extra,+ }) as any;++describe('selectEffectiveToolManifestMap', () => {+ it('returns the static map itself when nothing is activated or deferred', () => {+ const operationToolSet = toolSet();++ expect(selectEffectiveToolManifestMap({ operationToolSet })).toBe(operationToolSet.manifestMap);+ });++ // A call to an API the run has not been offered yet must still find that+ // API's approval rule, not a narrowed manifest that does not list it.+ it('resolves a deferred tool to its full manifest before it is promoted', () => {+ const map = selectEffectiveToolManifestMap({+ operationToolSet: toolSet({ deferredManifestMap: { 'lobe-skills': fullManifest } }),+ });++ expect(map['lobe-skills']).toBe(fullManifest);+ });++ it('lets a step activation win over the static and deferred manifests', () => {+ const map = selectEffectiveToolManifestMap({+ activatedStepTools: [+ { activatedAtStep: 1, id: 'web-search', manifest: searchManifest, source: 'discovery' },+ ] as any,+ operationToolSet: toolSet({ deferredManifestMap: { 'lobe-skills': fullManifest } }),+ });++ expect(map).toEqual({ 'lobe-skills': fullManifest, 'web-search': searchManifest });+ });+});diff --git a/packages/agent-runtime/src/utils/operationToolSet.ts b/packages/agent-runtime/src/utils/operationToolSet.tsindex 9b0b1949158..ee42efb1680 100644--- a/packages/agent-runtime/src/utils/operationToolSet.ts+++ b/packages/agent-runtime/src/utils/operationToolSet.ts@@ -39,15 +39,22 @@ export const selectToolManifestMap = (state: Partial<ToolSetCarrier>): Record<st* tool exposed only through `activatedStepTools` has no entry in the static* map, and reading the static map alone silently degrades a pre-check to the* wrong branch.+ *+ * A tool the operation deferred (`deferredManifestMap`) resolves to its full+ * manifest here even before it is promoted, so a call to an API that is not+ * offered yet still answers to that API's own approval rule instead of looking+ * like an API without one.*/export const selectEffectiveToolManifestMap = (state: Partial<ToolSetCarrier>,): Record<string, any> => {const staticMap = selectToolManifestMap(state);const activated = state.activatedStepTools ?? [];- if (activated.length === 0) return staticMap;+ const deferredMap = state.operationToolSet?.deferredManifestMap;+ if (activated.length === 0 && !deferredMap) return staticMap;return {...staticMap,+ ...deferredMap,...Object.fromEntries(activated.filter((activation) => activation.manifest)diff --git a/packages/builtin-tool-activator/src/index.ts b/packages/builtin-tool-activator/src/index.tsindex 6e26e8f61fc..b70a3964186 100644--- a/packages/builtin-tool-activator/src/index.ts+++ b/packages/builtin-tool-activator/src/index.ts@@ -1,6 +1,6 @@export { ACTIVATE_TOOLS_AUDIT, activateToolsAudit } from './interventionAudit';export { LobeActivatorManifest } from './manifest';-export { getSystemPromptForShareVisitor, systemPrompt } from './systemRole';+export { getSystemPrompt, getSystemPromptForShareVisitor, systemPrompt } from './systemRole';export {type ActivatedToolInfo,type ActivateSkillParams,diff --git a/packages/builtin-tool-activator/src/systemRole.ts b/packages/builtin-tool-activator/src/systemRole.tsindex 27d266976fd..6c8e90cc0ca 100644--- a/packages/builtin-tool-activator/src/systemRole.ts+++ b/packages/builtin-tool-activator/src/systemRole.ts@@ -11,13 +11,15 @@ const skillStoreDiscovery = `<skill_store_discovery>For marketplace skill searches, skill install requests (including SKILL.md, GitHub or LobeHub skill URLs), or a specialized task that needs a capability missing from the available tools and skills, use the Skill Store. If lobe-skill-store is in <available_tools>, activate it before browsing or trying a CLI. If already active, call it directly.</skill_store_discovery>`;-export const systemPrompt = `${intro}+export const getSystemPrompt = ({ withSkills }: { withSkills: boolean }) => `${intro}-${guidelines({ withSkills: true })}+${guidelines({ withSkills })}${skillStoreDiscovery}`;+export const systemPrompt = getSystemPrompt({ withSkills: true });+/*** Agent Share visitors cannot use the Skill Store. Keep discovery scoped to* the granted tools and omit the marketplace instructions. Thediff --git a/packages/builtin-tool-skills/src/index.ts b/packages/builtin-tool-skills/src/index.tsindex f51aec1eb50..5389fe9f65e 100644--- a/packages/builtin-tool-skills/src/index.ts+++ b/packages/builtin-tool-skills/src/index.ts@@ -4,6 +4,7 @@ export {agentShareSystemPrompt,resolveSkillsRestrictedManifest,} from './resolveRestrictedManifest';+export { resolveSkillsShellManifest, SKILL_BOUND_API_NAMES } from './resolveShellManifest';export { deviceSystemPrompt, systemPrompt } from './systemRole';export {type ActivateSkillParams,diff --git a/packages/builtin-tool-skills/src/resolveManifest.ts b/packages/builtin-tool-skills/src/resolveManifest.tsindex 21ed65762ac..cb4a053569c 100644--- a/packages/builtin-tool-skills/src/resolveManifest.ts+++ b/packages/builtin-tool-skills/src/resolveManifest.ts@@ -1,7 +1,7 @@import type { BuiltinManifestResolver, BuiltinToolResolveContext } from '@lobechat/types';import { SkillsManifest } from './manifest';-import { deviceSystemPrompt } from './systemRole';+import { appendExecutionEnvironment, deviceSystemPrompt } from './systemRole';import { SkillsApiName } from './types';/**@@ -160,8 +160,6 @@ export const resolveSkillsManifest: BuiltinManifestResolver = (context) => {? { ...api, description: `${preamble} ${api.description}` }: api,),- systemRole: fact- ? `${baseSystemRole}\n<execution_environment>\n${fact}\n</execution_environment>\n`- : baseSystemRole,+ systemRole: fact ? appendExecutionEnvironment(baseSystemRole, fact) : baseSystemRole,};};diff --git a/packages/builtin-tool-skills/src/resolveShellManifest.test.ts b/packages/builtin-tool-skills/src/resolveShellManifest.test.tsnew file mode 100644index 00000000000..5ef0d98f62d--- /dev/null+++ b/packages/builtin-tool-skills/src/resolveShellManifest.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';++import { SkillsManifest } from './manifest';+import { resolveSkillsManifest } from './resolveManifest';+import { resolveSkillsRestrictedManifest } from './resolveRestrictedManifest';+import { resolveSkillsShellManifest } from './resolveShellManifest';+import { AGENT_SHARE_SKILL_API_NAMES, SkillsApiName } from './types';++const apiNames = (manifest: { api: { name: string }[] } | undefined) =>+ manifest?.api.map(({ name }) => name);++describe('resolveSkillsShellManifest', () => {+ it('keeps the sandbox shell and file export, and drops the APIs that need a skill', () => {+ const shell = resolveSkillsShellManifest(SkillsManifest)!;++ expect(apiNames(shell)).toEqual([SkillsApiName.runCommand, SkillsApiName.exportFile]);+ expect(shell.identifier).toBe(SkillsManifest.identifier);+ });++ it('describes only the offered APIs and keeps the sandbox workspace placeholder', () => {+ const { systemRole } = resolveSkillsShellManifest(SkillsManifest)!;++ expect(systemRole).toContain('**runCommand**');+ expect(systemRole).toContain('**exportFile**');+ expect(systemRole).toContain('{{sandbox_workspace}}');+ expect(systemRole).not.toContain('activateSkill');+ expect(systemRole).not.toContain('readReference');+ expect(systemRole).not.toContain('execScript');+ });++ it('carries over what the execution environment resolved', () => {+ const resolved = resolveSkillsManifest({+ executionEnv: 'device-unrouted',+ executionEnvUnroutedReason: 'bound-device-offline',+ })!;+ const shell = resolveSkillsShellManifest(resolved)!;++ expect(shell.api.find(({ name }) => name === SkillsApiName.runCommand)?.description).toMatch(+ /^Fallback execution environment/,+ );+ expect(shell.systemRole).toContain(+ '<execution_environment>\nBound device offline; shell commands execute in the cloud sandbox this run.\n</execution_environment>',+ );+ });++ it('keeps only exportFile in page scope, without the runCommand instructions', () => {+ const shell = resolveSkillsShellManifest(resolveSkillsManifest({ scope: 'page' })!)!;++ expect(apiNames(shell)).toEqual([SkillsApiName.exportFile]);+ expect(shell.systemRole).not.toContain('runCommand');+ expect(shell.systemRole).not.toContain('{{sandbox_workspace}}');+ });++ it.each(['device', 'local'] as const)(+ 'has nothing to offer on a routed device (%s)',+ (executionEnv) => {+ expect(resolveSkillsShellManifest(resolveSkillsManifest({ executionEnv })!)).toBeUndefined();+ },+ );++ it('has nothing to offer on the Agent Share surface', () => {+ const shared = resolveSkillsRestrictedManifest({+ allowedApiNames: [...AGENT_SHARE_SKILL_API_NAMES],+ restriction: 'agentShare',+ })!;++ expect(resolveSkillsShellManifest(shared)).toBeUndefined();+ });+});diff --git a/packages/builtin-tool-skills/src/resolveShellManifest.ts b/packages/builtin-tool-skills/src/resolveShellManifest.tsnew file mode 100644index 00000000000..1cd3c92e03c--- /dev/null+++ b/packages/builtin-tool-skills/src/resolveShellManifest.ts@@ -0,0 +1,48 @@+import { extractExecutionEnvironment, getShellSystemPrompt } from './systemRole';+import { SkillsApiName } from './types';++/**+ * APIs that only do something once a skill is loaded: `activateSkill` and+ * `readReference` resolve against the run's skill pool, and `execScript` runs+ * inside the directory of an activated skill.+ *+ * Listed by what needs a skill rather than by what is the shell, so an API+ * added to this tool later stays offered on a run without skills unless it is+ * added here on purpose.+ */+export const SKILL_BOUND_API_NAMES: ReadonlySet<string> = new Set<string>([+ SkillsApiName.activateSkill,+ SkillsApiName.execScript,+ SkillsApiName.readReference,+]);++/**+ * The part of the Skills tool that works with no skill available: the sandbox+ * shell (`runCommand`) and `exportFile`.+ *+ * Takes the manifest the run already resolved, so whatever the execution+ * environment or scope did to it (description preambles, hidden APIs, the+ * `<execution_environment>` fact) carries over. Returns `undefined` when+ * nothing is left, which is the case on a routed device and on an Agent Share+ * run: neither offers the sandbox shell through this tool.+ */+export const resolveSkillsShellManifest = <+ T extends { api: { name: string }[]; systemRole?: string },+>(+ manifest: T,+): T | undefined => {+ const api = manifest.api.filter(({ name }) => !SKILL_BOUND_API_NAMES.has(name));+ if (api.length === 0) return undefined;++ const offered = new Set(api.map(({ name }) => name));+ const role = getShellSystemPrompt({+ exportFile: offered.has(SkillsApiName.exportFile),+ runCommand: offered.has(SkillsApiName.runCommand),+ });++ return {+ ...manifest,+ api,+ systemRole: `${role}${extractExecutionEnvironment(manifest.systemRole)}`,+ };+};diff --git a/packages/builtin-tool-skills/src/systemRole.desktop.ts b/packages/builtin-tool-skills/src/systemRole.desktop.tsindex d29f85ea0ce..9c0efae2d18 100644--- a/packages/builtin-tool-skills/src/systemRole.desktop.ts+++ b/packages/builtin-tool-skills/src/systemRole.desktop.ts@@ -1,5 +1,8 @@export {+ appendExecutionEnvironment,deviceSystemPrompt,+ extractExecutionEnvironment,+ getShellSystemPrompt,sharedSkillGuidelines,deviceSystemPrompt as systemPrompt,} from './systemRole';diff --git a/packages/builtin-tool-skills/src/systemRole.ts b/packages/builtin-tool-skills/src/systemRole.tsindex 98eaa08fc6b..3f87e1bd330 100644--- a/packages/builtin-tool-skills/src/systemRole.ts+++ b/packages/builtin-tool-skills/src/systemRole.ts@@ -3,14 +3,18 @@ const intro = `You have access to a Skills tool that loads and executes skillsexport 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.`;+const runCommandGuideline = `Execute general CLI and shell commands (e.g., \`lh\` CLI, \`npm\`, system commands) in the cloud sandbox. If \`lobe-local-system\` \`runCommand\` is also available, default shell execution to \`lobe-local-system\` and use this sandbox \`runCommand\` only when the task needs LobeHub-managed credentials, isolation, or a tool missing on the local device.`;++const exportFileGuideline = `- **exportFile**: Export files generated in the cloud sandbox to return a permanent download URL for the user. Sandbox paths are not reachable by the user: to show or link a sandbox file in your reply (including a Markdown image), export it and use the returned Download URL, never the sandbox path.`;+export const systemPrompt = `${intro}<guidelines>${sharedSkillGuidelines}- **runCommand vs execScript**:- - **runCommand (default)**: Execute general CLI and shell commands (e.g., \`lh\` CLI, \`npm\`, system commands) in the cloud sandbox. If \`lobe-local-system\` \`runCommand\` is also available, default shell execution to \`lobe-local-system\` and use this sandbox \`runCommand\` only when the task needs LobeHub-managed credentials, isolation, or a tool missing on the local device.+ - **runCommand (default)**: ${runCommandGuideline}- **execScript**: Use only when a command requires skill-bundled resources (ZIP packages, scripts, or config files) from the activated skill.-- **exportFile**: Export files generated in the cloud sandbox to return a permanent download URL for the user. Sandbox paths are not reachable by the user: to show or link a sandbox file in your reply (including a Markdown image), export it and use the returned Download URL, never the sandbox path.+${exportFileGuideline}</guidelines><sandbox_environment>@@ -19,6 +23,54 @@ ${sharedSkillGuidelines}</sandbox_environment>`;+const shellSandboxEnvironment = `+<sandbox_environment>+\`runCommand\` runs in the conversation's isolated cloud sandbox session and working directory:+{{sandbox_workspace}}+</sandbox_environment>+`;++/**+ * System prompt for a run with no skill to load, where the tool keeps only its+ * sandbox shell surface (see `resolveSkillsShellManifest`). A line is included+ * only when its API is offered, so the role never names an API the manifest+ * does not carry.+ */+export const getShellSystemPrompt = ({+ exportFile,+ runCommand,+}: {+ exportFile: boolean;+ runCommand: boolean;+}) => {+ const guidelines = [+ runCommand && `- **runCommand**: ${runCommandGuideline}`,+ exportFile && exportFileGuideline,+ ]+ .filter(Boolean)+ .join('\n');+ const role = `You have access to the conversation's isolated cloud sandbox.++<guidelines>+${guidelines}+</guidelines>+`;++ return runCommand ? `${role}${shellSandboxEnvironment}` : role;+};++const EXECUTION_ENVIRONMENT_OPEN = '\n<execution_environment>\n';++/** Append the per-run execution fact that `resolveSkillsManifest` resolves. */+export const appendExecutionEnvironment = (role: string, fact: string) =>+ `${role}${EXECUTION_ENVIRONMENT_OPEN}${fact}\n</execution_environment>\n`;++/** The block {@link appendExecutionEnvironment} added to `role`, or an empty string. */+export const extractExecutionEnvironment = (role: string | undefined): string => {+ const index = role?.lastIndexOf(EXECUTION_ENVIRONMENT_OPEN) ?? -1;+ return index < 0 ? '' : role!.slice(index);+};+/*** System prompt for device-routed runs (`executionEnv: 'device' | 'local'`),* where `runCommand` and `exportFile` are stripped from the manifest anddiff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex d671f1ab2f6..97e958f61eb 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -93,7 +93,9 @@ export const defaultToolIds = [/*** Builtins enabled by default in Agent mode. The activator loads other tools- * on demand, and Skills loads skill instructions.+ * on demand, and Skills loads skill instructions and carries the sandbox+ * shell. A run with no skill to offer keeps only that shell until a skill+ * arrives (`planSkillsToolDeferral` in `@lobechat/mecha`).*/export const alwaysOnToolIds = [LobeActivatorManifest.identifier, SkillsManifest.identifier];diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex b83e4928ad9..45bcf7874eb 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -269,8 +269,15 @@ export class MessagesEngine {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);+ // agent or a goal turn that did not pin Skills still reaches them through readFile, and a run+ // that deferred the skill APIs has Skills enabled with its sandbox shell only.+ const skillsManifest = toolsConfig?.manifests?.find(+ (manifest) => manifest.identifier === SKILLS_TOOL_ID,+ );+ const canActivateSkill =+ toolIds.includes(SKILLS_TOOL_ID) &&+ (!skillsManifest || skillsManifest.api.some((api) => api.name === 'activateSkill')) &&+ !!canUseFC(model, provider);const injectedActivatedSkills =isAgentMode && (skillsConfig?.enabledSkills?.length ?? 0) > 0? selectActivatedSkills(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.tsindex 8adfb6fdbcc..98f07505e88 100644--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.filesystemSkillLoading.test.ts+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.filesystemSkillLoading.test.ts@@ -5,7 +5,10 @@ import type { UIChatMessage } from '@/types/index';import { MessagesEngine } from '../MessagesEngine';import type { MessagesEngineParams } from '../types';-const createParams = (tools: string[]): MessagesEngineParams => ({+const createParams = (+ tools: string[],+ manifests: NonNullable<MessagesEngineParams['toolsConfig']>['manifests'] = [],+): MessagesEngineParams => ({messages: [{content: 'Deploy the project',@@ -29,11 +32,14 @@ const createParams = (tools: string[]): MessagesEngineParams => ({],},systemRole: 'You are a helpful assistant.',- toolsConfig: { manifests: [], tools },+ toolsConfig: { manifests, tools },});-const systemPromptFor = async (tools: string[]) => {- const result = await new MessagesEngine(createParams(tools)).process();+const systemPromptFor = async (+ tools: string[],+ manifests?: NonNullable<MessagesEngineParams['toolsConfig']>['manifests'],+) => {+ const result = await new MessagesEngine(createParams(tools, manifests)).process();return result.messages[0].content as string;};@@ -54,4 +60,23 @@ describe('MessagesEngine filesystem skill loading instruction', () => {expect(system).toContain('calling the readFile tool on its `location` path');expect(system).not.toContain('do not bypass activation with readFile');});++ it('keeps the readFile route when Skills was sent with its sandbox shell only', async () => {+ // A run that deferred the skill APIs still has Skills enabled; requiring+ // `activateSkill` there would point at a function the model was not sent.+ const system = await systemPromptFor(+ ['lobe-skills', 'lobe-local-system'],+ [+ {+ api: [{ description: 'Run a command', name: 'runCommand', parameters: {} }],+ identifier: 'lobe-skills',+ meta: { title: 'Skills' },+ type: 'builtin',+ },+ ],+ );++ expect(system).toContain('calling the readFile tool on its `location` path');+ expect(system).not.toContain('load it with activateSkill by name');+ });});diff --git a/packages/context-engine/src/engine/tools/ToolResolver.ts b/packages/context-engine/src/engine/tools/ToolResolver.tsindex f48464ad6bc..6c02a39f51b 100644--- a/packages/context-engine/src/engine/tools/ToolResolver.ts+++ b/packages/context-engine/src/engine/tools/ToolResolver.ts@@ -47,14 +47,30 @@ export class ToolResolver {}}+ const deferredManifestMap = operationToolSet.deferredManifestMap ?? {};+// Apply accumulated step-level activations from previous stepsfor (const activation of accumulatedActivations) {- this.applyActivation(activation, tools, manifestMap, sourceMap, enabledToolIds);+ this.applyActivation(+ activation,+ tools,+ manifestMap,+ sourceMap,+ enabledToolIds,+ deferredManifestMap,+ );}// Apply current step delta activationsfor (const activation of stepDelta.activatedTools) {- this.applyActivation(activation, tools, manifestMap, sourceMap, enabledToolIds);+ this.applyActivation(+ activation,+ tools,+ manifestMap,+ sourceMap,+ enabledToolIds,+ deferredManifestMap,+ );}const shouldFilterByToolNames = allowedToolNames !== undefined;@@ -125,13 +141,19 @@ export class ToolResolver {manifestMap: Record<string, LobeToolManifest>,sourceMap: Record<string, ToolSource>,enabledToolIds: string[],+ deferredManifestMap: Record<string, LobeToolManifest>,): void {- // Skip if already present- if (manifestMap[activation.id]) return;-- if (activation.manifest) {- manifestMap[activation.id] = activation.manifest;- const newTools = generateToolsFromManifest(activation.manifest);+ // A tool the operation deferred is promoted to its full manifest, even when+ // a narrowed one is already enabled. The schemas both manifests share are+ // deduplicated by function name afterwards.+ const deferredManifest = deferredManifestMap[activation.id];+ const presentManifest = manifestMap[activation.id];+ if (presentManifest && (!deferredManifest || presentManifest === deferredManifest)) return;++ const manifest = deferredManifest ?? activation.manifest;+ if (manifest) {+ manifestMap[activation.id] = manifest;+ const newTools = generateToolsFromManifest(manifest);tools.push(...newTools);enabledToolIds.push(activation.id);diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.tsindex 185666ed1ae..94e7cf12a20 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts@@ -193,6 +193,67 @@ describe('ToolResolver', () => {});});+ describe('deferred manifests', () => {+ const shellOnlyManifest: LobeToolManifest = {+ ...mockLocalSystemManifest,+ api: [mockLocalSystemManifest.api[0]],+ systemRole: 'shell only',+ };+ const fullManifest: LobeToolManifest = { ...mockLocalSystemManifest, systemRole: 'full' };+ const activation: ActivatedStepTool = {+ activatedAtStep: 1,+ id: 'local-system',+ manifest: fullManifest,+ source: 'discovery',+ };++ it('should keep the narrowed manifest until the tool is activated', () => {+ const result = resolver.resolve(+ {+ ...makeOperationToolSet([shellOnlyManifest]),+ deferredManifestMap: { 'local-system': fullManifest },+ },+ { activatedTools: [] },+ );++ expect(result.manifestMap['local-system']).toBe(shellOnlyManifest);+ expect(result.tools).toHaveLength(1);+ });++ it('should promote an enabled narrowed tool to its full manifest without duplicating schemas', () => {+ const result = resolver.resolve(+ {+ ...makeOperationToolSet([shellOnlyManifest]),+ deferredManifestMap: { 'local-system': fullManifest },+ },+ { activatedTools: [] },+ [activation, { ...activation, activatedAtStep: 2 }],+ );++ expect(result.manifestMap['local-system']).toBe(fullManifest);+ expect(result.enabledToolIds).toEqual(['local-system']);+ expect(result.tools.map((tool) => tool.function.name)).toEqual([+ toolNameResolver.generate('local-system', 'run_command', 'builtin'),+ toolNameResolver.generate('local-system', 'read_file', 'builtin'),+ ]);+ });++ it('should enable a tool that was left out of the operation entirely', () => {+ const result = resolver.resolve(+ {+ ...makeOperationToolSet([mockSearchManifest]),+ deferredManifestMap: { 'local-system': fullManifest },+ },+ { activatedTools: [] },+ [activation],+ );++ expect(result.enabledToolIds).toEqual(['web-search', 'local-system']);+ expect(result.manifestMap['local-system']).toBe(fullManifest);+ expect(result.tools).toHaveLength(3);+ });+ });+describe('deactivation', () => {it('should strip all tools when deactivatedToolIds contains wildcard', () => {const opSet = makeOperationToolSet([mockSearchManifest, mockCalcManifest]);diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.tsindex 3c43a9bd81c..1a8ed489d4f 100644--- a/packages/context-engine/src/engine/tools/types.ts+++ b/packages/context-engine/src/engine/tools/types.ts@@ -188,6 +188,13 @@ export type ActivationSource = 'active_tools' | 'mention' | 'device' | 'discoverexport interface OperationToolSet {/** Tool IDs that may be restored from historical explicit activations for this run. */activatableToolIds?: string[];+ /**+ * Full manifests of tools the operation starts with narrowed or left out,+ * keyed by identifier. An activation of one of these ids replaces whatever+ * `manifestMap` holds for it. They are not offered in `<available_tools>`:+ * the runtime activates them itself once the run comes to need them.+ */+ deferredManifestMap?: Record<string, LobeToolManifest>;enabledToolIds: string[];executorMap?: Record<string, ToolExecutor>;manifestMap: Record<string, LobeToolManifest>;diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex c5627b14fb1..f82f77f3678 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -558,11 +558,12 @@ export const gatherContextFacts = async (const docsAgentId = documentsAgentId(request);const sandboxEnabled = request.enabledToolIds.includes(CloudSandboxIdentifier);// Two tools reach the sandbox, and the optional one is not the common case:- // `lobe-skills` is always on, and when no device is routed its runCommand /- // execScript open the SAME session in the SAME directory as the cloud-sandbox- // tool. When a device IS routed and the cloud-sandbox tool is not enabled,- // `lobe-skills` executes on the device and uses `deviceSystemPrompt` (which- // has no `{{sandbox_workspace}}` placeholder), so no sandbox lookup is needed.+ // `lobe-skills` keeps its shell on even for a run without skills, and when no+ // device is routed its runCommand / execScript open the SAME session in the+ // SAME directory as the cloud-sandbox tool. When a device IS routed and the+ // cloud-sandbox tool is not enabled, `lobe-skills` executes on the device and+ // uses `deviceSystemPrompt` (which has no `{{sandbox_workspace}}`+ // placeholder), so no sandbox lookup is needed.const sandboxShellEnabled =sandboxEnabled ||(!request.activeDeviceId && request.enabledToolIds.includes(SkillsIdentifier));diff --git a/packages/mecha/src/toolSet/deferSkillsTool.test.ts b/packages/mecha/src/toolSet/deferSkillsTool.test.tsnew file mode 100644index 00000000000..11724631749--- /dev/null+++ b/packages/mecha/src/toolSet/deferSkillsTool.test.ts@@ -0,0 +1,174 @@+import {+ getSystemPrompt as getActivatorSystemPrompt,+ LobeActivatorIdentifier,+ LobeActivatorManifest,+} from '@lobechat/builtin-tool-activator';+import {+ resolveSkillsManifest,+ SkillsApiName,+ SkillsIdentifier,+ SkillsManifest,+} from '@lobechat/builtin-tool-skills';+import { generateToolsFromManifest, type LobeToolManifest } from '@lobechat/context-engine';+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ applySkillsToolDeferral,+ canDeferSkillsTool,+ planSkillsToolDeferral,+} from './deferSkillsTool';++const userTurn = { content: 'Hello', id: 'u-1', role: 'user' } as UIChatMessage;+const skillsTool = (apiName: string) => `${SkillsIdentifier}____${apiName}`;++const buildToolSet = (skillsManifest = SkillsManifest as LobeToolManifest) => {+ const manifestMap: Record<string, LobeToolManifest> = {+ [LobeActivatorIdentifier]: { ...LobeActivatorManifest },+ [SkillsIdentifier]: skillsManifest,+ };++ return {+ enabledToolIds: [LobeActivatorIdentifier, SkillsIdentifier],+ manifestMap,+ tools: Object.values(manifestMap).flatMap((manifest) => generateToolsFromManifest(manifest)),+ };+};++describe('canDeferSkillsTool', () => {+ it('defers only an Agent-mode run known to have no skills', () => {+ expect(canDeferSkillsTool({ hasSkills: false, messages: [userTurn] })).toBe(true);+ expect(canDeferSkillsTool({ hasSkills: true, messages: [userTurn] })).toBe(false);+ // The host could not establish the skill list.+ expect(canDeferSkillsTool({ hasSkills: undefined, messages: [userTurn] })).toBe(false);+ expect(+ canDeferSkillsTool({+ chatConfig: { toolMode: 'custom' },+ hasSkills: false,+ messages: [userTurn],+ }),+ ).toBe(false);+ });++ const toolRow = (apiName: string) =>+ ({+ content: 'ok',+ id: `t-${apiName}`,+ plugin: { apiName, identifier: SkillsIdentifier },+ role: 'tool',+ }) as unknown as UIChatMessage;++ it('does not defer once the conversation called a skill API', () => {+ expect(+ canDeferSkillsTool({+ hasSkills: false,+ messages: [userTurn, toolRow(SkillsApiName.readReference)],+ }),+ ).toBe(false);+ });++ // The shell stays declared either way, so using it must not bring the skill+ // APIs back for the rest of the conversation.+ it('still defers after the conversation used the sandbox shell', () => {+ expect(+ canDeferSkillsTool({+ hasSkills: false,+ messages: [userTurn, toolRow(SkillsApiName.runCommand), toolRow(SkillsApiName.exportFile)],+ }),+ ).toBe(true);+ });++ it('does not defer once a skill was loaded through the activator', () => {+ const activation = {+ content: 'Skill loaded',+ id: 't-1',+ plugin: { apiName: 'activateTools', identifier: LobeActivatorIdentifier },+ pluginState: { activatedSkills: [{ name: 'pptx' }], activatedTools: [] },+ role: 'tool',+ } as unknown as UIChatMessage;++ expect(canDeferSkillsTool({ hasSkills: false, messages: [userTurn, activation] })).toBe(false);+ });+});++describe('planSkillsToolDeferral', () => {+ it('keeps the sandbox shell and removes the tools of the skill APIs', () => {+ const { manifestMap } = buildToolSet();+ const deferral = planSkillsToolDeferral(manifestMap)!;++ expect(deferral.fullManifest).toBe(manifestMap[SkillsIdentifier]);+ expect(deferral.shellManifest?.api.map(({ name }) => name)).toEqual([+ SkillsApiName.runCommand,+ SkillsApiName.exportFile,+ ]);+ expect([...deferral.removedToolNames].sort()).toEqual(+ [+ skillsTool(SkillsApiName.activateSkill),+ skillsTool(SkillsApiName.execScript),+ skillsTool(SkillsApiName.readReference),+ ].sort(),+ );+ expect(deferral.activatorManifest?.systemRole).toBe(+ getActivatorSystemPrompt({ withSkills: false }),+ );+ });++ it('has no shell to keep on a routed device', () => {+ const { manifestMap } = buildToolSet(+ resolveSkillsManifest({ executionEnv: 'device' }) as LobeToolManifest,+ );+ const deferral = planSkillsToolDeferral(manifestMap)!;++ expect(deferral.shellManifest).toBeUndefined();+ expect(deferral.removedToolNames.size).toBe(manifestMap[SkillsIdentifier].api.length);+ });++ it('leaves a customised activator role alone', () => {+ const { manifestMap } = buildToolSet();+ manifestMap[LobeActivatorIdentifier] = { ...LobeActivatorManifest, systemRole: 'custom role' };++ expect(planSkillsToolDeferral(manifestMap)?.activatorManifest).toBeUndefined();+ });++ it('returns nothing when the tool is not in the set', () => {+ expect(planSkillsToolDeferral({})).toBeUndefined();+ });+});++describe('applySkillsToolDeferral', () => {+ it('narrows the enabled tool in place and stores the full manifest', () => {+ const toolSet: ReturnType<typeof buildToolSet> & {+ deferredManifestMap?: Record<string, LobeToolManifest>;+ } = buildToolSet();+ const { enabledToolIds, tools } = toolSet;+ const deferral = planSkillsToolDeferral(toolSet.manifestMap)!;++ applySkillsToolDeferral(toolSet, deferral);++ // Same arrays the host already handed out.+ expect(toolSet.enabledToolIds).toBe(enabledToolIds);+ expect(toolSet.tools).toBe(tools);+ expect(enabledToolIds).toEqual([LobeActivatorIdentifier, SkillsIdentifier]);+ expect(+ tools.map((tool) => tool.function.name).filter((name) => name.startsWith(SkillsIdentifier)),+ ).toEqual([skillsTool(SkillsApiName.runCommand), skillsTool(SkillsApiName.exportFile)]);+ expect(toolSet.manifestMap[SkillsIdentifier]).toBe(deferral.shellManifest);+ expect(toolSet.deferredManifestMap).toEqual({ [SkillsIdentifier]: deferral.fullManifest });+ });++ it('takes the tool out of the enabled set when there is no shell to keep', () => {+ const toolSet: ReturnType<typeof buildToolSet> & {+ deferredManifestMap?: Record<string, LobeToolManifest>;+ } = buildToolSet(resolveSkillsManifest({ executionEnv: 'local' }) as LobeToolManifest);+ const deferral = planSkillsToolDeferral(toolSet.manifestMap)!;++ applySkillsToolDeferral(toolSet, deferral);++ expect(toolSet.enabledToolIds).toEqual([LobeActivatorIdentifier]);+ expect(toolSet.manifestMap[SkillsIdentifier]).toBeUndefined();+ expect(toolSet.tools.some((tool) => tool.function.name.startsWith(SkillsIdentifier))).toBe(+ false,+ );+ expect(toolSet.deferredManifestMap?.[SkillsIdentifier]).toBe(deferral.fullManifest);+ });+});diff --git a/packages/mecha/src/toolSet/deferSkillsTool.ts b/packages/mecha/src/toolSet/deferSkillsTool.tsnew file mode 100644index 00000000000..741684f3b8d--- /dev/null+++ b/packages/mecha/src/toolSet/deferSkillsTool.ts@@ -0,0 +1,137 @@+import {+ extractActivatedSkillsFromMessages,+ hasHistoricalToolInvocation,+} from '@lobechat/agent-runtime';+import {+ getSystemPrompt as getActivatorSystemPrompt,+ LobeActivatorIdentifier,+ systemPrompt as activatorSystemPrompt,+} from '@lobechat/builtin-tool-activator';+import {+ resolveSkillsShellManifest,+ SKILL_BOUND_API_NAMES,+ SkillsIdentifier,+} from '@lobechat/builtin-tool-skills';+import { type LobeToolManifest, ToolNameResolver } from '@lobechat/context-engine';+import { type LobeAgentChatConfig, resolveToolMode, type UIChatMessage } from '@lobechat/types';++const toolNameResolver = new ToolNameResolver();++export interface SkillsToolDeferralRequest {+ chatConfig?: Pick<LobeAgentChatConfig, 'enableAgentMode' | 'toolMode'> | null;+ /**+ * Whether the run has a skill to offer. `undefined` means the host could not+ * establish it (its skill list failed to load), and the tool is left alone.+ */+ hasSkills: boolean | undefined;+ messages: UIChatMessage[];+}++/**+ * Whether a run may start without the skill APIs of `lobe-skills`.+ *+ * Only an Agent-mode run that is known to have no skill qualifies, and only+ * while the conversation has never used one: a provider rejects a history that+ * calls a function the request no longer declares, and a skill loaded earlier+ * still needs `readReference` / `execScript` after it was uninstalled. Earlier+ * shell calls do not count, since `runCommand` / `exportFile` stay declared.+ */+export const canDeferSkillsTool = ({+ chatConfig,+ hasSkills,+ messages,+}: SkillsToolDeferralRequest): boolean =>+ hasSkills === false &&+ resolveToolMode(chatConfig) === 'agent' &&+ !hasHistoricalToolInvocation(messages, SkillsIdentifier, SKILL_BOUND_API_NAMES) &&+ !extractActivatedSkillsFromMessages(messages)?.length;++export interface SkillsToolDeferral {+ /** `lobe-activator` without its `activateSkill` guidance; absent when its role is not the default one. */+ activatorManifest?: LobeToolManifest;+ /** The manifest to restore once a skill arrives (`OperationToolSet.deferredManifestMap`). */+ fullManifest: LobeToolManifest;+ /** Function-calling names that leave `tools[]`. */+ removedToolNames: ReadonlySet<string>;+ /**+ * What stays enabled: the sandbox shell and `exportFile`. Absent when the+ * resolved manifest offers neither (a routed device), and the whole tool+ * leaves the enabled set.+ */+ shellManifest?: LobeToolManifest;+}++/**+ * Work out what deferring `lobe-skills` does to a tool set, without touching+ * it. Both hosts apply the same plan to their own structures, so the server+ * and client runtimes cannot disagree on which APIs a run without skills keeps.+ */+export const planSkillsToolDeferral = (+ manifestMap: Record<string, LobeToolManifest>,+): SkillsToolDeferral | undefined => {+ const fullManifest = manifestMap[SkillsIdentifier];+ if (!fullManifest) return undefined;++ const shellManifest = resolveSkillsShellManifest(fullManifest);+ const keptApiNames = new Set(shellManifest?.api.map(({ name }) => name));+ const removedToolNames = new Set(+ fullManifest.api+ .filter(({ name }) => !keptApiNames.has(name))+ .map(({ name }) => toolNameResolver.generate(SkillsIdentifier, name, fullManifest.type)),+ );++ const activatorManifest = manifestMap[LobeActivatorIdentifier];++ return {+ activatorManifest:+ activatorManifest?.systemRole === activatorSystemPrompt+ ? { ...activatorManifest, systemRole: getActivatorSystemPrompt({ withSkills: false }) }+ : undefined,+ fullManifest,+ removedToolNames,+ shellManifest,+ };+};++export interface SkillsDeferrableToolSet {+ deferredManifestMap?: Record<string, LobeToolManifest>;+ enabledToolIds: string[];+ manifestMap: Record<string, LobeToolManifest>;+ tools?: Array<{ function?: { name?: string } }>;+}++const pruneInPlace = <T>(array: T[], keep: (item: T) => boolean) => {+ for (let index = array.length - 1; index >= 0; index -= 1) {+ if (!keep(array[index])) array.splice(index, 1);+ }+};++/**+ * Apply {@link planSkillsToolDeferral} to an operation tool set, in place: the+ * arrays and maps are the ones the host already handed to the rest of its+ * pipeline, which must see the same narrowed surface.+ */+export const applySkillsToolDeferral = (+ toolSet: SkillsDeferrableToolSet,+ deferral: SkillsToolDeferral,+): void => {+ const { activatorManifest, fullManifest, removedToolNames, shellManifest } = deferral;++ toolSet.deferredManifestMap = {+ ...toolSet.deferredManifestMap,+ [SkillsIdentifier]: fullManifest,+ };++ if (shellManifest) {+ toolSet.manifestMap[SkillsIdentifier] = shellManifest;+ } else {+ delete toolSet.manifestMap[SkillsIdentifier];+ pruneInPlace(toolSet.enabledToolIds, (id) => id !== SkillsIdentifier);+ }++ if (toolSet.tools) {+ pruneInPlace(toolSet.tools, (tool) => !removedToolNames.has(tool?.function?.name ?? ''));+ }++ if (activatorManifest) toolSet.manifestMap[LobeActivatorIdentifier] = activatorManifest;+};diff --git a/packages/mecha/src/toolSet/index.ts b/packages/mecha/src/toolSet/index.tsindex ba3b9ab78ca..2c144143794 100644--- a/packages/mecha/src/toolSet/index.ts+++ b/packages/mecha/src/toolSet/index.ts@@ -1,5 +1,6 @@export * from './builtinSkillGate';export * from './connectorActivation';+export * from './deferSkillsTool';export * from './deviceTools';export * from './discoveryPool';export * from './manifestPool';diff --git a/packages/mecha/src/toolSet/skillPool.ts b/packages/mecha/src/toolSet/skillPool.tsindex 0e96eba0a5a..d1b86d2bbdb 100644--- a/packages/mecha/src/toolSet/skillPool.ts+++ b/packages/mecha/src/toolSet/skillPool.ts@@ -47,7 +47,8 @@ export interface AssembleSkillPoolOptions {* "only user-selected tools and skills are available to AI" — so the* selectable sources collapse to `enabledPluginIds`. Withholding the* discovery tools is not enough on its own: `activateSkill` ships with the- * always-on `lobe-skills` tool and resolves against this pool.+ * always-on `lobe-skills` tool, which offers it whenever this pool is not+ * empty, and resolves against this pool.*/skillActivateMode?: 'auto' | 'manual';/**diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.tsindex e40b6a1b9c7..e3745133868 100644--- a/src/services/chat/mecha/skillEngineering.test.ts+++ b/src/services/chat/mecha/skillEngineering.test.ts@@ -2,8 +2,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { agentSkillService } from '@/services/skill';import { getToolStoreState } from '@/store/tool';+import { confirmedUninstalledBuiltinTools } from '@/store/tool/slices/builtin/projection';-import { resolveClientSkills } from './skillEngineering';+import { resolveClientRunHasSkills, resolveClientSkills } from './skillEngineering';++vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: { getAgentById: () => () => undefined },+}));++vi.mock('@/store/tool/slices/builtin/projection', () => ({+ confirmedUninstalledBuiltinTools: vi.fn(),+ installedImplicitBuiltinSkillIds: () => [],+ legacyDisabledBuiltinSkillsForRun: () => [],+}));vi.mock('@/store/tool', () => ({getToolStoreState: vi.fn(),@@ -240,3 +253,100 @@ describe('resolveClientSkills', () => {});});});++describe('resolveClientRunHasSkills', () => {+ const agentConfig = {+ agentConfig: { plugins: [] },+ chatConfig: {},+ plugins: [],+ } as any;+ const syncedList = { entries: { all: { source: 'server' } } };+ const userMessage = (extra: Record<string, unknown> = {}) =>+ ({ content: 'Hi', id: 'u-1', role: 'user', ...extra }) as any;++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(confirmedUninstalledBuiltinTools).mockReturnValue([]);+ });++ it('reports no skills once the server confirmed an empty pool', async () => {+ setToolState({ agentSkillListReplica: syncedList });++ await expect(+ resolveClientRunHasSkills({ agentConfig, messages: [userMessage()] }),+ ).resolves.toBe(false);+ });++ it('reports skills when the agent has one enabled', async () => {+ setToolState({+ agentSkillListReplica: syncedList,+ agentSkills: [{ description: 'mine', id: 'db-1', identifier: 'my-skill', name: 'Mine' }],+ });++ await expect(+ resolveClientRunHasSkills({+ agentConfig: { ...agentConfig, plugins: ['my-skill'] },+ messages: [userMessage()],+ }),+ ).resolves.toBe(true);+ });++ // The main send path persists a `/` selection on the user message instead of+ // passing it with the run, and the skill need not be enabled on the agent.+ it('reports skills when a user turn selected one the agent has not enabled', async () => {+ setToolState({ agentSkillListReplica: syncedList });++ await expect(+ resolveClientRunHasSkills({+ agentConfig,+ messages: [userMessage({ metadata: { selectedSkillIds: ['my-skill'] } })],+ }),+ ).resolves.toBe(true);+ });++ it('reads a selection from the editor state of an older user turn', async () => {+ setToolState({ agentSkillListReplica: syncedList });+ const editorData = {+ root: {+ children: [+ {+ children: [+ {+ actionCategory: 'skill',+ actionLabel: 'Mine',+ actionType: 'my-skill',+ type: 'action-tag',+ },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };++ await expect(+ resolveClientRunHasSkills({+ agentConfig,+ messages: [userMessage({ editorData }), userMessage({ id: 'u-2' })],+ }),+ ).resolves.toBe(true);+ });++ it('cannot tell while the installed skill list is unconfirmed', async () => {+ setToolState({});++ await expect(+ resolveClientRunHasSkills({ agentConfig, messages: [userMessage()] }),+ ).resolves.toBeUndefined();+ });++ it('cannot tell while the builtin uninstall list is unconfirmed', async () => {+ setToolState({ agentSkillListReplica: syncedList });+ vi.mocked(confirmedUninstalledBuiltinTools).mockReturnValue(undefined);++ await expect(+ resolveClientRunHasSkills({ agentConfig, messages: [userMessage()] }),+ ).resolves.toBeUndefined();+ });+});diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.tsindex 44a6470936b..6c3d5a91e2a 100644--- a/src/services/chat/mecha/skillEngineering.ts+++ b/src/services/chat/mecha/skillEngineering.ts@@ -1,11 +1,23 @@+import { LobeHubIdentifier } from '@lobechat/builtin-skills/manifests';+import { getUserDisabledToolIds } from '@lobechat/builtin-tools';import { isDesktop } from '@lobechat/const';import type { OperationSkillSet } from '@lobechat/context-engine';-import { assembleSkillPool } from '@lobechat/mecha';+import { mentionsTopic } from '@lobechat/context-engine';+import { assembleSkillPool, type ResolvedAgentConfig } from '@lobechat/mecha';+import { getAutoPluginIds, type UIChatMessage } from '@lobechat/types';import debug from 'debug';+import { getAgentStoreState } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';+import { collectSelectedSkillIds } from '@/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands';import { getToolStoreState } from '@/store/tool';import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';import { loadBuiltinSkills } from '@/store/tool/slices/builtin/loadBuiltinSkills';+import {+ confirmedUninstalledBuiltinTools,+ installedImplicitBuiltinSkillIds,+ legacyDisabledBuiltinSkillsForRun,+} from '@/store/tool/slices/builtin/projection';const log = debug('context-engine:resolveClientSkills');@@ -61,3 +73,66 @@ export const resolveClientSkills = async (},);};++/**+ * Whether a client-side run has any skill to offer, for deciding if the skill+ * APIs of `lobe-skills` can be left out of its first request.+ *+ * Answers from the run's own resolved agent config, so it reads the same+ * plugins and chat config the run does, and from the same agent profile the+ * context build uses for implicit builtin skills. The context build removes+ * more from its pool than this does (unavailable builtins, switched-off+ * connectors), so where the two differ this one errs towards keeping the+ * skill APIs loaded.+ *+ * Returns `undefined` when the installed skill list could not be confirmed+ * with the server, which must not be read as "no skills".+ */+export const resolveClientRunHasSkills = async ({+ agentConfig,+ agentId,+ messages,+}: {+ agentConfig: Pick<ResolvedAgentConfig, 'agentConfig' | 'chatConfig' | 'plugins'>;+ /** The agent the context build reads its profile from (`ClientContextBuilder`). */+ agentId?: string;+ messages: UIChatMessage[];+}): Promise<boolean | undefined> => {+ // A skill picked with `/` is injected into the user message and is callable+ // even when the agent has not opted into it, so it never reaches the pool.+ if (collectSelectedSkillIds(messages).length > 0) return true;++ const { chatConfig } = agentConfig;+ const rawPlugins = agentConfig.agentConfig?.plugins;+ const agentItem = agentId+ ? agentByIdSelectors.getAgentById(agentId)(getAgentStoreState())+ : undefined;++ const { skills } = await resolveClientSkills(+ agentConfig.plugins ?? [],+ [+ ...getUserDisabledToolIds(rawPlugins, chatConfig),+ ...legacyDisabledBuiltinSkillsForRun(getToolStoreState(), rawPlugins),+ ],+ chatConfig?.skillActivateMode,+ mentionsTopic(messages) ? [LobeHubIdentifier] : undefined,+ getAutoPluginIds(rawPlugins),+ installedImplicitBuiltinSkillIds(getToolStoreState(), agentItem?.createdAt, chatConfig),+ );+ if (skills.length > 0) return true;++ // An empty pool only counts once the server confirmed both lists it is built+ // from: `resolveClientSkills` falls back to whatever the store holds when the+ // installed skills fail to load, and implicit builtin skills are withheld+ // until the uninstall list is confirmed.+ const toolState = getToolStoreState();+ if (+ !agentSkillsSelectors.isAgentSkillListSynced(toolState) ||+ !confirmedUninstalledBuiltinTools(toolState)+ ) {+ log('Skill lists are not confirmed by the server; keeping lobe-skills loaded');+ return undefined;+ }++ return false;+};diff --git a/src/store/chat/agents/transports/ClientContextBuilder.test.ts b/src/store/chat/agents/transports/ClientContextBuilder.test.tsindex d310edfee91..53aaf39bd82 100644--- a/src/store/chat/agents/transports/ClientContextBuilder.test.ts+++ b/src/store/chat/agents/transports/ClientContextBuilder.test.ts@@ -154,4 +154,89 @@ describe('ClientContextBuilder', () => {(result.modelParameters as { params: Record<string, unknown> }).params,).not.toHaveProperty('additionalContexts');});++ it('promotes a deferred tool to its full manifest once it is activated', async () => {+ const api = (name: string) => ({ description: name, name, parameters: {} });+ const tool = (name: string) => ({+ function: { description: name, name: `lobe-skills____${name}`, parameters: {} },+ type: 'function' as const,+ });+ const shellManifest = {+ api: [api('runCommand')],+ identifier: 'lobe-skills',+ meta: { title: 'Skills' },+ systemRole: 'shell only',+ type: 'builtin' as const,+ };+ const fullManifest = {+ ...shellManifest,+ api: [api('activateSkill'), api('runCommand')],+ systemRole: 'full',+ };+ const otherManifest = { ...shellManifest, identifier: 'other-tool', systemRole: 'other' };+ const toolsEngine = {+ generateToolsDetailed: vi.fn().mockReturnValue({+ enabledManifests: [fullManifest],+ enabledToolIds: ['lobe-skills'],+ filteredTools: [],+ tools: [tool('activateSkill'), tool('runCommand')],+ }),+ } as unknown as ToolsEngine;+ const agentConfig: ResolvedAgentConfig = {+ agentConfig: { ...DEFAULT_AGENT_CONFIG, model: 'test-model', provider: 'test-provider' },+ chatConfig: { ...DEFAULT_AGENT_CHAT_CONFIG },+ enabledManifests: [shellManifest, otherManifest],+ enabledToolIds: ['lobe-skills', 'other-tool'],+ isBuiltinAgent: false,+ plugins: [],+ tools: [tool('runCommand')],+ };+ const store = {+ operations: { 'operation-1': { context: { agentId: 'agent-1' }, metadata: {} } },+ } as unknown as ChatStore;+ const prepareContext = vi+ .spyOn(chatService, 'buildAssistantMessageContext')+ .mockImplementation(async ({ messages }) => ({+ options: {},+ params: { messages: messages as any, model: 'test-model', provider: 'test-provider' },+ }));+ const builder = new ClientContextBuilder({+ agentConfig,+ get: () => store,+ operationId: 'operation-1',+ toolsEngine,+ });+ const userMessage = { content: 'Install it', id: 'user-1', role: 'user' as const };+ const state = {+ ...AgentRuntime.createInitialState({+ messages: [userMessage],+ operationId: 'operation-1',+ operationToolSet: {+ deferredManifestMap: { 'lobe-skills': fullManifest },+ enabledToolIds: ['lobe-skills', 'other-tool'],+ manifestMap: { 'lobe-skills': shellManifest, 'other-tool': otherManifest },+ sourceMap: {},+ tools: [tool('runCommand')],+ },+ }),+ activatedStepTools: [+ { activatedAtStep: 1, id: 'lobe-skills', manifest: fullManifest, source: 'discovery' },+ ],+ };++ await builder.build({+ model: 'test-model',+ payload: { messages: [userMessage], model: 'test-model', provider: 'test-provider' } as any,+ provider: 'test-provider',+ state: state as any,+ });++ const { resolvedAgentConfig } = prepareContext.mock.calls[0][0];+ // The full manifest takes the narrowed one's place, in the same position.+ expect(resolvedAgentConfig?.enabledManifests).toEqual([fullManifest, otherManifest]);+ expect(resolvedAgentConfig?.tools?.map((item) => item.function.name)).toEqual([+ 'lobe-skills____runCommand',+ 'lobe-skills____activateSkill',+ ]);+ });});diff --git a/src/store/chat/agents/transports/ClientContextBuilder.ts b/src/store/chat/agents/transports/ClientContextBuilder.tsindex 695df50cda3..b540657f1b3 100644--- a/src/store/chat/agents/transports/ClientContextBuilder.ts+++ b/src/store/chat/agents/transports/ClientContextBuilder.ts@@ -149,10 +149,24 @@ export class ClientContextBuilder implements ContextBuilder {if (!additional.tools?.length) return this.context.agentConfig;+ // A tool the run deferred starts with a narrowed manifest; once activated,+ // the engine's full one takes its place instead of losing to it below.+ const deferredManifestMap = input.state.operationToolSet?.deferredManifestMap ?? {};+ const promotedManifests = new Map(+ additional.enabledManifests+ .filter((manifest) => deferredManifestMap[manifest.identifier])+ .map((manifest) => [manifest.identifier, manifest]),+ );+return {...this.context.agentConfig,enabledManifests: dedupeBy(- [...(this.context.agentConfig.enabledManifests ?? []), ...additional.enabledManifests],+ [+ ...(this.context.agentConfig.enabledManifests ?? []).map(+ (manifest) => promotedManifests.get(manifest.identifier) ?? manifest,+ ),+ ...additional.enabledManifests,+ ],(manifest) => manifest.identifier,),enabledToolIds: [diff --git a/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts b/src/store/chat/slices/agentRun/actions/__tests__/helpers.tsindex 23af545ed98..755d9d8941e 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts@@ -7,6 +7,7 @@ import {agentChatConfigSelectors,agentSelectors,} from '@/store/agent/selectors';+import { useToolStore } from '@/store/tool';import { useChatStore } from '../../../../store';import { messageMapKey } from '../../../../utils/messageMapKey';@@ -40,6 +41,8 @@ export const setupMockSelectors = (vi.spyOn(agentSelectors, 'currentAgentMeta').mockImplementation(() => options.agentMeta || { tags: [] },);++ vi.spyOn(useToolStore.getState(), 'ensureAgentSkillsLoaded').mockResolvedValue(undefined);};/**diff --git a/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.ts b/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.tsindex dfd897e71c0..684da7bcd84 100644--- a/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.ts+++ b/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.ts@@ -2,6 +2,7 @@ import type {RuntimeMentionedAgent,RuntimeSelectedSkill,RuntimeSelectedTool,+ UIChatMessage,} from '@lobechat/types';import { FILESYSTEM_SKILL_SELECTION_PREFIX } from '@lobechat/types';@@ -81,6 +82,24 @@ export const parseSelectedSkillsFromEditorData = (}, []);};+/**+ * Identifiers of every skill the user selected across these turns. A selection+ * is persisted on the user message (`metadata.selectedSkillIds`, or the editor+ * state on older rows), not passed along with the run.+ */+export const collectSelectedSkillIds = (+ messages: readonly Pick<UIChatMessage, 'editorData' | 'metadata' | 'role'>[],+): string[] =>+ messages+ .filter((message) => message.role === 'user')+ .flatMap(+ (message) =>+ message.metadata?.selectedSkillIds ??+ parseSelectedSkillsFromEditorData(message.editorData ?? undefined).map(+ (skill) => skill.identifier,+ ),+ );+export const parseGatewaySkillIdsFromEditorData = (editorData: Record<string, any> | undefined,): string[] => {diff --git a/src/store/chat/slices/agentRun/actions/transports/client/deferSkillsTool.test.ts b/src/store/chat/slices/agentRun/actions/transports/client/deferSkillsTool.test.tsnew file mode 100644index 00000000000..94d9e6ea3c0--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/client/deferSkillsTool.test.ts@@ -0,0 +1,178 @@+import { AgentRuntime } from '@lobechat/agent-runtime';+import {+ getSystemPrompt as getActivatorSystemPrompt,+ LobeActivatorIdentifier,+ LobeActivatorManifest,+} from '@lobechat/builtin-tool-activator';+import { SkillsApiName, SkillsIdentifier, SkillsManifest } from '@lobechat/builtin-tool-skills';+import { generateToolsFromManifest, type LobeToolManifest } from '@lobechat/context-engine';+import type { UIChatMessage } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settings';+import type { ResolvedAgentConfig } from '@/services/chat/mecha';+import { resolveClientRunHasSkills } from '@/services/chat/mecha/skillEngineering';++import { deferClientSkillsTool } from './deferSkillsTool';++vi.mock('@/services/chat/mecha/skillEngineering', () => ({+ resolveClientRunHasSkills: vi.fn(),+}));++const webBrowsingManifest: LobeToolManifest = {+ api: [{ description: 'Search the web', name: 'search', parameters: {} }],+ identifier: 'lobe-web-browsing',+ meta: { description: 'Web search', title: 'Web Browsing' },+ type: 'builtin',+};++const userTurn = { content: 'Hello', id: 'u-1', role: 'user' } as UIChatMessage;+const skillsTool = (apiName: string) => `${SkillsIdentifier}____${apiName}`;+const skillsToolNames = (tools: { function: { name: string } }[] = []) =>+ tools.map((tool) => tool.function.name).filter((name) => name.startsWith(SkillsIdentifier));++const buildRun = (chatConfig: Partial<ResolvedAgentConfig['chatConfig']> = {}) => {+ const enabledManifests = [+ LobeActivatorManifest,+ SkillsManifest,+ webBrowsingManifest,+ ] as LobeToolManifest[];+ const enabledToolIds = enabledManifests.map((manifest) => manifest.identifier);+ const tools = enabledManifests.flatMap((manifest) => generateToolsFromManifest(manifest));+ const agentConfig: ResolvedAgentConfig = {+ agentConfig: { ...DEFAULT_AGENT_CONFIG, model: 'test-model', provider: 'test-provider' },+ chatConfig: { ...DEFAULT_AGENT_CHAT_CONFIG, ...chatConfig },+ enabledManifests,+ enabledToolIds,+ isBuiltinAgent: false,+ plugins: [],+ tools,+ };+ const state = AgentRuntime.createInitialState({+ messages: [userTurn],+ operationId: 'operation-1',+ operationToolSet: {+ enabledToolIds: [...enabledToolIds],+ // Wider than the prompt set: it also holds what the activator can discover.+ manifestMap: {+ ...Object.fromEntries(enabledManifests.map((manifest) => [manifest.identifier, manifest])),+ 'lobe-skill-store': { ...webBrowsingManifest, identifier: 'lobe-skill-store' },+ },+ sourceMap: {},+ tools: [...tools],+ },+ });++ return { agentConfig, state };+};++describe('deferClientSkillsTool', () => {+ beforeEach(() => {+ vi.mocked(resolveClientRunHasSkills).mockReset();+ });++ it('keeps the sandbox shell and defers the skill APIs when the run has no skills', async () => {+ vi.mocked(resolveClientRunHasSkills).mockResolvedValue(false);+ const run = buildRun();++ const deferred = await deferClientSkillsTool(run, { messages: [userTurn] });++ const shellTools = [skillsTool(SkillsApiName.runCommand), skillsTool(SkillsApiName.exportFile)];+ expect(deferred.agentConfig.enabledToolIds).toContain(SkillsIdentifier);+ expect(skillsToolNames(deferred.agentConfig.tools)).toEqual(shellTools);+ expect(skillsToolNames(deferred.state.operationToolSet!.tools)).toEqual(shellTools);++ const promptManifest = deferred.agentConfig.enabledManifests!.find(+ (manifest) => manifest.identifier === SkillsIdentifier,+ )!;+ expect(promptManifest.api.map((api) => api.name)).toEqual([+ SkillsApiName.runCommand,+ SkillsApiName.exportFile,+ ]);+ expect(promptManifest.systemRole).not.toContain('activateSkill');+ expect(deferred.state.operationToolSet!.manifestMap[SkillsIdentifier]).toBe(promptManifest);++ // The full manifest waits for a mid-run skill install.+ expect(deferred.state.operationToolSet!.deferredManifestMap).toEqual({+ [SkillsIdentifier]: SkillsManifest,+ });+ // Discoverable tools stay in the state's map.+ expect(deferred.state.operationToolSet!.manifestMap['lobe-skill-store']).toBeDefined();++ const activator = deferred.agentConfig.enabledManifests!.find(+ (manifest) => manifest.identifier === LobeActivatorIdentifier,+ )!;+ expect(activator.systemRole).toBe(getActivatorSystemPrompt({ withSkills: false }));++ // The run it was given is not mutated.+ expect(skillsToolNames(run.agentConfig.tools)).toHaveLength(SkillsManifest.api.length);+ expect(run.state.operationToolSet!.deferredManifestMap).toBeUndefined();+ });++ it.each([+ ['has skills', true],+ ['could not confirm its skill list', undefined],+ ])('returns the run untouched when it %s', async (_, hasSkills) => {+ vi.mocked(resolveClientRunHasSkills).mockResolvedValue(hasSkills);+ const run = buildRun();++ await expect(deferClientSkillsTool(run, { messages: [userTurn] })).resolves.toBe(run);+ });++ it('skips the skill lookup for a run that cannot defer', async () => {+ const usedSkills = {+ content: 'ok',+ id: 't-1',+ plugin: { apiName: SkillsApiName.execScript, identifier: SkillsIdentifier },+ role: 'tool',+ } as unknown as UIChatMessage;++ const custom = buildRun({ toolMode: 'custom' });+ await expect(deferClientSkillsTool(custom, { messages: [userTurn] })).resolves.toBe(custom);++ const history = buildRun();+ await expect(+ deferClientSkillsTool(history, { messages: [userTurn, usedSkills] }),+ ).resolves.toBe(history);++ const broadcast = buildRun();+ await expect(+ deferClientSkillsTool(broadcast, { disableTools: true, messages: [userTurn] }),+ ).resolves.toBe(broadcast);++ expect(resolveClientRunHasSkills).not.toHaveBeenCalled();+ });++ describe('a resumed run', () => {+ it('keeps the full tool when the run did not defer at start', async () => {+ const run = buildRun();++ await expect(+ deferClientSkillsTool(run, { messages: [userTurn], resumed: true }),+ ).resolves.toBe(run);+ expect(resolveClientRunHasSkills).not.toHaveBeenCalled();+ });++ // The agent config is rebuilt in full on every resume; a run that started+ // deferred must not get the skill APIs back just because it was approved.+ it('narrows the rebuilt agent config again when the run started deferred', async () => {+ vi.mocked(resolveClientRunHasSkills).mockResolvedValue(false);+ const started = await deferClientSkillsTool(buildRun(), { messages: [userTurn] });+ const rebuilt = { agentConfig: buildRun().agentConfig, state: started.state };+ vi.mocked(resolveClientRunHasSkills).mockClear();++ const resumed = await deferClientSkillsTool(rebuilt, {+ messages: [userTurn],+ resumed: true,+ });++ expect(skillsToolNames(resumed.agentConfig.tools)).toEqual([+ skillsTool(SkillsApiName.runCommand),+ skillsTool(SkillsApiName.exportFile),+ ]);+ // The state already carries the narrowed set and the deferred manifest.+ expect(resumed.state).toBe(started.state);+ expect(resolveClientRunHasSkills).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/client/deferSkillsTool.ts b/src/store/chat/slices/agentRun/actions/transports/client/deferSkillsTool.tsnew file mode 100644index 00000000000..10257f2670b--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/client/deferSkillsTool.ts@@ -0,0 +1,97 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';+import {+ applySkillsToolDeferral,+ canDeferSkillsTool,+ planSkillsToolDeferral,+} from '@lobechat/mecha';+import type { UIChatMessage } from '@lobechat/types';++import type { ResolvedAgentConfig } from '@/services/chat/mecha';+import { resolveClientRunHasSkills } from '@/services/chat/mecha/skillEngineering';++interface ClientRun {+ agentConfig: ResolvedAgentConfig;+ state: AgentState;+}++/**+ * Start a client-side run without the skill APIs of `lobe-skills` when it has+ * no skill to offer, as the server does (`deferUnusedSkillsTool`).+ *+ * The sandbox shell and `exportFile` stay enabled. The full manifest moves to+ * `operationToolSet.deferredManifestMap`, where installing a skill mid-run+ * promotes it back. Returns the run untouched whenever it does not qualify.+ *+ * A resumed run (after a tool approval) keeps the surface it started with: its+ * state already says whether it deferred, so only the freshly rebuilt agent+ * config is narrowed again and the skill list is not consulted a second time.+ */+export const deferClientSkillsTool = async <Run extends ClientRun>(+ run: Run,+ {+ agentId,+ disableTools,+ messages,+ resumed,+ }: {+ /** The agent whose profile the context build reads skills from. */+ agentId?: string;+ disableTools?: boolean;+ messages: UIChatMessage[];+ /** The run continues an existing state instead of starting one. */+ resumed?: boolean;+ },+): Promise<Run> => {+ const { agentConfig, state } = run;+ const { chatConfig, enabledToolIds } = agentConfig;+ const { operationToolSet } = state;++ if (disableTools || !operationToolSet || !enabledToolIds?.includes(SkillsIdentifier)) return run;++ const startedDeferred = !!operationToolSet.deferredManifestMap?.[SkillsIdentifier];+ if (resumed && !startedDeferred) return run;++ if (!resumed) {+ // The skill list is only looked up for a run that could defer at all.+ if (!canDeferSkillsTool({ chatConfig, hasSkills: false, messages })) return run;++ const hasSkills = await resolveClientRunHasSkills({ agentConfig, agentId, messages });+ if (!canDeferSkillsTool({ chatConfig, hasSkills, messages })) return run;+ }++ const promptToolSet = {+ enabledToolIds: [...enabledToolIds],+ manifestMap: Object.fromEntries(+ (agentConfig.enabledManifests ?? []).map((manifest) => [manifest.identifier, manifest]),+ ),+ tools: [...(agentConfig.tools ?? [])],+ };+ const deferral = planSkillsToolDeferral(promptToolSet.manifestMap);+ if (!deferral) return run;++ applySkillsToolDeferral(promptToolSet, deferral);+ const narrowedAgentConfig = {+ ...agentConfig,+ enabledManifests: Object.values(promptToolSet.manifestMap),+ enabledToolIds: promptToolSet.enabledToolIds,+ tools: promptToolSet.tools.length > 0 ? promptToolSet.tools : undefined,+ };+ if (resumed) return { ...run, agentConfig: narrowedAgentConfig };++ // The state's set is wider than the prompt's (it also holds what the+ // activator can discover), so it is narrowed separately with the same plan.+ const deferredToolSet = {+ ...operationToolSet,+ enabledToolIds: [...operationToolSet.enabledToolIds],+ manifestMap: { ...operationToolSet.manifestMap },+ tools: [...operationToolSet.tools],+ };+ applySkillsToolDeferral(deferredToolSet, deferral);++ return {+ ...run,+ agentConfig: narrowedAgentConfig,+ state: { ...state, operationToolSet: deferredToolSet },+ };+};diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 78f40871239..b2829e918d1 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -76,6 +76,7 @@ import { getFollowUpMode } from '../../lifecycle/followUpMode';import type { RunParkedReason, RunScope } from '../../lifecycle/types';import { buildViewedTaskPrompt } from '../viewedTaskPrompt';import { steerQueuedFollowUps } from './clientSteer';+import { deferClientSkillsTool } from './deferSkillsTool';import { buildRunManifestMap } from './discoverableManifests';import { clientInterventionAudits } from './interventionAudits';@@ -643,12 +644,7 @@ export class StreamingExecutorActionImpl {// Step 1: Create Agent State (resolves config once)// ===========================================// agentConfig already has isSubAgent filtering applied and is passed to callLLM executor- const {- state: initialAgentState,- context: initialAgentContext,- agentConfig,- toolsEngine,- } = this.#get().internal_createAgentState({+ const createdRun = this.#get().internal_createAgentState({messages,parentMessageId: params.parentMessageId,agentId,@@ -664,6 +660,18 @@ export class StreamingExecutorActionImpl {modelOverride: params.modelOverride,chatConfigOverride: params.chatConfigOverride,});+ // A run with no skill to offer starts without the skill APIs of lobe-skills.+ const {+ state: initialAgentState,+ context: initialAgentContext,+ agentConfig,+ toolsEngine,+ } = await deferClientSkillsTool(createdRun, {+ agentId: groupId && subAgentId ? subAgentId : agentId,+ disableTools,+ messages,+ resumed: !!params.initialState,+ });if (params.skipCreateFirstMessage) {initialAgentState.pendingAssistantMessageId = params.parentMessageId;diff --git a/src/store/tool/slices/builtin/executors/clientSkillCatalog.ts b/src/store/tool/slices/builtin/executors/clientSkillCatalog.tsindex 6e4e7ca8a69..64744de831e 100644--- a/src/store/tool/slices/builtin/executors/clientSkillCatalog.ts+++ b/src/store/tool/slices/builtin/executors/clientSkillCatalog.ts@@ -13,7 +13,7 @@ import { filterBuiltinSkills } from '@/helpers/skillFilters';import { agentSkillService } from '@/services/skill';import { getAgentStoreState } from '@/store/agent';import { getChatStoreState } from '@/store/chat';-import { parseSelectedSkillsFromEditorData } from '@/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands';+import { collectSelectedSkillIds } from '@/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { getToolStoreState } from '@/store/tool';@@ -44,15 +44,7 @@ export const clientSkillCatalog = (ctx: BuiltinToolContext) => {] ?? []): [];const userTurns = messages.filter((message) => message.role === 'user');- const selected = new Set(- userTurns.flatMap(- (message) =>- message.metadata?.selectedSkillIds ??- parseSelectedSkillsFromEditorData(message.editorData ?? undefined).map(- (skill) => skill.identifier,- ),- ),- );+ const selected = new Set(collectSelectedSkillIds(userTurns));if (mentionsTopic(userTurns)) selected.add(LobeHubIdentifier);const disabled = new Set([...getDisabledPluginIds(plugins),