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.

♻️ refactor(server): split the 1442-line toolDiscovery into cohesive modules (#21141)

Arvin Xu01ec0fe40529
diff --git a/.agents/skills/add-model-provider/references/integration-map.md b/.agents/skills/add-model-provider/references/integration-map.md
index 866cf7bb59c..3338d0d0eb9 100644
--- a/.agents/skills/add-model-provider/references/integration-map.md
+++ b/.agents/skills/add-model-provider/references/integration-map.md
@@ -4,23 +4,23 @@ Use this map to locate the current code. Verify paths and consumers before editi
## Registration and Configuration
-| Concern | Current location | What to verify |
-| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Provider identity | `packages/model-bank/src/const/modelProvider.ts` | Stable `ModelProvider` ID used by all maps |
-| Provider card | `packages/model-bank/src/modelProviders/<provider>.ts` | Name, public URLs, `checkModel`, authentication, fetcher and browser settings |
-| Provider registration | `packages/model-bank/src/modelProviders/index.ts` | Import, `DEFAULT_MODEL_PROVIDER_LIST` position, card export |
-| Model cards | `packages/model-bank/src/aiModels/<provider>.ts` | Evidence-backed metadata, supported abilities, default enablement, prices |
-| Model registration | `packages/model-bank/src/aiModels/index.ts` | Import, `staticModelMap`, named export keyed to the provider ID |
-| Package access | `packages/model-bank/package.json` | New model module's subpath export, including filename casing |
-| Runtime implementation | `packages/model-runtime/src/providers/<provider>/index.ts` | Factory reuse, endpoint, protocol, payload and response behavior |
-| Runtime registration | `packages/model-runtime/src/runtimeMap.ts`, `packages/model-runtime/src/index.ts` | ID-to-runtime map and public export |
-| Distinct routed adapter | `packages/model-runtime/src/core/RouterRuntime/apiTypes.ts`, `baseRuntimeMap.ts` | Add only when this adapter is needed; test runtime selection |
-| API-key environment | `packages/env/src/llm.ts` | Schema and `runtimeEnv`; enablement semantics |
-| Server provider configuration | `apps/server/src/globalConfig/genServerAiProviderConfig.ts` | Generic uppercase ID conventions, model list and enablement overrides |
-| Runtime credentials/options | `apps/server/src/modules/ModelRuntime/index.ts` | Generic API-key/proxy handling versus provider-specific initialization |
-| OAuth flow | `apps/server/src/services/oauthDeviceFlow/`, `apps/server/src/routers/lambda/oauthDeviceFlow.ts` | Factory registration, token exchange/refresh, account metadata, disconnect |
-| New parameter controls | `packages/model-bank/src/types/aiModel.ts`, `packages/types/src/agent/chatConfig.ts`, `packages/mecha/src/modelParams/resolveModelParams.ts` | The shared resolver owns the policy for every host; `src/services/chat/mecha/modelParamsResolver.ts` and `apps/server/src/modules/Mecha/ModelParams/providers.ts` only fetch. Trace consumers into controls and translations; avoid changing types alone. A server run resolves the params from the `modelRuntimeConfig.modelFacts` snapshot frozen once in `toolDiscovery.ts`, so a new source the rules must read has to be added to `readFrozenModelFacts` as well, or it stays unread on every step |
-| Default list consumption | `packages/database/src/repositories/aiInfra/index.ts`, `src/store/aiInfra/slices/aiProvider/selectors.ts` | Built-in order versus enabled-provider custom sort |
+| Concern | Current location | What to verify |
+| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Provider identity | `packages/model-bank/src/const/modelProvider.ts` | Stable `ModelProvider` ID used by all maps |
+| Provider card | `packages/model-bank/src/modelProviders/<provider>.ts` | Name, public URLs, `checkModel`, authentication, fetcher and browser settings |
+| Provider registration | `packages/model-bank/src/modelProviders/index.ts` | Import, `DEFAULT_MODEL_PROVIDER_LIST` position, card export |
+| Model cards | `packages/model-bank/src/aiModels/<provider>.ts` | Evidence-backed metadata, supported abilities, default enablement, prices |
+| Model registration | `packages/model-bank/src/aiModels/index.ts` | Import, `staticModelMap`, named export keyed to the provider ID |
+| Package access | `packages/model-bank/package.json` | New model module's subpath export, including filename casing |
+| Runtime implementation | `packages/model-runtime/src/providers/<provider>/index.ts` | Factory reuse, endpoint, protocol, payload and response behavior |
+| Runtime registration | `packages/model-runtime/src/runtimeMap.ts`, `packages/model-runtime/src/index.ts` | ID-to-runtime map and public export |
+| Distinct routed adapter | `packages/model-runtime/src/core/RouterRuntime/apiTypes.ts`, `baseRuntimeMap.ts` | Add only when this adapter is needed; test runtime selection |
+| API-key environment | `packages/env/src/llm.ts` | Schema and `runtimeEnv`; enablement semantics |
+| Server provider configuration | `apps/server/src/globalConfig/genServerAiProviderConfig.ts` | Generic uppercase ID conventions, model list and enablement overrides |
+| Runtime credentials/options | `apps/server/src/modules/ModelRuntime/index.ts` | Generic API-key/proxy handling versus provider-specific initialization |
+| OAuth flow | `apps/server/src/services/oauthDeviceFlow/`, `apps/server/src/routers/lambda/oauthDeviceFlow.ts` | Factory registration, token exchange/refresh, account metadata, disconnect |
+| New parameter controls | `packages/model-bank/src/types/aiModel.ts`, `packages/types/src/agent/chatConfig.ts`, `packages/mecha/src/modelParams/resolveModelParams.ts` | The shared resolver owns the policy for every host; `src/services/chat/mecha/modelParamsResolver.ts` and `apps/server/src/modules/Mecha/ModelParams/providers.ts` only fetch. Trace consumers into controls and translations; avoid changing types alone. A server run resolves the params from the `modelRuntimeConfig.modelFacts` snapshot frozen once by `resolveModelContext` in `apps/server/src/services/aiAgent/pipeline/toolDiscovery/modelFacts.ts`, so a new source the rules must read has to be added to `readFrozenModelFacts` as well, or it stays unread on every step |
+| Default list consumption | `packages/database/src/repositories/aiInfra/index.ts`, `src/store/aiInfra/slices/aiProvider/selectors.ts` | Built-in order versus enabled-provider custom sort |
Provider-specific `*_MODEL_LIST` and `*_PROXY_URL` may be consumed dynamically. Trace the configuration path before adding redundant schema entries or documenting an unsupported variable. The deprecated `LOBE_DEFAULT_MODEL_LIST` is not a substitute for the modern model map; inspect actual consumers before changing it.
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
deleted file mode 100644
index b330e86f923..00000000000
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ /dev/null
@@ -1,1439 +0,0 @@
-import { CredsIdentifier } from '@lobechat/builtin-tool-creds';
-import { GoalIdentifier, isGoalPrompt } from '@lobechat/builtin-tool-goal';
-import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
-import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
-import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
-import { generateSystemPrompt, RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
-import {
- injectSelfFeedbackIntentTool,
- shouldExposeSelfFeedbackIntentTool,
-} from '@lobechat/builtin-tool-self-iteration';
-import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';
-import { getFeatureDisabledToolIds } from '@lobechat/builtin-tools/featureGates';
-import type {
- AgentGroupConfig,
- LobeToolManifest,
- ToolExecutor,
- ToolsEngine,
- ToolSource,
-} from '@lobechat/context-engine';
-import type { LobeChatDatabase } from '@lobechat/database';
-import type { DeviceUnavailableErrorData } from '@lobechat/device-gateway-client';
-import {
- dropInvalidManifests,
- readFrozenModelFacts,
- resolveClientExecutors,
- resolveDiscoveryPool,
- resolveInvocationToolIds,
-} from '@lobechat/mecha';
-import { FILE_PREVIEW_CHARS, isOversizedFileContent } from '@lobechat/prompts';
-import type {
- BuiltinToolResolveContext,
- ChatTopicBotContext,
- FrozenCredentialFacts,
- FrozenModelFacts,
- RequestTrigger,
-} from '@lobechat/types';
-import {
- agentShareFileAccessScope,
- getActivePluginIds,
- ordinaryFileAccessScope,
-} from '@lobechat/types';
-import { TRPCError } from '@trpc/server';
-import debug from 'debug';
-import type { AiModelConfig, ModelAbilities } from 'model-bank';
-
-import { loadModels } from '@/business/client/model-bank/loadModels';
-import { AiModelModel } from '@/database/models/aiModel';
-import { AiProviderModel } from '@/database/models/aiProvider';
-import { ChatGroupModel } from '@/database/models/chatGroup';
-import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';
-import { ConnectorToolModel } from '@/database/models/connectorTool';
-import { DocumentModel } from '@/database/models/document';
-import { FileModel } from '@/database/models/file';
-import type { MessageModel } from '@/database/models/message';
-import type { PluginModel } from '@/database/models/plugin';
-import type { UserConnectorToolItem } from '@/database/schemas';
-import {
- type ExecutionPlan,
- executionPlanToManifestExecutionEnv,
- isDeviceCapablePlan,
- isDeviceLockedPlan,
- resolveExecutionPlan,
- resolveToolMode,
-} from '@/helpers/executionTarget';
-import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
-import { patchManifestWithPermissions } from '@/libs/mcp/connectorPermissionCheck';
-import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
-import { resolveModelMediaCapabilities } from '@/server/modules/AgentRuntime/resolveModelMediaCapabilities';
-import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
-import type { ServerAgentToolsContext } from '@/server/modules/Mecha';
-import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
-import { createServerModelParamsProviders } from '@/server/modules/Mecha/ModelParams/providers';
-import type { AgentDocumentsService } from '@/server/services/agentDocuments';
-import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
-import { resolveUnsupportedMessageApis } from '@/server/services/bot/platforms/messageCapabilities';
-import type { ComposioService } from '@/server/services/composio';
-import {
- buildLastSyncedAtMap,
- scheduleStaleConnectorToolsRefresh,
-} from '@/server/services/connector/refresh';
-import { deviceGateway } from '@/server/services/deviceGateway';
-import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
-import type { MarketService } from '@/server/services/market';
-import {
- buildConnectorOwnershipPrompt,
- collectBorrowedConnectors,
- resolveUserDisplayMap,
-} from '@/server/utils/connectorAttribution';
-
-import { buildAllowedBuiltinTools } from '../deviceToolRegistry';
-import { buildBotConversationGroupContext, buildGroupAgentContext } from '../helpers/groupContext';
-import {
- getMediaAvailabilityFromFileTypes,
- getMediaAvailabilityFromMessages,
- isMultimodalUnderstandingConfigured,
-} from '../helpers/mediaAvailability';
-import { resolveServerSearchDecision } from '../searchDecision';
-import {
- filterPluginsByShareGate,
- getShareGrantActivatedPluginIds,
- shareGateGrantsCloudSandbox,
-} from '../shareGate';
-import type { ExecRunContext, InternalExecAgentParams } from '../types';
-import { markDegradedStage, traceDiscoveryStage } from './discoveryTracing';
-
-const log = debug('lobe-server:ai-agent-service');
-
-/**
- * Start a read now and keep its rejection for the caller's `await`.
- *
- * A promise that rejects before anything awaits it trips Node's
- * `unhandledRejection` even though this code does await it a few lines later,
- * so register a no-op handler on the original and hand the same promise back.
- */
-const started = <T>(task: Promise<T>): Promise<T> => {
- task.catch(() => undefined);
- return task;
-};
-
-export interface ToolDiscoveryDeps {
- agentDocumentsService: AgentDocumentsService;
- composioService: ComposioService;
- connectorModel: ConnectorModel;
- connectorToolModel: ConnectorToolModel;
- db: LobeChatDatabase;
- getMarketService: () => Promise<MarketService>;
- messageModel: MessageModel;
- pluginModel: PluginModel;
- userId: string;
- workspaceId?: string;
-}
-
-export interface ToolDiscoveryInput {
- additionalPluginIds?: string[];
- agentSlug?: string | null;
- attachedFileIds?: string[];
- botContext?: ChatTopicBotContext;
- /** Tri-state disabled plugin identifiers captured before pinned-id collapse. */
- disabledPluginIds: string[];
- disableLocalSystem?: boolean;
- disableSelfFeedbackIntentTool?: boolean;
- disableTools?: boolean;
- discordContext?: any;
- exclusivePluginIds?: string[];
- /**
- * Mime types of the raw bot/IM uploads. The stage only ever looked at the
- * mime type, and keeping the request JSON-safe is what lets a deferred init
- * carry it on the operation state.
- */
- externalFileTypes?: string[];
- functionTools?: InternalExecAgentParams['functionTools'];
- globalMemoryEnabled: boolean;
- hasMentionedAgents: boolean;
- isFixedDeviceTarget: boolean;
- /** Shared lazy history loader β€” also consumed by the caller after discovery. */
- loadHistoryMessages: () => Promise<any[]>;
- localDeviceId?: string;
- requestedDeviceId?: string;
- requestTrigger?: RequestTrigger;
- selectedToolIds?: string[];
- throwIfExecutionAborted: (stage: string) => Promise<void>;
- topicBoundDeviceId?: string | null;
-}
-
-export interface ToolDiscoveryResult {
- activeDeviceId?: string;
- activeDeviceScope?: 'personal' | 'workspace';
- agentPlugins: string[];
- builtinModels: Awaited<ReturnType<typeof loadModels>>;
- composioManifests: LobeToolManifest[];
- connectorManifests: ReturnType<typeof buildConnectorManifests>;
- /**
- * Tells the model whose connected account each borrowed tool runs on. Run
- * context: it travels on the operation and the context engine injects it.
- */
- connectorOwnershipNote?: string;
- /**
- * Credentials listed once for the whole operation; see
- * {@link FrozenCredentialFacts}. Absent when the run cannot inject
- * credentials.
- *
- * Deliberately still a promise: awaiting it here would put a Market round
- * trip between tool discovery and operation preparation, on the path to the
- * first token. The caller awaits it once the preparation it overlaps with is
- * done. Never rejects β€” a failed read resolves to `undefined` and the run
- * reads the list live, as it did before the snapshot existed.
- */
- credentialFactsPromise?: Promise<FrozenCredentialFacts | undefined>;
- executionPlan?: ExecutionPlan;
- hasAgentDocuments: boolean;
- hasEnabledKnowledgeBases: boolean;
- lobehubSkillManifests: LobeToolManifest[];
- /** Model facts read once for the whole operation; see {@link FrozenModelFacts}. */
- modelFacts: FrozenModelFacts;
- modelMediaCapabilities: Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;
- onlineDevices: DeviceAttachment[];
- operationAgentGroup?: AgentGroupConfig;
- searchDecision: ReturnType<typeof resolveServerSearchDecision>;
- toolExecutorMap: Record<string, ToolExecutor>;
- toolManifestMap: Record<string, any>;
- tools?: any[];
- toolsEngine?: ToolsEngine;
- toolSourceMap: Record<string, ToolSource>;
- toolsResult: { enabledToolIds: string[]; tools?: any[] | undefined };
-}
-
-/**
- * Stage 5 (5a–5f) of {@link AiAgentService.execAgent}: tool discovery.
- *
- * Resolves the full tool surface for the run β€” installed plugins, connectors
- * (real-MCP replacement + permission patching), LobeHub Skills, Composio
- * manifests, device pool + execution plan, group-orchestration authorization,
- * the tools-engine invocation pool, and the activator-discoverable manifest
- * map β€” plus the Response-API client function tools and the RemoteDevice
- * systemRole override.
- *
- * Short-circuits when `disableTools` is set (only the client function tools
- * are honored), matching the pre-extraction behavior.
- *
- * Returns the connector credential ownership note as run context when the run
- * borrows connectors other members authorized; the context engine injects it.
- */
-/**
- * The credentials the run may reference, read once. Inside a workspace an agent
- * only sees the workspace's shared organization credentials, never the
- * operator's personal ones β€” the scope is recorded on the snapshot so a step in
- * another scope falls back to a live read.
- *
- * Never fails the turn: without an answer the steps read the list live, exactly
- * as they did before the snapshot existed.
- */
-const readCredentialFacts = async (
- deps: ToolDiscoveryDeps,
-): Promise<FrozenCredentialFacts | undefined> => {
- try {
- const marketService = await deps.getMarketService();
- const result = deps.workspaceId
- ? await marketService.market.organizations.creds({ workspaceId: deps.workspaceId }).list()
- : await marketService.market.creds.list();
- const creds = (result as any)?.data ?? [];
- return {
- credentials: creds.map((cred: any) => ({
- description: cred.description,
- key: cred.key,
- name: cred.name,
- ownerDisplayName: cred.ownerDisplayName,
- ownerType: cred.ownerType,
- type: cred.type,
- })),
- workspaceId: deps.workspaceId,
- };
- } catch (error) {
- log('execAgent: failed to freeze credential facts: %O', error);
- return undefined;
- }
-};
-
-export const discoverTools = async (
- deps: ToolDiscoveryDeps,
- ctx: ExecRunContext,
- input: ToolDiscoveryInput,
-): Promise<ToolDiscoveryResult> => {
- /** Filled below when the run borrows connectors; returned as run context. */
- let connectorOwnershipNote: string | undefined;
- const {
- agentConfig,
- appContext,
- assistantMessageId,
- canUseDevice,
- model,
- prompt,
- provider,
- resolvedAgentId,
- shareGate,
- topicId,
- } = ctx;
- const {
- additionalPluginIds,
- attachedFileIds,
- botContext,
- disableLocalSystem,
- disableSelfFeedbackIntentTool,
- disableTools,
- disabledPluginIds: requestedDisabledPluginIds,
- discordContext,
- exclusivePluginIds,
- externalFileTypes: rawExternalFileTypes,
- functionTools,
- globalMemoryEnabled,
- hasMentionedAgents,
- isFixedDeviceTarget,
- loadHistoryMessages,
- localDeviceId,
- requestTrigger,
- requestedDeviceId,
- selectedToolIds,
- throwIfExecutionAborted,
- topicBoundDeviceId,
- } = input;
- // Feature-flagged builtin tools (e.g. lobe-dashboard) leave the pool while
- // their flag is off for this user; a flag read failure keeps them out.
- const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(deps.userId).catch(
- () => undefined,
- );
- const disabledPluginIds = [
- ...requestedDisabledPluginIds,
- ...getFeatureDisabledToolIds(featureFlags),
- ];
-
- let tools: any[] | undefined;
- /** Started once the tool set is known; awaited at the return. */
- let credentialFactsPromise: Promise<FrozenCredentialFacts | undefined> | undefined;
- let toolsResult: { enabledToolIds: string[]; tools?: any[] | undefined } = {
- enabledToolIds: [],
- tools: undefined,
- };
- let toolsEngine: ToolsEngine | undefined;
- const toolManifestMap: Record<string, any> = {};
- const toolSourceMap: Record<string, ToolSource> = {};
- const toolExecutorMap: Record<string, ToolExecutor> = {};
- let onlineDevices: DeviceAttachment[] = [];
- let activeDeviceId: string | undefined;
- let activeDeviceScope: 'personal' | 'workspace' | undefined;
- let executionPlan: ExecutionPlan | undefined;
- let hasAgentDocuments = false;
- let hasEnabledKnowledgeBases = false;
- let operationAgentGroup: AgentGroupConfig | undefined;
- const isBotConversation = !!(botContext || discordContext);
-
- // Device-tool access (`canUseDevice` / `deviceAccessReason`) was resolved
- // once before the hetero early exit; the decision flows into the
- // engine's enable gates (LocalSystem / RemoteDevice) and the RemoteDevice
- // systemRole injection below.
-
- // These are needed outside the tools block (for agent management context, skill engine, etc.)
- let lobehubSkillManifests: LobeToolManifest[] = [];
- let composioManifests: LobeToolManifest[] = [];
- let connectorManifests: ReturnType<typeof buildConnectorManifests> = [];
-
- // `selectedToolIds` are the user's @-mention picks for this turn; merged in
- // (deduped) alongside the agent's pinned plugins and any internal
- // `additionalPluginIds` so a mentioned-but-not-pinned tool (e.g. a custom MCP
- // connector) is both queried for manifests and enabled by the tools engine.
- const isGoalTurn = isGoalPrompt(prompt);
- let agentPlugins: string[] = exclusivePluginIds
- ? [...new Set(exclusivePluginIds)]
- : isGoalTurn
- ? [GoalIdentifier]
- : [
- ...new Set([
- ...getActivePluginIds(agentConfig?.plugins),
- ...(additionalPluginIds || []),
- ...(selectedToolIds || []),
- ...(hasMentionedAgents ? ['lobe-agent-management'] : []),
- ...(shareGate ? getShareGrantActivatedPluginIds(shareGate) : []),
- ]),
- ];
-
- // Share allowlist runs EARLY, before connector resolution / credential
- // decryption / stale-tool refresh scheduling β€” otherwise an ungranted HTTP
- // connector pinned on the creator's agent would still be resolved and its
- // OAuth credentials touched for a visitor turn (issuing background MCP
- // traffic and refresh jobs on behalf of the creator). The later pass right
- // before manifest discovery (~line 618) stays as defense in depth: internal
- // additions like the bot message / multimodal
- // understanding tool are appended after this point and must run through the
- // same allowlist.
- if (shareGate) {
- agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);
- }
-
- // Model metadata is needed both for tool support checks and agent-management context.
- const builtinModels = await loadModels();
- // Started, not awaited: the tool reads below hit other backends entirely, so
- // this round trip overlaps them instead of gating them.
- const modelMetadataTask = traceDiscoveryStage('model_metadata', async (span) => {
- const results = await Promise.allSettled([
- new AiModelModel(deps.db, deps.userId, deps.workspaceId).findByIdAndProvider(model, provider),
- new AiProviderModel(deps.db, deps.userId, deps.workspaceId).findById(provider),
- ]);
- markDegradedStage(
- span,
- results.filter((result) => result.status === 'rejected').length,
- 'metadata lookups',
- );
- return results;
- });
- /**
- * Connector resolution: the gatekeeper decrypts the stored OAuth tokens, or
- * `buildConnectorManifests` gets no auth and every tool call 401s.
- */
- async function readConnectors() {
- // Snapshot the candidate ids now β€” `agentPlugins` gains turn-scoped builtins
- // (topic reference, bot message, multimodal understanding) further down, and
- // those must not reach connector resolution or the stale-tools refresh.
- const candidateIds = [...agentPlugins];
- let connectorGateKeeper: KeyVaultsGateKeeper | undefined;
- try {
- connectorGateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
- } catch (err) {
- log('execAgent: failed to init gatekeeper for connector credentials: %O', err);
- }
-
- return traceDiscoveryStage('connectors', async () => {
- const connectors =
- candidateIds.length > 0
- ? await deps.connectorModel.resolveByIdentifiers(
- candidateIds,
- resolvedAgentId,
- connectorGateKeeper,
- )
- : [];
-
- // Only connectors WITH a real MCP endpoint (mcpServerUrl or stdio) can replace plugins in the
- // manifest. Connectors WITHOUT an endpoint (e.g. Lobehub/Composio OAuth skills synced via
- // syncToolsFromClient) must continue using their original plugin executor path β€” otherwise
- // after humanIntervention approval the runtime tries to call mcpServerUrl='' and returns empty.
- const connectorsMcp = connectors.filter(
- (c) => c.mcpServerUrl || c.mcpConnectionType === 'stdio',
- );
-
- // Fetch ALL tools for all real-MCP connectors (including disabled tools) so that
- // buildConnectorManifests can show blocking descriptions for disabled tools.
- // The runtime hot-path still uses queryByConnectorIds (non-disabled only) elsewhere.
- const connectorTools =
- connectorsMcp.length > 0
- ? await deps.connectorToolModel.queryAllByConnectorIds(connectorsMcp.map((c) => c.id))
- : [];
-
- const discoverable = await readDiscoverableConnectors(candidateIds, connectorGateKeeper);
-
- return {
- connectorGateKeeper,
- connectors,
- connectorsMcp,
- connectorTools,
- discoverableConnectorManifests: discoverable.manifests,
- discoverableConnectorsMcp: discoverable.connectorsMcp,
- discoverableConnectorTools: discoverable.tools,
- };
- });
- }
-
- /**
- * Connectors the agent has not pinned β€” `auto` in the three-state plugin
- * config, which is simply "absent from `plugins`". A custom MCP is stored as
- * a connector, so without this source an unpinned one is resolvable only on
- * the turn that @-mentions it: the next turn's activator answers
- * "Not found" and the model's direct call is rejected as an unknown name.
- * Like installed plugins they are discoverable but never enabled.
- *
- * Share runs skip it: the early allowlist above exists so ungranted creator
- * connectors never get their credentials decrypted for a visitor turn.
- * Degrades to nothing on failure β€” widening discovery must not fail the run.
- */
- async function readDiscoverableConnectors(
- candidateIds: string[],
- gateKeeper: KeyVaultsGateKeeper | undefined,
- ): Promise<{
- connectorsMcp: DecryptedConnector[];
- manifests: LobeToolManifest[];
- tools: UserConnectorToolItem[];
- }> {
- const none = { connectorsMcp: [], manifests: [], tools: [] };
- if (shareGate || exclusivePluginIds || isGoalTurn) return none;
- try {
- const candidates = new Set(candidateIds);
- const connectorsMcp = (
- await deps.connectorModel.resolveAll(resolvedAgentId, gateKeeper)
- ).filter(
- (c) => !candidates.has(c.identifier) && (c.mcpServerUrl || c.mcpConnectionType === 'stdio'),
- );
- if (connectorsMcp.length === 0) return none;
-
- const tools = await deps.connectorToolModel.queryAllByConnectorIds(
- connectorsMcp.map((c) => c.id),
- );
- return {
- connectorsMcp,
- manifests: buildConnectorManifests(connectorsMcp, tools) as LobeToolManifest[],
- tools,
- };
- } catch (error) {
- log('execAgent: failed to read discoverable connectors: %O', error);
- return none;
- }
- }
-
- async function readLobehubSkillManifests(): Promise<LobeToolManifest[]> {
- try {
- const marketService = await deps.getMarketService();
- return await traceDiscoveryStage('lobehub_skills', async (span) => {
- // The service degrades to fewer (or zero) manifests instead of
- // throwing, so count what it absorbed β€” otherwise a Market timeout
- // looks exactly like a user with no connected skills.
- let failureCount = 0;
- const manifests = await marketService.getLobehubSkillManifests({
- onError: () => {
- failureCount += 1;
- },
- });
- span.setAttribute('lobehub.tool_discovery.manifest_count', manifests.length);
- markDegradedStage(span, failureCount, 'skill discovery requests');
- return manifests;
- });
- } catch (error) {
- log('execAgent: failed to fetch lobehub skill manifests: %O', error);
- return [];
- }
- }
-
- async function readDevicePool(): Promise<DeviceAttachment[]> {
- if (!deviceGateway.isConfigured) return [];
- try {
- // Personal pool βˆͺ the current workspace pool, DB rows βŠ• gateway online,
- // tagged with `scope` and the user-set `friendlyName` alias (see
- // `getScopedOnlineDevices`) so the systemRole snapshot lets the model
- // tell a personal machine apart from its workspace-enrolled counterpart
- // (same physical machine under both principals). Keep only live devices:
- // downstream `onlineDeviceIds` / `deviceOnline` treat this list as the
- // online set.
- let devices = (
- await traceDiscoveryStage('online_devices', () =>
- getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId),
- )
- ).filter((d) => d.online);
-
- // A workspace run that targets one of the caller's PERSONAL devices
- // needs that device visible in this run's pool β€” otherwise
- // `resolveExecutionPlan` treats it as offline (`bound-device-offline`)
- // and the run stays unrouted. The workspace pool never includes
- // personal devices by design (`getScopedOnlineDevices` enforces the
- // strict scope), so union the specific personal device in here. The
- // device is dispatchable because the gateway routes it by
- // `(userId, deviceId)` β€” the caller owns it.
- //
- // Candidates mirror the ids `resolveExecutionPlan` routes by:
- // - `agencyConfig.boundDeviceId`: the per-user override written by the
- // `local` code path in `useSelectExecutionTarget`;
- // - `requestedDeviceId`: the desktop's own id sent with a `local` run
- // (or the topic's pinned device, folded in by `turnSetup`). Without
- // it, an agent whose stored target is `local` but which has no
- // override is told the user's online desktop is offline. A `fixed`
- // selection policy ignores it, as the resolver does.
- const isFixedSelection = agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
- const personalCandidateIds = [
- ...new Set(
- [
- agentConfig.agencyConfig?.boundDeviceId,
- isFixedSelection ? undefined : requestedDeviceId,
- ].filter((id): id is string => !!id && !devices.some((d) => d.deviceId === id)),
- ),
- ];
- if (deps.workspaceId && personalCandidateIds.length > 0) {
- const personalPool = await getScopedOnlineDevices(deps.db, deps.userId).catch(
- () => [] as DeviceAttachment[],
- );
- const personalMatches = personalPool.filter(
- (d) => d.online && personalCandidateIds.includes(d.deviceId),
- );
- if (personalMatches.length > 0) {
- devices = [...devices, ...personalMatches];
- log(
- 'execAgent: augmented device pool with caller personal device(s) %o',
- personalMatches.map((d) => d.deviceId),
- );
- }
- }
- log('execAgent: found %d online device(s)', devices.length);
- return devices;
- } catch (error) {
- log('execAgent: failed to query device list: %O', error);
- return [];
- }
- }
-
- async function readAttachedFileTypes(): Promise<string[]> {
- if (!attachedFileIds || attachedFileIds.length === 0) return [];
- const fileModel = new FileModel(deps.db, deps.userId, deps.workspaceId);
- const uniqueFileIds = Array.from(new Set(attachedFileIds));
- const fileRecords = await traceDiscoveryStage('attached_files', () =>
- fileModel.findByIds(
- uniqueFileIds,
- shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
- ),
- );
- return fileRecords.map((file) => file.fileType || '');
- }
-
- /**
- * Whether this turn can send any file as a truncated preview (see `previewLongFileContent`):
- * an enabled agent file over the inline limit, or a parsed attachment of this turn or topic
- * longer than a preview. Attachments under the inline limit are still previewed once the
- * request's attachment budget is spent (`planAttachmentPreviews`), which is only known per step,
- * so any attachment a preview would shorten enables the tool.
- * Enables the attachments tool in the modes whose rules include it (agent / chat). The preview
- * only names `readAttachment` when the final tool set carries it (see `MessagesEngine`), so
- * custom / exclusive tool turns and share visitors fall back to a plain preview.
- */
- async function readHasOversizedFiles(): Promise<boolean> {
- const hasOversizedAgentFile = agentConfig.files?.some(
- (file: { content?: string | null; enabled?: boolean | null; originalCharCount?: number }) =>
- file.enabled === true &&
- isOversizedFileContent(file.content?.length ?? 0, file.originalCharCount),
- );
- if (hasOversizedAgentFile) return true;
- if (!topicId && !attachedFileIds?.length) return false;
-
- return traceDiscoveryStage('oversized_files', () =>
- new DocumentModel(deps.db, deps.userId, deps.workspaceId).hasFileDocumentsOverChars({
- fileIds: attachedFileIds,
- minChars: FILE_PREVIEW_CHARS,
- topicId,
- }),
- );
- }
-
- // Every other read this send needs, started together. They hit different
- // backends β€” Postgres rows, the Market's live skill discovery, the device
- // gateway β€” and none of them feeds another, so the user waits for the slowest
- // one instead of the sum of all of them. Each keeps the degrade-to-empty
- // behavior it had when it ran in sequence; only the plugin list still fails
- // the run, because a run with no plugins is not the same run.
- const toolReads = disableTools
- ? undefined
- : {
- // The fallbacks sit OUTSIDE `traceDiscoveryStage` on purpose: the wrapper
- // only marks a span errored when its callback throws, so absorbing the
- // failure inside it would report a healthy stage for a failed read.
- agentDocuments: started(
- traceDiscoveryStage('agent_documents', () =>
- deps.agentDocumentsService.hasDocuments(resolvedAgentId),
- ).catch(() => false), // non-critical
- ),
- attachedFileTypes: started(readAttachedFileTypes()),
- oversizedFiles: started(readHasOversizedFiles().catch(() => false)), // non-critical
- composioManifests: started(
- traceDiscoveryStage('composio', () =>
- deps.composioService.getComposioManifests(resolvedAgentId),
- ).catch((error) => {
- log('execAgent: failed to fetch composio manifests: %O', error);
- return [] as LobeToolManifest[];
- }),
- ),
- connectors: started(readConnectors()),
- devicePool: started(readDevicePool()),
- installedPlugins: started(
- traceDiscoveryStage('installed_plugins', () => deps.pluginModel.query()),
- ),
- lobehubSkillManifests: started(readLobehubSkillManifests()),
- };
-
- const [modelMetadataResult, providerMetadataResult] = await modelMetadataTask;
- if (modelMetadataResult.status === 'rejected') {
- log('execAgent: failed to load active model search metadata: %O', modelMetadataResult.reason);
- }
- if (providerMetadataResult.status === 'rejected') {
- log(
- 'execAgent: failed to load active provider search metadata: %O',
- providerMetadataResult.reason,
- );
- }
- const activeModelMetadata =
- modelMetadataResult.status === 'fulfilled' ? modelMetadataResult.value : undefined;
- const activeProviderMetadata =
- providerMetadataResult.status === 'fulfilled' ? providerMetadataResult.value : undefined;
- const activeModelAbilities = activeModelMetadata?.abilities as ModelAbilities | undefined;
- const modelMediaCapabilities =
- resolveModelMediaCapabilities({
- builtinModels,
- model,
- provider,
- userAbilities: activeModelAbilities,
- }) ?? {};
- // The rest of the run's model facts, read here because this stage already
- // holds the loaded bank and the user's model row. Everything downstream β€” one
- // per step, retries included β€” reads them back off the operation instead.
- const modelFacts = await readFrozenModelFacts(
- {
- agent: { id: agentConfig.id },
- mediaCapabilities: modelMediaCapabilities,
- model,
- provider,
- topicId,
- },
- {
- ...createServerModelParamsProviders({
- builtinModels,
- serverDB: deps.db,
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- }),
- // Reuse the row read above rather than querying it a second time.
- getUserModelRow: async () =>
- activeModelMetadata
- ? {
- abilities: activeModelMetadata.abilities,
- // Deployment-catalog providers resolve the request model by the
- // user-configured alias when present (merged over the bundled
- // card when the facts freeze).
- deploymentName:
- (activeModelMetadata.config as AiModelConfig | null)?.deploymentName ?? null,
- displayName: activeModelMetadata.displayName,
- extendParams: activeModelMetadata.settings?.extendParams ?? undefined,
- }
- : null,
- },
- );
- const searchDecision = resolveServerSearchDecision({
- builtinModels,
- chatConfig: agentConfig.chatConfig ?? undefined,
- hasModelAbilitiesOverride:
- !!activeModelAbilities && Object.keys(activeModelAbilities).length > 0,
- model,
- modelSearchAbility: activeModelAbilities?.search,
- modelSearchImpl: activeModelMetadata?.settings?.searchImpl,
- provider,
- providerSearchMode: activeProviderMetadata?.settings?.searchMode,
- });
-
- if (!toolReads) {
- log('execAgent: tools disabled by disableTools flag, skipping all tool discovery');
- } else {
- // 5a. Get installed plugins from database. Disabled identifiers are
- // excluded from this candidate pool entirely β€” not just from the pinned
- // `rules` allowlist β€” because `createEnableChecker`'s explicit-activation
- // bypass (auto activator) short-circuits before rules are consulted, so a
- // present-but-rule-disabled manifest could still be auto-activated.
- const disabledPluginIdSet = new Set(disabledPluginIds);
- const installedPlugins = (await toolReads.installedPlugins).filter(
- (p) => !disabledPluginIdSet.has(p.identifier),
- );
- log(
- 'execAgent: got %d installed plugins (%d disabled excluded)',
- installedPlugins.length,
- disabledPluginIdSet.size,
- );
-
- // 5a-1. Resolve connectors β€” connector identifier takes priority over plugin.
- const {
- connectorGateKeeper,
- connectors,
- connectorsMcp,
- connectorTools,
- discoverableConnectorManifests,
- discoverableConnectorsMcp,
- discoverableConnectorTools,
- } = await toolReads.connectors;
-
- // 5a-1b. Model awareness: when the caller runs a shared agent whose tools
- // were authorized by OTHER members (workspace dimension), tell the model
- // whose connected account each such tool runs on. Skipped entirely when
- // the caller authorized everything (owner runs own agent β†’ empty set), so
- // it costs nothing in the common case. Appended to `systemRole`, which is
- // consumed by `createOperation` further below.
- try {
- const borrowed = collectBorrowedConnectors(connectors, deps.userId!);
- if (borrowed.length > 0) {
- const displayMap = await resolveUserDisplayMap(
- deps.db,
- borrowed.map((b) => b.authorizerId),
- );
- const note = buildConnectorOwnershipPrompt(borrowed, displayMap);
- if (note) {
- // Returned as run context for the context engine to inject, rather
- // than concatenated onto the agent's systemRole here.
- connectorOwnershipNote = note;
- log(
- 'execAgent: injected tool credential ownership note for %d connector(s)',
- borrowed.length,
- );
- }
- }
- } catch (err) {
- log('execAgent: failed to build tool credential ownership note: %O', err);
- }
-
- connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);
-
- // Auto-refresh stale connector tool lists in the background so upstream MCP
- // tool changes propagate without the user manually re-syncing β€” the freshness
- // the connectors migration lost from the old plugin system. Reuses the tools
- // just fetched as the last-sync marker (no extra query), HTTP-only, throttled,
- // and deferred via after() so it adds no latency to this run. Wrapped
- // defensively: it is a pure optimization and must never break the agent run.
- try {
- // The background sync decrypts stored OAuth/bearer credentials to auth
- // against the MCP server, so it needs a gatekeeper-backed model β€” the
- // same `connectorGateKeeper` used above. `deps.connectorModel` has none,
- // which would decrypt to null and make an authed connector 401 β†’ error.
- const refreshConnectorModel = connectorGateKeeper
- ? new ConnectorModel(deps.db, deps.userId, deps.workspaceId, connectorGateKeeper)
- : deps.connectorModel;
- // Discoverable (unpinned) connectors are refreshed too: the model can
- // activate them, so a stale list would offer removed APIs and hide new ones.
- scheduleStaleConnectorToolsRefresh(
- [...connectorsMcp, ...discoverableConnectorsMcp],
- buildLastSyncedAtMap([...connectorTools, ...discoverableConnectorTools]),
- { connectorModel: refreshConnectorModel, connectorToolModel: deps.connectorToolModel },
- );
- } catch (err) {
- log('execAgent: failed to schedule connector tool refresh (ignored): %O', err);
- }
-
- // Only connectors that ACTUALLY produced a manifest (enabled + with synced
- // tools) replace a same-named plugin. Deriving the set from connectorsMcp
- // instead would let a disabled / not-yet-synced connector evict the plugin
- // while contributing no tools β€” leaving the runtime with nothing to call.
- // Unpinned connectors supersede a leftover plugin row the same way.
- const connectorIdentifierSet = new Set(
- [...connectorManifests, ...discoverableConnectorManifests].map((m) => m.identifier),
- );
-
- // Filter out plugin entries that are now handled by real MCP connectors.
- // `let` because community-MCP plugins may be patched with connector
- // permissions below (their connector row has no endpoint, so they stay here).
- // Composio connections also leave a plugin row behind (customParams.composio),
- // but they are executable only through `getComposioManifests`, which gates
- // on an ACTIVE connection and tags the tool source as `composio`. Letting a
- // PENDING/EXPIRED row through here exposes the full tool schema with no
- // Composio source, so every call falls to the builtin executor and fails
- // as "not implemented".
- let pluginsWithoutConnectors = installedPlugins.filter(
- (p) => !connectorIdentifierSet.has(p.identifier) && !p.customParams?.composio,
- );
- log('execAgent: got %d connector manifests', connectorManifests.length);
-
- // 5b. Get model abilities from model-bank for function calling support check
- const isModelSupportToolUse = (m: string, p: string) => {
- const info = builtinModels.find((item) => item.id === m && item.providerId === p);
- return info?.abilities?.functionCall ?? true;
- };
-
- // 5c / 5d. LobeHub Skills and Composio manifests, read in the wave above.
- lobehubSkillManifests = await toolReads.lobehubSkillManifests;
- log('execAgent: got %d lobehub skill manifests', lobehubSkillManifests.length);
- composioManifests = await toolReads.composioManifests;
- log('execAgent: got %d composio manifests', composioManifests.length);
-
- // 5d-1. Patch Lobehub/Composio manifests AND community-MCP plugin manifests
- // with connector tool permissions. This enables needs_approval (β†’
- // humanIntervention: 'required') and disabled (β†’ blocking description) for
- // any tool managed via the connector system but executed through a
- // non-connector path (Lobehub/Composio skills, community MCP plugins).
- // The 'disabled' hard-block is already enforced universally in
- // ToolExecutionService; this surfaces the permission to the model too.
- if (
- lobehubSkillManifests.length > 0 ||
- composioManifests.length > 0 ||
- pluginsWithoutConnectors.length > 0
- ) {
- try {
- const allIdentifiers = [
- ...lobehubSkillManifests.map((m) => m.identifier),
- ...composioManifests.map((m) => m.identifier),
- ...pluginsWithoutConnectors.map((p) => p.identifier),
- ];
- const connectorEntries =
- allIdentifiers.length > 0
- ? await deps.connectorModel.resolveByIdentifiers(allIdentifiers, resolvedAgentId)
- : [];
-
- if (connectorEntries.length > 0) {
- const toolModel = new ConnectorToolModel(deps.db, deps.userId, deps.workspaceId);
- const connectorToolsMap = new Map<string, Map<string, string>>();
- await Promise.all(
- connectorEntries.map(async (c) => {
- const tools = await toolModel.queryByConnector(c.id);
- const perms = new Map(tools.map((t) => [t.toolName, t.permission]));
- connectorToolsMap.set(c.identifier, perms);
- }),
- );
-
- lobehubSkillManifests = lobehubSkillManifests.map((m) => {
- const perms = connectorToolsMap.get(m.identifier);
- return perms && perms.size > 0
- ? (patchManifestWithPermissions(m as any, perms as any) as any)
- : m;
- });
-
- composioManifests = composioManifests.map((m) => {
- const perms = connectorToolsMap.get(m.identifier);
- return perms && perms.size > 0
- ? (patchManifestWithPermissions(m as any, perms as any) as any)
- : m;
- });
-
- // Community-MCP plugins execute via the plugin path, so patch their
- // manifest in place (the connector row holds the user's permissions).
- pluginsWithoutConnectors = pluginsWithoutConnectors.map((p) => {
- const perms = connectorToolsMap.get(p.identifier);
- if (perms && perms.size > 0 && (p as any).manifest?.api) {
- return {
- ...p,
- manifest: patchManifestWithPermissions((p as any).manifest, perms as any) as any,
- };
- }
- return p;
- });
- }
- } catch (err) {
- log('execAgent: failed to patch manifests with connector permissions: %O', err);
- }
- }
-
- await throwIfExecutionAborted('tool discovery');
-
- // 5e. Create tools using Server AgentToolsEngine
- hasEnabledKnowledgeBases =
- agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??
- false;
-
- hasAgentDocuments = await toolReads.agentDocuments;
- const hasOversizedFiles = await toolReads.oversizedFiles;
-
- log('execAgent: isBotConversation=%s', isBotConversation);
-
- // Device context for the ToolsEngine enableChecker, read in the wave above.
- const gatewayConfigured = deviceGateway.isConfigured;
- const agentBoundDeviceId = agentConfig.agencyConfig?.boundDeviceId;
- const boundDeviceId = topicBoundDeviceId || agentBoundDeviceId;
- onlineDevices = await toolReads.devicePool;
- const deviceOnline = onlineDevices.length > 0;
-
- const toolsContext: ServerAgentToolsContext = {
- installedPlugins: pluginsWithoutConnectors,
- isModelSupportToolUse,
- };
-
- // Dynamically inject turn-scoped builtin tools.
- const modelAbilities =
- builtinModels.find((item) => item.id === model && item.providerId === provider)?.abilities ??
- builtinModels.find((item) => item.id === model)?.abilities;
- const externalFileTypes = rawExternalFileTypes ?? [];
- const inputFileTypes = [...externalFileTypes, ...(await toolReads.attachedFileTypes)];
- const inputMediaAvailability = getMediaAvailabilityFromFileTypes(inputFileTypes);
- let historyMediaAvailability = { hasAudios: false, hasImages: false, hasVideos: false };
- const multimodalUnderstandingConfigured = isMultimodalUnderstandingConfigured();
-
- if (
- multimodalUnderstandingConfigured &&
- ((!modelMediaCapabilities?.audio && !inputMediaAvailability.hasAudios) ||
- (!modelMediaCapabilities?.vision && !inputMediaAvailability.hasImages) ||
- (!modelMediaCapabilities?.video && !inputMediaAvailability.hasVideos))
- ) {
- historyMediaAvailability = getMediaAvailabilityFromMessages(await loadHistoryMessages());
- }
-
- const needsAudioUnderstanding =
- (inputMediaAvailability.hasAudios || historyMediaAvailability.hasAudios) &&
- !modelMediaCapabilities?.audio;
- const needsImageUnderstanding =
- (inputMediaAvailability.hasImages || historyMediaAvailability.hasImages) &&
- !modelMediaCapabilities?.vision;
- const needsVideoUnderstanding =
- (inputMediaAvailability.hasVideos || historyMediaAvailability.hasVideos) &&
- !modelMediaCapabilities?.video;
- const shouldEnableMultimodalUnderstanding =
- multimodalUnderstandingConfigured &&
- (needsAudioUnderstanding || needsImageUnderstanding || needsVideoUnderstanding);
- agentPlugins = [
- ...agentPlugins,
- ...(isBotConversation ? [MessageToolIdentifier] : []),
- ...(shouldEnableMultimodalUnderstanding ? [LobeAgentManifest.identifier] : []),
- ];
-
- // Share allowlist filters the full candidate set (pinned + mentioned +
- // internal additions) before manifest discovery. This only trims which
- // plugin ids get *activated*; the separate skill candidate pool built in
- // `operationPrep` (`skills`, consumed by `SkillEngine`) needs its own pass
- // against the same allowlist, since building the skill list is a distinct
- // step from `SkillEngine.generate` and is not scoped by the plugin id list
- // on its own. The operationToolSet snapshot then carries the restricted
- // surface into every later step.
- //
- // Defense in depth: the same filter also runs at the top of
- // `discoverTools` (before connector resolution) so that ungranted
- // connectors never reach `resolveByIdentifiers` /
- // `scheduleStaleConnectorToolsRefresh`. Keep this second pass β€” the
- // internal additions above (bot message tool, multimodal understanding)
- // are appended after the first pass and would
- // otherwise slip through.
- if (shareGate) {
- agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);
- }
-
- // Resolve THE device decision for this run. All rules live in
- // `resolveExecutionPlan` (gated on `canUseDevice` first, `none`/`sandbox`
- // never route to a device, offline bindings stay unrouted, unbound runs
- // auto-activate only with exactly one device online). Without the
- // `canUseDevice` gate an external bot sender's turn would still populate
- // `state.binding.device.id`, and `buildStepToolDelta` re-injects
- // `LocalSystemManifest` whenever activeDeviceId is set, bypassing the
- // engine's enabledToolIds exclusion β€” resolving the plan here closes
- // that bypass at the source.
- //
- // `clientExecutionAvailable` is `gatewayConfigured` here: a server with a
- // device gateway can tunnel a `local` target to the user's device, so the
- // unset-target default resolves to `local` there and `none` otherwise.
- //
- // Chat mode is orthogonal to `executionTarget` (the UI toggle only writes
- // `enableAgentMode`), so a default/stored `local` target would otherwise
- // resolve a device and `buildStepToolDelta` would re-inject local-system.
- // Pass `chatConfig` so the plan degrades to `none` in chat mode β€” the
- // chat-mode derivation lives in `resolveExecutionPlan` (`resolveToolMode`),
- // the same source of truth the tools engine uses.
- //
- // A share visitor never passes `canUseDevice`, so a creator agent that
- // targets `local`/`auto` would collapse to `none` and silently drop a
- // `lobe-cloud-sandbox` grant (the sandbox manifest only materializes when
- // the plan resolves to `sandbox`). `sandboxFallback` keeps that decision
- // inside the resolver instead of patching its result here.
- executionPlan = resolveExecutionPlan({
- agencyConfig: agentConfig.agencyConfig,
- canUseDevice,
- chatConfig: agentConfig.chatConfig ?? undefined,
- clientExecutionAvailable: gatewayConfigured,
- localDeviceId,
- onlineDeviceIds: onlineDevices.map((device) => device.deviceId),
- requestedDeviceId,
- sandboxFallback: shareGate ? shareGateGrantsCloudSandbox(shareGate) : false,
- trigger: requestTrigger,
- });
- // A fixed device target must never degrade to the cloud sandbox or a
- // different device. Persist a visible assistant error and fail the RPC
- // before tool/runtime preparation so no operation can start elsewhere.
- if (
- isFixedDeviceTarget &&
- boundDeviceId &&
- resolveToolMode(agentConfig.chatConfig ?? undefined) !== 'chat' &&
- executionPlan.kind !== 'device'
- ) {
- const errorData: DeviceUnavailableErrorData = {
- code: 'DEVICE_NOT_FOUND',
- deviceId: boundDeviceId,
- retryable: true,
- scope: deps.workspaceId ? 'workspace' : 'personal',
- ...(deps.workspaceId ? { workspaceId: deps.workspaceId } : {}),
- };
- const detail =
- executionPlan.kind === 'device-unrouted' && executionPlan.reason === 'bound-device-offline'
- ? 'The device fixed by this agent is offline. Ask an editor to bring it online or change the agent device policy.'
- : 'The device fixed by this agent is unavailable for this run. Ask an editor to check the agent device policy.';
- await deps.messageModel.update(assistantMessageId, {
- content: '',
- error: {
- body: { detail, ...errorData },
- message: 'Fixed agent device unavailable',
- type: 'ServerAgentRuntimeError',
- },
- });
- throw new TRPCError({
- cause: { data: errorData },
- code: 'PRECONDITION_FAILED',
- message: detail,
- });
- }
- // Device tools (local-system / remote-device proxy) only exist in a
- // device-capable session β€” `none` and `sandbox` sessions must never see
- // them, not even the proxy that could activate a device mid-run.
- const deviceCapable = isDeviceCapablePlan(executionPlan);
- // Locked = routed to a device, or explicitly bound but offline. Such a
- // run has no device decision left, so the remote-device picker is
- // physically stripped below (and in the engine walls) β€” the model must
- // follow the user's choice, never re-list or switch machines mid-run.
- const deviceLocked = isDeviceLockedPlan(executionPlan);
- activeDeviceId = executionPlan.kind === 'device' ? executionPlan.deviceId : undefined;
- // Which principal pool the routed device lives in. A workspace run with a
- // per-user `local` override routes to the caller's PERSONAL
- // device β€” the union above added it from the personal pool β€” and the
- // device runtimes must address it via `(userId, deviceId)`, not the
- // `workspace:<id>` pool where it has no connection. Carried through
- // operation metadata into `ToolExecutionContext` and read by
- // `resolveRunWorkspaceId`.
- activeDeviceScope = activeDeviceId
- ? onlineDevices.find((d) => d.deviceId === activeDeviceId)?.scope
- : undefined;
- log(
- 'execAgent: execution plan β†’ kind=%s deviceId=%s scope=%s',
- executionPlan.kind,
- activeDeviceId ?? 'none',
- activeDeviceScope ?? 'none',
- );
- // A device-targeted run that could not be routed silently degrades exec
- // (lobe-skills runCommand/execScript) to the cloud sandbox. Surface it as
- // a structured warn β€” `bound-device-offline` with a requestedDeviceId is
- // the desktop "local device" pick whose gateway connection dropped, and
- // this log is the breadcrumb for diagnosing WHY the device was judged
- // offline (lazy WS connect vs getScopedOnlineDevices failing silently).
- if (executionPlan.kind === 'device-unrouted') {
- console.warn('[AiAgentService] device-unrouted: exec degrades to cloud sandbox', {
- boundDeviceId,
- onlineDeviceCount: onlineDevices.length,
- reason: executionPlan.reason,
- requestedDeviceId,
- topicId,
- userId: deps.userId,
- });
- }
-
- // Opt-in capability from the existing system-info RPC. Older desktop and CLI
- // clients omit it, so they must never receive the new Computer Use manifest.
- const systemInfoDeviceId = canUseDevice && !disableLocalSystem ? activeDeviceId : undefined;
- const supportedDeviceTools = systemInfoDeviceId
- ? (
- await traceDiscoveryStage('device_system_info', () =>
- ctx.runFacts.deviceSystemInfo(systemInfoDeviceId, activeDeviceScope),
- )
- )?.supportedTools
- : undefined;
-
- // Resolve the operation's group context ONCE here and snapshot it into op
- // metadata below β€” the per-step context engine reads it back without a DB
- // lookup, mirroring agentConfig/botContext. The same roster fetch also
- // authorizes the group-orchestration toolset.
- let isGroupSupervisor = false;
- if (appContext?.groupId) {
- const chatGroupModel = new ChatGroupModel(deps.db, deps.userId, deps.workspaceId);
- const [group, roster] = await Promise.all([
- chatGroupModel.findById(appContext.groupId),
- chatGroupModel.getGroupAgentsWithMeta(appContext.groupId),
- ]);
-
- // `appContext.orchestrationRole` is client-supplied (execGroupAgent stamps
- // it for whatever agentId the caller passed), so it must NOT alone
- // authorize the group-orchestration toolset β€” otherwise any run marked
- // `{ orchestrationRole: 'supervisor', groupId }` could dispatch members.
- // Verify against the persisted, ownership-scoped membership instead.
- if (appContext.orchestrationRole === 'supervisor') {
- isGroupSupervisor = roster.some(
- (member) => member.agentId === resolvedAgentId && member.role === 'supervisor',
- );
- if (!isGroupSupervisor)
- log(
- 'execAgent: orchestrationRole=supervisor but agent %s is not the supervisor of group %s β€” denying group tools',
- resolvedAgentId,
- appContext.groupId,
- );
- }
-
- operationAgentGroup = buildGroupAgentContext(resolvedAgentId, group, roster);
- } else if (botContext) {
- operationAgentGroup = buildBotConversationGroupContext(resolvedAgentId, agentConfig);
- }
-
- // Skills/Composio/connector identifiers share the same `plugins`
- // identifier space as installed plugins, so a disabled entry must be
- // excluded from their manifests too β€” otherwise the disabled tool stays
- // discoverable/activatable via these additionalManifests even though
- // `installedPlugins` above already dropped it.
- const dropDisabledManifests = <T extends { identifier: string }>(manifests: T[]): T[] =>
- disabledPluginIdSet.size === 0
- ? manifests
- : manifests.filter((m) => !disabledPluginIdSet.has(m.identifier));
- const activeLobehubSkillManifests = dropDisabledManifests(lobehubSkillManifests);
- const activeComposioManifests = dropDisabledManifests(composioManifests);
- const activeConnectorManifests = dropDisabledManifests(connectorManifests);
- const activeDiscoverableConnectorManifests = dropDisabledManifests(
- discoverableConnectorManifests,
- );
-
- // Context-aware builtin manifests: inside a sub-agent (or group) run,
- // lobe-agent drops `callSubAgent` so the model can't recurse into nested
- // sub-agents (which the runtime rejects, looping until the inactivity
- // watchdog kills the op). Mirrors the frontend `createAgentToolsEngine`.
- // `executionEnv` mirrors the resolved plan, while preserving the local
- // target for a routed desktop because its readFile implementation can
- // return images. It also keeps the `device-unrouted` degradation, where
- // the user picked a local device that is offline and exec silently lands
- // in the sandbox.
- // For bot conversations we also pass the IM platform so `lobe-message`
- // can drop APIs the platform can't fulfil (e.g. WeChat has no
- // `readMessages`). Telegram Guest Mode uses a stricter overlay β€”
- // the bot is not a chat member and has no regular channel tools.
- // The discovery pool below resolves with the same context, so a tool
- // activated mid-run carries the trimmed manifest too.
- const manifestContext: BuiltinToolResolveContext = {
- ...(botContext?.platform && {
- botPlatform: {
- id: botContext.platform,
- unsupportedMessageApis: resolveUnsupportedMessageApis(
- botContext.platform,
- botContext.platformThreadId,
- ),
- },
- }),
- executionEnv: executionPlanToManifestExecutionEnv(executionPlan, localDeviceId),
- executionEnvUnroutedReason:
- executionPlan.kind === 'device-unrouted' ? executionPlan.reason : undefined,
- isSubAgent: appContext?.isSubAgent,
- scope: appContext?.scope ?? undefined,
- };
-
- toolsEngine = createServerAgentToolsEngine(toolsContext, {
- additionalManifests: [
- ...activeLobehubSkillManifests,
- ...activeComposioManifests,
- ...activeConnectorManifests,
- // Known to the engine but never invocation candidates (they stay out of
- // `connectorIds` below), so they are not enabled by default β€” this only
- // lets a previous turn's activation pass the explicit-activation
- // re-check when the next operation restores it.
- ...activeDiscoverableConnectorManifests,
- ],
- agentConfig: {
- chatConfig: isGoalTurn
- ? { ...agentConfig.chatConfig, toolMode: 'custom' }
- : (agentConfig.chatConfig ?? undefined),
- plugins: agentPlugins,
- },
- canUseDevice,
- deviceContext: gatewayConfigured
- ? {
- autoActivated: activeDeviceId ? true : undefined,
- boundDeviceId,
- deviceOnline,
- gatewayConfigured: true,
- supportedTools: supportedDeviceTools,
- }
- : undefined,
- disableLocalSystem,
- disabledPluginIds,
- executionPlan,
- globalMemoryEnabled,
- hasEnabledKnowledgeBases,
- hasOversizedFiles,
- isBotConversation,
- isGroupSupervisor,
- modelAbilities,
- manifestContext,
- model,
- provider,
- useApplicationBuiltinSearchTool: searchDecision.useApplicationBuiltinSearchTool,
- });
-
- // 5f. Generate tools and manifest map
- // Which identifiers the engine considers, what the activator may discover
- // mid-run, and which tools dispatch to the client are shared rules in
- // `@lobechat/mecha`; this pipeline only supplies the run's facts.
- const pluginIds = resolveInvocationToolIds({
- agentPlugins,
- composioIds: activeComposioManifests.map((m) => m.identifier),
- connectorIds: activeConnectorManifests.map((m) => m.identifier),
- disableLocalSystem,
- exclusivePluginIds,
- lobehubSkillIds: activeLobehubSkillManifests.map((m) => m.identifier),
- });
- log('execAgent: agent configured plugins: %O', pluginIds);
-
- const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';
-
- toolsResult = toolsEngine.generateToolsDetailed({
- excludeDefaultToolIds: isManualMode ? manualModeExcludeToolIds : undefined,
- model,
- provider,
- skipDefaultTools: !!exclusivePluginIds,
- toolIds: pluginIds,
- });
-
- tools = toolsResult.tools;
- log('execAgent: enabled tool ids: %O', toolsResult.enabledToolIds);
-
- // Only a run that can inject credentials renders {{CREDS_LIST}}. Kick the
- // read off here and await it at the end: it is one Market round trip, and
- // every step of the run reads the answer back off the operation instead of
- // asking again.
- if (toolsResult.enabledToolIds?.includes(CredsIdentifier)) {
- credentialFactsPromise = readCredentialFacts(deps);
- }
-
- // Start with the scoped manifest map (pluginIds + defaultToolIds)
- const manifestMap = toolsEngine.getEnabledPluginManifests(pluginIds);
- const discovery = resolveDiscoveryPool({
- builtinTools: buildAllowedBuiltinTools({
- canUseDevice,
- deviceLocked,
- disableLocalSystem,
- supportedDeviceTools: gatewayConfigured ? (supportedDeviceTools ?? []) : undefined,
- }),
- composio: activeComposioManifests,
- device: gatewayConfigured ? { supportedTools: supportedDeviceTools } : undefined,
- deviceAccess: { canUseDevice, deviceLocked },
- deviceCapable,
- disableLocalSystem,
- disabledPluginIds,
- enabledManifests: manifestMap,
- exclusivePluginIds,
- executionTarget: executionPlan.target,
- // Installed-but-not-pinned plugins (`auto` in the three-state plugin
- // config): the model must be able to discover and activate them mid-run,
- // exactly as the client runtime lists them from `installedPlugins`.
- // They never join `enabledToolIds` β€” the engine's rules stay pinned-only
- // β€” so this widens what the activator can reach, not what the run gets
- // by default. Disabled ids were dropped in 5a and the pool's own ingest
- // wall re-checks them; a connector / Composio / LobeHub skill manifest
- // of the same identifier still wins, because the pool seeds this source
- // last.
- // Unpinned connectors join them on the same terms.
- installedManifests: [
- ...activeDiscoverableConnectorManifests,
- ...dropInvalidManifests(
- pluginsWithoutConnectors.map((plugin) => plugin.manifest as LobeToolManifest | undefined),
- 'installedPlugins(auto)',
- ),
- ],
- lobehubSkills: activeLobehubSkillManifests,
- manifestContext,
- });
- Object.assign(toolManifestMap, discovery.manifestMap);
- Object.assign(toolSourceMap, discovery.sourceMap);
- Object.assign(
- toolExecutorMap,
- resolveClientExecutors({
- hasDeviceProxy: gatewayConfigured,
- manifestMap: toolManifestMap,
- stdioIdentifiers: [
- ...installedPlugins
- .filter((plugin) => plugin.customParams?.mcp?.type === 'stdio')
- .map((plugin) => plugin.identifier),
- ...[...connectorsMcp, ...discoverableConnectorsMcp]
- .filter((connector) => connector.mcpConnectionType === 'stdio')
- .map((connector) => connector.identifier),
- ],
- }),
- );
-
- log(
- 'execAgent: generated %d tools, %d lobehub skills, %d composio tools',
- tools?.length ?? 0,
- lobehubSkillManifests.length,
- composioManifests.length,
- );
-
- // Share-visitor fail-closed gate β€” never expose the
- // `declareSelfFeedbackIntent` tool to a share-visitor turn. This tool sits
- // outside the normal `toolManifestMap` / `applyShareGateToToolSet`
- // allowlist (it's injected directly into `tools` below), so the visitor's
- // own model call can reach it even with an empty `enabledToolIds`. Its
- // execution context is stamped with the share CREATOR's user id, and the
- // resulting `agent.self_feedback_intent.declared` event dispatches a full
- // autonomous background run under the creator's account, which can write
- // to the creator's memory. Same root cause as the `agent.user.message`
- // gate in `turnSetup`; `allowReadMemory` is a read-only grant so this must
- // not be conditional on it either.
- //
- // There is no per-agent switch: Labs β†’ Self-evolving covers every agent.
- if (!shareGate && !disableSelfFeedbackIntentTool) {
- // The run already reads `users.preference` for expertise injection; reuse that row.
- // A failed read leaves the tool off (fail closed).
- const featureUserEnabled = await isAgentSignalEnabledForUser(deps.db, deps.userId, {
- preference: await ctx.runFacts.userPreference().catch(() => undefined),
- });
-
- if (
- shouldExposeSelfFeedbackIntentTool({
- agentSelfIterationEnabled: featureUserEnabled,
- disableSelfFeedbackIntentTool,
- featureUserEnabled,
- })
- ) {
- tools = tools ?? [];
- injectSelfFeedbackIntentTool({
- enabledToolIds: toolsResult.enabledToolIds,
- manifestMap: toolManifestMap,
- sourceMap: toolSourceMap,
- tools,
- });
- log('execAgent: injected self-feedback intent declaration tool');
- }
- }
- }
-
- // Inject client function tools from Response API
- const CLIENT_FN_IDENTIFIER = 'lobe-client-fn';
- if (functionTools?.length) {
- for (const ft of functionTools) {
- tools?.push({
- function: {
- description: ft.description,
- name: `${CLIENT_FN_IDENTIFIER}____${ft.name}`,
- parameters: ft.parameters,
- },
- type: 'function',
- });
- }
- toolSourceMap[CLIENT_FN_IDENTIFIER] = 'client';
- toolManifestMap[CLIENT_FN_IDENTIFIER] = {
- api: functionTools.map((ft) => ({
- description: ft.description ?? '',
- name: ft.name,
- parameters: ft.parameters ?? {},
- })),
- identifier: CLIENT_FN_IDENTIFIER,
- meta: { title: 'Client Functions' },
- type: 'default',
- };
- toolsResult.enabledToolIds.push(CLIENT_FN_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),
- };
- }
-
- return {
- activeDeviceId,
- activeDeviceScope,
- agentPlugins,
- builtinModels,
- composioManifests,
- connectorManifests,
- connectorOwnershipNote,
- executionPlan,
- hasAgentDocuments,
- credentialFactsPromise,
- hasEnabledKnowledgeBases,
- lobehubSkillManifests,
- modelFacts,
- modelMediaCapabilities,
- onlineDevices,
- operationAgentGroup,
- searchDecision,
- toolExecutorMap,
- toolManifestMap,
- toolSourceMap,
- tools,
- toolsEngine,
- toolsResult,
- };
-};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts
new file mode 100644
index 00000000000..d3d6996b6b0
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts
@@ -0,0 +1,188 @@
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import debug from 'debug';
+import pMap from 'p-map';
+
+import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import type { UserConnectorToolItem } from '@/database/schemas';
+import { patchManifestWithPermissions } from '@/libs/mcp/connectorPermissionCheck';
+import type { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import {
+ buildLastSyncedAtMap,
+ scheduleStaleConnectorToolsRefresh,
+} from '@/server/services/connector/refresh';
+import {
+ buildConnectorOwnershipPrompt,
+ collectBorrowedConnectors,
+ resolveUserDisplayMap,
+} from '@/server/utils/connectorAttribution';
+
+import type { ToolDiscoveryDeps } from './types';
+
+/** Caps concurrent per-connector permission reads against the database. */
+const CONNECTOR_TOOLS_QUERY_CONCURRENCY = 5;
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Model awareness: when the caller runs a shared agent whose tools were
+ * authorized by OTHER members (workspace dimension), tell the model whose
+ * connected account each such tool runs on. Skipped entirely when the caller
+ * authorized everything (owner runs own agent β†’ empty set), so it costs
+ * nothing in the common case.
+ *
+ * Returned as run context for the context engine to inject, rather than
+ * concatenated onto the agent's systemRole here. Never fails the run.
+ */
+export const buildOwnershipNote = async (
+ deps: ToolDiscoveryDeps,
+ connectors: DecryptedConnector[],
+): Promise<string | undefined> => {
+ try {
+ const borrowed = collectBorrowedConnectors(connectors, deps.userId!);
+ if (borrowed.length > 0) {
+ const displayMap = await resolveUserDisplayMap(
+ deps.db,
+ borrowed.map((b) => b.authorizerId),
+ );
+ const note = buildConnectorOwnershipPrompt(borrowed, displayMap);
+ if (note) {
+ log(
+ 'execAgent: injected tool credential ownership note for %d connector(s)',
+ borrowed.length,
+ );
+ return note;
+ }
+ }
+ } catch (err) {
+ log('execAgent: failed to build tool credential ownership note: %O', err);
+ }
+ return undefined;
+};
+
+/**
+ * Auto-refresh stale connector tool lists in the background so upstream MCP
+ * tool changes propagate without the user manually re-syncing β€” the freshness
+ * the connectors migration lost from the old plugin system. Reuses the tools
+ * just fetched as the last-sync marker (no extra query), HTTP-only, throttled,
+ * and deferred via after() so it adds no latency to this run. Wrapped
+ * defensively: it is a pure optimization and must never break the agent run.
+ */
+export const scheduleConnectorRefresh = (
+ deps: ToolDiscoveryDeps,
+ params: {
+ connectorGateKeeper: KeyVaultsGateKeeper | undefined;
+ connectorsMcp: DecryptedConnector[];
+ connectorTools: UserConnectorToolItem[];
+ discoverableConnectorsMcp: DecryptedConnector[];
+ discoverableConnectorTools: UserConnectorToolItem[];
+ },
+) => {
+ try {
+ // The background sync decrypts stored OAuth/bearer credentials to auth
+ // against the MCP server, so it needs a gatekeeper-backed model β€” the
+ // same `connectorGateKeeper` used for resolution. `deps.connectorModel`
+ // has none, which would decrypt to null and make an authed connector 401 β†’ error.
+ const refreshConnectorModel = params.connectorGateKeeper
+ ? new ConnectorModel(deps.db, deps.userId, deps.workspaceId, params.connectorGateKeeper)
+ : deps.connectorModel;
+ // Discoverable (unpinned) connectors are refreshed too: the model can
+ // activate them, so a stale list would offer removed APIs and hide new ones.
+ scheduleStaleConnectorToolsRefresh(
+ [...params.connectorsMcp, ...params.discoverableConnectorsMcp],
+ buildLastSyncedAtMap([...params.connectorTools, ...params.discoverableConnectorTools]),
+ { connectorModel: refreshConnectorModel, connectorToolModel: deps.connectorToolModel },
+ );
+ } catch (err) {
+ log('execAgent: failed to schedule connector tool refresh (ignored): %O', err);
+ }
+};
+
+interface PermissionPatchTargets<P> {
+ composioManifests: LobeToolManifest[];
+ lobehubSkillManifests: LobeToolManifest[];
+ pluginsWithoutConnectors: P[];
+}
+
+/**
+ * Patch Lobehub/Composio manifests AND community-MCP plugin manifests with
+ * connector tool permissions. This enables needs_approval (β†’
+ * humanIntervention: 'required') and disabled (β†’ blocking description) for any
+ * tool managed via the connector system but executed through a non-connector
+ * path (Lobehub/Composio skills, community MCP plugins). The 'disabled'
+ * hard-block is already enforced universally in ToolExecutionService; this
+ * surfaces the permission to the model too.
+ *
+ * Returns the inputs unchanged when nothing applies or the lookup fails.
+ */
+export const patchConnectorPermissions = async <P extends { identifier: string }>(
+ deps: ToolDiscoveryDeps,
+ resolvedAgentId: string,
+ targets: PermissionPatchTargets<P>,
+): Promise<PermissionPatchTargets<P>> => {
+ let { composioManifests, lobehubSkillManifests, pluginsWithoutConnectors } = targets;
+ if (
+ lobehubSkillManifests.length === 0 &&
+ composioManifests.length === 0 &&
+ pluginsWithoutConnectors.length === 0
+ ) {
+ return targets;
+ }
+
+ try {
+ const allIdentifiers = [
+ ...lobehubSkillManifests.map((m) => m.identifier),
+ ...composioManifests.map((m) => m.identifier),
+ ...pluginsWithoutConnectors.map((p) => p.identifier),
+ ];
+ const connectorEntries =
+ allIdentifiers.length > 0
+ ? await deps.connectorModel.resolveByIdentifiers(allIdentifiers, resolvedAgentId)
+ : [];
+
+ if (connectorEntries.length > 0) {
+ const toolModel = new ConnectorToolModel(deps.db, deps.userId, deps.workspaceId);
+ const connectorToolsMap = new Map<string, Map<string, string>>();
+ await pMap(
+ connectorEntries,
+ async (c) => {
+ const tools = await toolModel.queryByConnector(c.id);
+ const perms = new Map(tools.map((t) => [t.toolName, t.permission]));
+ connectorToolsMap.set(c.identifier, perms);
+ },
+ { concurrency: CONNECTOR_TOOLS_QUERY_CONCURRENCY },
+ );
+
+ lobehubSkillManifests = lobehubSkillManifests.map((m) => {
+ const perms = connectorToolsMap.get(m.identifier);
+ return perms && perms.size > 0
+ ? (patchManifestWithPermissions(m as any, perms as any) as any)
+ : m;
+ });
+
+ composioManifests = composioManifests.map((m) => {
+ const perms = connectorToolsMap.get(m.identifier);
+ return perms && perms.size > 0
+ ? (patchManifestWithPermissions(m as any, perms as any) as any)
+ : m;
+ });
+
+ // Community-MCP plugins execute via the plugin path, so patch their
+ // manifest in place (the connector row holds the user's permissions).
+ pluginsWithoutConnectors = pluginsWithoutConnectors.map((p) => {
+ const perms = connectorToolsMap.get(p.identifier);
+ if (perms && perms.size > 0 && (p as any).manifest?.api) {
+ return {
+ ...p,
+ manifest: patchManifestWithPermissions((p as any).manifest, perms as any) as any,
+ };
+ }
+ return p;
+ });
+ }
+ } catch (err) {
+ log('execAgent: failed to patch manifests with connector permissions: %O', err);
+ }
+
+ return { composioManifests, lobehubSkillManifests, pluginsWithoutConnectors };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts
new file mode 100644
index 00000000000..2dd602df1ee
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts
@@ -0,0 +1,185 @@
+import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
+import type { DeviceUnavailableErrorData } from '@lobechat/device-gateway-client';
+import { TRPCError } from '@trpc/server';
+import debug from 'debug';
+
+import {
+ isDeviceCapablePlan,
+ isDeviceLockedPlan,
+ resolveExecutionPlan,
+ resolveToolMode,
+} from '@/helpers/executionTarget';
+
+import { shareGateGrantsCloudSandbox } from '../../shareGate';
+import type { ExecRunContext } from '../../types';
+import { traceDiscoveryStage } from '../discoveryTracing';
+import type { ToolDiscoveryDeps, ToolDiscoveryInput } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Resolve THE device decision for this run. All rules live in
+ * `resolveExecutionPlan` (gated on `canUseDevice` first, `none`/`sandbox`
+ * never route to a device, offline bindings stay unrouted, unbound runs
+ * auto-activate only with exactly one device online). Without the
+ * `canUseDevice` gate an external bot sender's turn would still populate
+ * `state.binding.device.id`, and `buildStepToolDelta` re-injects
+ * `LocalSystemManifest` whenever activeDeviceId is set, bypassing the
+ * engine's enabledToolIds exclusion β€” resolving the plan here closes
+ * that bypass at the source.
+ *
+ * `clientExecutionAvailable` is `gatewayConfigured` here: a server with a
+ * device gateway can tunnel a `local` target to the user's device, so the
+ * unset-target default resolves to `local` there and `none` otherwise.
+ *
+ * Chat mode is orthogonal to `executionTarget` (the UI toggle only writes
+ * `enableAgentMode`), so a default/stored `local` target would otherwise
+ * resolve a device and `buildStepToolDelta` would re-inject local-system.
+ * Pass `chatConfig` so the plan degrades to `none` in chat mode β€” the
+ * chat-mode derivation lives in `resolveExecutionPlan` (`resolveToolMode`),
+ * the same source of truth the tools engine uses.
+ *
+ * A share visitor never passes `canUseDevice`, so a creator agent that
+ * targets `local`/`auto` would collapse to `none` and silently drop a
+ * `lobe-cloud-sandbox` grant (the sandbox manifest only materializes when
+ * the plan resolves to `sandbox`). `sandboxFallback` keeps that decision
+ * inside the resolver instead of patching its result here.
+ */
+export const resolveDevicePlan = async (
+ deps: ToolDiscoveryDeps,
+ ctx: Pick<
+ ExecRunContext,
+ 'agentConfig' | 'assistantMessageId' | 'canUseDevice' | 'runFacts' | 'shareGate' | 'topicId'
+ >,
+ input: Pick<
+ ToolDiscoveryInput,
+ | 'disableLocalSystem'
+ | 'isFixedDeviceTarget'
+ | 'localDeviceId'
+ | 'requestedDeviceId'
+ | 'requestTrigger'
+ >,
+ devices: {
+ boundDeviceId?: string | null;
+ gatewayConfigured: boolean;
+ onlineDevices: DeviceAttachment[];
+ },
+) => {
+ const { agentConfig, assistantMessageId, canUseDevice, shareGate, topicId } = ctx;
+ const {
+ disableLocalSystem,
+ isFixedDeviceTarget,
+ localDeviceId,
+ requestTrigger,
+ requestedDeviceId,
+ } = input;
+ const { boundDeviceId, gatewayConfigured, onlineDevices } = devices;
+
+ const executionPlan = resolveExecutionPlan({
+ agencyConfig: agentConfig.agencyConfig,
+ canUseDevice,
+ chatConfig: agentConfig.chatConfig ?? undefined,
+ clientExecutionAvailable: gatewayConfigured,
+ localDeviceId,
+ onlineDeviceIds: onlineDevices.map((device) => device.deviceId),
+ requestedDeviceId,
+ sandboxFallback: shareGate ? shareGateGrantsCloudSandbox(shareGate) : false,
+ trigger: requestTrigger,
+ });
+ // A fixed device target must never degrade to the cloud sandbox or a
+ // different device. Persist a visible assistant error and fail the RPC
+ // before tool/runtime preparation so no operation can start elsewhere.
+ if (
+ isFixedDeviceTarget &&
+ boundDeviceId &&
+ resolveToolMode(agentConfig.chatConfig ?? undefined) !== 'chat' &&
+ executionPlan.kind !== 'device'
+ ) {
+ const errorData: DeviceUnavailableErrorData = {
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: boundDeviceId,
+ retryable: true,
+ scope: deps.workspaceId ? 'workspace' : 'personal',
+ ...(deps.workspaceId ? { workspaceId: deps.workspaceId } : {}),
+ };
+ const detail =
+ executionPlan.kind === 'device-unrouted' && executionPlan.reason === 'bound-device-offline'
+ ? 'The device fixed by this agent is offline. Ask an editor to bring it online or change the agent device policy.'
+ : 'The device fixed by this agent is unavailable for this run. Ask an editor to check the agent device policy.';
+ await deps.messageModel.update(assistantMessageId, {
+ content: '',
+ error: {
+ body: { detail, ...errorData },
+ message: 'Fixed agent device unavailable',
+ type: 'ServerAgentRuntimeError',
+ },
+ });
+ throw new TRPCError({
+ cause: { data: errorData },
+ code: 'PRECONDITION_FAILED',
+ message: detail,
+ });
+ }
+ // Device tools (local-system / remote-device proxy) only exist in a
+ // device-capable session β€” `none` and `sandbox` sessions must never see
+ // them, not even the proxy that could activate a device mid-run.
+ const deviceCapable = isDeviceCapablePlan(executionPlan);
+ // Locked = routed to a device, or explicitly bound but offline. Such a
+ // run has no device decision left, so the remote-device picker is
+ // physically stripped (here and in the engine walls) β€” the model must
+ // follow the user's choice, never re-list or switch machines mid-run.
+ const deviceLocked = isDeviceLockedPlan(executionPlan);
+ const activeDeviceId = executionPlan.kind === 'device' ? executionPlan.deviceId : undefined;
+ // Which principal pool the routed device lives in. A workspace run with a
+ // per-user `local` override routes to the caller's PERSONAL
+ // device β€” the device pool read added it from the personal pool β€” and the
+ // device runtimes must address it via `(userId, deviceId)`, not the
+ // `workspace:<id>` pool where it has no connection. Carried through
+ // operation metadata into `ToolExecutionContext` and read by
+ // `resolveRunWorkspaceId`.
+ const activeDeviceScope = activeDeviceId
+ ? onlineDevices.find((d) => d.deviceId === activeDeviceId)?.scope
+ : undefined;
+ log(
+ 'execAgent: execution plan β†’ kind=%s deviceId=%s scope=%s',
+ executionPlan.kind,
+ activeDeviceId ?? 'none',
+ activeDeviceScope ?? 'none',
+ );
+ // A device-targeted run that could not be routed silently degrades exec
+ // (lobe-skills runCommand/execScript) to the cloud sandbox. Surface it as
+ // a structured warn β€” `bound-device-offline` with a requestedDeviceId is
+ // the desktop "local device" pick whose gateway connection dropped, and
+ // this log is the breadcrumb for diagnosing WHY the device was judged
+ // offline (lazy WS connect vs getScopedOnlineDevices failing silently).
+ if (executionPlan.kind === 'device-unrouted') {
+ console.warn('[AiAgentService] device-unrouted: exec degrades to cloud sandbox', {
+ boundDeviceId,
+ onlineDeviceCount: onlineDevices.length,
+ reason: executionPlan.reason,
+ requestedDeviceId,
+ topicId,
+ userId: deps.userId,
+ });
+ }
+
+ // Opt-in capability from the existing system-info RPC. Older desktop and CLI
+ // clients omit it, so they must never receive the new Computer Use manifest.
+ const systemInfoDeviceId = canUseDevice && !disableLocalSystem ? activeDeviceId : undefined;
+ const supportedDeviceTools = systemInfoDeviceId
+ ? (
+ await traceDiscoveryStage('device_system_info', () =>
+ ctx.runFacts.deviceSystemInfo(systemInfoDeviceId, activeDeviceScope),
+ )
+ )?.supportedTools
+ : undefined;
+
+ return {
+ activeDeviceId,
+ activeDeviceScope,
+ deviceCapable,
+ deviceLocked,
+ executionPlan,
+ supportedDeviceTools,
+ };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
new file mode 100644
index 00000000000..7fd88b52d15
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
@@ -0,0 +1,479 @@
+/**
+ * Characterization tests for the branches of `discoverTools` that the
+ * existing scenario suites (installed plugins, discoverable connectors, share
+ * gate, feature gate, parallel reads) do not reach: the disabled-tools short
+ * circuit, client function tools, connector permission patching, the
+ * ownership note, turn-scoped builtins, device routing and the fixed-device
+ * failure, group-supervisor authorization, and the credential snapshot.
+ */
+import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
+import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as MechaModule from '@/server/modules/Mecha';
+import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
+import {
+ buildConnectorOwnershipPrompt,
+ collectBorrowedConnectors,
+} from '@/server/utils/connectorAttribution';
+
+import { discoverTools } from '.';
+
+vi.mock('@/business/client/model-bank/loadModels', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('@/database/models/aiModel', () => ({
+ AiModelModel: class {
+ findByIdAndProvider = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+vi.mock('@/database/models/aiProvider', () => ({
+ AiProviderModel: class {
+ findById = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+const { chatGroupState } = vi.hoisted(() => ({
+ chatGroupState: {
+ roster: [] as Array<{ agentId: string; role: string | null; title: string | null }>,
+ },
+}));
+vi.mock('@/database/models/chatGroup', () => ({
+ ChatGroupModel: class {
+ findById = vi.fn(async () => ({ content: 'group prompt', title: 'Group' }));
+ getGroupAgentsWithMeta = vi.fn(async () => chatGroupState.roster);
+ },
+}));
+const { connectorToolState } = vi.hoisted(() => ({
+ connectorToolState: { tools: [] as Array<{ permission: string; toolName: string }> },
+}));
+// Permission patching builds its own model rather than using `deps`.
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: class {
+ queryByConnector = vi.fn(async () => connectorToolState.tools);
+ },
+}));
+vi.mock('@/server/services/connector/refresh', () => ({
+ buildLastSyncedAtMap: vi.fn().mockReturnValue(new Map()),
+ scheduleStaleConnectorToolsRefresh: vi.fn(),
+}));
+const { deviceGatewayState } = vi.hoisted(() => ({ deviceGatewayState: { isConfigured: false } }));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ get isConfigured() {
+ return deviceGatewayState.isConfigured;
+ },
+ },
+}));
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
+ getScopedOnlineDevices: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('@/server/utils/connectorAttribution', () => ({
+ buildConnectorOwnershipPrompt: vi.fn().mockReturnValue(''),
+ collectBorrowedConnectors: vi.fn().mockReturnValue([]),
+ resolveUserDisplayMap: vi.fn().mockResolvedValue(new Map()),
+}));
+vi.mock('@/server/services/aiAgent/helpers/mediaAvailability', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ isMultimodalUnderstandingConfigured: vi.fn(() => true),
+}));
+vi.mock('@/server/modules/Mecha', async (importOriginal) => {
+ const actual = await importOriginal<typeof MechaModule>();
+ return {
+ ...actual,
+ createServerAgentToolsEngine: vi.fn(actual.createServerAgentToolsEngine),
+ };
+});
+
+const skillManifest = (identifier: string) => ({
+ api: [
+ {
+ description: `${identifier} api`,
+ name: 'doThing',
+ parameters: { properties: {}, type: 'object' },
+ },
+ ],
+ identifier,
+ meta: { title: identifier },
+ type: 'builtin',
+});
+
+interface RunOptions {
+ agentConfig?: Record<string, unknown>;
+ appContext?: Record<string, unknown>;
+ canUseDevice?: boolean;
+ composioManifests?: unknown[];
+ connectorResolve?: (ids: string[]) => unknown[];
+ connectorTools?: Array<{ permission: string; toolName: string }>;
+ credsList?: () => Promise<unknown>;
+ input?: Record<string, unknown>;
+ installedPlugins?: unknown[];
+ lobehubSkillManifests?: unknown[];
+ workspaceId?: string;
+}
+
+const run = (options: RunOptions = {}) => {
+ connectorToolState.tools = options.connectorTools ?? [];
+ const messageModel = { update: vi.fn() };
+ const credsList = options.credsList ?? vi.fn().mockResolvedValue({ data: [] });
+ const promise = discoverTools(
+ {
+ agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
+ composioService: {
+ getComposioManifests: vi.fn().mockResolvedValue(options.composioManifests ?? []),
+ },
+ connectorModel: {
+ resolveAll: vi.fn().mockResolvedValue([]),
+ resolveByIdentifiers: vi.fn(async (ids: string[]) => options.connectorResolve?.(ids) ?? []),
+ },
+ connectorToolModel: {
+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
+ },
+ db: {} as never,
+ getMarketService: vi.fn().mockResolvedValue({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue(options.lobehubSkillManifests ?? []),
+ market: {
+ creds: { list: credsList },
+ organizations: { creds: () => ({ list: credsList }) },
+ },
+ }),
+ messageModel,
+ pluginModel: { query: vi.fn().mockResolvedValue(options.installedPlugins ?? []) },
+ userId: 'user-1',
+ workspaceId: options.workspaceId,
+ } as never,
+ {
+ agentConfig: { chatConfig: {}, id: 'agent-1', plugins: [], ...options.agentConfig },
+ appContext: options.appContext,
+ assistantMessageId: 'assistant-1',
+ canUseDevice: options.canUseDevice ?? false,
+ model: 'test-model',
+ prompt: 'hello',
+ provider: 'test-provider',
+ resolvedAgentId: 'agent-1',
+ runFacts: {
+ deviceSystemInfo: vi.fn().mockResolvedValue(undefined),
+ userPreference: vi.fn().mockResolvedValue(undefined),
+ },
+ shareGate: undefined,
+ topicId: undefined,
+ } as never,
+ {
+ disabledPluginIds: [],
+ globalMemoryEnabled: false,
+ hasMentionedAgents: false,
+ isFixedDeviceTarget: false,
+ loadHistoryMessages: vi.fn().mockResolvedValue([]),
+ throwIfExecutionAborted: vi.fn(),
+ ...options.input,
+ } as never,
+ );
+ return { messageModel, promise };
+};
+
+const lastEngineOptions = () =>
+ vi.mocked(createServerAgentToolsEngine).mock.calls.at(-1)?.[1] as Record<string, any>;
+
+beforeEach(() => {
+ deviceGatewayState.isConfigured = false;
+ chatGroupState.roster = [];
+ vi.mocked(getScopedOnlineDevices).mockReset().mockResolvedValue([]);
+ vi.mocked(collectBorrowedConnectors).mockReset().mockReturnValue([]);
+ vi.mocked(buildConnectorOwnershipPrompt).mockReset().mockReturnValue('');
+ vi.mocked(createServerAgentToolsEngine).mockClear();
+});
+
+const functionTools = [
+ { description: 'Look up the weather', name: 'getWeather', parameters: { type: 'object' } },
+];
+
+describe('discoverTools β€” disabled tools and client function tools', () => {
+ it('skips discovery entirely but still registers client function tools', async () => {
+ const result = await run({ input: { disableTools: true, functionTools } }).promise;
+
+ expect(result.toolsEngine).toBeUndefined();
+ expect(result.tools).toBeUndefined();
+ expect(createServerAgentToolsEngine).not.toHaveBeenCalled();
+ expect(result.toolsResult.enabledToolIds).toEqual(['lobe-client-fn']);
+ expect(result.toolSourceMap['lobe-client-fn']).toBe('client');
+ expect(result.toolManifestMap['lobe-client-fn']).toEqual({
+ api: [
+ { description: 'Look up the weather', name: 'getWeather', parameters: { type: 'object' } },
+ ],
+ identifier: 'lobe-client-fn',
+ meta: { title: 'Client Functions' },
+ type: 'default',
+ });
+ expect(result.executionPlan).toBeUndefined();
+ });
+
+ it('appends client function tools after the generated tool list', async () => {
+ const result = await run({ input: { functionTools } }).promise;
+
+ expect(result.tools?.at(-1)).toEqual({
+ function: {
+ description: 'Look up the weather',
+ name: 'lobe-client-fn____getWeather',
+ parameters: { type: 'object' },
+ },
+ type: 'function',
+ });
+ expect(result.toolsResult.enabledToolIds.at(-1)).toBe('lobe-client-fn');
+ });
+});
+
+describe('discoverTools β€” connector permissions and ownership', () => {
+ it('patches skill, composio and community-MCP plugin manifests with connector permissions', async () => {
+ const plugin = {
+ customParams: {},
+ identifier: 'community-mcp',
+ manifest: skillManifest('community-mcp'),
+ };
+ const result = await run({
+ composioManifests: [skillManifest('composio-gmail')],
+ connectorResolve: (ids) =>
+ ids.map((identifier, index) => ({ id: `conn-${index}`, identifier })),
+ connectorTools: [{ permission: 'needs_approval', toolName: 'doThing' }],
+ installedPlugins: [plugin],
+ lobehubSkillManifests: [skillManifest('lobehub-notion')],
+ }).promise;
+
+ expect(result.lobehubSkillManifests[0].api[0]).toMatchObject({
+ humanIntervention: 'required',
+ });
+ expect(result.composioManifests[0].api[0]).toMatchObject({ humanIntervention: 'required' });
+ expect(lastEngineOptions().additionalManifests.map((m: any) => m.identifier)).toEqual([
+ 'lobehub-notion',
+ 'composio-gmail',
+ ]);
+ // The patched plugin is what the engine is built from.
+ const engineContext = vi.mocked(createServerAgentToolsEngine).mock.calls.at(-1)?.[0] as any;
+ expect(engineContext.installedPlugins[0].manifest.api[0]).toMatchObject({
+ humanIntervention: 'required',
+ });
+ });
+
+ it('returns the borrowed-connector ownership note as run context', async () => {
+ vi.mocked(collectBorrowedConnectors).mockReturnValue([{ authorizerId: 'user-2' }] as never);
+ vi.mocked(buildConnectorOwnershipPrompt).mockReturnValue('runs on user-2 account');
+
+ const result = await run().promise;
+
+ expect(result.connectorOwnershipNote).toBe('runs on user-2 account');
+ });
+
+ it('leaves the ownership note unset when nothing is borrowed', async () => {
+ const result = await run().promise;
+
+ expect(result.connectorOwnershipNote).toBeUndefined();
+ });
+});
+
+describe('discoverTools β€” turn-scoped builtins', () => {
+ it('adds the message tool and a participant group context for bot conversations', async () => {
+ const result = await run({
+ agentConfig: { title: 'Helper' },
+ input: { botContext: { platform: 'discord' } },
+ }).promise;
+
+ expect(result.agentPlugins).toContain(MessageToolIdentifier);
+ expect(result.operationAgentGroup).toMatchObject({
+ currentAgentId: 'agent-1',
+ currentAgentName: 'Helper',
+ currentAgentRole: 'participant',
+ });
+ expect(lastEngineOptions().isBotConversation).toBe(true);
+ expect(lastEngineOptions().manifestContext.botPlatform.id).toBe('discord');
+ });
+
+ it('adds multimodal understanding when the model cannot see an attached image', async () => {
+ const result = await run({ input: { externalFileTypes: ['image/png'] } }).promise;
+
+ expect(result.agentPlugins).toContain(LobeAgentManifest.identifier);
+ });
+
+ it('adds nothing turn-scoped for a plain text turn', async () => {
+ const result = await run().promise;
+
+ expect(result.agentPlugins).not.toContain(MessageToolIdentifier);
+ expect(result.agentPlugins).not.toContain(LobeAgentManifest.identifier);
+ expect(result.operationAgentGroup).toBeUndefined();
+ });
+});
+
+describe('discoverTools β€” device routing', () => {
+ it('routes to the single online device and strips the device picker', async () => {
+ deviceGatewayState.isConfigured = true;
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { deviceId: 'dev-1', online: true, scope: 'personal' },
+ ] as never);
+
+ const result = await run({
+ agentConfig: { agencyConfig: { executionTarget: 'auto' } },
+ canUseDevice: true,
+ }).promise;
+
+ expect(result.executionPlan).toMatchObject({ deviceId: 'dev-1', kind: 'device' });
+ expect(result.activeDeviceId).toBe('dev-1');
+ expect(result.activeDeviceScope).toBe('personal');
+ expect(result.onlineDevices.map((d) => d.deviceId)).toEqual(['dev-1']);
+ // A routed run is device-locked: the picker never reaches the model.
+ expect(result.toolManifestMap[RemoteDeviceManifest.identifier]).toBeUndefined();
+ });
+
+ it('lists every online device in the RemoteDevice systemRole when none is routed', async () => {
+ deviceGatewayState.isConfigured = true;
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { deviceId: 'dev-1', online: true, scope: 'personal' },
+ { deviceId: 'dev-2', online: true, scope: 'personal' },
+ ] as never);
+
+ const result = await run({
+ agentConfig: { agencyConfig: { executionTarget: 'auto' } },
+ canUseDevice: true,
+ }).promise;
+
+ expect(result.activeDeviceId).toBeUndefined();
+ const systemRole = result.toolManifestMap[RemoteDeviceManifest.identifier]?.systemRole;
+ expect(systemRole).toContain('dev-1');
+ expect(systemRole).toContain('dev-2');
+ });
+
+ it('adds the caller personal device to a workspace pool when the agent binds it', async () => {
+ deviceGatewayState.isConfigured = true;
+ vi.mocked(getScopedOnlineDevices).mockImplementation(async (_db, _userId, workspaceId) =>
+ workspaceId ? [] : ([{ deviceId: 'dev-p', online: true, scope: 'personal' }] as never),
+ );
+
+ const result = await run({
+ agentConfig: { agencyConfig: { boundDeviceId: 'dev-p', executionTarget: 'local' } },
+ canUseDevice: true,
+ workspaceId: 'ws-1',
+ }).promise;
+
+ expect(getScopedOnlineDevices).toHaveBeenCalledTimes(2);
+ expect(result.activeDeviceId).toBe('dev-p');
+ expect(result.activeDeviceScope).toBe('personal');
+ });
+
+ it('does not route a device when device access is denied', async () => {
+ deviceGatewayState.isConfigured = true;
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { deviceId: 'dev-1', online: true, scope: 'personal' },
+ ] as never);
+
+ const result = await run({ canUseDevice: false }).promise;
+
+ expect(result.activeDeviceId).toBeUndefined();
+ expect(result.executionPlan?.kind).not.toBe('device');
+ });
+
+ it('fails the run with a persisted error when a fixed device is offline', async () => {
+ deviceGatewayState.isConfigured = true;
+ const { messageModel, promise } = run({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: 'dev-fixed',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ },
+ canUseDevice: true,
+ input: { isFixedDeviceTarget: true },
+ });
+
+ const error = await promise.catch((e) => e);
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error.code).toBe('PRECONDITION_FAILED');
+ expect(error.message).toBe(
+ 'The device fixed by this agent is offline. Ask an editor to bring it online or change the agent device policy.',
+ );
+ expect(messageModel.update).toHaveBeenCalledWith('assistant-1', {
+ content: '',
+ error: {
+ body: {
+ code: 'DEVICE_NOT_FOUND',
+ detail: error.message,
+ deviceId: 'dev-fixed',
+ retryable: true,
+ scope: 'personal',
+ },
+ message: 'Fixed agent device unavailable',
+ type: 'ServerAgentRuntimeError',
+ },
+ });
+ });
+});
+
+describe('discoverTools β€” group orchestration', () => {
+ it.each([
+ { expected: true, name: 'a persisted supervisor', role: 'supervisor' },
+ { expected: false, name: 'a participant claiming supervisor', role: 'participant' },
+ ])('authorizes group tools only for $name', async ({ expected, role }) => {
+ chatGroupState.roster = [{ agentId: 'agent-1', role, title: 'Me' }];
+
+ const result = await run({
+ appContext: { groupId: 'group-1', orchestrationRole: 'supervisor' },
+ }).promise;
+
+ expect(lastEngineOptions().isGroupSupervisor).toBe(expected);
+ expect(result.operationAgentGroup?.currentAgentId).toBe('agent-1');
+ });
+});
+
+describe('discoverTools β€” credential snapshot', () => {
+ it('freezes the credential list when the creds tool is enabled', async () => {
+ const credsList = vi.fn().mockResolvedValue({
+ data: [
+ {
+ description: 'd',
+ extra: 'dropped',
+ key: 'github',
+ name: 'GitHub',
+ ownerDisplayName: 'Me',
+ ownerType: 'user',
+ type: 'oauth',
+ },
+ ],
+ });
+ const result = await run({
+ agentConfig: { plugins: ['lobe-creds'] },
+ credsList,
+ workspaceId: 'ws-1',
+ }).promise;
+
+ expect(result.toolsResult.enabledToolIds).toContain('lobe-creds');
+ await expect(result.credentialFactsPromise).resolves.toEqual({
+ credentials: [
+ {
+ description: 'd',
+ key: 'github',
+ name: 'GitHub',
+ ownerDisplayName: 'Me',
+ ownerType: 'user',
+ type: 'oauth',
+ },
+ ],
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('resolves to undefined when the credential read fails', async () => {
+ const result = await run({
+ agentConfig: { plugins: ['lobe-creds'] },
+ credsList: vi.fn().mockRejectedValue(new Error('market down')),
+ }).promise;
+
+ await expect(result.credentialFactsPromise).resolves.toBeUndefined();
+ });
+
+ it('does not read credentials when the creds tool is not enabled', async () => {
+ const credsList = vi.fn();
+ const result = await run({ credsList }).promise;
+
+ expect(result.credentialFactsPromise).toBeUndefined();
+ expect(credsList).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
new file mode 100644
index 00000000000..650112905e7
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
@@ -0,0 +1,666 @@
+import { CredsIdentifier } from '@lobechat/builtin-tool-creds';
+import { GoalIdentifier, isGoalPrompt } from '@lobechat/builtin-tool-goal';
+import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
+import { generateSystemPrompt, RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import {
+ injectSelfFeedbackIntentTool,
+ shouldExposeSelfFeedbackIntentTool,
+} from '@lobechat/builtin-tool-self-iteration';
+import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';
+import { getFeatureDisabledToolIds } from '@lobechat/builtin-tools/featureGates';
+import type {
+ AgentGroupConfig,
+ LobeToolManifest,
+ ToolExecutor,
+ ToolsEngine,
+ ToolSource,
+} from '@lobechat/context-engine';
+import {
+ dropInvalidManifests,
+ resolveClientExecutors,
+ resolveDiscoveryPool,
+ resolveInvocationToolIds,
+} from '@lobechat/mecha';
+import type { BuiltinToolResolveContext, FrozenCredentialFacts } from '@lobechat/types';
+import { getActivePluginIds } from '@lobechat/types';
+import debug from 'debug';
+
+import { loadModels } from '@/business/client/model-bank/loadModels';
+import { type ExecutionPlan, executionPlanToManifestExecutionEnv } from '@/helpers/executionTarget';
+import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+import type { ServerAgentToolsContext } from '@/server/modules/Mecha';
+import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
+import { resolveUnsupportedMessageApis } from '@/server/services/bot/platforms/messageCapabilities';
+import { deviceGateway } from '@/server/services/deviceGateway';
+
+import { buildAllowedBuiltinTools } from '../../deviceToolRegistry';
+import { filterPluginsByShareGate, getShareGrantActivatedPluginIds } from '../../shareGate';
+import type { ExecRunContext } from '../../types';
+import {
+ buildOwnershipNote,
+ patchConnectorPermissions,
+ scheduleConnectorRefresh,
+} from './connectors';
+import { resolveDevicePlan } from './devicePlan';
+import { resolveModelContext, startModelMetadataRead } from './modelFacts';
+import { readCredentialFacts, startToolReads } from './reads';
+import { resolveOperationGroup, resolveTurnScopedPluginIds } from './turnContext';
+import type { ToolDiscoveryDeps, ToolDiscoveryInput, ToolDiscoveryResult } from './types';
+
+export type { ToolDiscoveryDeps, ToolDiscoveryInput, ToolDiscoveryResult } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Stage 5 (5a–5f) of {@link AiAgentService.execAgent}: tool discovery.
+ *
+ * Resolves the full tool surface for the run β€” installed plugins, connectors
+ * (real-MCP replacement + permission patching), LobeHub Skills, Composio
+ * manifests, device pool + execution plan, group-orchestration authorization,
+ * the tools-engine invocation pool, and the activator-discoverable manifest
+ * map β€” plus the Response-API client function tools and the RemoteDevice
+ * systemRole override.
+ *
+ * Short-circuits when `disableTools` is set (only the client function tools
+ * are honored), matching the pre-extraction behavior.
+ *
+ * Returns the connector credential ownership note as run context when the run
+ * borrows connectors other members authorized; the context engine injects it.
+ */
+export const discoverTools = async (
+ deps: ToolDiscoveryDeps,
+ ctx: ExecRunContext,
+ input: ToolDiscoveryInput,
+): Promise<ToolDiscoveryResult> => {
+ /** Filled below when the run borrows connectors; returned as run context. */
+ let connectorOwnershipNote: string | undefined;
+ const {
+ agentConfig,
+ appContext,
+ canUseDevice,
+ model,
+ prompt,
+ provider,
+ resolvedAgentId,
+ shareGate,
+ } = ctx;
+ const {
+ additionalPluginIds,
+ attachedFileIds,
+ botContext,
+ disableLocalSystem,
+ disableSelfFeedbackIntentTool,
+ disableTools,
+ disabledPluginIds: requestedDisabledPluginIds,
+ discordContext,
+ exclusivePluginIds,
+ externalFileTypes: rawExternalFileTypes,
+ functionTools,
+ globalMemoryEnabled,
+ hasMentionedAgents,
+ loadHistoryMessages,
+ localDeviceId,
+ requestedDeviceId,
+ selectedToolIds,
+ throwIfExecutionAborted,
+ topicBoundDeviceId,
+ } = input;
+ // Feature-flagged builtin tools (e.g. lobe-dashboard) leave the pool while
+ // their flag is off for this user; a flag read failure keeps them out.
+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(deps.userId).catch(
+ () => undefined,
+ );
+ const disabledPluginIds = [
+ ...requestedDisabledPluginIds,
+ ...getFeatureDisabledToolIds(featureFlags),
+ ];
+
+ let tools: any[] | undefined;
+ /** Started once the tool set is known; awaited at the return. */
+ let credentialFactsPromise: Promise<FrozenCredentialFacts | undefined> | undefined;
+ let toolsResult: { enabledToolIds: string[]; tools?: any[] | undefined } = {
+ enabledToolIds: [],
+ tools: undefined,
+ };
+ let toolsEngine: ToolsEngine | undefined;
+ const toolManifestMap: Record<string, any> = {};
+ const toolSourceMap: Record<string, ToolSource> = {};
+ const toolExecutorMap: Record<string, ToolExecutor> = {};
+ let onlineDevices: DeviceAttachment[] = [];
+ let activeDeviceId: string | undefined;
+ let activeDeviceScope: 'personal' | 'workspace' | undefined;
+ let executionPlan: ExecutionPlan | undefined;
+ let hasAgentDocuments = false;
+ let hasEnabledKnowledgeBases = false;
+ let operationAgentGroup: AgentGroupConfig | undefined;
+ const isBotConversation = !!(botContext || discordContext);
+
+ // Device-tool access (`canUseDevice` / `deviceAccessReason`) was resolved
+ // once before the hetero early exit; the decision flows into the
+ // engine's enable gates (LocalSystem / RemoteDevice) and the RemoteDevice
+ // systemRole injection below.
+
+ // These are needed outside the tools block (for agent management context, skill engine, etc.)
+ let lobehubSkillManifests: LobeToolManifest[] = [];
+ let composioManifests: LobeToolManifest[] = [];
+ let connectorManifests: ReturnType<typeof buildConnectorManifests> = [];
+
+ // `selectedToolIds` are the user's @-mention picks for this turn; merged in
+ // (deduped) alongside the agent's pinned plugins and any internal
+ // `additionalPluginIds` so a mentioned-but-not-pinned tool (e.g. a custom MCP
+ // connector) is both queried for manifests and enabled by the tools engine.
+ const isGoalTurn = isGoalPrompt(prompt);
+ let agentPlugins: string[] = exclusivePluginIds
+ ? [...new Set(exclusivePluginIds)]
+ : isGoalTurn
+ ? [GoalIdentifier]
+ : [
+ ...new Set([
+ ...getActivePluginIds(agentConfig?.plugins),
+ ...(additionalPluginIds || []),
+ ...(selectedToolIds || []),
+ ...(hasMentionedAgents ? ['lobe-agent-management'] : []),
+ ...(shareGate ? getShareGrantActivatedPluginIds(shareGate) : []),
+ ]),
+ ];
+
+ // Share allowlist runs EARLY, before connector resolution / credential
+ // decryption / stale-tool refresh scheduling β€” otherwise an ungranted HTTP
+ // connector pinned on the creator's agent would still be resolved and its
+ // OAuth credentials touched for a visitor turn (issuing background MCP
+ // traffic and refresh jobs on behalf of the creator). The later pass right
+ // before manifest discovery (~line 618) stays as defense in depth: internal
+ // additions like the bot message / multimodal
+ // understanding tool are appended after this point and must run through the
+ // same allowlist.
+ if (shareGate) {
+ agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);
+ }
+
+ // Model metadata is needed both for tool support checks and agent-management context.
+ const builtinModels = await loadModels();
+ // Started, not awaited: the tool reads below hit other backends entirely, so
+ // this round trip overlaps them instead of gating them.
+ const modelMetadataTask = startModelMetadataRead(deps, model, provider);
+
+ // Every other read this send needs, started together; see `startToolReads`.
+ const toolReads = disableTools
+ ? undefined
+ : startToolReads(deps, {
+ agentConfig,
+ attachedFileIds,
+ candidateIds: [...agentPlugins],
+ exclusivePluginIds,
+ isGoalTurn,
+ requestedDeviceId,
+ resolvedAgentId,
+ shareGate,
+ topicId: ctx.topicId,
+ });
+
+ // The rest of the run's model facts, read here because this stage already
+ // holds the loaded bank and the user's model row.
+ const { modelFacts, modelMediaCapabilities, searchDecision } = await resolveModelContext(
+ deps,
+ ctx,
+ builtinModels,
+ modelMetadataTask,
+ );
+
+ if (!toolReads) {
+ log('execAgent: tools disabled by disableTools flag, skipping all tool discovery');
+ } else {
+ // 5a. Get installed plugins from database. Disabled identifiers are
+ // excluded from this candidate pool entirely β€” not just from the pinned
+ // `rules` allowlist β€” because `createEnableChecker`'s explicit-activation
+ // bypass (auto activator) short-circuits before rules are consulted, so a
+ // present-but-rule-disabled manifest could still be auto-activated.
+ const disabledPluginIdSet = new Set(disabledPluginIds);
+ const installedPlugins = (await toolReads.installedPlugins).filter(
+ (p) => !disabledPluginIdSet.has(p.identifier),
+ );
+ log(
+ 'execAgent: got %d installed plugins (%d disabled excluded)',
+ installedPlugins.length,
+ disabledPluginIdSet.size,
+ );
+
+ // 5a-1. Resolve connectors β€” connector identifier takes priority over plugin.
+ const {
+ connectorGateKeeper,
+ connectors,
+ connectorsMcp,
+ connectorTools,
+ discoverableConnectorManifests,
+ discoverableConnectorsMcp,
+ discoverableConnectorTools,
+ } = await toolReads.connectors;
+
+ // 5a-1b. Model awareness: tell the model whose connected account each
+ // borrowed tool runs on (see `buildOwnershipNote`).
+ connectorOwnershipNote = await buildOwnershipNote(deps, connectors);
+
+ connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);
+
+ scheduleConnectorRefresh(deps, {
+ connectorGateKeeper,
+ connectorsMcp,
+ connectorTools,
+ discoverableConnectorsMcp,
+ discoverableConnectorTools,
+ });
+
+ // Only connectors that ACTUALLY produced a manifest (enabled + with synced
+ // tools) replace a same-named plugin. Deriving the set from connectorsMcp
+ // instead would let a disabled / not-yet-synced connector evict the plugin
+ // while contributing no tools β€” leaving the runtime with nothing to call.
+ // Unpinned connectors supersede a leftover plugin row the same way.
+ const connectorIdentifierSet = new Set(
+ [...connectorManifests, ...discoverableConnectorManifests].map((m) => m.identifier),
+ );
+
+ // Filter out plugin entries that are now handled by real MCP connectors.
+ // `let` because community-MCP plugins may be patched with connector
+ // permissions below (their connector row has no endpoint, so they stay here).
+ // Composio connections also leave a plugin row behind (customParams.composio),
+ // but they are executable only through `getComposioManifests`, which gates
+ // on an ACTIVE connection and tags the tool source as `composio`. Letting a
+ // PENDING/EXPIRED row through here exposes the full tool schema with no
+ // Composio source, so every call falls to the builtin executor and fails
+ // as "not implemented".
+ let pluginsWithoutConnectors = installedPlugins.filter(
+ (p) => !connectorIdentifierSet.has(p.identifier) && !p.customParams?.composio,
+ );
+ log('execAgent: got %d connector manifests', connectorManifests.length);
+
+ // 5b. Get model abilities from model-bank for function calling support check
+ const isModelSupportToolUse = (m: string, p: string) => {
+ const info = builtinModels.find((item) => item.id === m && item.providerId === p);
+ return info?.abilities?.functionCall ?? true;
+ };
+
+ // 5c / 5d. LobeHub Skills and Composio manifests, read in the wave above.
+ lobehubSkillManifests = await toolReads.lobehubSkillManifests;
+ log('execAgent: got %d lobehub skill manifests', lobehubSkillManifests.length);
+ composioManifests = await toolReads.composioManifests;
+ log('execAgent: got %d composio manifests', composioManifests.length);
+
+ // 5d-1. Patch Lobehub/Composio manifests AND community-MCP plugin manifests
+ // with connector tool permissions (see `patchConnectorPermissions`).
+ ({ composioManifests, lobehubSkillManifests, pluginsWithoutConnectors } =
+ await patchConnectorPermissions(deps, resolvedAgentId, {
+ composioManifests,
+ lobehubSkillManifests,
+ pluginsWithoutConnectors,
+ }));
+
+ await throwIfExecutionAborted('tool discovery');
+
+ // 5e. Create tools using Server AgentToolsEngine
+ hasEnabledKnowledgeBases =
+ agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??
+ false;
+
+ hasAgentDocuments = await toolReads.agentDocuments;
+ const hasOversizedFiles = await toolReads.oversizedFiles;
+
+ log('execAgent: isBotConversation=%s', isBotConversation);
+
+ // Device context for the ToolsEngine enableChecker, read in the wave above.
+ const gatewayConfigured = deviceGateway.isConfigured;
+ const agentBoundDeviceId = agentConfig.agencyConfig?.boundDeviceId;
+ const boundDeviceId = topicBoundDeviceId || agentBoundDeviceId;
+ onlineDevices = await toolReads.devicePool;
+ const deviceOnline = onlineDevices.length > 0;
+
+ const toolsContext: ServerAgentToolsContext = {
+ installedPlugins: pluginsWithoutConnectors,
+ isModelSupportToolUse,
+ };
+
+ // Dynamically inject turn-scoped builtin tools.
+ const modelAbilities =
+ builtinModels.find((item) => item.id === model && item.providerId === provider)?.abilities ??
+ builtinModels.find((item) => item.id === model)?.abilities;
+ agentPlugins = [
+ ...agentPlugins,
+ ...(await resolveTurnScopedPluginIds({
+ attachedFileTypes: await toolReads.attachedFileTypes,
+ externalFileTypes: rawExternalFileTypes,
+ isBotConversation,
+ loadHistoryMessages,
+ modelMediaCapabilities,
+ })),
+ ];
+
+ // Share allowlist filters the full candidate set (pinned + mentioned +
+ // internal additions) before manifest discovery. This only trims which
+ // plugin ids get *activated*; the separate skill candidate pool built in
+ // `operationPrep` (`skills`, consumed by `SkillEngine`) needs its own pass
+ // against the same allowlist, since building the skill list is a distinct
+ // step from `SkillEngine.generate` and is not scoped by the plugin id list
+ // on its own. The operationToolSet snapshot then carries the restricted
+ // surface into every later step.
+ //
+ // Defense in depth: the same filter also runs at the top of
+ // `discoverTools` (before connector resolution) so that ungranted
+ // connectors never reach `resolveByIdentifiers` /
+ // `scheduleStaleConnectorToolsRefresh`. Keep this second pass β€” the
+ // internal additions above (bot message tool, multimodal understanding)
+ // are appended after the first pass and would
+ // otherwise slip through.
+ if (shareGate) {
+ agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);
+ }
+
+ // Resolve THE device decision for this run; see `resolveDevicePlan`.
+ const devicePlan = await resolveDevicePlan(deps, ctx, input, {
+ boundDeviceId,
+ gatewayConfigured,
+ onlineDevices,
+ });
+ executionPlan = devicePlan.executionPlan;
+ activeDeviceId = devicePlan.activeDeviceId;
+ activeDeviceScope = devicePlan.activeDeviceScope;
+ const { deviceCapable, deviceLocked, supportedDeviceTools } = devicePlan;
+
+ const group = await resolveOperationGroup(deps, ctx, botContext);
+ const { isGroupSupervisor } = group;
+ operationAgentGroup = group.operationAgentGroup;
+
+ // Skills/Composio/connector identifiers share the same `plugins`
+ // identifier space as installed plugins, so a disabled entry must be
+ // excluded from their manifests too β€” otherwise the disabled tool stays
+ // discoverable/activatable via these additionalManifests even though
+ // `installedPlugins` above already dropped it.
+ const dropDisabledManifests = <T extends { identifier: string }>(manifests: T[]): T[] =>
+ disabledPluginIdSet.size === 0
+ ? manifests
+ : manifests.filter((m) => !disabledPluginIdSet.has(m.identifier));
+ const activeLobehubSkillManifests = dropDisabledManifests(lobehubSkillManifests);
+ const activeComposioManifests = dropDisabledManifests(composioManifests);
+ const activeConnectorManifests = dropDisabledManifests(connectorManifests);
+ const activeDiscoverableConnectorManifests = dropDisabledManifests(
+ discoverableConnectorManifests,
+ );
+
+ // Context-aware builtin manifests: inside a sub-agent (or group) run,
+ // lobe-agent drops `callSubAgent` so the model can't recurse into nested
+ // sub-agents (which the runtime rejects, looping until the inactivity
+ // watchdog kills the op). Mirrors the frontend `createAgentToolsEngine`.
+ // `executionEnv` mirrors the resolved plan, while preserving the local
+ // target for a routed desktop because its readFile implementation can
+ // return images. It also keeps the `device-unrouted` degradation, where
+ // the user picked a local device that is offline and exec silently lands
+ // in the sandbox.
+ // For bot conversations we also pass the IM platform so `lobe-message`
+ // can drop APIs the platform can't fulfil (e.g. WeChat has no
+ // `readMessages`). Telegram Guest Mode uses a stricter overlay β€”
+ // the bot is not a chat member and has no regular channel tools.
+ // The discovery pool below resolves with the same context, so a tool
+ // activated mid-run carries the trimmed manifest too.
+ const manifestContext: BuiltinToolResolveContext = {
+ ...(botContext?.platform && {
+ botPlatform: {
+ id: botContext.platform,
+ unsupportedMessageApis: resolveUnsupportedMessageApis(
+ botContext.platform,
+ botContext.platformThreadId,
+ ),
+ },
+ }),
+ executionEnv: executionPlanToManifestExecutionEnv(executionPlan, localDeviceId),
+ executionEnvUnroutedReason:
+ executionPlan.kind === 'device-unrouted' ? executionPlan.reason : undefined,
+ isSubAgent: appContext?.isSubAgent,
+ scope: appContext?.scope ?? undefined,
+ };
+
+ toolsEngine = createServerAgentToolsEngine(toolsContext, {
+ additionalManifests: [
+ ...activeLobehubSkillManifests,
+ ...activeComposioManifests,
+ ...activeConnectorManifests,
+ // Known to the engine but never invocation candidates (they stay out of
+ // `connectorIds` below), so they are not enabled by default β€” this only
+ // lets a previous turn's activation pass the explicit-activation
+ // re-check when the next operation restores it.
+ ...activeDiscoverableConnectorManifests,
+ ],
+ agentConfig: {
+ chatConfig: isGoalTurn
+ ? { ...agentConfig.chatConfig, toolMode: 'custom' }
+ : (agentConfig.chatConfig ?? undefined),
+ plugins: agentPlugins,
+ },
+ canUseDevice,
+ deviceContext: gatewayConfigured
+ ? {
+ autoActivated: activeDeviceId ? true : undefined,
+ boundDeviceId,
+ deviceOnline,
+ gatewayConfigured: true,
+ supportedTools: supportedDeviceTools,
+ }
+ : undefined,
+ disableLocalSystem,
+ disabledPluginIds,
+ executionPlan,
+ globalMemoryEnabled,
+ hasEnabledKnowledgeBases,
+ hasOversizedFiles,
+ isBotConversation,
+ isGroupSupervisor,
+ modelAbilities,
+ manifestContext,
+ model,
+ provider,
+ useApplicationBuiltinSearchTool: searchDecision.useApplicationBuiltinSearchTool,
+ });
+
+ // 5f. Generate tools and manifest map
+ // Which identifiers the engine considers, what the activator may discover
+ // mid-run, and which tools dispatch to the client are shared rules in
+ // `@lobechat/mecha`; this pipeline only supplies the run's facts.
+ const pluginIds = resolveInvocationToolIds({
+ agentPlugins,
+ composioIds: activeComposioManifests.map((m) => m.identifier),
+ connectorIds: activeConnectorManifests.map((m) => m.identifier),
+ disableLocalSystem,
+ exclusivePluginIds,
+ lobehubSkillIds: activeLobehubSkillManifests.map((m) => m.identifier),
+ });
+ log('execAgent: agent configured plugins: %O', pluginIds);
+
+ const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';
+
+ toolsResult = toolsEngine.generateToolsDetailed({
+ excludeDefaultToolIds: isManualMode ? manualModeExcludeToolIds : undefined,
+ model,
+ provider,
+ skipDefaultTools: !!exclusivePluginIds,
+ toolIds: pluginIds,
+ });
+
+ tools = toolsResult.tools;
+ log('execAgent: enabled tool ids: %O', toolsResult.enabledToolIds);
+
+ // Only a run that can inject credentials renders {{CREDS_LIST}}. Kick the
+ // read off here and await it at the end: it is one Market round trip, and
+ // every step of the run reads the answer back off the operation instead of
+ // asking again.
+ if (toolsResult.enabledToolIds?.includes(CredsIdentifier)) {
+ credentialFactsPromise = readCredentialFacts(deps);
+ }
+
+ // Start with the scoped manifest map (pluginIds + defaultToolIds)
+ const manifestMap = toolsEngine.getEnabledPluginManifests(pluginIds);
+ const discovery = resolveDiscoveryPool({
+ builtinTools: buildAllowedBuiltinTools({
+ canUseDevice,
+ deviceLocked,
+ disableLocalSystem,
+ supportedDeviceTools: gatewayConfigured ? (supportedDeviceTools ?? []) : undefined,
+ }),
+ composio: activeComposioManifests,
+ device: gatewayConfigured ? { supportedTools: supportedDeviceTools } : undefined,
+ deviceAccess: { canUseDevice, deviceLocked },
+ deviceCapable,
+ disableLocalSystem,
+ disabledPluginIds,
+ enabledManifests: manifestMap,
+ exclusivePluginIds,
+ executionTarget: executionPlan.target,
+ // Installed-but-not-pinned plugins (`auto` in the three-state plugin
+ // config): the model must be able to discover and activate them mid-run,
+ // exactly as the client runtime lists them from `installedPlugins`.
+ // They never join `enabledToolIds` β€” the engine's rules stay pinned-only
+ // β€” so this widens what the activator can reach, not what the run gets
+ // by default. Disabled ids were dropped in 5a and the pool's own ingest
+ // wall re-checks them; a connector / Composio / LobeHub skill manifest
+ // of the same identifier still wins, because the pool seeds this source
+ // last.
+ // Unpinned connectors join them on the same terms.
+ installedManifests: [
+ ...activeDiscoverableConnectorManifests,
+ ...dropInvalidManifests(
+ pluginsWithoutConnectors.map((plugin) => plugin.manifest as LobeToolManifest | undefined),
+ 'installedPlugins(auto)',
+ ),
+ ],
+ lobehubSkills: activeLobehubSkillManifests,
+ manifestContext,
+ });
+ Object.assign(toolManifestMap, discovery.manifestMap);
+ Object.assign(toolSourceMap, discovery.sourceMap);
+ Object.assign(
+ toolExecutorMap,
+ resolveClientExecutors({
+ hasDeviceProxy: gatewayConfigured,
+ manifestMap: toolManifestMap,
+ stdioIdentifiers: [
+ ...installedPlugins
+ .filter((plugin) => plugin.customParams?.mcp?.type === 'stdio')
+ .map((plugin) => plugin.identifier),
+ ...[...connectorsMcp, ...discoverableConnectorsMcp]
+ .filter((connector) => connector.mcpConnectionType === 'stdio')
+ .map((connector) => connector.identifier),
+ ],
+ }),
+ );
+
+ log(
+ 'execAgent: generated %d tools, %d lobehub skills, %d composio tools',
+ tools?.length ?? 0,
+ lobehubSkillManifests.length,
+ composioManifests.length,
+ );
+
+ // Share-visitor fail-closed gate β€” never expose the
+ // `declareSelfFeedbackIntent` tool to a share-visitor turn. This tool sits
+ // outside the normal `toolManifestMap` / `applyShareGateToToolSet`
+ // allowlist (it's injected directly into `tools` below), so the visitor's
+ // own model call can reach it even with an empty `enabledToolIds`. Its
+ // execution context is stamped with the share CREATOR's user id, and the
+ // resulting `agent.self_feedback_intent.declared` event dispatches a full
+ // autonomous background run under the creator's account, which can write
+ // to the creator's memory. Same root cause as the `agent.user.message`
+ // gate in `turnSetup`; `allowReadMemory` is a read-only grant so this must
+ // not be conditional on it either.
+ //
+ // There is no per-agent switch: Labs β†’ Self-evolving covers every agent.
+ if (!shareGate && !disableSelfFeedbackIntentTool) {
+ // The run already reads `users.preference` for expertise injection; reuse that row.
+ // A failed read leaves the tool off (fail closed).
+ const featureUserEnabled = await isAgentSignalEnabledForUser(deps.db, deps.userId, {
+ preference: await ctx.runFacts.userPreference().catch(() => undefined),
+ });
+
+ if (
+ shouldExposeSelfFeedbackIntentTool({
+ agentSelfIterationEnabled: featureUserEnabled,
+ disableSelfFeedbackIntentTool,
+ featureUserEnabled,
+ })
+ ) {
+ tools = tools ?? [];
+ injectSelfFeedbackIntentTool({
+ enabledToolIds: toolsResult.enabledToolIds,
+ manifestMap: toolManifestMap,
+ sourceMap: toolSourceMap,
+ tools,
+ });
+ log('execAgent: injected self-feedback intent declaration tool');
+ }
+ }
+ }
+
+ // Inject client function tools from Response API
+ const CLIENT_FN_IDENTIFIER = 'lobe-client-fn';
+ if (functionTools?.length) {
+ for (const ft of functionTools) {
+ tools?.push({
+ function: {
+ description: ft.description,
+ name: `${CLIENT_FN_IDENTIFIER}____${ft.name}`,
+ parameters: ft.parameters,
+ },
+ type: 'function',
+ });
+ }
+ toolSourceMap[CLIENT_FN_IDENTIFIER] = 'client';
+ toolManifestMap[CLIENT_FN_IDENTIFIER] = {
+ api: functionTools.map((ft) => ({
+ description: ft.description ?? '',
+ name: ft.name,
+ parameters: ft.parameters ?? {},
+ })),
+ identifier: CLIENT_FN_IDENTIFIER,
+ meta: { title: 'Client Functions' },
+ type: 'default',
+ };
+ toolsResult.enabledToolIds.push(CLIENT_FN_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),
+ };
+ }
+
+ return {
+ activeDeviceId,
+ activeDeviceScope,
+ agentPlugins,
+ builtinModels,
+ composioManifests,
+ connectorManifests,
+ connectorOwnershipNote,
+ executionPlan,
+ hasAgentDocuments,
+ credentialFactsPromise,
+ hasEnabledKnowledgeBases,
+ lobehubSkillManifests,
+ modelFacts,
+ modelMediaCapabilities,
+ onlineDevices,
+ operationAgentGroup,
+ searchDecision,
+ toolExecutorMap,
+ toolManifestMap,
+ toolSourceMap,
+ tools,
+ toolsEngine,
+ toolsResult,
+ };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/modelFacts.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/modelFacts.ts
new file mode 100644
index 00000000000..f67f04ba722
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/modelFacts.ts
@@ -0,0 +1,118 @@
+import { readFrozenModelFacts } from '@lobechat/mecha';
+import debug from 'debug';
+import type { AiModelConfig, ModelAbilities } from 'model-bank';
+
+import type { loadModels } from '@/business/client/model-bank/loadModels';
+import { AiModelModel } from '@/database/models/aiModel';
+import { AiProviderModel } from '@/database/models/aiProvider';
+import { resolveModelMediaCapabilities } from '@/server/modules/AgentRuntime/resolveModelMediaCapabilities';
+import { createServerModelParamsProviders } from '@/server/modules/Mecha/ModelParams/providers';
+
+import { resolveServerSearchDecision } from '../../searchDecision';
+import type { ExecRunContext } from '../../types';
+import { markDegradedStage, traceDiscoveryStage } from '../discoveryTracing';
+import type { ToolDiscoveryDeps } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+type BuiltinModels = Awaited<ReturnType<typeof loadModels>>;
+
+/**
+ * Started, not awaited: the tool reads hit other backends entirely, so this
+ * round trip overlaps them instead of gating them.
+ */
+export const startModelMetadataRead = (deps: ToolDiscoveryDeps, model: string, provider: string) =>
+ traceDiscoveryStage('model_metadata', async (span) => {
+ const results = await Promise.allSettled([
+ new AiModelModel(deps.db, deps.userId, deps.workspaceId).findByIdAndProvider(model, provider),
+ new AiProviderModel(deps.db, deps.userId, deps.workspaceId).findById(provider),
+ ]);
+ markDegradedStage(
+ span,
+ results.filter((result) => result.status === 'rejected').length,
+ 'metadata lookups',
+ );
+ return results;
+ });
+
+/**
+ * The run's model facts, read here because this stage already holds the loaded
+ * bank and the user's model row: media capabilities, the frozen model facts and
+ * the server search decision.
+ */
+export const resolveModelContext = async (
+ deps: ToolDiscoveryDeps,
+ ctx: Pick<ExecRunContext, 'agentConfig' | 'model' | 'provider' | 'topicId'>,
+ builtinModels: BuiltinModels,
+ modelMetadataTask: ReturnType<typeof startModelMetadataRead>,
+) => {
+ const { agentConfig, model, provider, topicId } = ctx;
+ const [modelMetadataResult, providerMetadataResult] = await modelMetadataTask;
+ if (modelMetadataResult.status === 'rejected') {
+ log('execAgent: failed to load active model search metadata: %O', modelMetadataResult.reason);
+ }
+ if (providerMetadataResult.status === 'rejected') {
+ log(
+ 'execAgent: failed to load active provider search metadata: %O',
+ providerMetadataResult.reason,
+ );
+ }
+ const activeModelMetadata =
+ modelMetadataResult.status === 'fulfilled' ? modelMetadataResult.value : undefined;
+ const activeProviderMetadata =
+ providerMetadataResult.status === 'fulfilled' ? providerMetadataResult.value : undefined;
+ const activeModelAbilities = activeModelMetadata?.abilities as ModelAbilities | undefined;
+ const modelMediaCapabilities =
+ resolveModelMediaCapabilities({
+ builtinModels,
+ model,
+ provider,
+ userAbilities: activeModelAbilities,
+ }) ?? {};
+ // Everything downstream β€” one per step, retries included β€” reads these back
+ // off the operation instead.
+ const modelFacts = await readFrozenModelFacts(
+ {
+ agent: { id: agentConfig.id },
+ mediaCapabilities: modelMediaCapabilities,
+ model,
+ provider,
+ topicId,
+ },
+ {
+ ...createServerModelParamsProviders({
+ builtinModels,
+ serverDB: deps.db,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ }),
+ // Reuse the row read above rather than querying it a second time.
+ getUserModelRow: async () =>
+ activeModelMetadata
+ ? {
+ abilities: activeModelMetadata.abilities,
+ // Deployment-catalog providers resolve the request model by the
+ // user-configured alias when present (merged over the bundled
+ // card when the facts freeze).
+ deploymentName:
+ (activeModelMetadata.config as AiModelConfig | null)?.deploymentName ?? null,
+ displayName: activeModelMetadata.displayName,
+ extendParams: activeModelMetadata.settings?.extendParams ?? undefined,
+ }
+ : null,
+ },
+ );
+ const searchDecision = resolveServerSearchDecision({
+ builtinModels,
+ chatConfig: agentConfig.chatConfig ?? undefined,
+ hasModelAbilitiesOverride:
+ !!activeModelAbilities && Object.keys(activeModelAbilities).length > 0,
+ model,
+ modelSearchAbility: activeModelAbilities?.search,
+ modelSearchImpl: activeModelMetadata?.settings?.searchImpl,
+ provider,
+ providerSearchMode: activeProviderMetadata?.settings?.searchMode,
+ });
+
+ return { modelFacts, modelMediaCapabilities, searchDecision };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
new file mode 100644
index 00000000000..aba3f87c86c
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
@@ -0,0 +1,365 @@
+import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import { FILE_PREVIEW_CHARS, isOversizedFileContent } from '@lobechat/prompts';
+import type { FrozenCredentialFacts } from '@lobechat/types';
+import { agentShareFileAccessScope, ordinaryFileAccessScope } from '@lobechat/types';
+import debug from 'debug';
+
+import type { DecryptedConnector } from '@/database/models/connector';
+import { DocumentModel } from '@/database/models/document';
+import { FileModel } from '@/database/models/file';
+import type { UserConnectorToolItem } from '@/database/schemas';
+import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { deviceGateway } from '@/server/services/deviceGateway';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
+
+import type { ExecRunContext } from '../../types';
+import { markDegradedStage, traceDiscoveryStage } from '../discoveryTracing';
+import type { ToolDiscoveryDeps } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Start a read now and keep its rejection for the caller's `await`.
+ *
+ * A promise that rejects before anything awaits it trips Node's
+ * `unhandledRejection` even though this code does await it a few lines later,
+ * so register a no-op handler on the original and hand the same promise back.
+ */
+const started = <T>(task: Promise<T>): Promise<T> => {
+ task.catch(() => undefined);
+ return task;
+};
+
+/** The run facts the read wave needs, captured when it starts. */
+export interface ToolReadsContext {
+ agentConfig: ExecRunContext['agentConfig'];
+ attachedFileIds?: string[];
+ /**
+ * Snapshot of the candidate plugin ids taken when the wave starts β€” the
+ * caller's list later gains turn-scoped builtins (topic reference, bot
+ * message, multimodal understanding), and those must not reach connector
+ * resolution or the stale-tools refresh.
+ */
+ candidateIds: string[];
+ exclusivePluginIds?: string[];
+ isGoalTurn: boolean;
+ requestedDeviceId?: string;
+ resolvedAgentId: string;
+ shareGate: ExecRunContext['shareGate'];
+ topicId: string;
+}
+
+/**
+ * The credentials the run may reference, read once. Inside a workspace an agent
+ * only sees the workspace's shared organization credentials, never the
+ * operator's personal ones β€” the scope is recorded on the snapshot so a step in
+ * another scope falls back to a live read.
+ *
+ * Never fails the turn: without an answer the steps read the list live, exactly
+ * as they did before the snapshot existed.
+ */
+export const readCredentialFacts = async (
+ deps: ToolDiscoveryDeps,
+): Promise<FrozenCredentialFacts | undefined> => {
+ try {
+ const marketService = await deps.getMarketService();
+ const result = deps.workspaceId
+ ? await marketService.market.organizations.creds({ workspaceId: deps.workspaceId }).list()
+ : await marketService.market.creds.list();
+ const creds = (result as any)?.data ?? [];
+ return {
+ credentials: creds.map((cred: any) => ({
+ description: cred.description,
+ key: cred.key,
+ name: cred.name,
+ ownerDisplayName: cred.ownerDisplayName,
+ ownerType: cred.ownerType,
+ type: cred.type,
+ })),
+ workspaceId: deps.workspaceId,
+ };
+ } catch (error) {
+ log('execAgent: failed to freeze credential facts: %O', error);
+ return undefined;
+ }
+};
+
+/**
+ * Connector resolution: the gatekeeper decrypts the stored OAuth tokens, or
+ * `buildConnectorManifests` gets no auth and every tool call 401s.
+ */
+const readConnectors = async (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) => {
+ const { candidateIds, resolvedAgentId } = ctx;
+ let connectorGateKeeper: KeyVaultsGateKeeper | undefined;
+ try {
+ connectorGateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ } catch (err) {
+ log('execAgent: failed to init gatekeeper for connector credentials: %O', err);
+ }
+
+ return traceDiscoveryStage('connectors', async () => {
+ const connectors =
+ candidateIds.length > 0
+ ? await deps.connectorModel.resolveByIdentifiers(
+ candidateIds,
+ resolvedAgentId,
+ connectorGateKeeper,
+ )
+ : [];
+
+ // Only connectors WITH a real MCP endpoint (mcpServerUrl or stdio) can replace plugins in the
+ // manifest. Connectors WITHOUT an endpoint (e.g. Lobehub/Composio OAuth skills synced via
+ // syncToolsFromClient) must continue using their original plugin executor path β€” otherwise
+ // after humanIntervention approval the runtime tries to call mcpServerUrl='' and returns empty.
+ const connectorsMcp = connectors.filter(
+ (c) => c.mcpServerUrl || c.mcpConnectionType === 'stdio',
+ );
+
+ // Fetch ALL tools for all real-MCP connectors (including disabled tools) so that
+ // buildConnectorManifests can show blocking descriptions for disabled tools.
+ // The runtime hot-path still uses queryByConnectorIds (non-disabled only) elsewhere.
+ const connectorTools =
+ connectorsMcp.length > 0
+ ? await deps.connectorToolModel.queryAllByConnectorIds(connectorsMcp.map((c) => c.id))
+ : [];
+
+ const discoverable = await readDiscoverableConnectors(deps, ctx, connectorGateKeeper);
+
+ return {
+ connectorGateKeeper,
+ connectors,
+ connectorsMcp,
+ connectorTools,
+ discoverableConnectorManifests: discoverable.manifests,
+ discoverableConnectorsMcp: discoverable.connectorsMcp,
+ discoverableConnectorTools: discoverable.tools,
+ };
+ });
+};
+
+/**
+ * Connectors the agent has not pinned β€” `auto` in the three-state plugin
+ * config, which is simply "absent from `plugins`". A custom MCP is stored as
+ * a connector, so without this source an unpinned one is resolvable only on
+ * the turn that @-mentions it: the next turn's activator answers
+ * "Not found" and the model's direct call is rejected as an unknown name.
+ * Like installed plugins they are discoverable but never enabled.
+ *
+ * Share runs skip it: the early allowlist in `discoverTools` exists so
+ * ungranted creator connectors never get their credentials decrypted for a
+ * visitor turn. Degrades to nothing on failure β€” widening discovery must not
+ * fail the run.
+ */
+const readDiscoverableConnectors = async (
+ deps: ToolDiscoveryDeps,
+ ctx: ToolReadsContext,
+ gateKeeper: KeyVaultsGateKeeper | undefined,
+): Promise<{
+ connectorsMcp: DecryptedConnector[];
+ manifests: LobeToolManifest[];
+ tools: UserConnectorToolItem[];
+}> => {
+ const none = { connectorsMcp: [], manifests: [], tools: [] };
+ if (ctx.shareGate || ctx.exclusivePluginIds || ctx.isGoalTurn) return none;
+ try {
+ const candidates = new Set(ctx.candidateIds);
+ const connectorsMcp = (
+ await deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper)
+ ).filter(
+ (c) => !candidates.has(c.identifier) && (c.mcpServerUrl || c.mcpConnectionType === 'stdio'),
+ );
+ if (connectorsMcp.length === 0) return none;
+
+ const tools = await deps.connectorToolModel.queryAllByConnectorIds(
+ connectorsMcp.map((c) => c.id),
+ );
+ return {
+ connectorsMcp,
+ manifests: buildConnectorManifests(connectorsMcp, tools) as LobeToolManifest[],
+ tools,
+ };
+ } catch (error) {
+ log('execAgent: failed to read discoverable connectors: %O', error);
+ return none;
+ }
+};
+
+const readLobehubSkillManifests = async (deps: ToolDiscoveryDeps): Promise<LobeToolManifest[]> => {
+ try {
+ const marketService = await deps.getMarketService();
+ return await traceDiscoveryStage('lobehub_skills', async (span) => {
+ // The service degrades to fewer (or zero) manifests instead of
+ // throwing, so count what it absorbed β€” otherwise a Market timeout
+ // looks exactly like a user with no connected skills.
+ let failureCount = 0;
+ const manifests = await marketService.getLobehubSkillManifests({
+ onError: () => {
+ failureCount += 1;
+ },
+ });
+ span.setAttribute('lobehub.tool_discovery.manifest_count', manifests.length);
+ markDegradedStage(span, failureCount, 'skill discovery requests');
+ return manifests;
+ });
+ } catch (error) {
+ log('execAgent: failed to fetch lobehub skill manifests: %O', error);
+ return [];
+ }
+};
+
+const readDevicePool = async (
+ deps: ToolDiscoveryDeps,
+ ctx: ToolReadsContext,
+): Promise<DeviceAttachment[]> => {
+ const { agentConfig, requestedDeviceId } = ctx;
+ if (!deviceGateway.isConfigured) return [];
+ try {
+ // Personal pool βˆͺ the current workspace pool, DB rows βŠ• gateway online,
+ // tagged with `scope` and the user-set `friendlyName` alias (see
+ // `getScopedOnlineDevices`) so the systemRole snapshot lets the model
+ // tell a personal machine apart from its workspace-enrolled counterpart
+ // (same physical machine under both principals). Keep only live devices:
+ // downstream `onlineDeviceIds` / `deviceOnline` treat this list as the
+ // online set.
+ let devices = (
+ await traceDiscoveryStage('online_devices', () =>
+ getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId),
+ )
+ ).filter((d) => d.online);
+
+ // A workspace run that targets one of the caller's PERSONAL devices
+ // needs that device visible in this run's pool β€” otherwise
+ // `resolveExecutionPlan` treats it as offline (`bound-device-offline`)
+ // and the run stays unrouted. The workspace pool never includes
+ // personal devices by design (`getScopedOnlineDevices` enforces the
+ // strict scope), so union the specific personal device in here. The
+ // device is dispatchable because the gateway routes it by
+ // `(userId, deviceId)` β€” the caller owns it.
+ //
+ // Candidates mirror the ids `resolveExecutionPlan` routes by:
+ // - `agencyConfig.boundDeviceId`: the per-user override written by the
+ // `local` code path in `useSelectExecutionTarget`;
+ // - `requestedDeviceId`: the desktop's own id sent with a `local` run
+ // (or the topic's pinned device, folded in by `turnSetup`). Without
+ // it, an agent whose stored target is `local` but which has no
+ // override is told the user's online desktop is offline. A `fixed`
+ // selection policy ignores it, as the resolver does.
+ const isFixedSelection = agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
+ const personalCandidateIds = [
+ ...new Set(
+ [
+ agentConfig.agencyConfig?.boundDeviceId,
+ isFixedSelection ? undefined : requestedDeviceId,
+ ].filter((id): id is string => !!id && !devices.some((d) => d.deviceId === id)),
+ ),
+ ];
+ if (deps.workspaceId && personalCandidateIds.length > 0) {
+ const personalPool = await getScopedOnlineDevices(deps.db, deps.userId).catch(
+ () => [] as DeviceAttachment[],
+ );
+ const personalMatches = personalPool.filter(
+ (d) => d.online && personalCandidateIds.includes(d.deviceId),
+ );
+ if (personalMatches.length > 0) {
+ devices = [...devices, ...personalMatches];
+ log(
+ 'execAgent: augmented device pool with caller personal device(s) %o',
+ personalMatches.map((d) => d.deviceId),
+ );
+ }
+ }
+ log('execAgent: found %d online device(s)', devices.length);
+ return devices;
+ } catch (error) {
+ log('execAgent: failed to query device list: %O', error);
+ return [];
+ }
+};
+
+const readAttachedFileTypes = async (
+ deps: ToolDiscoveryDeps,
+ ctx: ToolReadsContext,
+): Promise<string[]> => {
+ const { attachedFileIds, shareGate } = ctx;
+ if (!attachedFileIds || attachedFileIds.length === 0) return [];
+ const fileModel = new FileModel(deps.db, deps.userId, deps.workspaceId);
+ const uniqueFileIds = Array.from(new Set(attachedFileIds));
+ const fileRecords = await traceDiscoveryStage('attached_files', () =>
+ fileModel.findByIds(
+ uniqueFileIds,
+ shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
+ ),
+ );
+ return fileRecords.map((file) => file.fileType || '');
+};
+
+/**
+ * Whether this turn can send any file as a truncated preview (see `previewLongFileContent`):
+ * an enabled agent file over the inline limit, or a parsed attachment of this turn or topic
+ * longer than a preview. Attachments under the inline limit are still previewed once the
+ * request's attachment budget is spent (`planAttachmentPreviews`), which is only known per step,
+ * so any attachment a preview would shorten enables the tool.
+ * Enables the attachments tool in the modes whose rules include it (agent / chat). The preview
+ * only names `readAttachment` when the final tool set carries it (see `MessagesEngine`), so
+ * custom / exclusive tool turns and share visitors fall back to a plain preview.
+ */
+const readHasOversizedFiles = async (
+ deps: ToolDiscoveryDeps,
+ ctx: ToolReadsContext,
+): Promise<boolean> => {
+ const { agentConfig, attachedFileIds, topicId } = ctx;
+ const hasOversizedAgentFile = agentConfig.files?.some(
+ (file: { content?: string | null; enabled?: boolean | null; originalCharCount?: number }) =>
+ file.enabled === true &&
+ isOversizedFileContent(file.content?.length ?? 0, file.originalCharCount),
+ );
+ if (hasOversizedAgentFile) return true;
+ if (!topicId && !attachedFileIds?.length) return false;
+
+ return traceDiscoveryStage('oversized_files', () =>
+ new DocumentModel(deps.db, deps.userId, deps.workspaceId).hasFileDocumentsOverChars({
+ fileIds: attachedFileIds,
+ minChars: FILE_PREVIEW_CHARS,
+ topicId,
+ }),
+ );
+};
+
+/**
+ * Every other read this send needs, started together. They hit different
+ * backends β€” Postgres rows, the Market's live skill discovery, the device
+ * gateway β€” and none of them feeds another, so the user waits for the slowest
+ * one instead of the sum of all of them. Each keeps the degrade-to-empty
+ * behavior it had when it ran in sequence; only the plugin list still fails
+ * the run, because a run with no plugins is not the same run.
+ */
+export const startToolReads = (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) => ({
+ // The fallbacks sit OUTSIDE `traceDiscoveryStage` on purpose: the wrapper
+ // only marks a span errored when its callback throws, so absorbing the
+ // failure inside it would report a healthy stage for a failed read.
+ agentDocuments: started(
+ traceDiscoveryStage('agent_documents', () =>
+ deps.agentDocumentsService.hasDocuments(ctx.resolvedAgentId),
+ ).catch(() => false), // non-critical
+ ),
+ attachedFileTypes: started(readAttachedFileTypes(deps, ctx)),
+ oversizedFiles: started(readHasOversizedFiles(deps, ctx).catch(() => false)), // non-critical
+ composioManifests: started(
+ traceDiscoveryStage('composio', () =>
+ deps.composioService.getComposioManifests(ctx.resolvedAgentId),
+ ).catch((error) => {
+ log('execAgent: failed to fetch composio manifests: %O', error);
+ return [] as LobeToolManifest[];
+ }),
+ ),
+ connectors: started(readConnectors(deps, ctx)),
+ devicePool: started(readDevicePool(deps, ctx)),
+ installedPlugins: started(
+ traceDiscoveryStage('installed_plugins', () => deps.pluginModel.query()),
+ ),
+ lobehubSkillManifests: started(readLobehubSkillManifests(deps)),
+});
+
+export type ToolReads = ReturnType<typeof startToolReads>;
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
new file mode 100644
index 00000000000..79bd2e4d140
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
@@ -0,0 +1,113 @@
+import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
+import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
+import type { AgentGroupConfig } from '@lobechat/context-engine';
+import debug from 'debug';
+import type { ModelAbilities } from 'model-bank';
+
+import { ChatGroupModel } from '@/database/models/chatGroup';
+
+import {
+ buildBotConversationGroupContext,
+ buildGroupAgentContext,
+} from '../../helpers/groupContext';
+import {
+ getMediaAvailabilityFromFileTypes,
+ getMediaAvailabilityFromMessages,
+ isMultimodalUnderstandingConfigured,
+} from '../../helpers/mediaAvailability';
+import type { ExecRunContext } from '../../types';
+import type { ToolDiscoveryDeps, ToolDiscoveryInput } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Turn-scoped builtin tools to append to the candidate plugin ids: the IM
+ * message tool for bot conversations, and multimodal understanding when this
+ * turn or its history carries media the model cannot read itself.
+ */
+export const resolveTurnScopedPluginIds = async (params: {
+ attachedFileTypes: string[];
+ externalFileTypes?: string[];
+ isBotConversation: boolean;
+ loadHistoryMessages: ToolDiscoveryInput['loadHistoryMessages'];
+ modelMediaCapabilities: Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;
+}): Promise<string[]> => {
+ const { isBotConversation, loadHistoryMessages, modelMediaCapabilities } = params;
+ const externalFileTypes = params.externalFileTypes ?? [];
+ const inputFileTypes = [...externalFileTypes, ...params.attachedFileTypes];
+ const inputMediaAvailability = getMediaAvailabilityFromFileTypes(inputFileTypes);
+ let historyMediaAvailability = { hasAudios: false, hasImages: false, hasVideos: false };
+ const multimodalUnderstandingConfigured = isMultimodalUnderstandingConfigured();
+
+ if (
+ multimodalUnderstandingConfigured &&
+ ((!modelMediaCapabilities?.audio && !inputMediaAvailability.hasAudios) ||
+ (!modelMediaCapabilities?.vision && !inputMediaAvailability.hasImages) ||
+ (!modelMediaCapabilities?.video && !inputMediaAvailability.hasVideos))
+ ) {
+ historyMediaAvailability = getMediaAvailabilityFromMessages(await loadHistoryMessages());
+ }
+
+ const needsAudioUnderstanding =
+ (inputMediaAvailability.hasAudios || historyMediaAvailability.hasAudios) &&
+ !modelMediaCapabilities?.audio;
+ const needsImageUnderstanding =
+ (inputMediaAvailability.hasImages || historyMediaAvailability.hasImages) &&
+ !modelMediaCapabilities?.vision;
+ const needsVideoUnderstanding =
+ (inputMediaAvailability.hasVideos || historyMediaAvailability.hasVideos) &&
+ !modelMediaCapabilities?.video;
+ const shouldEnableMultimodalUnderstanding =
+ multimodalUnderstandingConfigured &&
+ (needsAudioUnderstanding || needsImageUnderstanding || needsVideoUnderstanding);
+
+ return [
+ ...(isBotConversation ? [MessageToolIdentifier] : []),
+ ...(shouldEnableMultimodalUnderstanding ? [LobeAgentManifest.identifier] : []),
+ ];
+};
+
+/**
+ * Resolve the operation's group context ONCE and snapshot it into op metadata
+ * β€” the per-step context engine reads it back without a DB lookup, mirroring
+ * agentConfig/botContext. The same roster fetch also authorizes the
+ * group-orchestration toolset.
+ */
+export const resolveOperationGroup = async (
+ deps: ToolDiscoveryDeps,
+ ctx: Pick<ExecRunContext, 'agentConfig' | 'appContext' | 'resolvedAgentId'>,
+ botContext: ToolDiscoveryInput['botContext'],
+): Promise<{ isGroupSupervisor: boolean; operationAgentGroup?: AgentGroupConfig }> => {
+ const { agentConfig, appContext, resolvedAgentId } = ctx;
+ let isGroupSupervisor = false;
+ let operationAgentGroup: AgentGroupConfig | undefined;
+ if (appContext?.groupId) {
+ const chatGroupModel = new ChatGroupModel(deps.db, deps.userId, deps.workspaceId);
+ const [group, roster] = await Promise.all([
+ chatGroupModel.findById(appContext.groupId),
+ chatGroupModel.getGroupAgentsWithMeta(appContext.groupId),
+ ]);
+
+ // `appContext.orchestrationRole` is client-supplied (execGroupAgent stamps
+ // it for whatever agentId the caller passed), so it must NOT alone
+ // authorize the group-orchestration toolset β€” otherwise any run marked
+ // `{ orchestrationRole: 'supervisor', groupId }` could dispatch members.
+ // Verify against the persisted, ownership-scoped membership instead.
+ if (appContext.orchestrationRole === 'supervisor') {
+ isGroupSupervisor = roster.some(
+ (member) => member.agentId === resolvedAgentId && member.role === 'supervisor',
+ );
+ if (!isGroupSupervisor)
+ log(
+ 'execAgent: orchestrationRole=supervisor but agent %s is not the supervisor of group %s β€” denying group tools',
+ resolvedAgentId,
+ appContext.groupId,
+ );
+ }
+
+ operationAgentGroup = buildGroupAgentContext(resolvedAgentId, group, roster);
+ } else if (botContext) {
+ operationAgentGroup = buildBotConversationGroupContext(resolvedAgentId, agentConfig);
+ }
+ return { isGroupSupervisor, operationAgentGroup };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
new file mode 100644
index 00000000000..973cf14aded
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
@@ -0,0 +1,117 @@
+import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
+import type {
+ AgentGroupConfig,
+ LobeToolManifest,
+ ToolExecutor,
+ ToolsEngine,
+ ToolSource,
+} from '@lobechat/context-engine';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type {
+ ChatTopicBotContext,
+ FrozenCredentialFacts,
+ FrozenModelFacts,
+ RequestTrigger,
+} from '@lobechat/types';
+import type { ModelAbilities } from 'model-bank';
+
+import type { loadModels } from '@/business/client/model-bank/loadModels';
+import type { ConnectorModel } from '@/database/models/connector';
+import type { ConnectorToolModel } from '@/database/models/connectorTool';
+import type { MessageModel } from '@/database/models/message';
+import type { PluginModel } from '@/database/models/plugin';
+import type { ExecutionPlan } from '@/helpers/executionTarget';
+import type { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
+import type { AgentDocumentsService } from '@/server/services/agentDocuments';
+import type { ComposioService } from '@/server/services/composio';
+import type { MarketService } from '@/server/services/market';
+
+import type { resolveServerSearchDecision } from '../../searchDecision';
+import type { InternalExecAgentParams } from '../../types';
+
+export interface ToolDiscoveryDeps {
+ agentDocumentsService: AgentDocumentsService;
+ composioService: ComposioService;
+ connectorModel: ConnectorModel;
+ connectorToolModel: ConnectorToolModel;
+ db: LobeChatDatabase;
+ getMarketService: () => Promise<MarketService>;
+ messageModel: MessageModel;
+ pluginModel: PluginModel;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface ToolDiscoveryInput {
+ additionalPluginIds?: string[];
+ agentSlug?: string | null;
+ attachedFileIds?: string[];
+ botContext?: ChatTopicBotContext;
+ /** Tri-state disabled plugin identifiers captured before pinned-id collapse. */
+ disabledPluginIds: string[];
+ disableLocalSystem?: boolean;
+ disableSelfFeedbackIntentTool?: boolean;
+ disableTools?: boolean;
+ discordContext?: any;
+ exclusivePluginIds?: string[];
+ /**
+ * Mime types of the raw bot/IM uploads. The stage only ever looked at the
+ * mime type, and keeping the request JSON-safe is what lets a deferred init
+ * carry it on the operation state.
+ */
+ externalFileTypes?: string[];
+ functionTools?: InternalExecAgentParams['functionTools'];
+ globalMemoryEnabled: boolean;
+ hasMentionedAgents: boolean;
+ isFixedDeviceTarget: boolean;
+ /** Shared lazy history loader β€” also consumed by the caller after discovery. */
+ loadHistoryMessages: () => Promise<any[]>;
+ localDeviceId?: string;
+ requestedDeviceId?: string;
+ requestTrigger?: RequestTrigger;
+ selectedToolIds?: string[];
+ throwIfExecutionAborted: (stage: string) => Promise<void>;
+ topicBoundDeviceId?: string | null;
+}
+
+export interface ToolDiscoveryResult {
+ activeDeviceId?: string;
+ activeDeviceScope?: 'personal' | 'workspace';
+ agentPlugins: string[];
+ builtinModels: Awaited<ReturnType<typeof loadModels>>;
+ composioManifests: LobeToolManifest[];
+ connectorManifests: ReturnType<typeof buildConnectorManifests>;
+ /**
+ * Tells the model whose connected account each borrowed tool runs on. Run
+ * context: it travels on the operation and the context engine injects it.
+ */
+ connectorOwnershipNote?: string;
+ /**
+ * Credentials listed once for the whole operation; see
+ * {@link FrozenCredentialFacts}. Absent when the run cannot inject
+ * credentials.
+ *
+ * Deliberately still a promise: awaiting it here would put a Market round
+ * trip between tool discovery and operation preparation, on the path to the
+ * first token. The caller awaits it once the preparation it overlaps with is
+ * done. Never rejects β€” a failed read resolves to `undefined` and the run
+ * reads the list live, as it did before the snapshot existed.
+ */
+ credentialFactsPromise?: Promise<FrozenCredentialFacts | undefined>;
+ executionPlan?: ExecutionPlan;
+ hasAgentDocuments: boolean;
+ hasEnabledKnowledgeBases: boolean;
+ lobehubSkillManifests: LobeToolManifest[];
+ /** Model facts read once for the whole operation; see {@link FrozenModelFacts}. */
+ modelFacts: FrozenModelFacts;
+ modelMediaCapabilities: Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;
+ onlineDevices: DeviceAttachment[];
+ operationAgentGroup?: AgentGroupConfig;
+ searchDecision: ReturnType<typeof resolveServerSearchDecision>;
+ toolExecutorMap: Record<string, ToolExecutor>;
+ toolManifestMap: Record<string, any>;
+ tools?: any[];
+ toolsEngine?: ToolsEngine;
+ toolSourceMap: Record<string, ToolSource>;
+ toolsResult: { enabledToolIds: string[]; tools?: any[] | undefined };
+}