🤯 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
✨ feat(agent-share): open the Agent's turned-on tools to visitors automatically (#23548)
YuTengjingae04fabd8d92
diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex 368ce076aba..d73536c62f6 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -42,6 +42,13 @@ const emptyDeliveryStats = {workCount: 0,};+const listShareGrantableSkills = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/agentShare/grantableSkills', () => ({ listShareGrantableSkills }));+const listShareActivatableExtensionIds = vi.hoisted(() => vi.fn(async () => [] as string[]));+vi.mock('@/server/services/agentShare/activatableExtensions', () => ({+ listShareActivatableExtensionIds,+}));+vi.mock('@/database/models/agentShareProfile', () => ({AgentShareProfileModel: class {constructor(...args: unknown[]) {@@ -266,6 +273,48 @@ describe('shareRouter', () => {expect(result.toolGrants).toEqual([]);});+ it('advertises the tools autoGrantAgentTools opens, minus skills and declined ones', async () => {+ listShareGrantableSkills.mockResolvedValue([+ { description: '', identifier: 'skill-pinned', name: 'Skill' },+ ]);+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue({+ ...agentShare,+ agentChatConfig: { memory: { enabled: true }, toolMode: 'chat' },+ agentPlugins: ['mcp-pinned', 'skill-pinned', 'mcp-declined'],+ shareConfig: {+ ...agentShare.shareConfig,+ autoGrantAgentTools: true,+ declinedGrantIds: ['mcp-declined'],+ },+ } as any);+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ const result = await caller.getSharedAgent({ slugOrId: 'shared-agent' });++ expect(result.toolGrants).toEqual(+ expect.arrayContaining(['lobe-web-browsing', 'mcp-pinned']),+ );+ expect(result.toolGrants).not.toContain('skill-pinned');+ expect(result.toolGrants).not.toContain('mcp-declined');+ expect(result.toolGrants).not.toContain('lobe-user-memory');+ });++ it('advertises a connected connector the Agent has no entry for', async () => {+ listShareGrantableSkills.mockResolvedValue([]);+ listShareActivatableExtensionIds.mockResolvedValueOnce(['mcp-connected']);+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue({+ ...agentShare,+ agentChatConfig: { toolMode: 'agent' },+ agentPlugins: [],+ shareConfig: { ...agentShare.shareConfig, autoGrantAgentTools: true },+ } as any);+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ const result = await caller.getSharedAgent({ slugOrId: 'shared-agent' });++ expect(result.toolGrants).toContain('mcp-connected');+ });+it('returns independent demos and selected deliveries in the owner scope', async () => {const demoCases = [{ prompt: 'Review this migration', description: 'Find deployment risks' }];const work = { id: 'work-selected', title: 'Migration review', totalCost: 0.2 };diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex 2145defa68d..dc24e85c314 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -1,10 +1,7 @@-import { builtinSkills } from '@lobechat/builtin-skills';import {AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,AGENT_SHARE_DEVICE_ALLOW_USERS_LIMIT,} from '@lobechat/const';-import { assembleSkillPool } from '@lobechat/mecha';-import { getActivePluginIds, getAutoPluginIds, getDisabledPluginIds } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { eq } from 'drizzle-orm';import pMap from 'p-map';@@ -16,7 +13,6 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport { AgentModel } from '@/database/models/agent';import { AgentShareModel } from '@/database/models/agentShare';import { AgentShareProfileModel } from '@/database/models/agentShareProfile';-import { AgentSkillModel } from '@/database/models/agentSkill';import { ContactModel } from '@/database/models/contact';import { FileModel } from '@/database/models/file';import { RbacModel } from '@/database/models/rbac';@@ -26,7 +22,7 @@ import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentService } from '@/server/services/agent';-import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { listShareGrantableSkills } from '@/server/services/agentShare/grantableSkills';import { isChannelEnabled } from '@/server/services/channel/featureGate';import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';@@ -59,6 +55,7 @@ export const agentShareConfigSchema = z.object({allowCreatorViewSessions: z.boolean().optional(),allowReadMemory: z.boolean().optional(),+ autoGrantAgentTools: z.boolean().optional(),demoCases: z.array(z@@ -379,22 +376,7 @@ export const agentShareRouter = router({}),/*** Skills this agent could offer a visitor — the candidate list behind the- * share settings skill picker, and the set `shareConfig.skillGrants` entries- * are chosen from.- *- * Built through the SAME `assembleSkillPool` a real run uses, on the same- * server-side sources, so the picker cannot offer a skill the run would never- * assemble (nor hide one it would). Three deliberate differences from a run:- *- * - no `shareAllowedIds` — the whole point is to list what COULD be granted;- * - no project/device skills — those are discovered on the execution device's- * filesystem, and a visitor run never routes a device;- * - `canExecuteOnDevice: false`, for the same reason.- *- * Skills are NOT filtered to the agent's pinned set: a skill is on-demand by- * default, so an unpinned skill is exactly the normal case. `manual` mode is- * the one exception, and `assembleSkillPool` applies it from- * `enabledPluginIds` on its own.+ * share settings skill picker (see `listShareGrantableSkills`).** Authorization matches the other share reads: `assertCanManageAgentShare`* for the workspace case, then `requireShare` on the ownership-scoped@@ -413,50 +395,13 @@ export const agentShareRouter = router({workspaceId,).getAgentConfigById(input.agentId);- const [dbSkills, agentSkills] = await Promise.all([- new AgentSkillModel(ctx.serverDB, ctx.userId, workspaceId)- .findAll()- .then((result) => result.data),- // A bundle-less agent is the common case and throws nothing; a genuine- // failure here must not take the whole picker down with it — the DB and- // builtin skills are still grantable.- new AgentDocumentsService(ctx.serverDB, ctx.userId, workspaceId)- .getAgentSkills(input.agentId)- .catch(() => []),- ]);-- const { skills } = assembleSkillPool(- {- agentSkills: agentSkills.map((skill) => ({- description: skill.description,- identifier: skill.identifier,- name: skill.name,- })),- builtin: builtinSkills.map((skill) => ({- description: skill.description,- identifier: skill.identifier,- name: skill.name,- })),- db: dbSkills.map((skill) => ({- description: skill.description ?? '',- identifier: skill.identifier,- name: skill.name,- })),- },- {- autoSkillIds: getAutoPluginIds(agentConfig?.plugins ?? undefined),- canExecuteOnDevice: false,- disabledIds: getDisabledPluginIds(agentConfig?.plugins ?? undefined),- enabledPluginIds: getActivePluginIds(agentConfig?.plugins ?? undefined),- skillActivateMode: agentConfig?.chatConfig?.skillActivateMode,- },- );-- return skills.map((skill) => ({- description: skill.description,- identifier: skill.identifier,- name: skill.name,- }));+ return listShareGrantableSkills({+ agentConfig,+ agentId: input.agentId,+ db: ctx.serverDB,+ userId: ctx.userId,+ workspaceId,+ });}),/**diff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex dadc8798d2e..e29173effc3 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -1,8 +1,11 @@+import { MemoryIdentifier } from '@lobechat/builtin-tool-memory';import {AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR,+ DEFAULT_AGENT_CHAT_CONFIG,} from '@lobechat/const';import {+ getOptedInPluginIds,type SharedAgentData,type SharedAgentDeliveryStats,type SharedAgentUploadAbility,@@ -25,7 +28,10 @@ import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { resolveModelMediaCapabilities } from '@/server/modules/AgentRuntime/resolveModelMediaCapabilities';import { AgentService } from '@/server/services/agent';+import { listShareActivatableExtensionIds } from '@/server/services/agentShare/activatableExtensions';import { getCachedDeliveryStats } from '@/server/services/agentShare/deliveryStatsCache';+import { listShareGrantableSkills } from '@/server/services/agentShare/grantableSkills';+import { applyShareAutoAgentGrants } from '@/server/services/aiAgent/shareGate/autoGrants';import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';import { sharedTopicText } from './_helpers/sharedTopicText';@@ -220,6 +226,43 @@ export const shareRouter = router({})(),]);+ // With `autoGrantAgentTools` on, visitors also get the tools the Agent+ // turns on; count those the way a visitor run resolves them.+ const { toolGrants } = share.shareConfig.autoGrantAgentTools+ ? applyShareAutoAgentGrants(share.shareConfig, {+ // LobeHub connections live in the creator's Market account, which a+ // visitor request cannot read; only the advertised count leaves them out.+ activatableExtensionIds: await listShareActivatableExtensionIds({+ agentId: share.agentId,+ db: ctx.serverDB,+ userId: share.ownerId,+ workspaceId: share.workspaceId ?? undefined,+ }).then(+ (ids) => [...ids, ...getOptedInPluginIds(share.agentPlugins ?? [])],+ (error) => {+ log('failed to list connected extensions for %s: %O', share.shareId, error);+ return undefined;+ },+ ),+ chatConfig: { ...DEFAULT_AGENT_CHAT_CONFIG, ...share.agentChatConfig },+ plugins: share.agentPlugins ?? [],+ skillIds: (+ await listShareGrantableSkills({+ agentConfig: { chatConfig: share.agentChatConfig, plugins: share.agentPlugins },+ agentId: share.agentId,+ db: ctx.serverDB,+ userId: share.ownerId,+ workspaceId: share.workspaceId ?? undefined,+ }).catch((error) => {+ // Only the advertised count degrades: pinned skills may be+ // counted as tools. The run resolves its own grants.+ log('failed to list grantable skills for %s: %O', share.shareId, error);+ return [];+ })+ ).map((skill) => skill.identifier),+ })+ : share.shareConfig;+return {agentId: share.agentId,agentMeta: {@@ -255,7 +298,13 @@ export const shareRouter = router({// advertised (the settings page hides them too).toolGrants: share.agentAgencyConfig?.heterogeneousProvider? []- : (share.shareConfig.toolGrants ?? []).map((grant) => grant.identifier),+ : (toolGrants ?? [])+ .map((grant) => grant.identifier)+ // A visitor run drops memory without the read permission.+ .filter(+ (identifier) =>+ identifier !== MemoryIdentifier || !!share.shareConfig.allowReadMemory,+ ),uploadAbility,// TODO(cloud budget gate): the spend gate itself is already enforced —// `shareChat.execAgent` checks `checkAgentShareSpendAllowance` beforediff --git a/apps/server/src/services/agentShare/activatableExtensions.test.ts b/apps/server/src/services/agentShare/activatableExtensions.test.tsnew file mode 100644index 00000000000..26b77b1fd44--- /dev/null+++ b/apps/server/src/services/agentShare/activatableExtensions.test.ts@@ -0,0 +1,60 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { listShareActivatableExtensionIds } from './activatableExtensions';++const mocks = vi.hoisted(() => ({+ queryAvailableForAgent: vi.fn(),+ queryPlugins: vi.fn(),+}));++// Constructor mocks must be `function`s: `new` on an arrow-function mock throws.+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn(function () {+ return { queryAvailableForAgent: mocks.queryAvailableForAgent };+ }),+}));+vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn(function () {+ return { query: mocks.queryPlugins };+ }),+}));++describe('listShareActivatableExtensionIds', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.queryAvailableForAgent.mockResolvedValue([+ { id: '1', identifier: 'mcp-connected', isEnabled: true, status: 'connected' },+ { id: '2', identifier: 'mcp-disconnected', isEnabled: true, status: 'error' },+ { id: '3', identifier: 'mcp-switched-off', isEnabled: false, status: 'connected' },+ ]);+ mocks.queryPlugins.mockResolvedValue([+ { identifier: 'plugin-installed' },+ { identifier: 'lobe-calculator' },+ ]);+ });++ it("lists the Agent's connected connectors, installed plugins and LobeHub connections", async () => {+ const ids = await listShareActivatableExtensionIds({+ agentId: 'agent-1',+ db: {} as any,+ listLobehubSkillProviderIds: async () => ['linear'],+ userId: 'owner',+ });++ expect(ids).toEqual(['mcp-connected', 'plugin-installed', 'linear']);+ expect(mocks.queryAvailableForAgent).toHaveBeenCalledWith('agent-1');+ });++ it('keeps the database extensions when the Market lookup fails', async () => {+ const ids = await listShareActivatableExtensionIds({+ agentId: 'agent-1',+ db: {} as any,+ listLobehubSkillProviderIds: async () => {+ throw new Error('market down');+ },+ userId: 'owner',+ });++ expect(ids).toEqual(['mcp-connected', 'plugin-installed']);+ });+});diff --git a/apps/server/src/services/agentShare/activatableExtensions.ts b/apps/server/src/services/agentShare/activatableExtensions.tsnew file mode 100644index 00000000000..e2ffd04f06e--- /dev/null+++ b/apps/server/src/services/agentShare/activatableExtensions.ts@@ -0,0 +1,46 @@+import { isBuiltinToolIdentifier } from '@lobechat/builtin-tools';++import { ConnectorModel } from '@/database/models/connector';+import { PluginModel } from '@/database/models/plugin';+import type { LobeChatDatabase } from '@/database/type';++/**+ * The creator's connected extensions an Agent's model could activate on+ * demand: enabled, connected MCP and Composio connectors the Agent loads,+ * installed plugins, and LobeHub connections. In agent mode the Agent's+ * 工具与连接 page shows each as on unless turned off, so `autoGrantAgentTools`+ * reads this list to open the same set to visitors.+ *+ * Reads identifiers only, never credentials. `listLobehubSkillProviderIds`+ * asks the Market for the creator's connections; a failure there drops those+ * connections instead of failing the run.+ */+export const listShareActivatableExtensionIds = async ({+ agentId,+ db,+ listLobehubSkillProviderIds,+ userId,+ workspaceId,+}: {+ agentId: string;+ db: LobeChatDatabase;+ listLobehubSkillProviderIds?: () => Promise<string[]>;+ userId: string;+ workspaceId?: string;+}): Promise<string[]> => {+ const [connectors, plugins, lobehubSkillIds] = await Promise.all([+ new ConnectorModel(db, userId, workspaceId).queryAvailableForAgent(agentId),+ new PluginModel(db, userId, workspaceId).query(),+ listLobehubSkillProviderIds?.().catch(() => []) ?? [],+ ]);++ return [+ ...new Set([+ ...connectors+ .filter((connector) => connector.isEnabled && connector.status === 'connected')+ .map((connector) => connector.identifier),+ ...plugins.map((plugin) => plugin.identifier),+ ...lobehubSkillIds,+ ]),+ ].filter((identifier) => !isBuiltinToolIdentifier(identifier));+};diff --git a/apps/server/src/services/agentShare/grantableSkills.test.ts b/apps/server/src/services/agentShare/grantableSkills.test.tsnew file mode 100644index 00000000000..a85cfafdfe1--- /dev/null+++ b/apps/server/src/services/agentShare/grantableSkills.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { listShareGrantableSkills } from './grantableSkills';++const mocks = vi.hoisted(() => ({+ getAgentVisibility: vi.fn(),+ listCatalog: vi.fn(),+ userSkillScope: vi.fn(),+}));++vi.mock('@lobechat/builtin-skills', () => ({ builtinSkills: [] }));+// Constructor mocks must be `function`s: `new` on an arrow-function mock throws.+vi.mock('@/database/models/agentSkill', () => ({+ AgentSkillModel: vi.fn(function () {+ return { findAll: async () => ({ data: [] }) };+ }),+}));+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn(function () {+ return { getAgentVisibility: mocks.getAgentVisibility };+ }),+}));+vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: vi.fn(function () {+ return { getAgentSkills: async () => [] };+ }),+}));+vi.mock('@/server/services/userSkill', () => ({+ UserSkillService: vi.fn(function (...args: unknown[]) {+ mocks.userSkillScope(...args);+ return { listCatalog: mocks.listCatalog };+ }),+}));++const librarySkill = {+ description: 'Summarize weekly notes',+ identifier: 'user-skills:weekly',+ name: 'weekly',+};++describe('listShareGrantableSkills', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.listCatalog.mockResolvedValue([librarySkill]);+ });++ it("lists the creator's skill library the Agent opted into, as a run does", async () => {+ const skills = await listShareGrantableSkills({+ agentConfig: { plugins: [{ identifier: librarySkill.identifier, mode: 'auto' }] },+ agentId: 'agent-1',+ db: {} as any,+ userId: 'owner',+ });++ expect(skills.map((skill) => skill.identifier)).toContain(librarySkill.identifier);+ expect(mocks.listCatalog).toHaveBeenCalledWith({ includeGenerated: false });+ });++ it("scopes a workspace Agent's library by the Agent's visibility", async () => {+ mocks.getAgentVisibility.mockResolvedValue('public');++ await listShareGrantableSkills({+ agentConfig: { plugins: [] },+ agentId: 'agent-1',+ db: {} as any,+ userId: 'owner',+ workspaceId: 'ws-1',+ });++ expect(mocks.getAgentVisibility).toHaveBeenCalledWith('agent-1');+ expect(mocks.userSkillScope).toHaveBeenCalledWith({}, 'owner', 'ws-1', 'public');+ });+});diff --git a/apps/server/src/services/agentShare/grantableSkills.ts b/apps/server/src/services/agentShare/grantableSkills.tsnew file mode 100644index 00000000000..a59e7f4439a--- /dev/null+++ b/apps/server/src/services/agentShare/grantableSkills.ts@@ -0,0 +1,125 @@+import { builtinSkills } from '@lobechat/builtin-skills';+import { assembleSkillPool } from '@lobechat/mecha';+import {+ type AgentPluginEntry,+ getActivePluginIds,+ getAutoPluginIds,+ getDisabledPluginIds,+} from '@lobechat/types';++import { AgentModel } from '@/database/models/agent';+import { AgentSkillModel } from '@/database/models/agentSkill';+import type { LobeChatDatabase } from '@/database/type';+import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { UserSkillService } from '@/server/services/userSkill';++export interface ShareGrantableSkill {+ description: string;+ identifier: string;+ name: string;+}++interface GrantableSkillsInput {+ agentConfig:+ | {+ chatConfig?: { skillActivateMode?: 'auto' | 'manual' } | null;+ plugins?: AgentPluginEntry[] | null;+ }+ | null+ | undefined;+ agentId: string;+ /**+ * Whether the run may use the creator's device. Off for the share picker;+ * a visitor run's automatic grants pass the visitor's device access, so a+ * device-only skill the Agent turns on is granted to visitors who can run it.+ */+ canExecuteOnDevice?: boolean;+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++/**+ * Skills this Agent could offer a visitor: the share settings skill picker's+ * list, and the skills `autoGrantAgentTools` opens.+ *+ * Built through the SAME `assembleSkillPool` a real run uses, on the same+ * server-side sources, so the picker cannot offer a skill the run would never+ * assemble (nor hide one it would). Three deliberate differences from a run:+ *+ * - no `shareAllowedIds` — the whole point is to list what COULD be granted;+ * - no project/device skills — those are discovered on the execution device's+ * filesystem, which this listing never scans;+ * - `canExecuteOnDevice` off by default; a visitor run passes its own device+ * access instead, so device-only builtin skills follow what it may run.+ *+ * The user's skill library is listed as a run lists it: its catalog without+ * generated skills, and none at all for a workspace-public Agent.+ *+ * Skills are NOT filtered to the agent's pinned set: a skill is on-demand by+ * default, so an unpinned skill is exactly the normal case. `manual` mode is+ * the one exception, and `assembleSkillPool` applies it from+ * `enabledPluginIds` on its own.+ *+ * Reads the creator's whole skill catalog: callers must have authorized the+ * Agent's share first.+ */+export const listShareGrantableSkills = async ({+ agentConfig,+ agentId,+ canExecuteOnDevice = false,+ db,+ userId,+ workspaceId,+}: GrantableSkillsInput): Promise<ShareGrantableSkill[]> => {+ const plugins = agentConfig?.plugins ?? undefined;+ const [dbSkills, agentSkills, userSkills] = await Promise.all([+ new AgentSkillModel(db, userId, workspaceId).findAll().then((result) => result.data),+ // A bundle-less agent is the common case and throws nothing; a genuine+ // failure here must not take the whole list down with it — the DB and+ // builtin skills are still grantable.+ new AgentDocumentsService(db, userId, workspaceId).getAgentSkills(agentId).catch(() => []),+ (async () =>+ new UserSkillService(+ db,+ userId,+ workspaceId,+ workspaceId+ ? await new AgentModel(db, userId, workspaceId).getAgentVisibility(agentId)+ : undefined,+ ).listCatalog({ includeGenerated: false }))(),+ ]);++ const { skills } = assembleSkillPool(+ {+ agentSkills: [...agentSkills, ...userSkills].map((skill) => ({+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ })),+ builtin: builtinSkills.map((skill) => ({+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ })),+ db: dbSkills.map((skill) => ({+ description: skill.description ?? '',+ identifier: skill.identifier,+ name: skill.name,+ })),+ },+ {+ autoSkillIds: getAutoPluginIds(plugins),+ canExecuteOnDevice,+ disabledIds: getDisabledPluginIds(plugins),+ enabledPluginIds: getActivePluginIds(plugins),+ skillActivateMode: agentConfig?.chatConfig?.skillActivateMode,+ },+ );++ return skills.map((skill) => ({+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ }));+};diff --git a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts b/apps/server/src/services/aiAgent/pipeline/deferredInit.tsindex fab01b8e022..324b78663bf 100644--- a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts+++ b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts@@ -9,6 +9,7 @@ import type { MarketService } from '@/server/services/market';import { createRunFacts, type RunFacts } from '../runFacts';import type { AgentShareGate } from '../shareGate';+import { resolveShareAutoAgentGrants, type ShareAutoGrantAgent } from '../shareGate/autoGrants';import { resolveShareVisitorDeviceAccess } from '../shareGate/deviceAccess';import type { ExecRunContext } from '../types';import { type OperationInitDeps, runOperationInit } from './operationInit';@@ -34,8 +35,10 @@ export type DeferredOperationInitDeps = Omit<* a share that is gone, no longer public or no longer this agent's ends the run.*/const resolveShareGate = async (- deps: Pick<DeferredOperationInitDeps, 'db' | 'userId'>,+ deps: Pick<DeferredOperationInitDeps, 'db' | 'userId' | 'workspaceId'>,shareVisitor: NonNullable<NonNullable<AgentState['principal']>['actor']>['shareVisitor'],+ agent: ShareAutoGrantAgent,+ listLobehubSkillProviderIds: () => Promise<string[]>,): Promise<AgentShareGate | undefined> => {if (!shareVisitor) return undefined;@@ -49,13 +52,27 @@ const resolveShareGate = async (throw new Error(`Share ${shareVisitor.shareId} no longer authorizes this run`);}- return {- agentId: share.agentId,- canUseDevice: await resolveShareVisitorDeviceAccess(deps.db, share, shareVisitor.visitorUserId),- shareConfig: share.shareConfig,- shareId: share.shareId,- visitorUserId: shareVisitor.visitorUserId,- };+ // Resolved against the operation's own Agent snapshot, as the send path does.+ return resolveShareAutoAgentGrants(+ {+ agentId: share.agentId,+ canUseDevice: await resolveShareVisitorDeviceAccess(+ deps.db,+ share,+ shareVisitor.visitorUserId,+ ),+ shareConfig: share.shareConfig,+ shareId: share.shareId,+ visitorUserId: shareVisitor.visitorUserId,+ },+ {+ agent,+ db: deps.db,+ listLobehubSkillProviderIds,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ },+ );};/**@@ -154,7 +171,17 @@ export const runDeferredOperationInit = async (}: { operationId: string; request: AgentRunInitRequest; state: AgentState },): Promise<{ context: AgentRuntimeContext; state: Partial<AgentState> }> => {const ctx = await restoreRunContext(deps, state, request);- ctx.shareGate = await resolveShareGate(deps, state.principal?.actor?.shareVisitor);+ ctx.shareGate = await resolveShareGate(+ deps,+ state.principal?.actor?.shareVisitor,+ {+ autoSkillIds: ctx.autoSkillIds,+ chatConfig: ctx.agentConfig.chatConfig,+ disabledPluginIds: ctx.disabledPluginIds,+ plugins: ctx.agentConfig.plugins,+ },+ async () => (await deps.getMarketService(ctx.runFacts)).listLobehubSkillProviderIds(),+ );const effectiveResume =!!request.resume ||diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.tsindex 53424bfc456..4f39269524e 100644--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts@@ -29,6 +29,7 @@ import type { MarketService } from '@/server/services/market';import { createRunFacts, type RunFacts } from '../runFacts';import { applyShareGateToAgentConfig } from '../shareGate';+import { resolveShareAutoAgentGrants } from '../shareGate/autoGrants';import { assertAgentRelayHop } from '../sourceAttribution';import type { ExecRunContext, InternalExecAgentParams } from '../types';import type { ApprovalClaimState } from './approvalResume';@@ -158,7 +159,7 @@ export const execAgentTurn = async (approvalSourceOperationId: providedApprovalSourceOperationId,selectedSkillIds,selectedToolIds,- shareGate,+ shareGate: requestedShareGate,mentionedAgents,suppressUserMessage,ephemeralUserMessage,@@ -173,7 +174,7 @@ export const execAgentTurn = async (// A share caller that sends no config falls back to `manual`, never to// this method's `headless` default: `headless` auto-runs `'required'`// calls, which would grant a consent nobody gave.- const userInterventionConfig: UserInterventionConfig = shareGate+ const userInterventionConfig: UserInterventionConfig = requestedShareGate? (params.userInterventionConfig ?? { approvalMode: 'manual' }): requestedUserInterventionConfig;@@ -289,7 +290,7 @@ export const execAgentTurn = async (instructions,modelOverride,providerOverride,- shareVisitorUserId: shareGate?.visitorUserId,+ shareVisitorUserId: requestedShareGate?.visitorUserId,throwIfExecutionAborted,toolModeOverride,},@@ -299,7 +300,25 @@ export const execAgentTurn = async (// Share-visitor runs must never see the creator's files/knowledge bases.// Applied to the resolved config before anything downstream (knowledge// flags, tools engine, context snapshot) reads it.- if (shareGate) applyShareGateToAgentConfig(agentConfig);+ if (requestedShareGate) applyShareGateToAgentConfig(agentConfig);++ // Resolve `autoGrantAgentTools` against this run's Agent config before any+ // stage reads the share's grants.+ const shareGate = requestedShareGate+ ? await resolveShareAutoAgentGrants(requestedShareGate, {+ agent: {+ autoSkillIds,+ chatConfig: agentConfig.chatConfig,+ disabledPluginIds,+ plugins: agentConfig.plugins,+ },+ db: deps.db,+ listLobehubSkillProviderIds: async () =>+ (await deps.getMarketService()).listLobehubSkillProviderIds(),+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ })+ : undefined;// Before the turn writes any row: a refused send leaves nothing behind.await claimRunSlot(runSlot, {diff --git a/apps/server/src/services/aiAgent/shareGate/autoGrants.test.ts b/apps/server/src/services/aiAgent/shareGate/autoGrants.test.tsnew file mode 100644index 00000000000..6d5a7311f1f--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/autoGrants.test.ts@@ -0,0 +1,184 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentShareConfig } from '@/database/schemas';++import { applyShareAutoAgentGrants, resolveShareAutoAgentGrants } from './autoGrants';+import type { AgentShareGate } from './types';++const listShareGrantableSkills = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/agentShare/grantableSkills', () => ({ listShareGrantableSkills }));+const listShareActivatableExtensionIds = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/agentShare/activatableExtensions', () => ({+ listShareActivatableExtensionIds,+}));++const agent = {+ chatConfig: { memory: { enabled: true } },+ plugins: ['mcp-pinned', 'skill-a'],+ skillIds: ['skill-a', 'skill-b'],+};++describe('applyShareAutoAgentGrants', () => {+ it('leaves the grants untouched while the switch is off', () => {+ const shareConfig: AgentShareConfig = { toolGrants: [{ identifier: 'mcp-pinned' }] };++ expect(applyShareAutoAgentGrants(shareConfig, agent)).toBe(shareConfig);+ });++ it('grants every tool and skill the Agent turns on', () => {+ const { skillGrants, toolGrants } = applyShareAutoAgentGrants(+ { autoGrantAgentTools: true },+ agent,+ );++ expect(toolGrants).toEqual(+ expect.arrayContaining([{ identifier: 'mcp-pinned' }, { identifier: 'lobe-calculator' }]),+ );+ expect(toolGrants?.map((grant) => grant.identifier)).not.toContain('skill-a');+ expect(skillGrants).toEqual(['skill-a', 'skill-b']);+ });++ it('keeps declined identifiers closed', () => {+ const { skillGrants, toolGrants } = applyShareAutoAgentGrants(+ { autoGrantAgentTools: true, declinedGrantIds: ['mcp-pinned', 'skill-b'] },+ agent,+ );++ expect(toolGrants?.map((grant) => grant.identifier)).not.toContain('mcp-pinned');+ expect(skillGrants).toEqual(['skill-a']);+ });++ it('never widens an explicit grant narrowed to some APIs', () => {+ const { toolGrants } = applyShareAutoAgentGrants(+ {+ autoGrantAgentTools: true,+ toolGrants: [{ apis: ['search'], identifier: 'lobe-web-browsing' }],+ },+ agent,+ );++ expect(toolGrants?.filter((grant) => grant.identifier === 'lobe-web-browsing')).toEqual([+ { apis: ['search'], identifier: 'lobe-web-browsing' },+ ]);+ });++ it('drops a tool once the Agent turns it off', () => {+ const { toolGrants } = applyShareAutoAgentGrants(+ { autoGrantAgentTools: true },+ { ...agent, plugins: [{ identifier: 'mcp-pinned', mode: 'disabled' }] },+ );++ expect(toolGrants?.map((grant) => grant.identifier)).not.toContain('mcp-pinned');+ });+});++describe('resolveShareAutoAgentGrants', () => {+ const gate = (shareConfig: AgentShareConfig): AgentShareGate => ({+ agentId: 'agent-1',+ canUseDevice: false,+ shareConfig,+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ });++ /** The run's Agent after config resolution: `plugins` collapsed to pinned ids. */+ const runAgent = {+ autoSkillIds: [],+ chatConfig: { memory: { enabled: true } },+ disabledPluginIds: [],+ plugins: ['mcp-pinned'],+ };++ beforeEach(() => {+ listShareGrantableSkills.mockReset();+ listShareGrantableSkills.mockResolvedValue([]);+ listShareActivatableExtensionIds.mockReset();+ listShareActivatableExtensionIds.mockResolvedValue([]);+ });++ it('opens a connected connector the Agent has no entry for, unless it is turned off', async () => {+ listShareActivatableExtensionIds.mockResolvedValue(['mcp-connected', 'mcp-off']);+ const listLobehubSkillProviderIds = vi.fn();++ const resolved = await resolveShareAutoAgentGrants(gate({ autoGrantAgentTools: true }), {+ agent: { ...runAgent, disabledPluginIds: ['mcp-off'] },+ db: {} as any,+ listLobehubSkillProviderIds,+ userId: 'owner',+ });++ const toolIds = resolved.shareConfig.toolGrants?.map((grant) => grant.identifier);+ expect(toolIds).toContain('mcp-connected');+ expect(toolIds).not.toContain('mcp-off');+ expect(listShareActivatableExtensionIds).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', listLobehubSkillProviderIds }),+ );+ });++ it('reads no skills while the switch is off', async () => {+ const off = gate({ toolGrants: [] });++ await expect(+ resolveShareAutoAgentGrants(off, { agent: runAgent, db: {} as any, userId: 'owner' }),+ ).resolves.toBe(off);+ expect(listShareGrantableSkills).not.toHaveBeenCalled();+ expect(listShareActivatableExtensionIds).not.toHaveBeenCalled();+ });++ it("opens the Agent's grantable skills for the creator's scope", async () => {+ listShareGrantableSkills.mockResolvedValue([+ { description: '', identifier: 'skill-b', name: 'B' },+ ]);++ const resolved = await resolveShareAutoAgentGrants(gate({ autoGrantAgentTools: true }), {+ agent: runAgent,+ db: {} as any,+ userId: 'owner',+ workspaceId: 'ws-1',+ });++ expect(listShareGrantableSkills).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ canExecuteOnDevice: false,+ userId: 'owner',+ workspaceId: 'ws-1',+ }),+ );+ expect(resolved.shareConfig.skillGrants).toEqual(['skill-b']);+ expect(resolved.shareId).toBe('share-1');+ });++ it("resolves the skill pool with the visitor's device access", async () => {+ await resolveShareAutoAgentGrants(+ { ...gate({ autoGrantAgentTools: true }), canUseDevice: true },+ { agent: runAgent, db: {} as any, userId: 'owner' },+ );++ expect(listShareGrantableSkills).toHaveBeenCalledWith(+ expect.objectContaining({ canExecuteOnDevice: true }),+ );+ });++ it('honors the auto and disabled entries the pinned-id collapse dropped', async () => {+ const resolved = await resolveShareAutoAgentGrants(gate({ autoGrantAgentTools: true }), {+ agent: {+ ...runAgent,+ autoSkillIds: ['mcp-auto', 'skill-auto'],+ disabledPluginIds: ['lobe-calculator', 'skill-off'],+ },+ db: {} as any,+ userId: 'owner',+ });++ const toolIds = resolved.shareConfig.toolGrants?.map((grant) => grant.identifier);+ expect(toolIds).toContain('mcp-auto');+ expect(toolIds).not.toContain('lobe-calculator');+ expect(listShareGrantableSkills.mock.calls[0][0].agentConfig.plugins).toEqual(+ expect.arrayContaining([+ { identifier: 'skill-auto', mode: 'auto' },+ { identifier: 'skill-off', mode: 'disabled' },+ ]),+ );+ });+});diff --git a/apps/server/src/services/aiAgent/shareGate/autoGrants.ts b/apps/server/src/services/aiAgent/shareGate/autoGrants.tsnew file mode 100644index 00000000000..c906dedc7e6--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/autoGrants.ts@@ -0,0 +1,143 @@+import {+ getShareAgentEnabledToolIds,+ type ShareAgentToolSource,+} from '@lobechat/builtin-tools/agentShare';+import { resolveShareToolGrants } from '@lobechat/const';+import { type AgentPluginEntry, getActivePluginIds, getOptedInPluginIds } from '@lobechat/types';++import type { AgentShareConfig } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { listShareActivatableExtensionIds } from '@/server/services/agentShare/activatableExtensions';+import { listShareGrantableSkills } from '@/server/services/agentShare/grantableSkills';++import type { AgentShareGate } from './types';++/**+ * `shareConfig` with `autoGrantAgentTools` resolved into plain grants: every+ * tool the Agent turns on and every skill it can load, minus what the creator+ * declined. An identifier that already has an explicit grant keeps it, so a+ * grant narrowed to some APIs is never widened.+ *+ * Returns `shareConfig` unchanged when the switch is off.+ */+export const applyShareAutoAgentGrants = <T extends AgentShareConfig>(+ shareConfig: T,+ agent: Pick<ShareAgentToolSource, 'activatableExtensionIds' | 'chatConfig' | 'plugins'> & {+ skillIds: string[];+ },+): T => {+ if (!shareConfig.autoGrantAgentTools) return shareConfig;++ const declined = new Set(shareConfig.declinedGrantIds ?? []);+ const toolGrants = shareConfig.toolGrants ?? [];+ const granted = resolveShareToolGrants(toolGrants);+ const skillGrants = shareConfig.skillGrants ?? [];+ const grantedSkills = new Set(skillGrants);++ return {+ ...shareConfig,+ skillGrants: [+ ...skillGrants,+ ...agent.skillIds.filter((id) => !grantedSkills.has(id) && !declined.has(id)),+ ],+ toolGrants: [+ ...toolGrants,+ ...getShareAgentEnabledToolIds(agent)+ .filter((id) => !granted.has(id) && !declined.has(id))+ .map((identifier) => ({ identifier })),+ ],+ };+};++/**+ * The run's resolved config collapses `plugins` to pinned ids, so the `auto`+ * and `disabled` entries the shared rule reads are rebuilt from what the+ * pipeline captured off the row before that collapse.+ */+const toPluginEntries = ({+ autoSkillIds,+ disabledPluginIds,+ plugins,+}: ShareAutoGrantAgent): AgentPluginEntry[] => {+ const pinnedPluginIds = getActivePluginIds(plugins);+ const pinned = new Set(pinnedPluginIds);+ return [+ ...pinnedPluginIds,+ ...autoSkillIds+ .filter((identifier) => !pinned.has(identifier))+ .map((identifier) => ({ identifier, mode: 'auto' as const })),+ ...disabledPluginIds.map((identifier) => ({ identifier, mode: 'disabled' as const })),+ ];+};++/** The run's Agent, as the pipeline holds it after resolving its config. */+export interface ShareAutoGrantAgent {+ /** `auto` plugin entries, captured before the pinned-id collapse. */+ autoSkillIds: string[];+ chatConfig?: ShareAgentToolSource['chatConfig'];+ /** `disabled` plugin entries, captured before the pinned-id collapse. */+ disabledPluginIds: string[];+ /** The resolved config's `plugins`, already collapsed to pinned ids. */+ plugins?: AgentPluginEntry[];+}++/**+ * The gate a visitor run executes under, with `autoGrantAgentTools` resolved+ * against the run's own Agent config.+ *+ * Resolved once, right after the Agent config and before anything reads the+ * grants (tool discovery, the tool-set gate, the skill pool, the dispatch-time+ * marker), so every layer sees the same grants. Nothing is written back: a+ * tool the Agent turns on later is granted on its next run, and one it turns+ * off is gone from the next run.+ */+export const resolveShareAutoAgentGrants = async (+ gate: AgentShareGate,+ {+ agent,+ db,+ listLobehubSkillProviderIds,+ userId,+ workspaceId,+ }: {+ agent: ShareAutoGrantAgent;+ db: LobeChatDatabase;+ /** The creator's LobeHub connections, which only the Market knows. */+ listLobehubSkillProviderIds?: () => Promise<string[]>;+ userId: string;+ workspaceId?: string;+ },+): Promise<AgentShareGate> => {+ if (!gate.shareConfig.autoGrantAgentTools) return gate;++ const plugins = toPluginEntries(agent);+ const [skills, connectedExtensionIds] = await Promise.all([+ listShareGrantableSkills({+ agentConfig: { chatConfig: agent.chatConfig, plugins },+ agentId: gate.agentId,+ canExecuteOnDevice: gate.canUseDevice,+ db,+ userId,+ workspaceId,+ }),+ listShareActivatableExtensionIds({+ agentId: gate.agentId,+ db,+ listLobehubSkillProviderIds,+ userId,+ workspaceId,+ }),+ ]);++ return {+ ...gate,+ shareConfig: applyShareAutoAgentGrants(gate.shareConfig, {+ // An opted-in extension still counts when its source was not listed+ // (say the Market lookup failed); the run's tool set drops a missing one.+ activatableExtensionIds: [...connectedExtensionIds, ...getOptedInPluginIds(plugins)],+ chatConfig: agent.chatConfig,+ plugins,+ skillIds: skills.map((skill) => skill.identifier),+ }),+ };+};diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex e882e764401..539e318f61b 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -822,6 +822,16 @@ export class MarketService {}}+ /** The provider ids of the user's LobeHub Skills connections, without listing their tools. */+ async listLobehubSkillProviderIds(): Promise<string[]> {+ const { connections } = await this.market.connect.listConnections({+ signal: AbortSignal.timeout(LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS),+ });+ return (connections ?? [])+ .map((connection) => (connection as { providerId?: string }).providerId)+ .filter((providerId): providerId is string => !!providerId);+ }+/*** Fetch LobeHub Skills manifests from Market API* Gets user's connected skills and builds tool manifests for agent executiondiff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 19342ae4e83..26b63277b3c 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -714,6 +714,8 @@"channel.wecom.secret": "Secret","channel.wecom.secretHint": "The bot's long-connection Secret. A bot can be connected in only one place at a time: saving here takes over a connection it has elsewhere, and connecting it elsewhere later disconnects it here.","share.entry": "Share this Agent",+ "share.settings.autoGrant.desc": "Visitors get every tool and skill turned on in this Agent, including ones you turn on later. Anything you untick below stays closed.",+ "share.settings.autoGrant.title": "Open new Agent tools and skills automatically","share.settings.device.desc": "Choose who may run this Agent on your execution environment, for example to read files or run commands. Local CLI Agents such as Claude Code and Codex run only there, so other visitors can’t use them. Chatting with the Agent doesn’t include device access.","share.settings.device.title": "Device access","share.settings.device.who": "Who can use your device",@@ -820,6 +822,7 @@"share.settings.profile.title": "Public profile","share.settings.profile.unsaved": "You have unsaved changes. Visitors will only see them after you save.","share.settings.profile.upToDate": "Visitors see the saved content.",+ "share.settings.skills.autoGranted": "Open automatically because this Agent can use it","share.settings.skills.availableGroup": "Not granted · {{count}}","share.settings.skills.desc": "Only the skills you tick here can be loaded during a visitor run. A skill you grant runs on your account, with whatever its instructions say.","share.settings.skills.empty": "This Agent has no skills that can be granted to visitors.",@@ -836,6 +839,7 @@"share.settings.tools.apiNotAvailableToVisitors": "This action is never available to visitors in a shared run.","share.settings.tools.apiWritesOwnerData": "Visitors can never write to your memory — this action stays off in shared runs.","share.settings.tools.apiWritesOwnerDocuments": "Visitors can never delete or copy your documents or change their load rules — this action stays off in shared runs.",+ "share.settings.tools.autoGranted": "Open automatically because it’s turned on in this Agent","share.settings.tools.availableGroup": "Not granted · {{count}}","share.settings.tools.configureApis": "Choose which APIs visitors can call","share.settings.tools.desc": "Only the tools you tick here can be called during a visitor run. Tools that could reach your device or local files are never offered.",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex a6d0ed5b7e2..0d7e2a29e59 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -714,6 +714,8 @@"channel.wecom.secret": "Secret","channel.wecom.secretHint": "机器人的长连接 Secret。同一个机器人同一时间只能接入一处:在这里保存会接管它在别处的连接,之后在别处接入也会让这里断开。","share.entry": "分享此助手",+ "share.settings.autoGrant.desc": "开启后,访客能使用助手里已开启的全部工具和技能,包括以后新开启的;你在下方取消勾选的不会开放。",+ "share.settings.autoGrant.title": "自动开放助手新开启的工具和技能","share.settings.device.desc": "设定哪些人可以在你的执行环境上运行这个助手,例如读取文件、执行命令。Claude Code、Codex 等本地 CLI 助手只能在这里运行,其他访客无法使用。能和助手对话不代表有设备权限。","share.settings.device.title": "设备权限","share.settings.device.who": "谁可以使用你的设备",@@ -820,6 +822,7 @@"share.settings.profile.title": "宣传页内容","share.settings.profile.unsaved": "有未保存的修改,保存后访客才能看到。","share.settings.profile.upToDate": "访客看到的是已保存的内容。",+ "share.settings.skills.autoGranted": "助手可以使用这个技能,已自动开放","share.settings.skills.availableGroup": "未开放 · {{count}}","share.settings.skills.desc": "只有在这里勾选的技能才能在访客运行中被加载。开放出去的技能会在你的账号下运行,并按它自身的指令行事。","share.settings.skills.empty": "这个助手没有可以开放给访客的技能。",@@ -836,6 +839,7 @@"share.settings.tools.apiNotAvailableToVisitors": "该操作在分享运行中始终不对访客开放。","share.settings.tools.apiWritesOwnerData": "访客不能写入你的记忆,该操作在分享运行中始终关闭。","share.settings.tools.apiWritesOwnerDocuments": "访客不能删除、复制你的文档或修改其加载规则,该操作在分享运行中始终关闭。",+ "share.settings.tools.autoGranted": "助手已开启这个工具,已自动开放","share.settings.tools.availableGroup": "未开放 · {{count}}","share.settings.tools.configureApis": "选择访客可调用的接口","share.settings.tools.desc": "只有在这里勾选的工具才能在访客运行中被调用。可能触达你设备或本地文件的工具永远不会出现在列表中。",diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.jsonindex d78d10f8524..4892c9af0d8 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -5,6 +5,7 @@"type": "module","exports": {".": "./src/index.ts",+ "./agentShare": "./src/agentShare.ts","./renders": "./src/renders.ts","./register": "./src/register.ts","./displayControls": "./src/displayControls.ts",diff --git a/packages/builtin-tools/src/agentShare.test.ts b/packages/builtin-tools/src/agentShare.test.tsnew file mode 100644index 00000000000..5907b2086b1--- /dev/null+++ b/packages/builtin-tools/src/agentShare.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest';++import { getShareAgentEnabledToolIds, getShareTurnedOffToolIds } from './agentShare';++describe('getShareTurnedOffToolIds', () => {+ it('adds memory and web browsing when chatConfig switches them off', () => {+ expect(+ getShareTurnedOffToolIds({+ chatConfig: { memory: { enabled: false }, searchMode: 'off' },+ plugins: [{ identifier: 'mcp-x', mode: 'disabled' }],+ }),+ ).toEqual(['mcp-x', 'lobe-user-memory', 'lobe-web-browsing']);+ });++ it('keeps web browsing on when no search mode is stored', () => {+ expect(getShareTurnedOffToolIds({ chatConfig: { memory: { enabled: true } } })).toEqual([]);+ });+});++describe('getShareAgentEnabledToolIds', () => {+ it('counts pinned plugins, runtime-managed tools and on-demand builtins in agent mode', () => {+ const ids = getShareAgentEnabledToolIds({+ chatConfig: { memory: { enabled: true } },+ plugins: ['mcp-pinned'],+ });++ expect(ids).toEqual(+ expect.arrayContaining([+ 'mcp-pinned',+ 'lobe-web-browsing',+ 'lobe-user-memory',+ 'lobe-calculator',+ 'lobe-image-generation',+ ]),+ );+ });++ it('counts an opted-in extension only in agent mode with automatic activation', () => {+ const plugins = [{ identifier: 'mcp-auto', mode: 'auto' as const }];++ expect(getShareAgentEnabledToolIds({ plugins })).toContain('mcp-auto');+ expect(+ getShareAgentEnabledToolIds({ chatConfig: { skillActivateMode: 'manual' }, plugins }),+ ).not.toContain('mcp-auto');+ expect(+ getShareAgentEnabledToolIds({ chatConfig: { toolMode: 'chat' }, plugins }),+ ).not.toContain('lobe-calculator');+ });++ it('limits extensions to the activatable list when one is given', () => {+ expect(+ getShareAgentEnabledToolIds({+ activatableExtensionIds: [],+ plugins: [{ identifier: 'mcp-auto', mode: 'auto' }],+ }),+ ).not.toContain('mcp-auto');+ });++ it('counts a connected extension the Agent has no entry for, as its tools page does', () => {+ const ids = getShareAgentEnabledToolIds({+ activatableExtensionIds: ['mcp-connected', 'mcp-off'],+ plugins: [{ identifier: 'mcp-off', mode: 'disabled' }],+ });++ expect(ids).toContain('mcp-connected');+ expect(ids).not.toContain('mcp-off');+ expect(+ getShareAgentEnabledToolIds({+ activatableExtensionIds: ['mcp-connected'],+ chatConfig: { skillActivateMode: 'manual' },+ }),+ ).not.toContain('mcp-connected');+ });++ it('drops what the Agent turned off, skills and tools visitors can never use', () => {+ const ids = getShareAgentEnabledToolIds({+ chatConfig: { searchMode: 'off' },+ plugins: [+ { identifier: 'lobe-calculator', mode: 'disabled' },+ 'skill-pinned',+ 'lobe-local-system',+ ],+ skillIds: ['skill-pinned'],+ });++ expect(ids).not.toContain('lobe-calculator');+ expect(ids).not.toContain('lobe-web-browsing');+ expect(ids).not.toContain('lobe-user-memory');+ expect(ids).not.toContain('skill-pinned');+ expect(ids).not.toContain('lobe-local-system');+ });+});diff --git a/packages/builtin-tools/src/agentShare.ts b/packages/builtin-tools/src/agentShare.tsnew file mode 100644index 00000000000..4253590855b--- /dev/null+++ b/packages/builtin-tools/src/agentShare.ts@@ -0,0 +1,138 @@+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';+import { MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';+import {+ type AgentPluginEntry,+ getActivePluginIds,+ getDisabledPluginIds,+ getOptedInPluginIds,+ type LobeAgentChatConfig,+ resolveToolMode,+} from '@lobechat/types';++import {+ AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,+ alwaysOnToolIds,+ builtinTools,+ defaultToolIds,+ isAgentShareAllowedBuiltinIdentifier,+ isBuiltinToolIdentifier,+ isOnDemandBuiltinTool,+ runtimeManagedToolIds,+} from './index';++/**+ * Whether a share can grant `identifier` to visitors at all: the builtin+ * allowlist admits it and no data rule blocks it outright. Non-builtin+ * identifiers (MCP servers, connections, plugins) always pass; the creator's+ * grant alone governs them.+ */+export const isShareGrantableToolIdentifier = (identifier: string): boolean =>+ isAgentShareAllowedBuiltinIdentifier(identifier) &&+ !AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(identifier);++/**+ * Builtins the share picker always lists, whether or not the Agent pinned+ * them: the runtime-managed tools, plus Agent Documents, whose share grant+ * doubles as its runtime opt-in.+ */+export const runtimeManagedShareCandidateToolIds: string[] = [+ ...runtimeManagedToolIds,+ AgentDocumentsIdentifier,+].filter((identifier) => isShareGrantableToolIdentifier(identifier));++export interface ShareAgentToolSource {+ /**+ * The creator's connected extensions (MCP servers, connections, installed+ * plugins) the model could activate. In agent mode an extension with no+ * `plugins` entry is on (`getConnectorMode`), so every listed one counts+ * unless the Agent turned it off. Omitted, only opted-in extensions count.+ */+ activatableExtensionIds?: string[];+ chatConfig?: Pick<+ LobeAgentChatConfig,+ 'enableAgentMode' | 'memory' | 'searchMode' | 'skillActivateMode' | 'toolMode'+ > | null;+ plugins?: AgentPluginEntry[];+ /**+ * The Agent's grantable skills. Pinning a skill writes its id into the same+ * `plugins` list, so these are subtracted: skills are granted through+ * `skillGrants`, never as tools.+ */+ skillIds?: string[];+}++/**+ * Tools the Agent's 工具与连接 page shows as turned off. Most record that as a+ * `disabled` plugin entry, but memory and web browsing are switched through+ * chatConfig instead (`memory.enabled`, `searchMode: 'off'`), so their plugin+ * list carries no entry.+ */+export const getShareTurnedOffToolIds = ({+ chatConfig,+ plugins,+}: Pick<ShareAgentToolSource, 'chatConfig' | 'plugins'>): string[] => [+ ...getDisabledPluginIds(plugins),+ ...(chatConfig?.memory?.enabled ? [] : [MemoryIdentifier]),+ ...((chatConfig?.searchMode || 'auto') === 'off' ? [WebBrowsingManifest.identifier] : []),+];++/**+ * The tools a visitor may use: pinned plugins plus the runtime-managed+ * builtins the picker always lists, minus skills.+ */+export const getShareToolCandidateIds = (pluginIds: string[], skillIds: string[] = []): string[] =>+ Array.from(new Set([...pluginIds, ...runtimeManagedShareCandidateToolIds])).filter(+ (toolId) => !skillIds.includes(toolId),+ );++/**+ * Tools the Agent's 工具与连接 page shows as turned on, limited to what a share+ * can grant. Both the share settings (default grants and the pending prompt)+ * and the server's automatic grants (`autoGrantAgentTools`) read this, so the+ * creator sees exactly what visitors get.+ *+ * - Pinned plugins and the runtime-managed builtins always count.+ * - On-demand tools count only in agent mode with automatic activation, the+ * only mode with an activator: every on-demand builtin and every connected+ * extension is on unless disabled. Without the connected list, an+ * extension counts only when the Agent opted in.+ * - Everything the Agent turned off ({@link getShareTurnedOffToolIds}) is+ * subtracted from both groups.+ *+ * Visitor-specific conditions (the memory permission, device-only MCP+ * servers) are left to the caller: the server gate already applies them to+ * every grant.+ */+export const getShareAgentEnabledToolIds = ({+ activatableExtensionIds,+ chatConfig,+ plugins,+ skillIds = [],+}: ShareAgentToolSource): string[] => {+ const turnedOff = new Set(getShareTurnedOffToolIds({ chatConfig, plugins }));+ const candidates = getShareToolCandidateIds(getActivePluginIds(plugins), skillIds);++ const onDemand: string[] = [];+ if (resolveToolMode(chatConfig) === 'agent' && chatConfig?.skillActivateMode !== 'manual') {+ const notOnDemand = new Set<string>([...alwaysOnToolIds, ...defaultToolIds, ...candidates]);+ const skills = new Set(skillIds);++ onDemand.push(+ ...builtinTools+ .filter((tool) => tool.discoverable !== false)+ .map((tool) => tool.identifier)+ .filter((identifier) => isOnDemandBuiltinTool(identifier) && !notOnDemand.has(identifier)),+ ...(activatableExtensionIds ?? getOptedInPluginIds(plugins)).filter(+ (identifier) =>+ !isBuiltinToolIdentifier(identifier) &&+ !skills.has(identifier) &&+ !notOnDemand.has(identifier),+ ),+ );+ }++ return [...new Set([...candidates, ...onDemand])].filter(+ (identifier) => !turnedOff.has(identifier) && isShareGrantableToolIdentifier(identifier),+ );+};diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex 75108d25f20..617948e2ef1 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -49,6 +49,7 @@ describe('AgentShareModel', () => {description: 'Shareable agent',id: agentId,name: 'Shareable Agent',+ plugins: ['mcp-pinned', { identifier: 'lobe-calculator', mode: 'disabled' }],// Explicit (the column defaults to random words): `create` seeds the// share slug from it, so tests below can assert the exact value.slug: 'shareable-agent',@@ -432,6 +433,7 @@ describe('AgentShareModel', () => {const config: AgentShareConfig = {allowCreatorViewSessions: true,allowReadMemory: true,+ autoGrantAgentTools: true,deviceAccess: 'allowlist',deviceAllowUserIds: ['user_alice'],maxFileStorage: 256 * 1024 * 1024,@@ -696,6 +698,7 @@ describe('AgentShareModel', () => {agentDescription: 'Shareable agent',agentId,agentName: 'Shareable Agent',+ agentPlugins: ['mcp-pinned', { identifier: 'lobe-calculator', mode: 'disabled' }],agentTitle: 'Shareable Agent Title',ownerId: userId,shareConfig: expect.objectContaining({ maxMessagesPerVisitor: 100 }),diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex 4f503a1ee9c..fa8b98f13cf 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -40,6 +40,7 @@ const normalizeAgentShareConfig = (allowCreatorViewSessions:config?.allowCreatorViewSessions ?? DEFAULT_AGENT_SHARE_CONFIG.allowCreatorViewSessions,allowReadMemory: config?.allowReadMemory ?? DEFAULT_AGENT_SHARE_CONFIG.allowReadMemory,+ autoGrantAgentTools: config?.autoGrantAgentTools,/** Left absent like `skillGrants`: absent marks a share whose Agent tools were never reviewed. */declinedGrantIds: config?.declinedGrantIds,demoCases: config?.demoCases ?? [],@@ -631,6 +632,9 @@ export class AgentShareModel {agentAgencyConfig: agents.agencyConfig,agentAvatar: agents.avatar,agentBackgroundColor: agents.backgroundColor,+ // Server-side only: the profile counts the tools `autoGrantAgentTools`+ // opens from the Agent's own tool settings.+ agentChatConfig: agents.chatConfig,agentDescription: agents.description,agentId: agentShares.agentId,// Model identity is for a server-side capability lookup only (what@@ -638,6 +642,7 @@ export class AgentShareModel {agentModel: agents.model,agentName: agents.name,agentOpeningQuestions: agents.openingQuestions,+ agentPlugins: agents.plugins,agentProvider: agents.provider,agentSlug: agents.slug,agentTags: agents.tags,diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex ec1bb95e488..1b03c060cba 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -18,11 +18,23 @@ export interface AgentShareConfig {* a shared conversation. Defaults to `false`.*/allowReadMemory?: boolean;+ /**+ * Whether visitors also get every tool and skill the Agent currently turns+ * on, beyond the explicit {@link toolGrants} / {@link skillGrants}. Resolved+ * per visitor run from the Agent config (`withShareAutoAgentGrants`), never+ * persisted as grants, so a tool added to the Agent later is open to+ * visitors without the creator revisiting the share, and one turned off on+ * the Agent leaves with it. {@link declinedGrantIds} still keeps an+ * identifier closed. Absent reads as off.+ */+ autoGrantAgentTools?: boolean;/*** Tool and skill identifiers the creator chose NOT to grant: dismissed from* the "new on this Agent" prompt, or unticked in a picker. Grants nothing and- * revokes nothing — the server gate never reads it. It only stops the share- * settings from offering these identifiers again as newly added to the Agent.+ * revokes nothing explicit — the server gate reads it only to keep these+ * identifiers out of {@link autoGrantAgentTools}. Otherwise it only stops the+ * share settings from offering these identifiers again as newly added to the+ * Agent.* Absent on shares created before the prompt existed, so their ungranted* Agent tools surface once for review instead of being granted silently.*/diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 3298ee53e76..b6b5ae57dd4 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -924,6 +924,9 @@ export default {'channel.statusStarting': 'Starting','share.entry': 'Share this Agent',+ 'share.settings.autoGrant.desc':+ 'Visitors get every tool and skill turned on in this Agent, including ones you turn on later. Anything you untick below stays closed.',+ 'share.settings.autoGrant.title': 'Open new Agent tools and skills automatically','share.settings.device.desc':'Choose who may run this Agent on your execution environment, for example to read files or run commands. Local CLI Agents such as Claude Code and Codex run only there, so other visitors can’t use them. Chatting with the Agent doesn’t include device access.','share.settings.device.title': 'Device access',@@ -1038,10 +1041,12 @@ export default {'share.settings.permissions.desc':'What a visitor’s run may read, and whether you can read visitor conversations.','share.settings.permissions.title': 'Permissions',+ 'share.settings.skills.autoGranted': 'Open automatically because this Agent can use it','share.settings.tabs.access': 'Access','share.settings.tabs.profile': 'Public profile','share.settings.tabs.stats': 'Stats','share.settings.title': 'Share Agent',+ 'share.settings.tools.autoGranted': 'Open automatically because it’s turned on in this Agent','share.settings.usage.conversations': 'Topics','share.settings.usage.conversationsHint': 'Topics created by visitors through this share.','share.settings.usage.desc': 'What this share has attracted, and what it has cost you.',