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.

⚑️ perf(agent): run tool discovery's independent reads together (#19755)

Arvin Xuedc0c44920b9
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
new file mode 100644
index 00000000000..e58f07d2868
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
@@ -0,0 +1,332 @@
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../../index';
+
+// The share-gate filter now runs at the top of `discoverTools`, before
+// connector resolution / stale-tool refresh β€” so an ungranted HTTP connector
+// pinned on the creator's agent must never reach either callsite for a
+// visitor turn. These spies live at hoist time so the `vi.mock` factories
+// below (which run before the test body) can wire them into stubbed models.
+const {
+ mockCreateOperation,
+ mockGetAgentConfig,
+ mockGetUserSettings,
+ mockMessageCreate,
+ discoverySpan,
+ mockScheduleStaleConnectorToolsRefresh,
+ reads,
+} = vi.hoisted(() => {
+ /**
+ * Every independent discovery read waits on the same barrier, which only
+ * opens once all of them have started. Sequential reads therefore deadlock
+ * (the first one waits for a barrier the others can never reach) and this
+ * test times out; overlapping reads open it and the run completes.
+ *
+ * The attached-file read is deliberately not part of it: `turnSetup` resolves
+ * attachments before discovery begins, so it cannot share this barrier.
+ */
+ const STAGE_COUNT = 6;
+ const started: string[] = [];
+ let openBarrier: () => void = () => {};
+ let barrier = new Promise<void>((resolve) => {
+ openBarrier = resolve;
+ });
+
+ const gated = <T>(stage: string, value: T) =>
+ vi.fn(async () => {
+ started.push(stage);
+ if (started.length >= STAGE_COUNT) openBarrier();
+ await barrier;
+ return value;
+ });
+
+ const reads = {
+ agentDocuments: gated('agentDocuments', false),
+ composio: gated('composio', [] as unknown[]),
+ connectors: gated('connectors', [] as unknown[]),
+ devices: gated('devices', [] as unknown[]),
+ plugins: gated('plugins', [] as unknown[]),
+ skills: gated('skills', [] as unknown[]),
+ reset: () => {
+ started.length = 0;
+ barrier = new Promise<void>((resolve) => {
+ openBarrier = resolve;
+ });
+ },
+ started,
+ };
+
+ return {
+ discoverySpan: { end: vi.fn(), setAttribute: vi.fn(), setStatus: vi.fn() },
+ mockCreateOperation: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockGetUserSettings: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockScheduleStaleConnectorToolsRefresh: vi.fn(),
+ reads,
+ };
+});
+
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn().mockImplementation(function () {
+ return {
+ findByIds: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@lobechat/observability-otel/modules/agent-runtime', () => ({
+ tracer: {
+ startActiveSpan: (_name: string, fn: (span: unknown) => unknown) => fn(discoverySpan),
+ },
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ create: mockMessageCreate,
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue({}),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn(),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: mockGetAgentConfig,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return {
+ query: reads.plugins,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi.fn().mockImplementation(function () {
+ return {
+ queryByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveByIdentifiers: reads.connectors,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn().mockImplementation(function () {
+ return {
+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ queryByConnectorIds: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ findById: vi.fn().mockResolvedValue(null),
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ updateMetadata: vi.fn().mockResolvedValue(undefined),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn().mockImplementation(function () {
+ return {
+ getUserPreference: vi.fn().mockResolvedValue({}),
+ getUserSettings: () => mockGetUserSettings(),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: mockCreateOperation,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(function () {
+ return {
+ getLobehubSkillManifests: reads.skills,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(function () {
+ return {
+ getComposioManifests: reads.composio,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ uploadFromUrl: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ isConfigured: true,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
+ getScopedOnlineDevices: reads.devices,
+}));
+
+vi.mock('@/server/services/agentDocuments', () => ({
+ AgentDocumentsService: vi.fn().mockImplementation(function () {
+ return {
+ hasDocuments: reads.agentDocuments,
+ };
+ }),
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+vi.mock('@/server/services/connector/refresh', () => ({
+ buildLastSyncedAtMap: vi.fn().mockReturnValue(new Map()),
+ scheduleStaleConnectorToolsRefresh: mockScheduleStaleConnectorToolsRefresh,
+}));
+
+// The share path's atomic cap reservations open real DB transactions β€” stub
+// them so this test can drive execAgent with a bare mock db.
+vi.mock('../../shareVisitorAbuseGuards', () => ({
+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ reserveShareVisitorTurn: vi.fn().mockResolvedValue({ id: 'msg-1' }),
+}));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { functionCall: true, video: false, vision: true },
+ id: 'gpt-4',
+ providerId: 'openai',
+ },
+ ],
+ };
+});
+
+describe('discoverTools - independent reads run together', () => {
+ let service: AiAgentService;
+ const mockDb = {} as any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ reads.reset();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: ['some-plugin'],
+ provider: 'openai',
+ systemRole: '',
+ });
+ service = new AiAgentService(mockDb, 'user-1');
+ });
+
+ // This is the whole point of the wave: the send waits for the slowest read,
+ // not for the sum. Each read blocks on a barrier that only opens once all of
+ // them have started, so a sequential discovery cannot finish at all β€” the
+ // first read would wait forever for stages that never start.
+ it('starts every independent read before any of them resolves', async () => {
+ const result = await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Hello',
+ });
+
+ expect(result.success).toBe(true);
+ expect([...new Set(reads.started)].sort()).toEqual([
+ 'agentDocuments',
+ 'composio',
+ 'connectors',
+ 'devices',
+ 'plugins',
+ 'skills',
+ ]);
+ }, 15_000);
+
+ // A stage that degrades to an empty result still has to report the failure on
+ // its span: absorbing it inside `traceDiscoveryStage` would leave the stage
+ // looking healthy, and these spans are the only per-stage breakdown there is.
+ it('reports a failed read on its span while the run still starts', async () => {
+ reads.composio.mockImplementationOnce(async () => {
+ reads.started.push('composio');
+ throw new Error('composio down');
+ });
+
+ const result = await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+
+ expect(result.success).toBe(true);
+ expect(discoverySpan.setStatus).toHaveBeenCalledWith({
+ code: SpanStatusCode.ERROR,
+ message: 'composio down',
+ });
+ }, 15_000);
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index c8570a6ab2f..2a312a67bb3 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -102,6 +102,18 @@ 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;
@@ -343,24 +355,187 @@ export const discoverTools = async (
// Model metadata is needed both for tool support checks and agent-management context.
const builtinModels = await loadModels();
- const [modelMetadataResult, providerMetadataResult] = await 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',
+ // 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',
);
- return results;
- },
- );
+
+ // 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))
+ : [];
+
+ return { connectorGateKeeper, connectors, connectorsMcp, connectorTools };
+ });
+ }
+
+ 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 agent whose caller pinned this desktop's personal
+ // deviceId via `users.preference.agentDeviceOverrides` (
+ // the `local` code path in `useSelectExecutionTarget`) needs its
+ // personal device to be visible in this run's device pool β€” otherwise
+ // `resolveExecutionPlan` treats the bound device as 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.
+ if (deps.workspaceId && agentConfig.agencyConfig?.boundDeviceId) {
+ const boundId = agentConfig.agencyConfig.boundDeviceId;
+ if (!devices.some((d) => d.deviceId === boundId)) {
+ const personalPool = await getScopedOnlineDevices(deps.db, deps.userId).catch(
+ () => [] as DeviceAttachment[],
+ );
+ const personalMatch = personalPool.find((d) => d.deviceId === boundId && d.online);
+ if (personalMatch) {
+ devices = [...devices, personalMatch];
+ log(
+ 'execAgent: augmented device pool with caller personal device %s (per-user override)',
+ boundId,
+ );
+ }
+ }
+ }
+ 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 || '');
+ }
+
+ // 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()),
+ 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);
}
@@ -423,7 +598,7 @@ export const discoverTools = async (
providerSearchMode: activeProviderMetadata?.settings?.searchMode,
});
- if (disableTools) {
+ if (!toolReads) {
log('execAgent: tools disabled by disableTools flag, skipping all tool discovery');
} else {
// 5a. Get installed plugins from database. Disabled identifiers are
@@ -432,7 +607,7 @@ export const discoverTools = async (
// 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 deps.pluginModel.query()).filter(
+ const installedPlugins = (await toolReads.installedPlugins).filter(
(p) => !disabledPluginIdSet.has(p.identifier),
);
log(
@@ -442,22 +617,8 @@ export const discoverTools = async (
);
// 5a-1. Resolve connectors β€” connector identifier takes priority over plugin.
- // Credentials (OAuth tokens) are encrypted at rest, so decrypt them with a
- // gatekeeper; otherwise buildConnectorManifests gets no auth and tool calls 401.
- let connectorGateKeeper: KeyVaultsGateKeeper | undefined;
- try {
- connectorGateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
- } catch (err) {
- log('execAgent: failed to init gatekeeper for connector credentials: %O', err);
- }
- const connectors =
- agentPlugins.length > 0
- ? await deps.connectorModel.resolveByIdentifiers(
- agentPlugins,
- resolvedAgentId,
- connectorGateKeeper,
- )
- : [];
+ const { connectorGateKeeper, connectors, connectorsMcp, connectorTools } =
+ 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
@@ -487,22 +648,6 @@ export const discoverTools = async (
log('execAgent: failed to build tool credential ownership note: %O', err);
}
- // 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))
- : [];
-
connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);
// Auto-refresh stale connector tool lists in the background so upstream MCP
@@ -547,36 +692,10 @@ export const discoverTools = async (
return info?.abilities?.functionCall ?? true;
};
- // 5c. Fetch LobeHub Skills manifests
- try {
- const marketService = await deps.getMarketService();
- lobehubSkillManifests = 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);
- }
+ // 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);
-
- // 5d. Fetch Composio tool manifests from database
- try {
- composioManifests = await traceDiscoveryStage('composio', () =>
- deps.composioService.getComposioManifests(resolvedAgentId),
- );
- } catch (error) {
- log('execAgent: failed to fetch composio manifests: %O', error);
- }
+ composioManifests = await toolReads.composioManifests;
log('execAgent: got %d composio manifests', composioManifests.length);
// 5d-1. Patch Lobehub/Composio manifests AND community-MCP plugin manifests
@@ -652,64 +771,15 @@ export const discoverTools = async (
agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??
false;
- try {
- hasAgentDocuments = await deps.agentDocumentsService.hasDocuments(resolvedAgentId);
- } catch {
- // Agent documents check is non-critical
- }
+ hasAgentDocuments = await toolReads.agentDocuments;
log('execAgent: isBotConversation=%s', isBotConversation);
- // Build device context for ToolsEngine enableChecker
+ // Device context for the ToolsEngine enableChecker, read in the wave above.
const gatewayConfigured = deviceGateway.isConfigured;
const agentBoundDeviceId = agentConfig.agencyConfig?.boundDeviceId;
const boundDeviceId = topicBoundDeviceId || agentBoundDeviceId;
- if (gatewayConfigured) {
- 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.
- onlineDevices = (
- await traceDiscoveryStage('online_devices', () =>
- getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId),
- )
- ).filter((d) => d.online);
- // A workspace agent whose caller pinned this desktop's personal
- // deviceId via `users.preference.agentDeviceOverrides` (
- // the `local` code path in `useSelectExecutionTarget`) needs its
- // personal device to be visible in this run's device pool β€” otherwise
- // `resolveExecutionPlan` treats the bound device as 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.
- if (deps.workspaceId && agentConfig.agencyConfig?.boundDeviceId) {
- const boundId = agentConfig.agencyConfig.boundDeviceId;
- const alreadyIncluded = onlineDevices.some((d) => d.deviceId === boundId);
- if (!alreadyIncluded) {
- const personalPool = await getScopedOnlineDevices(deps.db, deps.userId).catch(
- () => [] as DeviceAttachment[],
- );
- const personalMatch = personalPool.find((d) => d.deviceId === boundId && d.online);
- if (personalMatch) {
- onlineDevices = [...onlineDevices, personalMatch];
- log(
- 'execAgent: augmented device pool with caller personal device %s (per-user override)',
- boundId,
- );
- }
- }
- }
- log('execAgent: found %d online device(s)', onlineDevices.length);
- } catch (error) {
- log('execAgent: failed to query device list: %O', error);
- }
- }
+ onlineDevices = await toolReads.devicePool;
const deviceOnline = onlineDevices.length > 0;
const toolsContext: ServerAgentToolsContext = {
@@ -723,17 +793,7 @@ export const discoverTools = async (
builtinModels.find((item) => item.id === model && item.providerId === provider)?.abilities ??
builtinModels.find((item) => item.id === model)?.abilities;
const externalFileTypes = files?.map((file) => file.mimeType ?? '') ?? [];
- let attachedFileTypes: string[] = [];
- if (attachedFileIds && attachedFileIds.length > 0) {
- const fileModel = new FileModel(deps.db, deps.userId, deps.workspaceId);
- const uniqueFileIds = Array.from(new Set(attachedFileIds));
- const fileRecords = await fileModel.findByIds(
- uniqueFileIds,
- shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
- );
- attachedFileTypes = fileRecords.map((file) => file.fileType || '');
- }
- const inputFileTypes = [...externalFileTypes, ...attachedFileTypes];
+ const inputFileTypes = [...externalFileTypes, ...(await toolReads.attachedFileTypes)];
const inputMediaAvailability = getMediaAvailabilityFromFileTypes(inputFileTypes);
let historyMediaAvailability = { hasAudios: false, hasImages: false, hasVideos: false };
const multimodalUnderstandingConfigured = isMultimodalUnderstandingConfigured();