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): let visitors use the Agent's execution environment (#23240)

YuTengjinge5dc9e6f9bb1
diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
index 875fbff7ac7..5bba58e3fb7 100644
--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
@@ -411,12 +411,12 @@ describe('shareChatRouter', () => {
expect.objectContaining({
// Agent id comes from the share record, not client input.
agentId: share.agentId,
- shareGate: {
+ shareGate: expect.objectContaining({
agentId: share.agentId,
shareConfig: share.shareConfig,
shareId: share.shareId,
visitorUserId: VISITOR,
- },
+ }),
}),
);
});
diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.ts
index f1376d99c5c..f98701c432a 100644
--- a/apps/server/src/routers/lambda/agentShare.ts
+++ b/apps/server/src/routers/lambda/agentShare.ts
@@ -1,6 +1,7 @@
import { builtinSkills } from '@lobechat/builtin-skills';
import {
AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,
+ AGENT_SHARE_DEVICE_ALLOW_EMAILS_LIMIT,
AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT,
} from '@lobechat/const';
import { assembleSkillPool } from '@lobechat/mecha';
@@ -65,6 +66,16 @@ export const agentShareConfigSchema = z
)
.max(20)
.optional(),
+ deviceAccess: z.enum(['none', 'all', 'allowlist']).optional(),
+ /**
+ * Normalized to lower case before the duplicate check, because the
+ * runtime match against the visitor's account email is case-insensitive.
+ */
+ deviceAllowEmails: z
+ .array(z.string().trim().toLowerCase().pipe(z.email()))
+ .max(AGENT_SHARE_DEVICE_ALLOW_EMAILS_LIMIT)
+ .refine((emails) => new Set(emails).size === emails.length, 'Duplicate email')
+ .optional(),
featuredWorkIds: z
.array(z.string().trim().min(1))
.max(100)
diff --git a/apps/server/src/routers/lambda/shareChat/runScope.test.ts b/apps/server/src/routers/lambda/shareChat/runScope.test.ts
new file mode 100644
index 00000000000..f5f6f975b76
--- /dev/null
+++ b/apps/server/src/routers/lambda/shareChat/runScope.test.ts
@@ -0,0 +1,51 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createShareRunScope } from './runScope';
+
+const { resolveDeviceAccess } = vi.hoisted(() => ({ resolveDeviceAccess: vi.fn() }));
+
+vi.mock('@/database/models/message', () => ({ MessageModel: vi.fn() }));
+vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn().mockImplementation(function () {
+ return { getUserSettings: vi.fn().mockResolvedValue({}) };
+ }),
+}));
+vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));
+vi.mock('@/server/services/aiAgent/shareGate/deviceAccess', () => ({
+ resolveShareVisitorDeviceAccess: resolveDeviceAccess,
+}));
+
+const db = {} as any;
+const share = {
+ agentId: 'agt_shared',
+ ownerId: 'owner',
+ shareConfig: { deviceAccess: 'all', toolGrants: [] },
+ shareId: 'share-1',
+ workspaceId: null,
+} as any;
+
+describe('createShareRunScope', () => {
+ beforeEach(() => resolveDeviceAccess.mockReset());
+
+ it.each([true, false])(
+ "carries the share's device decision for this visitor (%s) on the gate",
+ async (granted) => {
+ resolveDeviceAccess.mockResolvedValue(granted);
+
+ const { dispatchContext, shareGate } = await createShareRunScope(db, share, 'visitor');
+
+ expect(resolveDeviceAccess).toHaveBeenCalledWith(db, share.shareConfig, 'visitor');
+ expect(shareGate).toEqual({
+ agentId: 'agt_shared',
+ canUseDevice: granted,
+ shareConfig: share.shareConfig,
+ shareId: 'share-1',
+ visitorUserId: 'visitor',
+ });
+ // An intervention continuation is gated by the same decision.
+ expect(dispatchContext.shareGate).toBe(shareGate);
+ },
+ );
+});
diff --git a/apps/server/src/routers/lambda/shareChat/runScope.ts b/apps/server/src/routers/lambda/shareChat/runScope.ts
index 436b3152edd..1a76ed28ebe 100644
--- a/apps/server/src/routers/lambda/shareChat/runScope.ts
+++ b/apps/server/src/routers/lambda/shareChat/runScope.ts
@@ -4,6 +4,7 @@ import { UserModel } from '@/database/models/user';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';
+import { resolveShareVisitorDeviceAccess } from '@/server/services/aiAgent/shareGate/deviceAccess';
import { type AgentInterventionDispatchContext } from '../aiAgent';
import type { resolveLinkShareOrThrow } from './guards';
@@ -31,6 +32,7 @@ export const createShareRunScope = async (
const shareGate: AgentShareGate = {
agentId: share.agentId,
+ canUseDevice: await resolveShareVisitorDeviceAccess(db, share.shareConfig, visitorUserId),
shareConfig: share.shareConfig,
// See `AgentShareGate.shareId`'s JSDoc — the share instance this run is
// authorized against, and the token every later revalidation compares.
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
index 0b22a4a389d..eadb7278156 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
@@ -440,6 +440,7 @@ describe('AiAgentService.runDeferredInit - parity with the send path', () => {
describe('a share visitor run', () => {
const shareGate = {
agentId: 'agent-1',
+ canUseDevice: false,
shareConfig: { toolGrants: [] },
shareId: 'share-1',
visitorUserId: 'visitor-1',
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorHetero.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorHetero.test.ts
new file mode 100644
index 00000000000..6fe9167e192
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorHetero.test.ts
@@ -0,0 +1,202 @@
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+const { mockCreateOperation, mockGetAgentConfig, mockGetUserSettings, mockMessageCreate } =
+ vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockGetUserSettings: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ }));
+
+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: vi.fn().mockResolvedValue([]),
+ 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(),
+ };
+ }),
+}));
+
+// `UserModel` here is what actually resolves `userTimezone`. Constructed with
+// the userId it was called with, so the test can distinguish "read the
+// creator's settings" from "read the visitor's settings" purely by which id
+// the call site passed in.
+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(),
+ };
+ }),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ 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 the forced-headless test below can drive execAgent with a bare mock db.
+vi.mock('../shareVisitorAbuseGuards', () => ({
+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ reserveShareVisitorTurn: vi.fn().mockResolvedValue({ id: 'msg-1' }),
+}));
+
+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 visitors and heterogeneous agents', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockGetUserSettings.mockResolvedValue({});
+ mockGetAgentConfig.mockResolvedValue({
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: '',
+ });
+ });
+
+ // The hetero dispatch path signs its gateway token for the run's user (the
+ // creator) and registers no visitor stream owner, so a share's device grant
+ // must not open it: the visitor would receive creator account access.
+ it('rejects a Claude Code Agent even when the share grants device access', async () => {
+ const service = new AiAgentService({} as any, 'creator-1');
+
+ await expect(
+ service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Hello',
+ shareGate: {
+ agentId: 'agent-1',
+ canUseDevice: true,
+ shareConfig: { deviceAccess: 'all', toolGrants: [] },
+ shareId: 'share-1',
+ visitorUserId: 'visitor-1',
+ },
+ }),
+ ).rejects.toMatchObject({ message: 'ShareHeterogeneousAgentUnsupported' });
+
+ expect(mockMessageCreate).not.toHaveBeenCalled();
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts b/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
index 4c2a59f2762..8da947c8f03 100644
--- a/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
+++ b/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
@@ -72,11 +72,22 @@ describe('resolveDeviceAccessPolicy', () => {
expect(
resolveDeviceAccessPolicy({
botContext: baseBotContext({ isDeviceTrusted: true }),
- shareVisitor: true,
+ shareVisitor: { canUseDevice: false },
}),
).toEqual({ canUseDevice: false, reason: 'share-visitor' });
});
+ it('grants devices to a shared-agent visitor only through the share grant', () => {
+ expect(resolveDeviceAccessPolicy({ shareVisitor: { canUseDevice: true } })).toEqual({
+ canUseDevice: true,
+ reason: 'share-visitor-granted',
+ });
+ expect(resolveDeviceAccessPolicy({ shareVisitor: { canUseDevice: false } })).toEqual({
+ canUseDevice: false,
+ reason: 'share-visitor',
+ });
+ });
+
describe('personal-scope bot platforms', () => {
it('grants device access on WeChat even when isOwner cannot be computed', () => {
// WeChat's schema has no `userId` field, so `isOwner` is structurally
diff --git a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts b/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
index 316492b961a..44a665ac322 100644
--- a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
+++ b/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
@@ -30,12 +30,20 @@ export type DeviceAccessReason =
*/
| 'bot-owner-not-configured'
/**
- * Shared-agent visitor conversation — DENY device tools. The run executes
- * under the creator's identity, so device access would hand the visitor the
- * creator's machines; hetero targets degrade to sandbox, native device tools
- * to plain chat.
+ * Shared-agent visitor conversation the share does not grant device access
+ * (`shareConfig.deviceAccess`) — DENY device tools. The run executes under
+ * the creator's identity, so device access would hand the visitor the
+ * creator's machines; hetero agents are refused, native device tools
+ * degrade to plain chat.
*/
- | 'share-visitor';
+ | 'share-visitor'
+ /**
+ * Shared-agent visitor the creator explicitly granted the Agent's execution
+ * environment (`shareConfig.deviceAccess` = `all`, or `allowlist` with the
+ * visitor listed). The device is still the Agent's configured one; the
+ * visitor never picks it.
+ */
+ | 'share-visitor-granted';
/**
* Bot platforms whose LobeHub integration is **personal-scope-only at the
@@ -62,8 +70,11 @@ const PERSONAL_SCOPE_BOT_PLATFORMS = new Set<string>(['wechat']);
export interface DeviceAccessPolicyInput {
/** Undefined when the caller is a first-party UI (web / desktop / mobile). */
botContext?: ChatTopicBotContext;
- /** True when the run serves a shared-agent visitor (share gate present). */
- shareVisitor?: boolean;
+ /**
+ * Present when the run serves a shared-agent visitor (share gate present);
+ * `canUseDevice` is the share's device grant resolved for this visitor.
+ */
+ shareVisitor?: { canUseDevice: boolean };
}
export interface DeviceAccessPolicyOutput {
@@ -87,10 +98,13 @@ export const resolveDeviceAccessPolicy = (
): DeviceAccessPolicyOutput => {
const { botContext, shareVisitor } = input;
- // Checked before every trust branch: a share visitor is never allowed to
- // reach the creator's devices, regardless of how the request arrived.
+ // Checked before every trust branch: a share visitor reaches the creator's
+ // devices only through the share's own grant, regardless of how the
+ // request arrived.
if (shareVisitor) {
- return { canUseDevice: false, reason: 'share-visitor' };
+ return shareVisitor.canUseDevice
+ ? { canUseDevice: true, reason: 'share-visitor-granted' }
+ : { canUseDevice: false, reason: 'share-visitor' };
}
if (!botContext) {
diff --git a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts
index 52c91ca3937..71eea7b1762 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 { resolveShareVisitorDeviceAccess } from '../shareGate/deviceAccess';
import type { ExecRunContext } from '../types';
import { type OperationInitDeps, runOperationInit } from './operationInit';
import { resolveOperationInitSlots } from './operationInitSlots';
@@ -50,6 +51,11 @@ const resolveShareGate = async (
return {
agentId: share.agentId,
+ canUseDevice: await resolveShareVisitorDeviceAccess(
+ deps.db,
+ share.shareConfig,
+ shareVisitor.visitorUserId,
+ ),
shareConfig: share.shareConfig,
shareId: share.shareId,
visitorUserId: shareVisitor.visitorUserId,
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 348c7deb746..2132a9f94cf 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -251,6 +251,9 @@ export const startOperation = async (
// actual chokepoint) via `isShareBlockedDataToolCall` — see
// `shareGate/dispatch.ts`.
allowReadMemory: shareGate.shareConfig.allowReadMemory,
+ // Re-applied at dispatch by the device-builtin and device-only MCP
+ // gates, so they decide exactly as the assembled tool set did.
+ canUseDevice: shareGate.canUseDevice,
// Mirrors `shareConfig.toolGrants` so tool runtimes resolved
// outside `toolManifestMap` (e.g. `activateSkill`, which queries
// builtin/DB skills by name) can enforce the same allowlist.
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 1eef8da4f48..c532a9f9f98 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -550,10 +550,14 @@ export const setupTurn = async (
// Share-visitor fail-closed gate — reject a heterogeneous (Claude Code /
// Codex / …) agent BEFORE any topic/message row is written. Heterogeneous
- // agents are not available for shared visitor runs. Checked here (using the
- // agent-level config, before any topic-pinned model override) rather than
- // at the later hetero-detection site (`isHeteroAgent`) so it runs ahead of
- // ALL row creation, not just the message rows.
+ // agents are not available for shared visitor runs, even when the share
+ // grants device access (`shareGate.canUseDevice`): the hetero dispatch path
+ // signs its gateway token for the run's user (the creator) and registers no
+ // visitor stream owner, so opening it would hand the visitor creator account
+ // access. Checked here (using the agent-level config, before any
+ // topic-pinned model override) rather than at the later hetero-detection
+ // site (`isHeteroAgent`) so it runs ahead of ALL row creation, not just the
+ // message rows.
if (shareGate && (heterogeneousProvider?.type || isHeterogeneousAgentModelId(model))) {
throw new TRPCError({
code: 'FORBIDDEN',
@@ -818,7 +822,7 @@ export const setupTurn = async (
}
// Re-assert the share restriction after topic overrides are applied.
- // Heterogeneous agents are not available for shared visitor runs.
+ // Heterogeneous agents are not available for shared visitor runs (see above).
if (shareGate && isHeterogeneousAgentModelId(model)) {
throw new TRPCError({
code: 'FORBIDDEN',
@@ -874,7 +878,7 @@ export const setupTurn = async (
// chat) and stops the device list from leaking into the LLM context.
const { canUseDevice, reason: deviceAccessReason } = resolveDeviceAccessPolicy({
botContext,
- shareVisitor: !!shareGate,
+ shareVisitor: shareGate ? { canUseDevice: shareGate.canUseDevice } : undefined,
});
log(
'execAgent: device access policy → canUseDevice=%s, reason=%s, hasBotContext=%s',
diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.md
index acd24543bac..07c0672b6d9 100644
--- a/apps/server/src/services/aiAgent/shareGate/README.md
+++ b/apps/server/src/services/aiAgent/shareGate/README.md
@@ -71,7 +71,21 @@ tool does not ship):
through `deviceGateway` to the creator's own registered physical
device(s). A visitor executing arbitrary commands or driving a live
browser session on the CREATOR's own machine is a far larger blast radius
- than any single data store.
+ than any single data store, so they are never offered through the tool
+ picker. They are granted only by `shareConfig.deviceAccess` (`all`, or
+ `allowlist` matching the visitor's verified email), an explicit creator
+ choice resolved once per gate by `resolveShareVisitorDeviceAccess` into
+ `canUseDevice` and re-applied at dispatch. The same grant admits
+ device-only MCP servers (which still need their own tool grant). The device
+ is always the Agent's configured execution environment; a visitor never
+ picks it, and project directories stay denied. The grant covers the
+ engine's device tools (`DEVICE_TOOL_IDENTIFIERS`, so computer use too)
+ except the `lobe-remote-device` picker: with it the visitor's model could
+ list and activate the creator's other machines, so it stays default-denied
+ even under the grant. Heterogeneous agents
+ (Claude Code / Codex) stay unavailable even with the grant: their dispatch
+ path signs the gateway token for the creator and registers no visitor
+ stream owner, so `setupTurn` rejects them for every share run.
- `lobe-web-onboarding`: reads and WRITES the creator's own onboarding
`SOUL.md` document and persona.
@@ -92,11 +106,12 @@ tool does not ship):
- Device-only MCP servers (stdio, or an HTTP endpoint on localhost / a
private network): not builtin identifiers, so the allowlist above never
- sees them, but a visitor run must still never reach them — the server can
- only call them by tunneling to the creator's online desktop app (or, with
- no device gateway, by spawning the binary on the server itself).
- `applyShareGateToToolSet` drops them regardless of `toolGrants`, and
- `ToolExecutionService.executeMCPTool` refuses the dispatch.
+ sees them — the server can only call them by tunneling to the creator's
+ online desktop app (or, with no device gateway, by spawning the binary on
+ the server itself), exactly as it would for the creator. Without the
+ share's device grant, `applyShareGateToToolSet` drops them regardless of
+ `toolGrants` and `ToolExecutionService.executeMCPTool` refuses the
+ dispatch; with it, they follow their ordinary `toolGrants` entry.
## Allowed builtins with general reach
@@ -122,7 +137,8 @@ absence of a known exploit.
- `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
+ Never picked by the owner: any tool grant implies it, and so does the
+ device grant (Computer Use is discoverable, not enabled), 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
diff --git a/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts b/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts
new file mode 100644
index 00000000000..f100df1fa8c
--- /dev/null
+++ b/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { resolveShareVisitorDeviceAccess } from './deviceAccess';
+
+vi.mock('@/database/models/user', () => ({ UserModel: { findById: vi.fn() } }));
+
+const db = {} as LobeChatDatabase;
+const findById = vi.mocked(UserModel.findById);
+
+const visitor = (email: string | null, emailVerified: boolean) =>
+ findById.mockResolvedValue({ email, emailVerified, id: 'visitor-1' } as any);
+
+describe('resolveShareVisitorDeviceAccess', () => {
+ beforeEach(() => findById.mockReset());
+
+ it('denies by default and under `none`', async () => {
+ expect(await resolveShareVisitorDeviceAccess(db, {}, 'visitor-1')).toBe(false);
+ expect(await resolveShareVisitorDeviceAccess(db, { deviceAccess: 'none' }, 'visitor-1')).toBe(
+ false,
+ );
+ expect(findById).not.toHaveBeenCalled();
+ });
+
+ it('grants every visitor under `all` without a user lookup', async () => {
+ expect(await resolveShareVisitorDeviceAccess(db, { deviceAccess: 'all' }, 'visitor-1')).toBe(
+ true,
+ );
+ expect(findById).not.toHaveBeenCalled();
+ });
+
+ it('grants a listed visitor whose email is verified, case-insensitively', async () => {
+ visitor('[email protected]', true);
+ expect(
+ await resolveShareVisitorDeviceAccess(
+ db,
+ { deviceAccess: 'allowlist', deviceAllowEmails: ['[email protected]'] },
+ 'visitor-1',
+ ),
+ ).toBe(true);
+ });
+
+ it('denies a listed email that is not verified', async () => {
+ visitor('[email protected]', false);
+ expect(
+ await resolveShareVisitorDeviceAccess(
+ db,
+ { deviceAccess: 'allowlist', deviceAllowEmails: ['[email protected]'] },
+ 'visitor-1',
+ ),
+ ).toBe(false);
+ });
+
+ it('denies an unlisted visitor and an empty allowlist', async () => {
+ visitor('[email protected]', true);
+ expect(
+ await resolveShareVisitorDeviceAccess(
+ db,
+ { deviceAccess: 'allowlist', deviceAllowEmails: ['[email protected]'] },
+ 'visitor-1',
+ ),
+ ).toBe(false);
+ expect(
+ await resolveShareVisitorDeviceAccess(
+ db,
+ { deviceAccess: 'allowlist', deviceAllowEmails: [] },
+ 'visitor-1',
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts b/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts
new file mode 100644
index 00000000000..111066c2e59
--- /dev/null
+++ b/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts
@@ -0,0 +1,73 @@
+import debug from 'debug';
+
+import { UserModel } from '@/database/models/user';
+import type { AgentShareConfig } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { DEVICE_TOOL_IDENTIFIERS, REMOTE_DEVICE_TOOL_IDENTIFIERS } from '../deviceToolRegistry';
+
+const log = debug('lobe-server:share-gate:device-access');
+
+/**
+ * Builtin tools that act on the agent's execution device. They are not picked
+ * in the share tool picker: `shareConfig.deviceAccess` is their grant, the same
+ * way an IM bot's `devicePolicy` governs device tools without a per-tool list.
+ *
+ * Derived from the engine's device-tool catalog so a new device tool follows
+ * the grant, minus the remote-device picker (`listOnlineDevices` /
+ * `activateDevice`): a visitor runs only on the device the Agent's execution
+ * environment routes to, never one the visitor's model picks from the
+ * creator's other machines. Not being on the share allowlist, the picker stays
+ * default-denied at assembly and dispatch.
+ */
+export const SHARE_DEVICE_BUILTIN_IDENTIFIERS: ReadonlySet<string> = new Set(
+ [...DEVICE_TOOL_IDENTIFIERS].filter((id) => !REMOTE_DEVICE_TOOL_IDENTIFIERS.has(id)),
+);
+
+export const isShareDeviceBuiltin = (identifier: string) =>
+ SHARE_DEVICE_BUILTIN_IDENTIFIERS.has(identifier);
+
+/**
+ * Whether `visitorUserId` may run on the shared agent's execution environment.
+ *
+ * The only place `shareConfig.deviceAccess` is interpreted; every share-gate
+ * builder calls it so a fresh turn and a deferred init decide alike.
+ *
+ * `allowlist` matches the visitor's account email only when it is verified:
+ * an unverified address is a claim anyone can make at sign-up, and the grant
+ * hands over the creator's machine. Deployments that never verify email
+ * therefore fail closed under `allowlist`; `all` still works there.
+ */
+export const resolveShareVisitorDeviceAccess = async (
+ db: LobeChatDatabase,
+ shareConfig: Pick<AgentShareConfig, 'deviceAccess' | 'deviceAllowEmails'>,
+ visitorUserId: string,
+): Promise<boolean> => {
+ switch (shareConfig.deviceAccess) {
+ case 'all': {
+ return true;
+ }
+ case 'allowlist': {
+ const allowEmails = shareConfig.deviceAllowEmails;
+ if (!allowEmails?.length) {
+ log('allowlist denied visitor %s: the list is empty', visitorUserId);
+ return false;
+ }
+
+ const visitor = await UserModel.findById(db, visitorUserId);
+ if (!visitor?.email || !visitor.emailVerified) {
+ // The most likely creator complaint ("I listed them but it doesn't
+ // work"), so it gets its own line; never log the address itself.
+ log('allowlist denied visitor %s: no verified account email', visitorUserId);
+ return false;
+ }
+
+ const listed = allowEmails.includes(visitor.email.trim().toLowerCase());
+ if (!listed) log('allowlist denied visitor %s: email not listed', visitorUserId);
+ return listed;
+ }
+ default: {
+ return false;
+ }
+ }
+};
diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
index c0d66f67dce..8bc4632c30f 100644
--- a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
@@ -4,13 +4,16 @@ import {
AgentDocumentsIdentifier,
} from '@lobechat/builtin-tool-agent-documents';
import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';
+import { BrowserIdentifier } from '@lobechat/builtin-tool-browser';
import { CalculatorIdentifier } from '@lobechat/builtin-tool-calculator';
import {
KnowledgeBaseApiName,
KnowledgeBaseIdentifier,
} from '@lobechat/builtin-tool-knowledge-base';
import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
+import { RemoteDeviceIdentifier } from '@lobechat/builtin-tool-remote-device';
import { SkillsApiName, SkillsIdentifier } from '@lobechat/builtin-tool-skills';
import {
AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,
@@ -187,6 +190,30 @@ describe('isShareBlockedBuiltinDispatch', () => {
expect(isShareBlockedBuiltinDispatch({}, CalculatorIdentifier, 'evalExpression')).toBe(true);
});
+ it('decides device builtins by the share device grant alone, not toolGrants', () => {
+ for (const identifier of [BrowserIdentifier, LocalSystemIdentifier]) {
+ expect(
+ isShareBlockedBuiltinDispatch({ toolGrants: [{ identifier }] }, identifier, 'anyApi'),
+ ).toBe(true);
+ expect(isShareBlockedBuiltinDispatch({ canUseDevice: true }, identifier, 'anyApi')).toBe(
+ false,
+ );
+ expect(isShareBlockedDataToolCall({ canUseDevice: true }, identifier, 'anyApi')).toBe(false);
+ expect(isShareBlockedDataToolCall({}, identifier, 'anyApi')).toBe(true);
+ }
+ });
+
+ // The visitor runs on the device the Agent's execution environment routes
+ // to; the picker would let the visitor's model switch to the creator's
+ // other machines.
+ it('blocks the remote-device picker even under the share device grant', () => {
+ for (const apiName of ['listOnlineDevices', 'activateDevice']) {
+ expect(
+ isShareBlockedBuiltinDispatch({ canUseDevice: true }, RemoteDeviceIdentifier, apiName),
+ ).toBe(true);
+ }
+ });
+
it('passes an enabled builtin with no intervention semantics', () => {
expect(
isShareBlockedBuiltinDispatch(
diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.ts
index 9340c77f3bf..abce21bba02 100644
--- a/apps/server/src/services/aiAgent/shareGate/dispatch.ts
+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.ts
@@ -8,6 +8,7 @@ import {
SHARE_VISITOR_ALLOWED_IDENTIFIERS,
} from './allowlist';
import { DATA_TOOL_ACCESS_RULES } from './dataToolRules';
+import { isShareDeviceBuiltin } from './deviceAccess';
import { resolveEffectiveShareToolGrants } from './grants';
import { SUB_AGENT_DISPATCH_APIS } from './subAgentDispatch';
import type { ShareDataToolPermissions } from './types';
@@ -45,6 +46,8 @@ export const isShareBlockedDataToolCall = (
// identifiers are governed by the toolGrants picker, not this allowlist.
if (!isGovernedByBuiltinAllowlist(identifier)) return false;
if (isShareVisitorChannelTool(identifier)) return !isShareVisitorChannelRead(identifier, apiName);
+ // Device builtins: granted by `shareConfig.deviceAccess` alone.
+ if (isShareDeviceBuiltin(identifier)) return !permissions.canUseDevice;
// Default-deny: a known builtin identifier not on the allowlist is blocked
// unconditionally, including any tool registered after this allowlist was
@@ -94,6 +97,9 @@ export const isShareBlockedBuiltinDispatch = (
// A Channel run's history reads only; see `isShareVisitorChannelRead`.
if (isShareVisitorChannelTool(identifier)) return !isShareVisitorChannelRead(identifier, apiName);
+ // Device builtins are granted by `shareConfig.deviceAccess` alone, never by
+ // `toolGrants`; the visitor's own approval mode still applies to them.
+ if (isShareDeviceBuiltin(identifier)) return !agentShare.canUseDevice;
if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;
// The owner's picker must grant this identifier at all (toolset-level or
// naming this specific `apiName`) — a grant scoped to a DIFFERENT api on
diff --git a/apps/server/src/services/aiAgent/shareGate/grants.test.ts b/apps/server/src/services/aiAgent/shareGate/grants.test.ts
index 17ecd128e57..ade31c99586 100644
--- a/apps/server/src/services/aiAgent/shareGate/grants.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/grants.test.ts
@@ -1,5 +1,6 @@
import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
+import { AuvIdentifier } from '@lobechat/builtin-tool-auv';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
import { describe, expect, it } from 'vitest';
@@ -31,6 +32,15 @@ describe('filterPluginsByShareGate', () => {
expect(filterPluginsByShareGate(['web-search'], buildGate({ toolGrants: [] }))).toEqual([]);
});
+ it('keeps a pinned device builtin only under the device grant', () => {
+ const ids = [AuvIdentifier, 'mcp-github'];
+
+ expect(filterPluginsByShareGate(ids, buildGate())).toEqual([]);
+ expect(filterPluginsByShareGate(ids, { ...buildGate(), canUseDevice: true })).toEqual([
+ AuvIdentifier,
+ ]);
+ });
+
it('treats a per-API grant as candidacy for the whole identifier', () => {
// Narrowing down to the specific granted API happens later, in
// `applyShareGateToToolSet`, once the real manifest is known — this pass
@@ -139,6 +149,12 @@ describe('resolveEffectiveShareToolGrants — lobe-activator', () => {
).toBe(false);
});
+ it('implies the activator from the device grant alone', () => {
+ expect(
+ resolveEffectiveShareToolGrants({ canUseDevice: true }).get(LobeActivatorIdentifier),
+ ).toEqual(new Set([ActivatorApiName.activateTools]));
+ });
+
it('never lets a stored activator entry widen the implied scope or stand alone', () => {
const widened = resolveEffectiveShareToolGrants({
toolGrants: [{ identifier: LobeActivatorIdentifier }, { identifier: 'mcp-github' }],
diff --git a/apps/server/src/services/aiAgent/shareGate/grants.ts b/apps/server/src/services/aiAgent/shareGate/grants.ts
index a8c97b18de2..6a095506624 100644
--- a/apps/server/src/services/aiAgent/shareGate/grants.ts
+++ b/apps/server/src/services/aiAgent/shareGate/grants.ts
@@ -10,6 +10,7 @@ import {
} from '@lobechat/const';
import { isGovernedByBuiltinAllowlist } from './allowlist';
+import { isShareDeviceBuiltin } from './deviceAccess';
import type { AgentShareGate, ShareDataToolPermissions } from './types';
/**
@@ -25,7 +26,11 @@ import type { AgentShareGate, ShareDataToolPermissions } from './types';
export const filterPluginsByShareGate = (pluginIds: string[], gate: AgentShareGate): string[] => {
const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);
- return pluginIds.filter((id) => hasShareToolGrant(grants, id));
+ // Device builtins (a pinned Computer Use, say) follow the device grant, not
+ // the tool picker, exactly as `applyShareGateToToolSet` decides them.
+ return pluginIds.filter((id) =>
+ isShareDeviceBuiltin(id) ? !!gate.canUseDevice : hasShareToolGrant(grants, id),
+ );
};
/**
@@ -128,7 +133,9 @@ export const hasShareSkillAuthorization = (permissions: ShareDataToolPermissions
* (`'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,
+ * - `lobe-activator`, implied by ANY tool grant or by the device grant
+ * (`canUseDevice`): Computer Use is discoverable, not enabled by default,
+ * so a device-only share needs it to turn that tool on. 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
@@ -145,7 +152,7 @@ export const resolveEffectiveShareToolGrants = (
const grants = resolveShareToolGrants(permissions.toolGrants);
grants.delete(LobeActivatorIdentifier);
- if (grants.size > 0) {
+ if (grants.size > 0 || permissions.canUseDevice) {
grants.set(LobeActivatorIdentifier, new Set([ActivatorApiName.activateTools]));
}
diff --git a/apps/server/src/services/aiAgent/shareGate/testUtils.ts b/apps/server/src/services/aiAgent/shareGate/testUtils.ts
index dfb4103436e..31652425263 100644
--- a/apps/server/src/services/aiAgent/shareGate/testUtils.ts
+++ b/apps/server/src/services/aiAgent/shareGate/testUtils.ts
@@ -4,6 +4,7 @@ import type { AgentShareGate, ShareGateToolSet } from '.';
export const buildGate = (config: Partial<AgentShareGate['shareConfig']> = {}): AgentShareGate => ({
agentId: 'agent-1',
+ canUseDevice: false,
shareConfig: {
maxTopicsPerVisitor: 5,
maxTurnsPerTopic: 20,
diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
index 353db4747cf..6522f14fcc8 100644
--- a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
@@ -11,17 +11,20 @@ import {
agentShareSystemPrompt,
} from '@lobechat/builtin-tool-agent-documents';
import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';
+import { AuvIdentifier } from '@lobechat/builtin-tool-auv';
import { CalculatorIdentifier } from '@lobechat/builtin-tool-calculator';
import {
LobeAgentApiName,
LobeAgentIdentifier,
systemPromptWithoutSubAgent,
} from '@lobechat/builtin-tool-lobe-agent';
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
import {
MemoryApiName,
MemoryIdentifier,
memoryReadOnlySystemPrompt,
} from '@lobechat/builtin-tool-memory';
+import { RemoteDeviceIdentifier } from '@lobechat/builtin-tool-remote-device';
import {
agentShareSystemPrompt as skillsAgentShareSystemPrompt,
SkillsApiName,
@@ -125,6 +128,36 @@ describe('applyShareGateToToolSet', () => {
]);
});
+ it('keeps device builtins and a granted device-only MCP only under the share device grant', () => {
+ const build = () => {
+ const toolSet = buildToolSet([
+ { apis: [{ name: 'runCommand' }], identifier: LocalSystemIdentifier },
+ { apis: [{ name: 'activateDevice' }], identifier: RemoteDeviceIdentifier },
+ { apis: [{ name: 'read_file' }], identifier: 'mcp-fs', type: 'mcp' },
+ { apis: [{ name: 'query' }], identifier: 'mcp-lan', type: 'mcp' },
+ ]);
+ (toolSet.manifestMap['mcp-fs'] as any).mcpParams = { name: 'mcp-fs', type: 'stdio' };
+ (toolSet.manifestMap['mcp-lan'] as any).mcpParams = {
+ name: 'mcp-lan',
+ type: 'http',
+ url: 'http://192.168.1.20:8000/mcp',
+ };
+ return toolSet;
+ };
+ // The device builtin needs no tool grant; device-only MCPs still do; the
+ // remote-device picker never reaches a visitor.
+ const config = { toolGrants: [{ identifier: 'mcp-fs' }] };
+
+ const denied = build();
+ applyShareGateToToolSet(denied, buildGate(config));
+ expect(denied.enabledToolIds).toEqual([]);
+
+ const granted = build();
+ applyShareGateToToolSet(granted, { ...buildGate(config), canUseDevice: true });
+ expect(granted.enabledToolIds).toEqual([LocalSystemIdentifier, 'mcp-fs']);
+ expect(Object.keys(granted.manifestMap)).toEqual([LocalSystemIdentifier, 'mcp-fs']);
+ });
+
it('collapses the whole set when no tools are enabled', () => {
const toolSet = buildToolSet([
{ apis: [{ name: 'calculate' }], identifier: CalculatorIdentifier },
@@ -777,6 +810,20 @@ describe('applyShareGateToToolSet — lobe-activator', () => {
expect(toolSet.manifestMap[AgentManagementIdentifier]).toBeUndefined();
});
+ it('keeps the activator for a device-only grant so Computer Use can be turned on', () => {
+ // Computer Use is discoverable, not enabled: the visitor model reaches it
+ // only through the activator, even when the share picks no other tool.
+ const toolSet = buildActivatorToolSet();
+ toolSet.manifestMap[AuvIdentifier] = { api: [], identifier: AuvIdentifier } as any;
+
+ applyShareGateToToolSet(toolSet, { ...buildGate(), canUseDevice: true });
+
+ expect(toolSet.enabledToolIds).toEqual([LobeActivatorIdentifier]);
+ expect(Object.keys(toolSet.manifestMap).sort()).toEqual(
+ [AuvIdentifier, LobeActivatorIdentifier].sort(),
+ );
+ });
+
it('drops the activator on a share that grants no tool', () => {
const toolSet = buildActivatorToolSet();
diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.ts
index 199fbc5ba01..45802c0be6d 100644
--- a/apps/server/src/services/aiAgent/shareGate/toolSet.ts
+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.ts
@@ -17,6 +17,7 @@ import {
SHARE_VISITOR_CHANNEL_BLOCKED_APIS,
} from './allowlist';
import { DATA_TOOL_ACCESS_RULES } from './dataToolRules';
+import { isShareDeviceBuiltin } from './deviceAccess';
import { resolveEffectiveShareToolGrants } from './grants';
import { stripSubAgentDispatchApis } from './subAgentDispatch';
import {
@@ -75,7 +76,10 @@ const applyShareGateToDataToolAccess = (toolSet: ShareGateToolSet, gate: AgentSh
* exempted; a share with no configured tools is a plain-chat run).
*/
export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentShareGate): void => {
- const grants = resolveEffectiveShareToolGrants(gate.shareConfig);
+ const grants = resolveEffectiveShareToolGrants({
+ ...gate.shareConfig,
+ canUseDevice: gate.canUseDevice,
+ });
// A tool must clear BOTH gates: the owner's own `toolGrants` picker
// (`grants` — toolset-level OR scoped to at least one API), AND — for
@@ -85,8 +89,10 @@ export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentSh
// they pass straight through to the owner-picker check unaffected — this
// allowlist must never decide their fate, in either direction.
// MCP servers only the creator's machine can reach (stdio / localhost / LAN)
- // never survive, grant or not: dispatching one tunnels to the creator's
- // device under the creator's identity. Decided from the manifest's runtime
+ // survive only when the share grants this visitor the device
+ // (`gate.canUseDevice`), and then still need their own tool grant:
+ // dispatching one tunnels to the creator's device under the creator's
+ // identity. Decided from the manifest's runtime
// `mcpParams` (set for connector manifests by `buildConnectorManifests`),
// the same field `ToolExecutionService.executeMCPTool` dispatches on — which
// also refuses these calls for visitor runs as the unbypassable backstop.
@@ -100,7 +106,10 @@ export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentSh
);
const isAllowed = (id: string) => {
- if (deviceOnlyMcpIds.has(id)) return false;
+ if (deviceOnlyMcpIds.has(id) && !gate.canUseDevice) return false;
+ // Device builtins are granted by `shareConfig.deviceAccess` alone — they
+ // are never picked in the tool picker, like an IM bot's device tools.
+ if (isShareDeviceBuiltin(id)) return gate.canUseDevice;
// Only a Channel run injects this tool; its reads are narrowed below.
if (isShareVisitorChannelTool(id)) return true;
if (!hasShareToolGrant(grants, id)) return false;
@@ -184,7 +193,8 @@ const applyShareGateToCloudSandbox = (toolSet: ShareGateToolSet): void => {
* 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`),
+ * Its grant is implied by any tool grant or the device 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
diff --git a/apps/server/src/services/aiAgent/shareGate/types.ts b/apps/server/src/services/aiAgent/shareGate/types.ts
index b06a9deb5f9..0ee580c4ddf 100644
--- a/apps/server/src/services/aiAgent/shareGate/types.ts
+++ b/apps/server/src/services/aiAgent/shareGate/types.ts
@@ -14,6 +14,13 @@ import type { AgentShareConfig } from '@/database/schemas';
*/
export interface AgentShareGate {
agentId: string;
+ /**
+ * Whether THIS visitor may run on the agent's configured execution
+ * environment — `shareConfig.deviceAccess` resolved against the visitor
+ * (see `resolveShareVisitorDeviceAccess`). Computed wherever the gate is
+ * built, never read from client input.
+ */
+ canUseDevice: boolean;
shareConfig: AgentShareConfig;
/**
* The `agentShares.id` this run was authorized against — read together with
@@ -48,6 +55,8 @@ export interface AgentShareGate {
*/
export interface ShareDataToolPermissions {
allowReadMemory?: boolean;
+ /** {@link AgentShareGate.canUseDevice}, carried to the dispatch-time gates. */
+ canUseDevice?: boolean;
/**
* Agent's own persisted, `enabled` knowledge-base ids (never
* visitor-supplied). Currently always empty for a share run — see
diff --git a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts b/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
index 4d85d3e7d51..e0560d94342 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
@@ -155,6 +155,8 @@ describe('dispatching a contact’s shared Agent', () => {
const [params] = execAgent.mock.calls[0];
expect(params.shareGate).toEqual({
agentId: 'agt_shared',
+ // The live share sets no `deviceAccess`, so the Channel visitor gets no device.
+ canUseDevice: false,
shareConfig: liveShare.shareConfig,
shareId: 'share-1',
visitorUserId: 'visitor',
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index d6f8115bf70..3ab214c7add 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -21,6 +21,7 @@ import { extractTextFromMessage } from '@/server/services/agentRuntime/Completio
import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import { AiAgentService } from '@/server/services/aiAgent';
import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';
+import { resolveShareVisitorDeviceAccess } from '@/server/services/aiAgent/shareGate/deviceAccess';
import { detectNoReply } from '@/server/services/conversationWake/noReply';
import { deviceGateway } from '@/server/services/deviceGateway';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
@@ -85,6 +86,7 @@ export class ChannelCoordinator {
if (!spend.allowed) throw new Error('This shared Agent reached its monthly usage limit');
return {
agentId,
+ canUseDevice: await resolveShareVisitorDeviceAccess(this.db, share.shareConfig, requesterId),
shareConfig: share.shareConfig,
shareId: share.shareId,
visitorUserId: requesterId,
diff --git a/apps/server/src/services/toolExecution/index.connectorLinks.test.ts b/apps/server/src/services/toolExecution/index.connectorLinks.test.ts
index 2111490b604..b6408a97fd3 100644
--- a/apps/server/src/services/toolExecution/index.connectorLinks.test.ts
+++ b/apps/server/src/services/toolExecution/index.connectorLinks.test.ts
@@ -164,6 +164,26 @@ describe('live connector account resolution at dispatch', () => {
expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
expect(mocks.call).not.toHaveBeenCalled();
});
+ it('lets a shared visitor reach a device-only MCP under the share device grant', async () => {
+ mocks.find.mockResolvedValue({
+ id: 'c',
+ identifier: 'multi',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'http://localhost:1234/mcp',
+ credentials: null,
+ oidcConfig: { clientId: 'client', scheme: 'dcr' },
+ });
+ const result = await service.executeTool(
+ payload,
+ context('http://localhost:1234/mcp', {
+ activeDeviceId: 'device',
+ agentShareVisitor: { canUseDevice: true },
+ }),
+ );
+ expect(result).not.toMatchObject({ error: { code: 'SHARE_GATE_BLOCKED' } });
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalled();
+ });
it('retains the selected account on serialized device failures', async () => {
mocks.find.mockResolvedValue({
id: 'c',
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index 45c71f05d9b..82b25bbef78 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -324,10 +324,11 @@ export class ToolExecutionService {
// Agent Share visitor runs execute with the CREATOR's identity, so a
// device-only MCP would access the creator's device or private network
- // on a visitor's behalf. The tool-set gate already drops
- // these manifests (`applyShareGateToToolSet`); this is the unbypassable
- // dispatch-site check, mirroring `isShareBlockedBuiltinDispatch`.
- if (context.agentShareVisitor && isDeviceOnlyMcp) {
+ // on a visitor's behalf — allowed only under the share's device grant.
+ // The tool-set gate already drops these manifests
+ // (`applyShareGateToToolSet`); this is the unbypassable dispatch-site
+ // check, mirroring `isShareBlockedBuiltinDispatch`.
+ if (context.agentShareVisitor && !context.agentShareVisitor.canUseDevice && isDeviceOnlyMcp) {
log('Share gate blocked device-only MCP dispatch: %s:%s', identifier, apiName);
const message = `MCP server '${identifier}' runs on the agent owner's own machine and is not available in shared conversations.`;
return {
@@ -376,7 +377,11 @@ export class ToolExecutionService {
if (tool.permission === ConnectorToolPermission.disabled)
return buildBlockedToolResponse(apiName);
const currentEndpoint = buildConnectorMcpParams({ ...connector, credentials: null });
- if (context.agentShareVisitor && isDeviceOnlyMcpEndpoint(currentEndpoint)) {
+ if (
+ context.agentShareVisitor &&
+ !context.agentShareVisitor.canUseDevice &&
+ isDeviceOnlyMcpEndpoint(currentEndpoint)
+ ) {
const message = `MCP server '${identifier}' runs on the agent owner's own machine and is not available in shared conversations.`;
return {
content: message,
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 4135d2d5814..200dcfc04d3 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -738,6 +738,13 @@
"share.settings.permissions.allowReadMemory": "Allow reading my memory",
"share.settings.permissions.allowReadMemoryHint": "The Agent may draw on your long-term memory while answering a visitor.",
"share.settings.permissions.desc": "What a visitor’s run may read, and what the visitor gets to see back.",
+ "share.settings.permissions.deviceAccess": "Execution environment",
+ "share.settings.permissions.deviceAccessHint": "Lets visitors use this Agent’s execution environment to run commands and read or write files there.",
+ "share.settings.permissions.deviceAccessOption.all": "All visitors",
+ "share.settings.permissions.deviceAccessOption.allowlist": "Specific visitors",
+ "share.settings.permissions.deviceAccessOption.none": "No visitors",
+ "share.settings.permissions.deviceAllowEmailsHint": "Matches the visitor’s verified account email. No one can use it until you add one.",
+ "share.settings.permissions.deviceAllowEmailsPlaceholder": "Enter the visitors’ account emails, then press Enter",
"share.settings.permissions.showErrorDetails": "Show error details to visitors",
"share.settings.permissions.showErrorDetailsHint": "Off by default: visitors see a generic failure notice instead of raw error text.",
"share.settings.permissions.showModelInfo": "Show which model is used",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 4c3ecc60575..1879de9eb73 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -738,6 +738,13 @@
"share.settings.permissions.allowReadMemory": "允许读取我的记忆",
"share.settings.permissions.allowReadMemoryHint": "助手在回答访客时可以参考你的长期记忆。",
"share.settings.permissions.desc": "访客的运行可以读取什么,以及访客能看到什么。",
+ "share.settings.permissions.deviceAccess": "执行环境",
+ "share.settings.permissions.deviceAccessHint": "允许访客使用这个助手的执行环境,在上面执行命令、读写文件。",
+ "share.settings.permissions.deviceAccessOption.all": "所有访客",
+ "share.settings.permissions.deviceAccessOption.allowlist": "指定访客",
+ "share.settings.permissions.deviceAccessOption.none": "不允许",
+ "share.settings.permissions.deviceAllowEmailsHint": "按访客已验证的账号邮箱匹配。添加邮箱前,没有访客能使用。",
+ "share.settings.permissions.deviceAllowEmailsPlaceholder": "输入访客的账号邮箱,按回车添加",
"share.settings.permissions.showErrorDetails": "向访客展示错误详情",
"share.settings.permissions.showErrorDetailsHint": "默认关闭:访客只会看到一句通用的失败提示,而不是原始报错。",
"share.settings.permissions.showModelInfo": "展示使用的模型",
diff --git a/packages/const/src/agentShare.ts b/packages/const/src/agentShare.ts
index 93b45c8309d..9696366f931 100644
--- a/packages/const/src/agentShare.ts
+++ b/packages/const/src/agentShare.ts
@@ -236,3 +236,9 @@ export const isShareToolApiGranted = (
if (!grant) return false;
return grant === 'all' || grant.has(apiName);
};
+
+/**
+ * Upper bound on `AgentShareConfig.deviceAllowEmails`. Device access is meant
+ * for a handful of trusted people; a larger audience should use `all`.
+ */
+export const AGENT_SHARE_DEVICE_ALLOW_EMAILS_LIMIT = 100;
diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.ts
index 82a88fb102f..35aa9e1dbca 100644
--- a/packages/database/src/models/__tests__/agentShare.test.ts
+++ b/packages/database/src/models/__tests__/agentShare.test.ts
@@ -389,6 +389,8 @@ describe('AgentShareModel', () => {
allowCreatorViewSessions: false,
allowReadMemory: false,
demoCases: [],
+ deviceAccess: 'none',
+ deviceAllowEmails: [],
featuredWorkIds: [],
maxFileStorage: 512 * 1024 * 1024,
maxTopicsPerVisitor: 5,
@@ -407,6 +409,8 @@ describe('AgentShareModel', () => {
const config: AgentShareConfig = {
allowCreatorViewSessions: true,
allowReadMemory: true,
+ deviceAccess: 'allowlist',
+ deviceAllowEmails: ['[email protected]'],
maxFileStorage: 256 * 1024 * 1024,
maxTopicsPerVisitor: 10,
maxTurnsPerTopic: 40,
diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.ts
index 530c941303f..6db3a0e63b7 100644
--- a/packages/database/src/models/agentShare.ts
+++ b/packages/database/src/models/agentShare.ts
@@ -45,6 +45,8 @@ const normalizeAgentShareConfig = (
config?.allowCreatorViewSessions ?? DEFAULT_AGENT_SHARE_CONFIG.allowCreatorViewSessions,
allowReadMemory: config?.allowReadMemory ?? DEFAULT_AGENT_SHARE_CONFIG.allowReadMemory,
demoCases: config?.demoCases ?? [],
+ deviceAccess: config?.deviceAccess ?? 'none',
+ deviceAllowEmails: config?.deviceAllowEmails ?? [],
featuredWorkIds: config?.featuredWorkIds ?? [],
maxFileStorage: config?.maxFileStorage ?? DEFAULT_AGENT_SHARE_CONFIG.maxFileStorage,
maxTopicsPerVisitor:
diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.ts
index 73f9edeb070..6e01b4ceb37 100644
--- a/packages/database/src/schemas/agentShare.ts
+++ b/packages/database/src/schemas/agentShare.ts
@@ -4,6 +4,8 @@ import { index, integer, jsonb, pgTable, text, uniqueIndex, uuid } from 'drizzle
import { timestamps } from './_helpers';
import { agents } from './agent';
+export type AgentShareDeviceAccess = 'all' | 'allowlist' | 'none';
+
export interface AgentShareConfig {
/**
* Whether the creator may view visitor sessions/topics created against this
@@ -18,6 +20,29 @@ export interface AgentShareConfig {
allowReadMemory?: boolean;
/** Visitor trial scenarios, maintained independently of agents.openingQuestions. */
demoCases?: AgentShareDemoCase[];
+ /**
+ * Which visitors may run on the Agent's configured execution environment
+ * (its bound or auto-selected device), mirroring an IM bot's `devicePolicy`:
+ *
+ * - `none` (default): no visitor reaches a device; device tools are dropped.
+ * - `all`: every signed-in visitor runs on the Agent's device.
+ * - `allowlist`: only visitors whose VERIFIED account email is listed in
+ * {@link deviceAllowEmails}.
+ *
+ * The visitor never picks the device — it always follows the Agent's own
+ * execution-environment setting. Resolved per run by
+ * `resolveShareVisitorDeviceAccess`. Heterogeneous (Claude Code / Codex)
+ * agents stay unavailable to visitors under every value.
+ */
+ deviceAccess?: AgentShareDeviceAccess;
+ /**
+ * Lower-cased account emails allowed to use the device when
+ * {@link deviceAccess} is `allowlist`; ignored otherwise. Stored as emails
+ * rather than user ids so the creator can authorize someone before they sign
+ * up, and so the settings page never needs a user lookup that would reveal
+ * whether an email has a LobeHub account.
+ */
+ deviceAllowEmails?: string[];
/** Ordered, explicitly selected creator Works for this share's public profile. */
featuredWorkIds?: string[];
/**
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index d5ba87d611f..186ecd3b16f 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -958,6 +958,16 @@ export default {
'share.settings.permissions.allowReadMemory': 'Allow reading my memory',
'share.settings.permissions.allowReadMemoryHint':
'The Agent may draw on your long-term memory while answering a visitor.',
+ 'share.settings.permissions.deviceAccess': 'Execution environment',
+ 'share.settings.permissions.deviceAccessHint':
+ 'Lets visitors use this Agent’s execution environment to run commands and read or write files there.',
+ 'share.settings.permissions.deviceAccessOption.all': 'All visitors',
+ 'share.settings.permissions.deviceAccessOption.allowlist': 'Specific visitors',
+ 'share.settings.permissions.deviceAccessOption.none': 'No visitors',
+ 'share.settings.permissions.deviceAllowEmailsHint':
+ 'Matches the visitor’s verified account email. No one can use it until you add one.',
+ 'share.settings.permissions.deviceAllowEmailsPlaceholder':
+ 'Enter the visitors’ account emails, then press Enter',
'share.settings.permissions.desc':
'What a visitor’s run may read, and what the visitor gets to see back.',
'share.settings.permissions.showErrorDetails': 'Show error details to visitors',
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index ec94ab9447f..997d0e15364 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -128,6 +128,13 @@ export interface AgentShareVisitorContext {
* `BuiltinToolsExecutor.execute`, the actual unbypassable chokepoint.
*/
allowReadMemory?: boolean;
+ /**
+ * Whether this visitor may run on the agent's execution environment, as
+ * resolved from `shareConfig.deviceAccess` when the run started. Lets the
+ * dispatch-time gates (device builtins, device-only MCP) re-apply the same
+ * decision the assembled tool set was built with.
+ */
+ canUseDevice?: boolean;
/**
* The agent's OWN persisted knowledge-base assignment, never derived from
* visitor input, so `isShareBlockedDataToolCall` can id-scope