π€― 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(bot): gate device tools by sender identity (#14634)
Arvin Xu3c8101128e0e
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex e426297e496..ddf094bdb92 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -31,6 +31,18 @@ export interface TopicUserMemoryExtractRunState {export interface ChatTopicBotContext {applicationId: string;+ /**+ * Whether the message sender is the bot owner. Computed at the bot+ * router/dispatcher entry point as+ * `senderExternalUserId === settings.userId`.+ *+ * Downstream policy (`resolveDeviceAccessPolicy`) consumes this directly+ * and never recomputes β the routers own the owner-identity check.+ *+ * Fail-closed: if `settings.userId` is missing or the sender ID can't be+ * resolved, this MUST be `false`. Never default to `true` "when in doubt".+ */+ isOwner: boolean;/*** Set when the run originated from the shared Messenger bot (Telegram global* token, Slack per-workspace install, Discord global token). The value is@@ -42,6 +54,14 @@ export interface ChatTopicBotContext {messengerInstallationKey?: string;platform: string;platformThreadId: string;+ /**+ * Platform-assigned ID of the actual sender of the inbound message+ * (e.g. Discord/Slack `user.id`, Telegram `from.id`). Distinct from+ * `applicationId` (the bot itself) β required so downstream code can tell+ * "owner @ bot" apart from "external user @ bot" without re-reading+ * platform-specific message shapes.+ */+ senderExternalUserId: string;}export interface OnboardingFeedbackEntry {diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 52fb87cfbfe..d43a9795901 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -15,6 +15,7 @@ import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import {AGENT_DOCUMENT_INJECTION_POSITIONS,type AgentContextDocument,+ type BotPlatformContext,buildStepSkillDelta,buildStepToolDelta,type LobeToolManifest,@@ -42,6 +43,11 @@ import { type EvalContext } from '@/server/modules/Mecha/ContextEngineering/typeimport { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { AgentDocumentsService } from '@/server/services/agentDocuments';import type { HookDispatcher } from '@/server/services/agentRuntime/hooks/HookDispatcher';+import {+ type DeviceAccessReason,+ isDeviceToolIdentifier,+ logDeviceToolAudit,+} from '@/server/services/aiAgent/deviceToolAudit';import { FileService } from '@/server/services/file';import { MessageService } from '@/server/services/message';import { OnboardingService } from '@/server/services/onboarding';@@ -200,7 +206,7 @@ const buildToolDiscoveryConfig = (operationToolSet: OperationToolSet, enabledTooexport interface RuntimeExecutorContext {agentConfig?: any;- botPlatformContext?: any;+ botPlatformContext?: BotPlatformContext;discordContext?: any;evalContext?: EvalContext;hookDispatcher?: HookDispatcher;@@ -233,8 +239,19 @@ export const createRuntimeExecutors = (// Fallback to state's modelRuntimeConfig if not in payloadconst model = llmPayload.model || state.modelRuntimeConfig?.model;const provider = llmPayload.provider || state.modelRuntimeConfig?.provider;- // Resolve tools via ToolResolver (unified tool injection)- const activeDeviceId = state.metadata?.activeDeviceId;+ // Resolve tools via ToolResolver (unified tool injection).+ //+ // Belt-and-suspenders: even if `aiAgent.execAgent` ever forgets to clear+ // `state.metadata.activeDeviceId` for a non-trusted sender, swallowing+ // it here keeps `buildStepToolDelta` from re-injecting `local-system` β+ // the engine's enabledToolIds exclusion alone is not enough, since the+ // delta builder treats activeDeviceId as an independent activation+ // signal and only dedupes against already-enabled tools.+ const devicePolicy = state.metadata?.deviceAccessPolicy as+ | { canUseDevice: boolean; reason: DeviceAccessReason }+ | undefined;+ const activeDeviceId =+ devicePolicy?.canUseDevice === false ? undefined : state.metadata?.activeDeviceId;const operationToolSet: OperationToolSet = state.operationToolSet ?? {enabledToolIds: [],executorMap: state.toolExecutorMap ?? {},@@ -1580,6 +1597,28 @@ export const createRuntimeExecutors = (: null;let execution: { result: ToolExecutionResultResponse; attempts: number };+ if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {+ // Per-call audit for device tools (local-system / remote-device).+ // Emitted before dispatch so the record exists even if dispatch+ // throws. We rely on the engine's enable gate to keep `canUseDevice`+ // true here; recording the policy reason inline lets an operator+ // distinguish first-party vs bot-owner runs without joining logs.+ const policy = state.metadata?.deviceAccessPolicy as+ | { canUseDevice: boolean; reason: DeviceAccessReason }+ | undefined;+ logDeviceToolAudit({+ apiName: chatToolPayload.apiName,+ botContext: state.metadata?.botContext,+ canUseDevice: policy?.canUseDevice ?? true,+ messageId: state.metadata?.sourceMessageId,+ operationId,+ reason: policy?.reason ?? 'first-party',+ toolIdentifier: chatToolPayload.identifier,+ topicId: ctx.topicId,+ userId: ctx.userId,+ });+ }+if (hookResult?.isMocked) {log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);toolCallMocked = true;@@ -2017,6 +2056,23 @@ export const createRuntimeExecutors = (})(): null;+ if (isDeviceToolIdentifier(chatToolPayload.identifier) && !batchHookResult?.isMocked) {+ const policy = state.metadata?.deviceAccessPolicy as+ | { canUseDevice: boolean; reason: DeviceAccessReason }+ | undefined;+ logDeviceToolAudit({+ apiName: chatToolPayload.apiName,+ botContext: state.metadata?.botContext,+ canUseDevice: policy?.canUseDevice ?? true,+ messageId: state.metadata?.sourceMessageId,+ operationId,+ reason: policy?.reason ?? 'first-party',+ toolIdentifier: chatToolPayload.identifier,+ topicId: ctx.topicId,+ userId: ctx.userId,+ });+ }+let execution: { result: ToolExecutionResultResponse; attempts: number };if (batchHookResult?.isMocked) {log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);diff --git a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.tsindex 87ebe492635..214caf16861 100644--- a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts@@ -363,10 +363,15 @@ describe('createServerAgentToolsEngine', () => {});describe('LocalSystem tool enable rules', () => {+ // These tests assume `canUseDevice: true` (i.e. trusted caller) so the+ // assertions exercise the engine-internal gates (runtimeMode, deviceContext)+ // rather than the access policy. The dedicated `canUseDevice gate` block+ // below covers the policy-level gating.it('should disable LocalSystem when no device context is provided', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [LocalSystemManifest.identifier] },+ canUseDevice: true,model: 'gpt-4',provider: 'openai',});@@ -384,6 +389,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [LocalSystemManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },model: 'gpt-4',provider: 'openai',@@ -402,6 +408,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [LocalSystemManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: true },model: 'gpt-4',provider: 'openai',@@ -420,6 +427,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [LocalSystemManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: false, autoActivated: true },model: 'gpt-4',provider: 'openai',@@ -441,6 +449,7 @@ describe('createServerAgentToolsEngine', () => {plugins: [LocalSystemManifest.identifier],chatConfig: { runtimeEnv: { runtimeMode: { desktop: 'cloud' } } },},+ canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },model: 'gpt-4',provider: 'openai',@@ -457,10 +466,15 @@ describe('createServerAgentToolsEngine', () => {});describe('RemoteDevice tool enable rules', () => {+ // Same pattern as LocalSystem above: `canUseDevice: true` is set so the+ // assertions exercise the engine-internal gates (gatewayConfigured,+ // autoActivated, hasClientExecutor). The `canUseDevice gate` block+ // below covers the policy-level gating.it('should enable RemoteDevice when gateway configured and no device auto-activated', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [RemoteDeviceManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: true },model: 'gpt-4',provider: 'openai',@@ -479,6 +493,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [RemoteDeviceManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: false },model: 'gpt-4',provider: 'openai',@@ -497,6 +512,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [RemoteDeviceManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: true, autoActivated: true },model: 'gpt-4',provider: 'openai',@@ -511,14 +527,16 @@ describe('createServerAgentToolsEngine', () => {expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);});- it('should disable RemoteDevice in bot conversations when no device auto-activated', () => {- // Bot callers (Telegram/Discord/Slack) have no client-executor, so the- // legacy rule would auto-enable RemoteDevice, and its systemRole would- // hijack the Activator and tell the model to ask the user to open the- // desktop app β blocking cloud-tool discovery (e.g. Klavis Gmail).+ it('should enable RemoteDevice in bot conversations when caller is trusted (canUseDevice=true)', () => {+ // The `!isBotConversation` clause was dropped in LOBE-8715 β the+ // confused-deputy concern that motivated it is now handled at a+ // stricter layer (`canUseDevice` from `resolveDeviceAccessPolicy`).+ // For owner / first-party turns the proxy is legitimately useful in+ // bot threads, so it should surface.const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [RemoteDeviceManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: true },isBotConversation: true,model: 'gpt-4',@@ -531,16 +549,17 @@ describe('createServerAgentToolsEngine', () => {provider: 'openai',});- expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);+ expect(result.enabledToolIds).toContain(RemoteDeviceManifest.identifier);});- it('should still enable RemoteDevice in bot conversations when a device is auto-activated', () => {+ it('should still disable RemoteDevice in bot conversations when a device is auto-activated', () => {// When a device is bound / auto-activated for the bot topic, LocalSystem// takes over the remote proxy anyway β so RemoteDevice stays disabled- // (its usual rule), not due to isBotConversation.+ // by the `!autoActivated` clause, regardless of isBotConversation.const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [RemoteDeviceManifest.identifier] },+ canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },isBotConversation: true,model: 'gpt-4',@@ -564,6 +583,7 @@ describe('createServerAgentToolsEngine', () => {agentConfig: {plugins: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],},+ canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: true },model: 'gpt-4',provider: 'openai',@@ -585,6 +605,7 @@ describe('createServerAgentToolsEngine', () => {agentConfig: {plugins: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],},+ canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },model: 'gpt-4',provider: 'openai',@@ -609,6 +630,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [LocalSystemManifest.identifier] },+ canUseDevice: true,clientRuntime: 'desktop',model: 'gpt-4',provider: 'openai',@@ -634,6 +656,7 @@ describe('createServerAgentToolsEngine', () => {},plugins: [LocalSystemManifest.identifier],},+ canUseDevice: true,clientRuntime: 'desktop',model: 'gpt-4',provider: 'openai',@@ -652,6 +675,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [LocalSystemManifest.identifier, WebBrowsingManifest.identifier] },+ canUseDevice: true,clientRuntime: 'desktop',disableLocalSystem: true,model: 'gpt-4',@@ -672,6 +696,7 @@ describe('createServerAgentToolsEngine', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: { plugins: [LocalSystemManifest.identifier] },+ canUseDevice: true,clientRuntime: 'web',deviceContext: { gatewayConfigured: true },model: 'gpt-4',@@ -697,6 +722,7 @@ describe('createServerAgentToolsEngine', () => {agentConfig: {plugins: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],},+ canUseDevice: true,clientRuntime: 'desktop',deviceContext: { gatewayConfigured: true },model: 'gpt-4',@@ -713,4 +739,70 @@ describe('createServerAgentToolsEngine', () => {expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);});});++ describe('canUseDevice gate (LOBE-8715 device access policy)', () => {+ it('drops LocalSystem when canUseDevice is false even on a desktop caller', () => {+ // External bot sender impersonating a desktop session must not get+ // local-system back through Phase 6.4 dispatch.+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [LocalSystemManifest.identifier] },+ canUseDevice: false,+ clientRuntime: 'desktop',+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [LocalSystemManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);+ });++ it('drops RemoteDevice when canUseDevice is false even with proxy configured', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [RemoteDeviceManifest.identifier] },+ canUseDevice: false,+ deviceContext: { gatewayConfigured: true },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [RemoteDeviceManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);+ });++ it('defaults to fail-closed when canUseDevice is omitted', () => {+ // Plumbing safety net: callers that forget to set `canUseDevice` get+ // the deny default rather than the legacy permissive behavior.+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: {+ plugins: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],+ },+ clientRuntime: 'desktop',+ deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);+ expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);+ });+ });});diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.tsindex d56e2d5f0e3..680c60127c7 100644--- a/src/server/modules/Mecha/AgentToolsEngine/index.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts@@ -95,6 +95,7 @@ export const createServerAgentToolsEngine = (const {additionalManifests,agentConfig,+ canUseDevice = false,clientRuntime,deviceContext,disableLocalSystem = false,@@ -139,7 +140,7 @@ export const createServerAgentToolsEngine = (const isSearchEnabled = searchMode !== 'off';log(- 'Creating agent tools engine model=%s provider=%s searchMode=%s platform=%s runtimeMode=%s additionalManifests=%d hasClientExecutor=%s hasDeviceProxy=%s',+ 'Creating agent tools engine model=%s provider=%s searchMode=%s platform=%s runtimeMode=%s additionalManifests=%d hasClientExecutor=%s hasDeviceProxy=%s canUseDevice=%s',model,provider,searchMode,@@ -148,6 +149,7 @@ export const createServerAgentToolsEngine = (additionalManifests?.length ?? 0,hasClientExecutor,hasDeviceProxy,+ canUseDevice,);return createServerToolsEngine(context, {@@ -166,14 +168,16 @@ export const createServerAgentToolsEngine = (// System-level rules (may override user selection for specific tools)[CloudSandboxManifest.identifier]: runtimeMode === 'cloud',[KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,- // Local-system: user must have opted into local runtime on this- // platform (`runtimeMode === 'local'`), AND one execution channel- // must exist:+ // Local-system: gated by `canUseDevice` (resolveDeviceAccessPolicy)+ // first β keeps external bot senders out before runtime checks even+ // run. Then user must have opted into local runtime on this platform+ // (`runtimeMode === 'local'`), AND one execution channel must exist:// - `hasClientExecutor` β Phase 6.4 dispatch over the Agent Gateway// WS that this request is already riding on; no extra server-side// prerequisite needed;// - legacy device-proxy with an online & auto-activated device.[LocalSystemManifest.identifier]:+ canUseDevice &&!disableLocalSystem &&runtimeMode === 'local' &&(hasClientExecutor ||@@ -186,19 +190,13 @@ export const createServerAgentToolsEngine = (// the caller itself can execute `executor: 'client'` tools, the// proxy is redundant β local-system goes directly to the caller.//- // Bot conversations (Telegram/Discord/Slack/β¦) never have a- // client-executor by definition, which would otherwise make- // RemoteDevice permanently auto-enabled there. Its systemRole- // tells the model to "inform the user to open their desktop- // application" when no device is online, overriding the- // Activator's own guidance and blocking discovery of cloud tools- // (e.g. Klavis Gmail). Keep RemoteDevice discoverable via the- // Activator in bot flows, but don't inject it by default.+ // `canUseDevice` is the first short-circuit: external bot senders+ // (and unconfigured bot owners) never reach the proxy, both because+ // it would let them poke at the owner's machine AND because its+ // systemRole would otherwise leak the device list into the LLM+ // context β see the gated injection in `aiAgent.execAgent`.[RemoteDeviceManifest.identifier]:- hasDeviceProxy &&- !deviceContext?.autoActivated &&- !hasClientExecutor &&- !isBotConversation,+ canUseDevice && hasDeviceProxy && !deviceContext?.autoActivated && !hasClientExecutor,[AgentDocumentsManifest.identifier]: hasAgentDocuments,[WebBrowsingManifest.identifier]: isSearchEnabled,},diff --git a/src/server/modules/Mecha/AgentToolsEngine/types.ts b/src/server/modules/Mecha/AgentToolsEngine/types.tsindex 188a3046d04..95d4eee4bf6 100644--- a/src/server/modules/Mecha/AgentToolsEngine/types.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/types.ts@@ -44,6 +44,15 @@ export interface ServerCreateAgentToolsEngineParams {/** Plugin IDs enabled for this agent */plugins?: string[];};+ /**+ * Whether device tools (local-system / remote-device) are allowed this turn.+ * Computed by `resolveDeviceAccessPolicy` from the caller identity:+ * first-party UI and bot-owner senders pass; external bot senders and+ * unconfigured bot owners do not. The engine treats this as the FINAL+ * answer β never re-derive from `isBotConversation` or `botContext`.+ * Defaults to `false` (fail-closed) when the caller forgets to plumb it.+ */+ canUseDevice?: boolean;/*** Runtime of the client initiating this request. When `'desktop'`, the* caller itself is an Electron client connected via the Agent Gateway WS,diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex cff35170c07..1e785d09c41 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -262,7 +262,9 @@ export class AgentRuntimeService {userInterventionConfig,queueRetries,queueRetryDelay,+ botContext,botPlatformContext,+ deviceAccessPolicy,discordContext,evalContext,maxSteps,@@ -307,7 +309,9 @@ export class AgentRuntimeService {metadata: {activeDeviceId,agentConfig,+ botContext,botPlatformContext,+ deviceAccessPolicy,deviceSystemInfo,discordContext,evalContext,diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.tsindex 64a1cc2bce1..212b1acde71 100644--- a/src/server/services/agentRuntime/types.ts+++ b/src/server/services/agentRuntime/types.ts@@ -1,13 +1,15 @@import { type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';import type {+ BotPlatformContext,LobeToolManifest,OperationSkillSet,ToolExecutor,ToolSource,} from '@lobechat/context-engine';-import { type UserInterventionConfig } from '@lobechat/types';+import type { ChatTopicBotContext, UserInterventionConfig } from '@lobechat/types';import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';+import type { DeviceAccessReason } from '@/server/services/aiAgent/deviceAccessPolicy';import { type AgentHook } from './hooks/types';@@ -161,8 +163,21 @@ export interface OperationCreationParams {trigger?: string;};autoStart?: boolean;+ /**+ * Sender/owner identity for bot-originated runs. Forwarded into+ * `state.metadata.botContext` so device-tool dispatch can audit who+ * triggered the call. `undefined` for first-party (web/desktop) callers.+ */+ botContext?: ChatTopicBotContext;/** Bot platform context for injecting platform capabilities (e.g. markdown support) */- botPlatformContext?: any;+ botPlatformContext?: BotPlatformContext;+ /**+ * Device-access policy decision computed once per turn by+ * `resolveDeviceAccessPolicy`. Forwarded into `state.metadata.deviceAccessPolicy`+ * so the dispatch site can include `reason` in the audit entry without+ * re-deriving it.+ */+ deviceAccessPolicy?: { canUseDevice: boolean; reason: DeviceAccessReason };/** Device system info for placeholder variable replacement in Local System systemRole */deviceSystemInfo?: Record<string, string>;/** Discord context for injecting channel/guild info into agent system message */diff --git a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts b/src/server/services/aiAgent/__tests__/execAgent.device.test.tsindex e07eb0b0c55..0692ff91866 100644--- a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.device.test.ts@@ -187,7 +187,13 @@ describe('AiAgentService.execAgent - device auto-activation', () => {await service.execAgent({agentId: 'agent-1',- botContext: { platform: 'discord' } as any,+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,prompt: 'List my files',});@@ -202,7 +208,13 @@ describe('AiAgentService.execAgent - device auto-activation', () => {await service.execAgent({agentId: 'agent-1',- botContext: { platform: 'discord' } as any,+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,prompt: 'List my files',});@@ -217,7 +229,13 @@ describe('AiAgentService.execAgent - device auto-activation', () => {await service.execAgent({agentId: 'agent-1',- botContext: { platform: 'discord' } as any,+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,prompt: 'List my files',});@@ -434,7 +452,13 @@ describe('AiAgentService.execAgent - device auto-activation', () => {await service.execAgent({agentId: 'agent-1',- botContext: { platform: 'discord' } as any,+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,prompt: 'List my files',});@@ -531,7 +555,13 @@ describe('AiAgentService.execAgent - device auto-activation', () => {await service.execAgent({agentId: 'agent-1',- botContext: { platform: 'discord' } as any,+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,prompt: 'List my files',});@@ -599,7 +629,13 @@ describe('AiAgentService.execAgent - device auto-activation', () => {await service.execAgent({agentId: 'agent-1',- botContext: { platform: 'discord' } as any,+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,prompt: 'List my files',});@@ -613,7 +649,13 @@ describe('AiAgentService.execAgent - device auto-activation', () => {await service.execAgent({agentId: 'agent-1',- botContext: { platform: 'discord' } as any,+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,prompt: 'List my files',});diff --git a/src/server/services/aiAgent/deviceAccessPolicy.test.ts b/src/server/services/aiAgent/deviceAccessPolicy.test.tsnew file mode 100644index 00000000000..a910a4609fd--- /dev/null+++ b/src/server/services/aiAgent/deviceAccessPolicy.test.ts@@ -0,0 +1,116 @@+import type { ChatTopicBotContext } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { resolveDeviceAccessPolicy } from './deviceAccessPolicy';++const baseBotContext = (overrides: Partial<ChatTopicBotContext> = {}): ChatTopicBotContext => ({+ applicationId: 'app-123',+ isOwner: false,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'discord-user-99',+ ...overrides,+});++describe('resolveDeviceAccessPolicy', () => {+ it('grants device access for first-party UI calls (no botContext)', () => {+ expect(resolveDeviceAccessPolicy({})).toEqual({+ canUseDevice: true,+ reason: 'first-party',+ });+ });++ it('grants device access when bot sender is the owner', () => {+ expect(+ resolveDeviceAccessPolicy({+ botContext: baseBotContext({ isOwner: true, senderExternalUserId: 'owner-id' }),+ }),+ ).toEqual({+ canUseDevice: true,+ reason: 'bot-owner',+ });+ });++ it('denies device access when bot sender is identified but not the owner', () => {+ expect(+ resolveDeviceAccessPolicy({+ botContext: baseBotContext({ isOwner: false, senderExternalUserId: 'random-user' }),+ }),+ ).toEqual({+ canUseDevice: false,+ reason: 'bot-external-sender',+ });+ });++ it('fails closed when bot context lacks a sender ID (settings.userId not configured)', () => {+ expect(+ resolveDeviceAccessPolicy({+ botContext: baseBotContext({ isOwner: false, senderExternalUserId: '' }),+ }),+ ).toEqual({+ canUseDevice: false,+ reason: 'bot-owner-not-configured',+ });+ });++ it('never returns canUseDevice=true for a non-owner bot sender, even with a trusted-looking ID', () => {+ // Future-proofing: until the trusted list lands, every non-owner bot+ // sender must be denied. This guards against accidentally reintroducing+ // a permissive default while wiring the future `bot-trusted` branch.+ const result = resolveDeviceAccessPolicy({+ botContext: baseBotContext({ isOwner: false, senderExternalUserId: 'team-mate' }),+ });+ expect(result.canUseDevice).toBe(false);+ expect(result.reason).not.toBe('bot-trusted');+ });++ 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+ // false on every turn. Without the personal-scope branch, every WeChat+ // bot would be permanently denied.+ const result = resolveDeviceAccessPolicy({+ botContext: baseBotContext({+ isOwner: false,+ platform: 'wechat',+ senderExternalUserId: 'wechat-openid-xyz',+ }),+ });+ expect(result).toEqual({+ canUseDevice: true,+ reason: 'bot-personal-platform',+ });+ });++ it('still prefers `bot-owner` over `bot-personal-platform` when isOwner is true', () => {+ // If a future WeChat schema adds owner identification, the more+ // specific match wins.+ const result = resolveDeviceAccessPolicy({+ botContext: baseBotContext({+ isOwner: true,+ platform: 'wechat',+ senderExternalUserId: 'owner-openid',+ }),+ });+ expect(result.reason).toBe('bot-owner');+ });++ it('does NOT grant device access on group-capable platforms even if userId is unconfigured', () => {+ // Regression guard: don't accidentally widen the personal-scope set+ // to platforms that DO have group chat. Discord/Slack/Telegram etc.+ // must keep going through the standard isOwner gate.+ const platforms = ['discord', 'slack', 'telegram', 'feishu', 'lark', 'qq', 'line'];+ for (const platform of platforms) {+ const result = resolveDeviceAccessPolicy({+ botContext: baseBotContext({+ isOwner: false,+ platform,+ senderExternalUserId: 'random-user',+ }),+ });+ expect(result.canUseDevice).toBe(false);+ expect(result.reason).toBe('bot-external-sender');+ }+ });+ });+});diff --git a/src/server/services/aiAgent/deviceAccessPolicy.ts b/src/server/services/aiAgent/deviceAccessPolicy.tsnew file mode 100644index 00000000000..da89434c654--- /dev/null+++ b/src/server/services/aiAgent/deviceAccessPolicy.ts@@ -0,0 +1,108 @@+import type { ChatTopicBotContext } from '@lobechat/types';++/**+ * Decision path produced by `resolveDeviceAccessPolicy`. Carried through to+ * `AgentToolsEngine` and the device-tool audit log so an operator can trace+ * which branch granted or denied access for a given turn.+ */+export type DeviceAccessReason =+ /** Non-bot caller (web / desktop / mobile UI). */+ | 'first-party'+ /** Bot caller, sender matches the configured owner platform ID. */+ | 'bot-owner'+ /**+ * Bot caller on a platform whose LobeHub integration is structurally+ * personal-scope (no group chat surfaced, no `settings.userId` to gate+ * on). See `PERSONAL_SCOPE_BOT_PLATFORMS` below.+ */+ | 'bot-personal-platform'+ /**+ * Bot caller, sender is on the operator's trusted external list. Reserved β+ * the resolver never returns this value yet; future work will plumb the+ * trusted list through `DeviceAccessPolicyInput` and add the branch here+ * without touching `AgentToolsEngine`.+ */+ | 'bot-trusted'+ /** Bot caller, sender is identifiable but not the owner β DENY device tools. */+ | 'bot-external-sender'+ /**+ * Bot caller but `senderExternalUserId` is missing (e.g. the platform's+ * webhook didn't deliver the author). Treated as untrusted external β+ * fail-closed.+ */+ | 'bot-owner-not-configured';++/**+ * Bot platforms whose LobeHub integration is **personal-scope-only at the+ * integration layer**. Two conditions must hold to qualify:+ *+ * 1. The platform's chat-adapter encodes every inbound thread as 1:1+ * (no group / channel handling), so the "external user @s the bot in+ * a group" attack surface from LOBE-8715 doesn't exist on this+ * platform today.+ * 2. The platform's settings schema has no `userId` field, so an owner+ * ID can't be configured even if we wanted to gate on it.+ *+ * For these platforms we treat the sender as trusted because there is no+ * group-chat fan-out path β every message is a direct conversation with+ * the bound account. The trade-off: messages from contacts of the bound+ * account also flow through; that's the accepted personal-scope risk.+ *+ * **Add a platform here only when both conditions hold.** Platforms that+ * support groups but lack a `userId` field (e.g. LINE today) MUST stay out+ * of this set β fix the schema first.+ */+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;+}++export interface DeviceAccessPolicyOutput {+ canUseDevice: boolean;+ reason: DeviceAccessReason;+}++/**+ * Decide whether device tools (`local-system`, `remote-device`) can be used+ * for the current turn. Pure function β the only authoritative place that+ * answers "is this caller allowed to touch the bot owner's machine?".+ *+ * Downstream consumers (`AgentToolsEngine` enable gates, `RemoteDeviceManifest`+ * system-prompt injection, audit log) read `canUseDevice` only β they MUST+ * NOT re-derive the answer from `botContext` themselves, so adding new rules+ * (trusted external list, channel policy, scope tiers) only changes this+ * resolver.+ */+export const resolveDeviceAccessPolicy = (+ input: DeviceAccessPolicyInput,+): DeviceAccessPolicyOutput => {+ const { botContext } = input;++ if (!botContext) {+ return { canUseDevice: true, reason: 'first-party' };+ }++ if (botContext.isOwner) {+ return { canUseDevice: true, reason: 'bot-owner' };+ }++ // Personal-scope platform check sits AFTER `isOwner` so that, if a future+ // schema for one of these platforms adds a `userId` field, the more+ // specific `bot-owner` decision still wins. While the field is absent+ // (current state for WeChat), this branch is the one that actually fires.+ if (PERSONAL_SCOPE_BOT_PLATFORMS.has(botContext.platform)) {+ return { canUseDevice: true, reason: 'bot-personal-platform' };+ }++ // Future: bot-trusted branch (operator-curated allowlist of external+ // senders). Falls through to the deny branch until the trusted list is+ // wired into `DeviceAccessPolicyInput`.++ if (!botContext.senderExternalUserId) {+ return { canUseDevice: false, reason: 'bot-owner-not-configured' };+ }++ return { canUseDevice: false, reason: 'bot-external-sender' };+};diff --git a/src/server/services/aiAgent/deviceToolAudit.ts b/src/server/services/aiAgent/deviceToolAudit.tsnew file mode 100644index 00000000000..51f9e9a4286--- /dev/null+++ b/src/server/services/aiAgent/deviceToolAudit.ts@@ -0,0 +1,86 @@+import type { ChatTopicBotContext } from '@lobechat/types';+import debug from 'debug';++import type { DeviceAccessReason } from './deviceAccessPolicy';++export type { DeviceAccessReason } from './deviceAccessPolicy';++const log = debug('lobe-server:agent-device-tool-audit');++/**+ * Identifiers we treat as device tools β kept inline to avoid pulling the+ * whole builtin-tool packages just to read their identifier strings.+ * If either package's identifier ever changes, the static string here will+ * fall behind the import in `aiAgent/index.ts`; the test in+ * `__tests__/deviceToolAudit.test.ts` (if added) should pin both.+ */+const DEVICE_TOOL_IDENTIFIERS = new Set(['local-system', 'remote-device']);++export const isDeviceToolIdentifier = (identifier: string): boolean =>+ DEVICE_TOOL_IDENTIFIERS.has(identifier);++export interface DeviceToolAuditEntry {+ apiName: string;+ canUseDevice: boolean;+ isOwner: boolean | null;+ messageId?: string;+ operationId?: string;+ /** `null` for first-party UI calls (no bot platform). */+ platform: string | null;+ reason: DeviceAccessReason;+ /** `null` for first-party UI calls (no external sender). */+ senderExternalUserId: string | null;+ toolIdentifier: string;+ topicId?: string;+ userId?: string;+}++export interface LogDeviceToolAuditParams {+ apiName: string;+ botContext?: ChatTopicBotContext;+ canUseDevice: boolean;+ messageId?: string;+ operationId?: string;+ reason: DeviceAccessReason;+ toolIdentifier: string;+ topicId?: string;+ userId?: string;+}++/**+ * Emit one audit record per device-tool dispatch. Caller is responsible for+ * gating on `isDeviceToolIdentifier(...)` first β calling this for non-device+ * tools is a no-op contract violation, not a runtime guard.+ *+ * Reason for being a logger (not a DB table): the goal here is post-incident+ * forensics ("who triggered this read_file?"), not real-time risk control.+ * The debug namespace keeps it cheap, fire-and-forget, and consistent with+ * the existing `lobe-server:device-proxy` line at the actual proxy dispatch.+ *+ * Sensitive payloads (file contents, shell stdout, tool args) are NEVER+ * recorded here β only identity + decision metadata.+ */+export const logDeviceToolAudit = (params: LogDeviceToolAuditParams): void => {+ const { botContext, canUseDevice, reason, ...rest } = params;+ const entry: DeviceToolAuditEntry = {+ ...rest,+ canUseDevice,+ isOwner: botContext ? botContext.isOwner : null,+ platform: botContext?.platform ?? null,+ reason,+ senderExternalUserId: botContext?.senderExternalUserId ?? null,+ };+ log(+ 'device-tool-call %s:%s userId=%s topicId=%s operationId=%s platform=%s sender=%s isOwner=%s reason=%s canUseDevice=%s',+ entry.toolIdentifier,+ entry.apiName,+ entry.userId ?? '-',+ entry.topicId ?? '-',+ entry.operationId ?? '-',+ entry.platform ?? '-',+ entry.senderExternalUserId ?? '-',+ entry.isOwner === null ? '-' : entry.isOwner,+ entry.reason,+ entry.canUseDevice,+ );+};diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 60f968987b0..d4934bff1ac 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -16,6 +16,7 @@ import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools'import { LOADING_FLAT } from '@lobechat/const';import type {AgentManagementContext,+ BotPlatformContext,LobeToolManifest,ToolExecutor,ToolSource,@@ -74,6 +75,7 @@ import { KlavisService } from '@/server/services/klavis';import { MarketService } from '@/server/services/market';import { deviceProxy } from '@/server/services/toolExecution/deviceProxy';+import { resolveDeviceAccessPolicy } from './deviceAccessPolicy';import { ingestAttachment } from './ingestAttachment';const log = debug('lobe-server:ai-agent-service');@@ -141,7 +143,7 @@ interface InternalExecAgentParams extends ExecAgentParams {/** Bot context for topic metadata (platform, applicationId, platformThreadId) */botContext?: ChatTopicBotContext;/** Bot platform context for injecting platform capabilities (e.g. markdown support) */- botPlatformContext?: any;+ botPlatformContext?: BotPlatformContext;/** Cron job ID that triggered this execution (if trigger is 'cron') */cronJobId?: string;/** Disable only local-system while preserving other tools. Useful for signal-only evals. */@@ -836,6 +838,23 @@ export class AiAgentService {let hasEnabledKnowledgeBases = false;const isBotConversation = !!(botContext || discordContext);+ // Resolve device-tool access ONCE per turn. The decision flows into both+ // the engine's enable gates (LocalSystem / RemoteDevice) and the+ // RemoteDevice systemRole injection below. Discord-only flows (no+ // botContext) keep the legacy first-party allow path; an external bot+ // sender returns canUseDevice=false and reason='bot-external-sender',+ // which both denies the tools and stops the device list from leaking+ // into the LLM context.+ const { canUseDevice, reason: deviceAccessReason } = resolveDeviceAccessPolicy({+ botContext,+ });+ log(+ 'execAgent: device access policy β canUseDevice=%s, reason=%s, hasBotContext=%s',+ canUseDevice,+ deviceAccessReason,+ !!botContext,+ );+// These are needed outside the tools block (for agent management context, skill engine, etc.)let lobehubSkillManifests: LobeToolManifest[] = [];let klavisManifests: LobeToolManifest[] = [];@@ -983,18 +1002,26 @@ export class AiAgentService {...(shouldEnableVisualUnderstanding ? [LobeAgentManifest.identifier] : []),];- // Derive activeDeviceId from device context:+ // Derive activeDeviceId from device context. Gated on `canUseDevice`+ // first β without this guard, an external bot sender's turn would still+ // populate `state.metadata.activeDeviceId`, and `buildStepToolDelta`+ // re-injects `LocalSystemManifest` whenever activeDeviceId is set,+ // bypassing the engine's enabledToolIds exclusion. Skipping the+ // assignment here closes that bypass at the source.+ //// 1. If this run explicitly requested a device and that device is online, use it// 2. Otherwise, if the current topic has a bound device and it is online, use that// 3. Otherwise, fall back to the agent-level bound device when it is online// 4. Otherwise, in IM/Bot scenarios, auto-activate only when exactly one device is online- activeDeviceId = boundDeviceId- ? onlineDevices.some((device) => device.deviceId === boundDeviceId)- ? boundDeviceId- : undefined- : (discordContext || botContext) && onlineDevices.length === 1- ? onlineDevices[0].deviceId- : undefined;+ activeDeviceId = !canUseDevice+ ? undefined+ : boundDeviceId+ ? onlineDevices.some((device) => device.deviceId === boundDeviceId)+ ? boundDeviceId+ : undefined+ : (discordContext || botContext) && onlineDevices.length === 1+ ? onlineDevices[0].deviceId+ : undefined;const toolsEngine = createServerAgentToolsEngine(toolsContext, {additionalManifests: [...lobehubSkillManifests, ...klavisManifests],@@ -1002,6 +1029,7 @@ export class AiAgentService {chatConfig: agentConfig.chatConfig ?? undefined,plugins: agentPlugins,},+ canUseDevice,clientRuntime,deviceContext: gatewayConfigured? {@@ -1176,9 +1204,14 @@ export class AiAgentService {toolsResult.enabledToolIds.push(CLIENT_FN_IDENTIFIER);}- // Override RemoteDevice manifest's systemRole with dynamic device list prompt- // The manifest is already included/excluded by ToolsEngine enableChecker- if (toolManifestMap[RemoteDeviceManifest.identifier]) {+ // Override RemoteDevice manifest's systemRole with the dynamic device+ // list prompt. Gated on `canUseDevice` so an external bot sender's turn+ // never sees the owner's device inventory in the LLM system prompt β the+ // engine gate above already drops the manifest, but other paths (e.g.+ // discoverable manifests for the activator) still leave the entry in+ // `toolManifestMap`. Without this guard, the device list leaks into the+ // context regardless of whether the tool was actually enabled.+ if (canUseDevice && toolManifestMap[RemoteDeviceManifest.identifier]) {toolManifestMap[RemoteDeviceManifest.identifier] = {...toolManifestMap[RemoteDeviceManifest.identifier],systemRole: generateSystemPrompt(onlineDevices),@@ -1858,7 +1891,9 @@ export class AiAgentService {trigger,},autoStart,+ botContext,botPlatformContext,+ deviceAccessPolicy: { canUseDevice, reason: deviceAccessReason },discordContext,evalContext,initialContext,diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.tsindex 1cdd382f6fb..c2fcca01c11 100644--- a/src/server/services/bot/BotMessageRouter.ts+++ b/src/server/services/bot/BotMessageRouter.ts@@ -872,10 +872,18 @@ export class BotMessageRouter {(context?.skipped?.length ?? 0) + 1,((merged as any).attachments as unknown[] | undefined)?.length ?? 0,);+ const senderExternalUserId = merged.author?.userId ?? '';+ const isOwner = !!operatorUserId && senderExternalUserId === operatorUserId;try {await bridge.handleMention(thread, merged, {agentId,- botContext: { applicationId, platform, platformThreadId: thread.id },+ botContext: {+ applicationId,+ isOwner,+ platform,+ platformThreadId: thread.id,+ senderExternalUserId,+ },charLimit,client,displayToolCalls,@@ -986,10 +994,18 @@ export class BotMessageRouter {((merged as any).attachments as unknown[] | undefined)?.length ?? 0,);+ const senderExternalUserId = merged.author?.userId ?? '';+ const isOwner = !!operatorUserId && senderExternalUserId === operatorUserId;try {await bridge.handleSubscribedMessage(thread, merged, {agentId,- botContext: { applicationId, platform, platformThreadId: thread.id },+ botContext: {+ applicationId,+ isOwner,+ platform,+ platformThreadId: thread.id,+ senderExternalUserId,+ },charLimit,client,displayToolCalls,@@ -1109,10 +1125,18 @@ export class BotMessageRouter {((merged as any).attachments as unknown[] | undefined)?.length ?? 0,);+ const senderExternalUserId = merged.author?.userId ?? '';+ const isOwner = !!operatorUserId && senderExternalUserId === operatorUserId;try {await bridge.handleMention(thread, merged, {agentId,- botContext: { applicationId, platform, platformThreadId: thread.id },+ botContext: {+ applicationId,+ isOwner,+ platform,+ platformThreadId: thread.id,+ senderExternalUserId,+ },charLimit,client,displayToolCalls,diff --git a/src/server/services/bot/__tests__/BotMessageRouter.test.ts b/src/server/services/bot/__tests__/BotMessageRouter.test.tsindex ebdfc50c106..150d13c4e00 100644--- a/src/server/services/bot/__tests__/BotMessageRouter.test.ts+++ b/src/server/services/bot/__tests__/BotMessageRouter.test.ts@@ -715,6 +715,70 @@ describe('BotMessageRouter', () => {expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");});+ it('should propagate sender + isOwner=true on botContext when the owner @s the bot', async () => {+ const handler = await loadMentionHandler({ dmPolicy: 'open', userId: 'owner-platform-id' });+ const thread = {+ id: 'telegram:group-1',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ };+ const message = {+ author: { isBot: false, userId: 'owner-platform-id', userName: 'owner' },+ isMention: true,+ text: '@bot run a tool',+ };++ await handler(thread, message);++ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ const opts = mockHandleMention.mock.calls[0][2];+ expect(opts.botContext.senderExternalUserId).toBe('owner-platform-id');+ expect(opts.botContext.isOwner).toBe(true);+ });++ it('should propagate sender + isOwner=false on botContext when an external user @s the bot', async () => {+ const handler = await loadMentionHandler({ dmPolicy: 'open', userId: 'owner-platform-id' });+ const thread = {+ id: 'telegram:group-1',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ };+ const message = {+ author: { isBot: false, userId: 'random-user-id', userName: 'random' },+ isMention: true,+ text: '@bot rm -rf',+ };++ await handler(thread, message);++ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ const opts = mockHandleMention.mock.calls[0][2];+ expect(opts.botContext.senderExternalUserId).toBe('random-user-id');+ expect(opts.botContext.isOwner).toBe(false);+ });++ it('should fall back to isOwner=false when settings.userId is missing (fail-closed)', async () => {+ // No `userId` configured on the bot β even a sender who happens to+ // share an ID with the operator can't claim owner status.+ const handler = await loadMentionHandler({ dmPolicy: 'open' });+ const thread = {+ id: 'telegram:group-1',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ };+ const message = {+ author: { isBot: false, userId: 'someone', userName: 'someone' },+ isMention: true,+ text: '@bot hi',+ };++ await handler(thread, message);++ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ const opts = mockHandleMention.mock.calls[0][2];+ expect(opts.botContext.isOwner).toBe(false);+ });+it('should block DM @-mentions from users outside the allowlist and notify the sender', async () => {const handler = await loadMentionHandler({allowFrom: 'bob-id',diff --git a/src/server/services/messenger/MessengerRouter.ts b/src/server/services/messenger/MessengerRouter.tsindex ad468a6346b..4583d21c3af 100644--- a/src/server/services/messenger/MessengerRouter.ts+++ b/src/server/services/messenger/MessengerRouter.ts@@ -871,6 +871,14 @@ export class MessengerRouter {const serverDB = await getServerDB();const bridge = new AgentBridgeService(serverDB, link.userId);+ // Messenger account-link routing already binds platform sender β+ // LobeHub user; the dispatch only fires for the linked sender. So+ // `isOwner` is true iff the inbound message's `author.userId` matches+ // the linked `platformUserId`. Falls back to false when either is+ // missing (fail-closed β never default device access to "trusted").+ const senderExternalUserId = message.author?.userId ?? '';+ const isOwner = !!link.platformUserId && senderExternalUserId === link.platformUserId;+await bridge.handleMention(thread, message, {agentId,botContext: {@@ -879,6 +887,7 @@ export class MessengerRouter {applicationId: link.tenantId? `messenger-${platform}-${link.tenantId}`: `messenger-${platform}`,+ isOwner,// Explicit, deterministic marker that this run originated from the// shared Messenger bot. `BotCallbackService` uses the presence of this// field to resolve credentials via the messenger install store instead@@ -889,6 +898,7 @@ export class MessengerRouter {: `${platform}:singleton`,platform,platformThreadId: thread.id,+ senderExternalUserId,},client,});