Skip to content

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

✨ feat(agent-share): open lobe-activator to share visitor runs (#20682)

YuTengjinga476946aa42c
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorActivator.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorActivator.test.ts
new file mode 100644
index 00000000000..4baa9cde0ec
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorActivator.test.ts
@@ -0,0 +1,284 @@
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+const {
+ mockCreateOperation,
+ mockGetAgentConfig,
+ mockGetUserSettings,
+ mockMessageCreate,
+ mockMessageQuery,
+ mockReserveShareVisitorTurn,
+ mockResolveAttachmentsByFileIds,
+} = vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockGetUserSettings: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockMessageQuery: vi.fn(),
+ mockReserveShareVisitorTurn: vi.fn(),
+ mockResolveAttachmentsByFileIds: vi.fn(),
+}));
+
+// `discoverTools` peeks at the attached files' MIME types for media routing.
+// Stub file reads so the bare mock db is never queried.
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn().mockImplementation(function () {
+ return {
+ findByIds: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/file/resolveAttachments', () => ({
+ resolveAttachmentsByFileIds: mockResolveAttachmentsByFileIds,
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ create: mockMessageCreate,
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: mockMessageQuery,
+ update: vi.fn().mockResolvedValue({}),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn(),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: mockGetAgentConfig,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return {
+ query: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return {
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ findById: vi.fn().mockResolvedValue(null),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn().mockImplementation(function (_db: unknown, userId: string) {
+ return {
+ getUserPreference: vi.fn().mockResolvedValue({}),
+ getUserSettings: () => mockGetUserSettings(userId),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: mockCreateOperation,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(function () {
+ return {
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(function () {
+ return {
+ getComposioManifests: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ uploadFromUrl: vi.fn(),
+ };
+ }),
+}));
+
+// The historical re-activation pass asks the engine to re-enable every id
+// restored from history (`isExplicitActivation`); echo them back so the share
+// gate, not this stub, is what decides which ones survive.
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn(
+ ({
+ context,
+ toolIds,
+ }: {
+ context?: { isExplicitActivation?: boolean };
+ toolIds: string[];
+ }) =>
+ context?.isExplicitActivation
+ ? { enabledToolIds: toolIds, tools: [] }
+ : { enabledToolIds: [], tools: [] },
+ ),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+// The share path's atomic cap reservations open real DB transactions β€” stub
+// them so execAgent can run against a bare mock db.
+vi.mock('../shareVisitorAbuseGuards', () => ({
+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ reserveShareVisitorTurn: mockReserveShareVisitorTurn,
+}));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { functionCall: true, video: false, vision: true },
+ id: 'gpt-4',
+ providerId: 'openai',
+ },
+ ],
+ };
+});
+
+describe('AiAgentService.execAgent - share-visitor historical activations', () => {
+ let service: AiAgentService;
+ const mockDb = {} as any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ // An earlier turn of this topic activated one granted and one ungranted
+ // tool through lobe-activator.
+ mockMessageQuery.mockResolvedValue([
+ { content: 'Use tools', id: 'msg-prev-user', role: 'user' },
+ {
+ content: 'Activated',
+ id: 'msg-prev-tool',
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: {
+ activatedTools: [
+ { apiCount: 1, identifier: 'lobe-calculator', name: 'Calculator' },
+ { apiCount: 9, identifier: 'lobe-agent-management', name: 'Agent Management' },
+ { apiCount: 1, identifier: 'mcp-private', name: 'Private MCP' },
+ ],
+ },
+ role: 'tool',
+ },
+ ]);
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: '',
+ });
+ mockGetUserSettings.mockResolvedValue({});
+ mockReserveShareVisitorTurn.mockResolvedValue({ id: 'msg-1' });
+ mockResolveAttachmentsByFileIds.mockResolvedValue({
+ audioList: [],
+ fileList: [],
+ imageList: [],
+ orderedFileIds: [],
+ videoList: [],
+ warnings: [],
+ });
+ service = new AiAgentService(mockDb, 'creator-1');
+ });
+
+ it('re-activates only the historical tools this share still grants', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Calculate again',
+ shareGate: {
+ agentId: 'agent-1',
+ shareConfig: { toolGrants: [{ identifier: 'lobe-calculator' }] },
+ shareId: 'share-1',
+ visitorUserId: 'visitor-1',
+ },
+ });
+
+ expect(mockMessageQuery).toHaveBeenCalled();
+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);
+ expect(mockCreateOperation.mock.calls[0][0].toolSet.activatableToolIds).toEqual([
+ 'lobe-calculator',
+ ]);
+ });
+
+ it('re-activates every historical tool on the creator own run', async () => {
+ // Control: without a share gate the same history restores all three,
+ // so the test above is measuring the gate rather than the stubs.
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Calculate again',
+ });
+
+ expect(mockCreateOperation.mock.calls[0][0].toolSet.activatableToolIds).toEqual([
+ 'lobe-calculator',
+ 'lobe-agent-management',
+ 'mcp-private',
+ ]);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.md
index 538f3ec0353..1a87db1ac56 100644
--- a/apps/server/src/services/aiAgent/shareGate/README.md
+++ b/apps/server/src/services/aiAgent/shareGate/README.md
@@ -99,11 +99,9 @@ tool does not ship):
it would only let the owner-facing tool picker confirm a grant no visitor
conversation can ever exercise.
-- `lobe-user-interaction` / `lobe-activator`: originally denied because
- share runs were forced headless, so neither could ever honestly complete.
- Share runs now honor the visitor's approval flow, but both stay denied
- until audited on their own: `lobe-activator` can widen the run's tool
- surface at runtime, which must be proven not to escape the share grant.
+- `lobe-user-interaction`: originally denied because share runs were forced
+ headless, so it could never honestly complete. Share runs now honor the
+ visitor's approval flow, but it stays denied until audited on its own.
- Device-only MCP servers (stdio, or an HTTP endpoint on localhost / a
private network): not builtin identifiers, so the allowlist above never
@@ -131,6 +129,49 @@ absence of a known exploit.
into that session either. No creator credential or JWT is therefore
reachable from inside a visitor's sandbox command.
+- `lobe-activator`: widens the run's tool surface at runtime, so it is
+ allowed only because every source it reads is already the gated set.
+ Never picked by the owner: any tool grant implies it, scoped to
+ `activateTools` (`shareGate/grants.ts:132`, which also overrides a stored entry so
+ nothing widens it to the runtime's unlisted `activateSkill`), and assembly
+ drops it again when no granted tool is left to activate, counting restored
+ historical activations as already enabled (`shareGate/toolSet.ts:166`). A
+ kept activator gets the share-visitor `systemRole`
+ (`getSystemPromptForShareVisitor`), which omits the default prompt's push
+ to activate `lobe-skill-store` / `lobe-creds` first (both stay denied
+ above) and keeps its `activateSkill` lines only when `lobe-skills` itself
+ survived the gate.
+
+ 1. What it can see. `<available_tools>` is the operation's `manifestMap`
+ minus enabled tools (`apps/server/src/modules/AgentRuntime/executorHelpers.ts:644`), and
+ that map is the one `applyShareGateToToolSet` pruned in place
+ (`apps/server/src/services/aiAgent/pipeline/operationPrep.ts:559`). An ungranted MCP server or plugin
+ contributes no name or description.
+ 2. What it can activate. `activateTools` only resolves ids present in
+ `context.toolManifestMap` (`apps/server/src/services/toolExecution/serverRuntimes/activator.ts:166`),
+ which is the step's `effectiveManifestMap`
+ (`apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts:310`): the gated
+ operation map plus manifests of earlier activations, themselves copied
+ from the same map (`packages/agent-runtime/src/executors/tool.ts:117`,
+ `:567`). An ungranted id comes back as "Not found".
+ 3. Calls in the same step. The tool-call resolver only accepts a call the
+ step offered, or one whose identifier and API exist in the step's
+ prompt manifests (`packages/context-engine/src/engine/tools/ToolNameResolver.ts:284`);
+ a tool activated in this response is not offered until the next step,
+ so a same-response call to it is dropped. Whatever does reach dispatch
+ still meets the dispatch-time gates: `isShareBlockedBuiltinDispatch` for
+ builtins (`apps/server/src/services/toolExecution/builtin.ts:192`) and the gated manifest lookup
+ for MCP (`apps/server/src/services/toolExecution/index.ts:253`).
+ 4. Activations restored from history. `operationPrep` re-derives them into
+ `activatableToolIds` (`apps/server/src/services/aiAgent/pipeline/operationPrep.ts:535`) before the share
+ gate prunes that list, and `AgentRuntimeService` restores only ids still
+ in it (`apps/server/src/services/agentRuntime/AgentRuntimeService.ts:1350`).
+ 5. Its skill fallback. `activateTools` retries a non-tool id as a skill
+ name. That lookup re-checks `shareConfig.skillGrants` on every source it
+ opens (`apps/server/src/services/toolExecution/serverRuntimes/activator.ts:97`), the same rule the
+ skills runtime enforces, so it cannot reach a skill the share did not
+ grant.
+
- `lobe-skills`: the tool DOES resolve skills out of the creator's personal
catalog β€” that is what it is for, and it was denied for exactly that reason
until the catalog stopped being the unit of authorization. What changed is
diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
index 669d767689c..56bf75551a9 100644
--- a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
@@ -1,3 +1,4 @@
+import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import {
AgentDocumentsApiName,
AgentDocumentsIdentifier,
@@ -336,3 +337,62 @@ describe('isShareBlockedBuiltinDispatch', () => {
).toBe(true);
});
});
+
+describe('isShareBlockedBuiltinDispatch β€” lobe-activator', () => {
+ it('allows activateTools once the share grants any tool', () => {
+ expect(
+ isShareBlockedBuiltinDispatch(
+ { toolGrants: [{ identifier: CalculatorIdentifier }] },
+ LobeActivatorIdentifier,
+ ActivatorApiName.activateTools,
+ ),
+ ).toBe(false);
+ });
+
+ it('blocks the activator on a share that grants no tool', () => {
+ expect(
+ isShareBlockedBuiltinDispatch({}, LobeActivatorIdentifier, ActivatorApiName.activateTools),
+ ).toBe(true);
+ expect(
+ isShareBlockedBuiltinDispatch(
+ { skillGrants: ['pdf-report'] },
+ LobeActivatorIdentifier,
+ ActivatorApiName.activateTools,
+ ),
+ ).toBe(true);
+ });
+
+ it('blocks the runtime-only activateSkill method even under a stored toolset-level entry', () => {
+ expect(
+ isShareBlockedBuiltinDispatch(
+ { toolGrants: [{ identifier: LobeActivatorIdentifier }, { identifier: 'mcp-github' }] },
+ LobeActivatorIdentifier,
+ ActivatorApiName.activateSkill,
+ ),
+ ).toBe(true);
+ });
+
+ it('still blocks an ungranted builtin called after an activation in the same run', () => {
+ // Activation only changes what the model is offered. The call itself is
+ // re-checked against the share grant at dispatch.
+ const permissions = { toolGrants: [{ identifier: CalculatorIdentifier }] };
+
+ expect(
+ isShareBlockedBuiltinDispatch(
+ permissions,
+ LobeActivatorIdentifier,
+ ActivatorApiName.activateTools,
+ ),
+ ).toBe(false);
+ expect(
+ isShareBlockedBuiltinDispatch(
+ permissions,
+ LobeAgentIdentifier,
+ LobeAgentApiName.analyzeMedia,
+ ),
+ ).toBe(true);
+ expect(
+ isShareBlockedBuiltinDispatch(permissions, AgentManagementIdentifier, 'searchAgent'),
+ ).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/shareGate/grants.test.ts b/apps/server/src/services/aiAgent/shareGate/grants.test.ts
index 41dfed2c426..17ecd128e57 100644
--- a/apps/server/src/services/aiAgent/shareGate/grants.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/grants.test.ts
@@ -1,3 +1,4 @@
+import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
@@ -10,6 +11,7 @@ import {
getShareGrantActivatedPluginIds,
shareGateGrantsCloudSandbox,
} from '.';
+import { resolveEffectiveShareToolGrants } from './grants';
import { buildGate } from './testUtils';
describe('filterPluginsByShareGate', () => {
@@ -121,3 +123,32 @@ describe('shareGateGrantsCloudSandbox', () => {
).toBe(true);
});
});
+
+describe('resolveEffectiveShareToolGrants β€” lobe-activator', () => {
+ it('implies the activator, scoped to activateTools, from any tool grant', () => {
+ const grants = resolveEffectiveShareToolGrants({ toolGrants: [{ identifier: 'mcp-github' }] });
+
+ expect(grants.get(LobeActivatorIdentifier)).toEqual(new Set([ActivatorApiName.activateTools]));
+ });
+
+ it('does not imply the activator when the share grants no tool', () => {
+ expect(resolveEffectiveShareToolGrants({}).has(LobeActivatorIdentifier)).toBe(false);
+ // A skill-only share already has lobe-skills to load what it granted.
+ expect(
+ resolveEffectiveShareToolGrants({ skillGrants: ['pdf-report'] }).has(LobeActivatorIdentifier),
+ ).toBe(false);
+ });
+
+ it('never lets a stored activator entry widen the implied scope or stand alone', () => {
+ const widened = resolveEffectiveShareToolGrants({
+ toolGrants: [{ identifier: LobeActivatorIdentifier }, { identifier: 'mcp-github' }],
+ });
+ expect(widened.get(LobeActivatorIdentifier)).toEqual(new Set([ActivatorApiName.activateTools]));
+
+ // An activator entry is not itself a grant of anything to activate.
+ const alone = resolveEffectiveShareToolGrants({
+ toolGrants: [{ identifier: LobeActivatorIdentifier }],
+ });
+ expect(alone.has(LobeActivatorIdentifier)).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/shareGate/grants.ts b/apps/server/src/services/aiAgent/shareGate/grants.ts
index 589e73227a0..f75eec9f88c 100644
--- a/apps/server/src/services/aiAgent/shareGate/grants.ts
+++ b/apps/server/src/services/aiAgent/shareGate/grants.ts
@@ -1,3 +1,4 @@
+import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';
@@ -105,11 +106,18 @@ export const hasShareSkillAuthorization = (permissions: ShareDataToolPermissions
/**
* `resolveShareToolGrants` plus the grants that are implied rather than picked.
*
- * Today that is only `lobe-skills`, whose opt-in lives in `skillGrants` (see
- * {@link hasShareSkillAuthorization}). The synthetic grant is toolset-level
- * (`'all'`) on purpose: narrowing the Skills tool down to its two visitor-safe
- * APIs is {@link DATA_TOOL_ACCESS_RULES}' job, and expressing it twice would
- * let the two lists drift.
+ * - `lobe-skills`, whose opt-in lives in `skillGrants` (see
+ * {@link hasShareSkillAuthorization}). The synthetic grant is toolset-level
+ * (`'all'`) on purpose: narrowing the Skills tool down to its two
+ * visitor-safe APIs is {@link DATA_TOOL_ACCESS_RULES}' job, and expressing it
+ * twice would let the two lists drift.
+ * - `lobe-activator`, implied by ANY tool grant: it is a runtime capability,
+ * not a tool the owner picks, and it can only surface manifests the gated
+ * tool set already holds. Whether a run actually keeps it (only while a
+ * granted tool is left to activate) is decided at assembly in
+ * `applyShareGateToToolSet`. Always written as `activateTools` only, so a
+ * stored or hand-edited `lobe-activator` entry can never widen it to the
+ * runtime's unlisted `activateSkill` method.
*
* Every gate that asks "did the creator grant this identifier" must go through
* here, or the tool passes one layer and is rejected by the next.
@@ -119,6 +127,11 @@ export const resolveEffectiveShareToolGrants = (
): Map<string, ShareToolGrant> => {
const grants = resolveShareToolGrants(permissions.toolGrants);
+ grants.delete(LobeActivatorIdentifier);
+ if (grants.size > 0) {
+ grants.set(LobeActivatorIdentifier, new Set([ActivatorApiName.activateTools]));
+ }
+
if (hasShareSkillAuthorization(permissions)) grants.set(SkillsIdentifier, 'all');
return grants;
diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
index 4e9e9e80332..cf52b2e4f9e 100644
--- a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
@@ -1,3 +1,9 @@
+import {
+ ActivatorApiName,
+ getSystemPromptForShareVisitor as getActivatorSystemPromptForShareVisitor,
+ LobeActivatorIdentifier,
+ systemPrompt as activatorSystemPrompt,
+} from '@lobechat/builtin-tool-activator';
import {
AgentDocumentsApiName,
AgentDocumentsIdentifier,
@@ -26,6 +32,8 @@ import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference
import { generateToolsFromManifest } from '@lobechat/context-engine';
import { describe, expect, it } from 'vitest';
+import { buildToolDiscoveryConfig } from '@/server/modules/AgentRuntime/executorHelpers';
+
import { applyShareGateToToolSet } from '.';
import { buildGate, buildToolSet, toolName } from './testUtils';
@@ -629,3 +637,185 @@ describe('applyShareGateToToolSet', () => {
]);
});
});
+
+describe('applyShareGateToToolSet β€” lobe-activator', () => {
+ /**
+ * An agent-mode run as discovery leaves it: the activator and one granted
+ * tool are enabled, the rest only sit in `manifestMap` waiting to be
+ * activated β€” including tools the share never granted.
+ */
+ const buildActivatorToolSet = () => {
+ const toolSet = buildToolSet([
+ { apis: [{ name: ActivatorApiName.activateTools }], identifier: LobeActivatorIdentifier },
+ { apis: [{ name: 'createIssue' }], identifier: 'mcp-github', type: 'mcp' },
+ { apis: [{ name: 'calculate' }], identifier: CalculatorIdentifier },
+ { apis: [{ name: 'searchAgent' }], identifier: AgentManagementIdentifier },
+ { apis: [{ name: 'readSecrets' }], identifier: 'mcp-private', type: 'mcp' },
+ ]);
+ toolSet.enabledToolIds.splice(
+ 0,
+ toolSet.enabledToolIds.length,
+ LobeActivatorIdentifier,
+ 'mcp-github',
+ );
+ toolSet.activatableToolIds.splice(0, toolSet.activatableToolIds.length);
+ return toolSet;
+ };
+
+ it('keeps the activator and shows it only granted tools to activate', () => {
+ const toolSet = buildActivatorToolSet();
+
+ applyShareGateToToolSet(
+ toolSet,
+ buildGate({
+ toolGrants: [{ identifier: 'mcp-github' }, { identifier: CalculatorIdentifier }],
+ }),
+ );
+
+ expect(toolSet.enabledToolIds).toEqual([LobeActivatorIdentifier, 'mcp-github']);
+ expect(Object.keys(toolSet.manifestMap).sort()).toEqual(
+ [CalculatorIdentifier, LobeActivatorIdentifier, 'mcp-github'].sort(),
+ );
+ // `<available_tools>` is rendered from this exact difference: the
+ // creator's other tools contribute neither a name nor a description.
+ const discovery = buildToolDiscoveryConfig(toolSet as any, toolSet.enabledToolIds);
+ expect(discovery?.availableTools.map((tool) => tool.identifier)).toEqual([
+ CalculatorIdentifier,
+ ]);
+ });
+
+ it('keeps the activator schema to activateTools', () => {
+ const toolSet = buildActivatorToolSet();
+
+ applyShareGateToToolSet(
+ toolSet,
+ buildGate({
+ toolGrants: [{ identifier: LobeActivatorIdentifier }, { identifier: CalculatorIdentifier }],
+ }),
+ );
+
+ expect(toolSet.manifestMap[LobeActivatorIdentifier].api.map((api) => api.name)).toEqual([
+ ActivatorApiName.activateTools,
+ ]);
+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toContain(
+ toolName(LobeActivatorIdentifier, ActivatorApiName.activateTools),
+ );
+ });
+
+ it('pins the share-visitor system prompt on a kept activator', () => {
+ const toolSet = buildActivatorToolSet();
+ toolSet.manifestMap[LobeActivatorIdentifier].systemRole = activatorSystemPrompt;
+
+ applyShareGateToToolSet(
+ toolSet,
+ buildGate({
+ toolGrants: [{ identifier: 'mcp-github' }, { identifier: CalculatorIdentifier }],
+ }),
+ );
+
+ const { systemRole } = toolSet.manifestMap[LobeActivatorIdentifier];
+ expect(systemRole).toBe(getActivatorSystemPromptForShareVisitor({ withSkills: false }));
+ // Both are denied to visitors, so the prompt must not send the model there.
+ expect(systemRole).not.toContain('lobe-skill-store');
+ expect(systemRole).not.toContain('lobe-creds');
+ // A tool-only share has no `lobe-skills`, so no `activateSkill` either.
+ expect(systemRole).not.toContain('activateSkill');
+ });
+
+ it('keeps the activateSkill guidance when the share grants skills', () => {
+ const toolSet = buildToolSet([
+ { apis: [{ name: ActivatorApiName.activateTools }], identifier: LobeActivatorIdentifier },
+ { apis: [{ name: 'activateSkill' }], identifier: SkillsIdentifier },
+ { apis: [{ name: 'calculate' }], identifier: CalculatorIdentifier },
+ ]);
+ toolSet.enabledToolIds.splice(
+ 0,
+ toolSet.enabledToolIds.length,
+ LobeActivatorIdentifier,
+ SkillsIdentifier,
+ );
+ toolSet.activatableToolIds.splice(0, toolSet.activatableToolIds.length);
+
+ applyShareGateToToolSet(
+ toolSet,
+ buildGate({
+ skillGrants: ['pdf-report'],
+ toolGrants: [{ identifier: CalculatorIdentifier }],
+ }),
+ );
+
+ expect(toolSet.manifestMap[SkillsIdentifier]).toBeDefined();
+ expect(toolSet.manifestMap[LobeActivatorIdentifier].systemRole).toBe(
+ getActivatorSystemPromptForShareVisitor({ withSkills: true }),
+ );
+ });
+
+ it('drops the activator when the only tool left was restored from an earlier activation', () => {
+ // Next visitor turn after activating Calculator: `AgentRuntimeService`
+ // restores it from `activatableToolIds`, so `<available_tools>` is empty.
+ const toolSet = buildActivatorToolSet();
+ toolSet.activatableToolIds.push(CalculatorIdentifier);
+
+ applyShareGateToToolSet(
+ toolSet,
+ buildGate({
+ toolGrants: [{ identifier: 'mcp-github' }, { identifier: CalculatorIdentifier }],
+ }),
+ );
+
+ expect(toolSet.manifestMap[LobeActivatorIdentifier]).toBeUndefined();
+ expect(toolSet.enabledToolIds).toEqual(['mcp-github']);
+ expect(toolSet.activatableToolIds).toEqual([CalculatorIdentifier]);
+ });
+
+ it('drops the activator when every granted tool is already enabled', () => {
+ const toolSet = buildActivatorToolSet();
+
+ applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [{ identifier: 'mcp-github' }] }));
+
+ expect(toolSet.manifestMap[LobeActivatorIdentifier]).toBeUndefined();
+ expect(toolSet.enabledToolIds).toEqual(['mcp-github']);
+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([
+ toolName('mcp-github', 'createIssue', 'mcp'),
+ ]);
+ });
+
+ it('drops the activator when the only grant left to activate is one the allowlist denies', () => {
+ const toolSet = buildActivatorToolSet();
+
+ applyShareGateToToolSet(
+ toolSet,
+ buildGate({
+ toolGrants: [{ identifier: 'mcp-github' }, { identifier: AgentManagementIdentifier }],
+ }),
+ );
+
+ expect(toolSet.manifestMap[LobeActivatorIdentifier]).toBeUndefined();
+ expect(toolSet.manifestMap[AgentManagementIdentifier]).toBeUndefined();
+ });
+
+ it('drops the activator on a share that grants no tool', () => {
+ const toolSet = buildActivatorToolSet();
+
+ applyShareGateToToolSet(toolSet, buildGate({ skillGrants: ['pdf-report'] }));
+
+ expect(toolSet.manifestMap[LobeActivatorIdentifier]).toBeUndefined();
+ expect(toolSet.enabledToolIds).toEqual([]);
+ });
+
+ it('prunes historical activations of tools the share does not grant', () => {
+ // `operationPrep` feeds activations restored from history in as
+ // `activatableToolIds`; `AgentRuntimeService` restores only what survives.
+ const toolSet = buildActivatorToolSet();
+ toolSet.activatableToolIds.push(CalculatorIdentifier, AgentManagementIdentifier, 'mcp-private');
+
+ applyShareGateToToolSet(
+ toolSet,
+ buildGate({
+ toolGrants: [{ identifier: 'mcp-github' }, { identifier: CalculatorIdentifier }],
+ }),
+ );
+
+ expect(toolSet.activatableToolIds).toEqual([CalculatorIdentifier]);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.ts
index 18f131e0f67..fbc6e998fd2 100644
--- a/apps/server/src/services/aiAgent/shareGate/toolSet.ts
+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.ts
@@ -1,3 +1,8 @@
+import {
+ getSystemPromptForShareVisitor as getActivatorSystemPromptForShareVisitor,
+ LobeActivatorIdentifier,
+} from '@lobechat/builtin-tool-activator';
+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';
import { hasShareToolGrant, PLUGIN_SCHEMA_SEPARATOR, type ShareToolGrant } from '@lobechat/const';
import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';
@@ -137,6 +142,47 @@ export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentSh
stripSubAgentDispatchApis(toolSet);
applyShareGateToDataToolAccess(toolSet, gate);
applyShareGateToPerApiGrants(toolSet, grants);
+ applyShareGateToActivator(toolSet);
+};
+
+/**
+ * Fit `lobe-activator` to the gated set, or drop it when that set leaves it
+ * nothing to activate.
+ *
+ * Its grant is implied by any tool grant (`resolveEffectiveShareToolGrants`),
+ * but the activator only ever discovers what is left in `manifestMap` and not
+ * already enabled β€” the same difference `buildToolDiscoveryConfig` renders as
+ * `<available_tools>`. A historical activation in `activatableToolIds` counts
+ * as enabled: `AgentRuntimeService` restores it into `activatedStepTools`, so
+ * it never reaches `<available_tools>` either. When nothing remains, keeping
+ * the activator would offer the visitor's model an empty discovery tool. Runs
+ * after every other pass so a tool those passes removed never keeps it alive.
+ *
+ * A kept activator gets the share-visitor `systemRole`: the default one sends
+ * the model to activate `lobe-skill-store` / `lobe-creds` first, which are
+ * 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 => {
+ const manifest = toolSet.manifestMap[LobeActivatorIdentifier];
+ if (!manifest) return;
+
+ const enabled = new Set([...toolSet.enabledToolIds, ...toolSet.activatableToolIds]);
+ const hasActivatableTool = Object.keys(toolSet.manifestMap).some(
+ (id) => id !== LobeActivatorIdentifier && !enabled.has(id),
+ );
+
+ if (!hasActivatableTool) {
+ dropToolFromSet(toolSet, LobeActivatorIdentifier);
+ return;
+ }
+
+ toolSet.manifestMap[LobeActivatorIdentifier] = {
+ ...manifest,
+ systemRole: getActivatorSystemPromptForShareVisitor({
+ withSkills: !!toolSet.manifestMap[SkillsIdentifier],
+ }),
+ };
};
/**
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
index c8d2cfab2b5..6b3b6178687 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
@@ -158,4 +158,95 @@ describe('activatorRuntime', () => {
expect(result.content).toContain('Not found: lobe-remote-device');
});
});
+
+ describe('Agent Share visitor runs', () => {
+ const userSkill = {
+ content: '# User skill',
+ id: 'user-skill-id',
+ identifier: 'user-skill-identifier',
+ name: 'user-skill',
+ };
+
+ const createVisitorRuntime = async (
+ agentShareVisitor: { skillGrants?: string[]; toolGrants?: { identifier: string }[] },
+ toolManifestMap: Record<string, unknown> = {},
+ ) => {
+ const { activatorRuntime } = await import('../activator');
+ return activatorRuntime.factory({
+ agentId: 'agent-1',
+ agentShareVisitor: agentShareVisitor as never,
+ serverDB: {} as never,
+ toolManifestMap: toolManifestMap as never,
+ userId: 'creator-1',
+ });
+ };
+
+ it('does not open a skill the share did not grant through the activateTools fallback', async () => {
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === userSkill.name ? userSkill : undefined,
+ );
+ mocks.findById.mockImplementation(async (id: string) =>
+ id === userSkill.id ? userSkill : undefined,
+ );
+ mocks.findAll.mockResolvedValue({ data: [userSkill], total: 1 });
+
+ const runtime = await createVisitorRuntime({
+ skillGrants: ['another-skill'],
+ toolGrants: [{ identifier: 'lobe-calculator' }],
+ });
+
+ const result = await runtime.activateTools({
+ identifiers: [userSkill.name],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain(`Not found: ${userSkill.name}`);
+ expect(result.content).not.toContain(userSkill.content);
+ expect(result.state?.activatedSkills).toEqual([]);
+ }, 20_000);
+
+ it('opens a skill the share granted', async () => {
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === userSkill.name ? userSkill : undefined,
+ );
+
+ const runtime = await createVisitorRuntime({
+ skillGrants: [userSkill.identifier],
+ toolGrants: [{ identifier: 'lobe-calculator' }],
+ });
+
+ const result = await runtime.activateTools({
+ identifiers: [userSkill.name],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain(userSkill.content);
+ expect(result.content).not.toContain('Not found');
+ });
+
+ it('activates only tools present in the gated manifest map', async () => {
+ // The share gate already pruned this map; an ungranted tool is simply
+ // absent, so naming it cannot pull its manifest into the run.
+ const runtime = await createVisitorRuntime(
+ { toolGrants: [{ identifier: 'lobe-calculator' }] },
+ {
+ 'lobe-calculator': {
+ api: [{ description: 'Calculate', name: 'calculate' }],
+ identifier: 'lobe-calculator',
+ meta: { title: 'Calculator' },
+ },
+ },
+ );
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-calculator', 'lobe-agent-management'],
+ reason: 'test',
+ });
+
+ expect(result.state?.activatedTools.map((tool: any) => tool.identifier)).toEqual([
+ 'lobe-calculator',
+ ]);
+ expect(result.state?.notFound).toEqual(['lobe-agent-management']);
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
index debbb539b5d..33e6d5b19e2 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
@@ -6,6 +6,7 @@ import {
type ToolManifestInfo,
} from '@lobechat/builtin-tool-activator/executionRuntime';
import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';
+import { resolveShareAllowedSkillIds } from '@lobechat/const';
import { describeLockedDevicePicker, getDisabledPluginIds } from '@lobechat/types';
import { AgentModel } from '@/database/models/agent';
@@ -86,22 +87,39 @@ export const activatorRuntime: ServerRuntimeRegistration = {
disabledSkillIds = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));
}
+ // An Agent Share visitor reaches only the skills the creator listed in
+ // `shareConfig.skillGrants`. `activateTools` falls back to this runtime
+ // for any identifier that is not a tool, so without this check a
+ // model-supplied name would open a skill the share never granted β€”
+ // the same model-supplied-name hole the skills runtime closes with its
+ // own `isSkillGranted` predicate (`skills.ts`).
+ const shareVisitor = context.agentShareVisitor;
+ const isSkillReachable = (identifier: string) =>
+ !disabledSkillIds.has(identifier) &&
+ (!shareVisitor || resolveShareAllowedSkillIds([identifier], shareVisitor).length > 0);
+
skillsRuntime = new SkillsExecutionRuntime({
// Same device gate as the skills runtime: device-only skills are
// activatable in device-capable runs (matching <available_skills>),
// with `activeDeviceId` as the fallback for callers without a plan.
builtinSkills: filterBuiltinSkills(builtinSkills, {
canExecuteOnDevice: context.deviceCapable ?? !!context.activeDeviceId,
- }).filter((skill) => !disabledSkillIds.has(skill.identifier)),
+ }).filter((skill) => isSkillReachable(skill.identifier)),
service: {
- findAll: () => skillModel.findAll(),
+ findAll: async () => {
+ const result = await skillModel.findAll();
+ if (!shareVisitor) return result;
+
+ const data = result.data.filter((skill) => isSkillReachable(skill.identifier));
+ return { data, total: data.length };
+ },
findById: async (id) => {
const skill = await skillModel.findById(id);
- return skill && disabledSkillIds.has(skill.identifier) ? undefined : skill;
+ return skill && isSkillReachable(skill.identifier) ? skill : undefined;
},
findByName: async (name) => {
const skill = await skillModel.findByName(name);
- return skill && disabledSkillIds.has(skill.identifier) ? undefined : skill;
+ return skill && isSkillReachable(skill.identifier) ? skill : undefined;
},
readResource: async () => {
throw new Error('readResource not available in tools runtime');
diff --git a/packages/builtin-tool-activator/src/index.ts b/packages/builtin-tool-activator/src/index.ts
index eb5b8b96215..11daf0da252 100644
--- a/packages/builtin-tool-activator/src/index.ts
+++ b/packages/builtin-tool-activator/src/index.ts
@@ -1,5 +1,5 @@
export { LobeActivatorManifest } from './manifest';
-export { systemPrompt } from './systemRole';
+export { 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.ts
index 2f439e043ab..8d790663cea 100644
--- a/packages/builtin-tool-activator/src/systemRole.ts
+++ b/packages/builtin-tool-activator/src/systemRole.ts
@@ -1,16 +1,26 @@
-export const systemPrompt = `You have access to a Tools Activator that allows you to dynamically activate tools on demand. Not all tools are loaded by default β€” you must activate them before use.
+const intro = `You have access to a Tools Activator that allows you to dynamically activate tools on demand. Not all tools are loaded by default β€” you must activate them before use.`;
-<how_it_works>
+const howItWorksSkill = `7. To activate a skill, use the \`activateSkill\` tool from lobe-skills β€” it returns instructions to follow
+`;
+
+const howItWorks = ({ withSkills }: { withSkills: boolean }) => `<how_it_works>
1. Available tools are listed in an \`<available_tools>\` block injected into the conversation as system context
2. Each entry shows the tool's identifier, name, and description
3. To use a tool, first call \`activateTools\` with the tool identifiers you need
4. After activation, the tool's full API schemas become available as native function calls in subsequent turns
5. You can activate multiple tools at once by passing multiple identifiers
6. Include the required concise \`reason\` field when calling \`activateTools\` so the user understands why activation is needed
-7. To activate a skill, use the \`activateSkill\` tool from lobe-skills β€” it returns instructions to follow
-</how_it_works>
+${withSkills ? howItWorksSkill : ''}</how_it_works>`;
+
+const toolSelectionSkill = `- **activateSkill** (provided by lobe-skills): Use this when the user's task matches one of the available skills
+ - **IMPORTANT**: If a skill's content is already provided in \`<selected_skill_context>\` within the user message, do NOT call activateSkill for that skill β€” its instructions are already loaded and ready to use
+`;
-<tool_selection_guidelines>
+const toolSelectionGuidelines = ({
+ withSkills,
+}: {
+ withSkills: boolean;
+}) => `<tool_selection_guidelines>
- **activateTools**: Call this when you need to use a tool that isn't yet activated
- Review the \`<available_tools>\` list to find relevant tools for the user's task
- Provide an array of tool identifiers to activate
@@ -18,11 +28,9 @@ export const systemPrompt = `You have access to a Tools Activator that allows yo
- After activation, the tools' APIs will be available for you to call directly
- Tools that are already active will be noted in the response
- If an identifier is not found, it will be reported in the response
-- **activateSkill** (provided by lobe-skills): Use this when the user's task matches one of the available skills
- - **IMPORTANT**: If a skill's content is already provided in \`<selected_skill_context>\` within the user message, do NOT call activateSkill for that skill β€” its instructions are already loaded and ready to use
-</tool_selection_guidelines>
+${withSkills ? toolSelectionSkill : ''}</tool_selection_guidelines>`;
-<skill_store_discovery>
+const skillStoreDiscovery = `<skill_store_discovery>
**CRITICAL: Always activate \`lobe-skill-store\` FIRST when ANY of the following conditions are met:**
**Trigger keywords/patterns (MUST activate lobe-skill-store immediately):**
@@ -60,9 +68,9 @@ export const systemPrompt = `You have access to a Tools Activator that allows yo
- Do NOT manually curl/fetch SKILL.md files or try to parse them yourself
- For \`lobehub.com/skills/xxx/skill.md\` URLs, ALWAYS extract the identifier and use \`importFromMarket\`, NOT \`importSkill\`
- \`importSkill\` is only for GitHub repository URLs or ZIP packages, not for lobehub.com skill URLs
-</skill_store_discovery>
+</skill_store_discovery>`;
-<credentials_management>
+const credentialsManagement = `<credentials_management>
**CRITICAL: Activate \`lobe-creds\` when ANY of the following conditions are met:**
**Trigger conditions (MUST activate lobe-creds immediately):**
@@ -105,15 +113,52 @@ When \`{{creds_sandbox_reachable}}\` is \`false\` (this run is routed to a devic
- Do NOT call \`injectCredsToSandbox\` β€” it would still report success, but it writes into a cloud sandbox nothing in this run actually executes in.
- There is currently no tool exposed to read a saved credential's plaintext value for inline use on a device-routed run. Tell the user this credential can't be used in this run rather than inventing a workaround.
</credential_usage_by_runtime>
-</credentials_management>
+</credentials_management>`;
-<best_practices>
-- **IMPORTANT: Plan ahead and activate all needed tools upfront in a single call.** Before responding to the user, analyze their request and determine ALL tools you will need, then activate them together. Do NOT activate tools incrementally during a multi-step task.
-- **SKILL-FIRST: Any mention of skills, SKILL.md, GitHub skill links, or LobeHub marketplace β†’ activate \`lobe-skill-store\` FIRST, no exceptions.**
+const bestPracticesSkillFirst = `- **SKILL-FIRST: Any mention of skills, SKILL.md, GitHub skill links, or LobeHub marketplace β†’ activate \`lobe-skill-store\` FIRST, no exceptions.**
- **CREDS-FIRST: Any need for authentication, API keys, OAuth, tokens, or env variables β†’ activate \`lobe-creds\` FIRST to manage credentials securely.**
-- Check the \`<available_tools>\` list before activating tools
-- For specialized tasks, search the Skill Marketplace first β€” a dedicated skill is almost always better than a generic approach
-- Only activate tools that are relevant to the user's current request
+`;
+
+const bestPracticesSkillMarketplace = `- For specialized tasks, search the Skill Marketplace first β€” a dedicated skill is almost always better than a generic approach
+`;
+
+const bestPractices = ({
+ withSkillStoreAndCreds,
+}: {
+ withSkillStoreAndCreds: boolean;
+}) => `<best_practices>
+- **IMPORTANT: Plan ahead and activate all needed tools upfront in a single call.** Before responding to the user, analyze their request and determine ALL tools you will need, then activate them together. Do NOT activate tools incrementally during a multi-step task.
+${withSkillStoreAndCreds ? bestPracticesSkillFirst : ''}- Check the \`<available_tools>\` list before activating tools
+${withSkillStoreAndCreds ? bestPracticesSkillMarketplace : ''}- Only activate tools that are relevant to the user's current request
- After activation, use the tools' APIs directly β€” no need to call activateTools again for the same tools
-</best_practices>
+</best_practices>`;
+
+export const systemPrompt = `${intro}
+
+${howItWorks({ withSkills: true })}
+
+${toolSelectionGuidelines({ withSkills: true })}
+
+${skillStoreDiscovery}
+
+${credentialsManagement}
+
+${bestPractices({ withSkillStoreAndCreds: true })}
+`;
+
+/**
+ * Variant for Agent Share visitor runs. `lobe-skill-store` and `lobe-creds`
+ * are never available to a visitor, so the sections that send the model to
+ * activate them first would divert requests (skills, auth, GitHub/Notion…)
+ * toward an impossible prerequisite instead of the granted tools. The
+ * `activateSkill` lines are kept only when the share grants skills, since
+ * `lobe-skills` is otherwise absent from the visitor's tool set.
+ */
+export const getSystemPromptForShareVisitor = ({ withSkills }: { withSkills: boolean }) => `${intro}
+
+${howItWorks({ withSkills })}
+
+${toolSelectionGuidelines({ withSkills })}
+
+${bestPractices({ withSkillStoreAndCreds: false })}
`;
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 9dbffb8b7d3..d7db39a42ea 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -227,7 +227,7 @@ export const runtimeManagedToolIds = [
* (`lobe-agent-management`, `lobe-task`, `lobe-creds`, `lobe-message`,
* `lobe-skill-store`, `lobe-agent-builder`,
* `lobe-group-agent-builder`, `lobe-group-management`, `agent-signal-review`,
- * `lobe-user-interaction`, `lobe-activator`,
+ * `lobe-user-interaction`,
* `lobe-local-system`, `lobe-browser`, `lobe-remote-device`,
* `lobe-topic-reference`, and the hidden system-only self-iteration tools),
* see the denied-builtins section of
@@ -259,6 +259,13 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([
KnowledgeBaseManifest.identifier,
MemoryManifest.identifier,
AgentDocumentsManifest.identifier,
+ // `lobe-activator`: never picked in the owner's tool picker β€” it is implied
+ // (scoped to `activateTools`) by any tool grant and kept only while the
+ // gated set still holds a granted tool to activate. It can only surface
+ // manifests from that already-gated set, and its skill fallback re-checks
+ // `shareConfig.skillGrants`. See the allowed-builtins section of
+ // `shareGate/README.md`.
+ LobeActivatorManifest.identifier,
// `lobe-skills`: a skill-driven agent is broken the moment it is shared
// without this, since skills are loaded on demand through this tool. It is
// allowed only in the narrow shape `DATA_TOOL_ACCESS_RULES` gives it β€”