π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β‘οΈ perf(agent): fetch LobeHub skill tools concurrently with a per-request timeout (#19533)
Arvin Xu0fff23f8b535
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/discoveryTracing.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/discoveryTracing.test.tsnew file mode 100644index 00000000000..270d07b3bb6--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/discoveryTracing.test.ts@@ -0,0 +1,70 @@+// @vitest-environment node+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { markDegradedStage, traceDiscoveryStage } from '../discoveryTracing';++const { span, startActiveSpan } = vi.hoisted(() => {+ const span = { end: vi.fn(), setAttribute: vi.fn(), setStatus: vi.fn() };+ return {+ span,+ startActiveSpan: vi.fn((_name: string, fn: (span: unknown) => unknown) => fn(span)),+ };+});++vi.mock('@lobechat/observability-otel/modules/agent-runtime', () => ({+ tracer: { startActiveSpan },+}));++describe('traceDiscoveryStage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('names the span after the stage and ends it on success', async () => {+ await expect(traceDiscoveryStage('composio', async () => 'ok')).resolves.toBe('ok');++ expect(startActiveSpan).toHaveBeenCalledWith('tool_discovery composio', expect.any(Function));+ expect(span.setStatus).not.toHaveBeenCalled();+ expect(span.end).toHaveBeenCalledTimes(1);+ });++ it('marks the span as errored, rethrows, and still ends it', async () => {+ const error = new Error('gateway down');++ await expect(+ traceDiscoveryStage('online_devices', async () => {+ throw error;+ }),+ ).rejects.toBe(error);++ expect(span.setStatus).toHaveBeenCalledWith({+ code: SpanStatusCode.ERROR,+ message: 'gateway down',+ });+ expect(span.end).toHaveBeenCalledTimes(1);+ });+});++describe('markDegradedStage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('marks a stage that absorbed failures as errored', () => {+ markDegradedStage(span as any, 2, 'skill discovery requests');++ expect(span.setAttribute).toHaveBeenCalledWith('lobehub.tool_discovery.failure_count', 2);+ expect(span.setStatus).toHaveBeenCalledWith({+ code: SpanStatusCode.ERROR,+ message: '2 skill discovery requests failed',+ });+ });++ it('leaves a clean stage unmarked', () => {+ markDegradedStage(span as any, 0, 'metadata lookups');++ expect(span.setAttribute).toHaveBeenCalledWith('lobehub.tool_discovery.failure_count', 0);+ expect(span.setStatus).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/discoveryTracing.ts b/apps/server/src/services/aiAgent/pipeline/discoveryTracing.tsnew file mode 100644index 00000000000..20df6b2e236--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/discoveryTracing.ts@@ -0,0 +1,35 @@+import type { Span } from '@lobechat/observability-otel/api';+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer as agentRuntimeTracer } from '@lobechat/observability-otel/modules/agent-runtime';++/**+ * Wrap an IO-bound discovery stage in a span. Discovery runs on the send path+ * before the operation exists, so these spans are the only breakdown of how+ * long a user waits between "message saved" and "operation started".+ */+export const traceDiscoveryStage = <T>(stage: string, fn: (span: Span) => Promise<T>): Promise<T> =>+ agentRuntimeTracer.startActiveSpan(`tool_discovery ${stage}`, async (span) => {+ try {+ return await fn(span);+ } catch (error) {+ span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message });+ throw error;+ } finally {+ span.end();+ }+ });++/**+ * Surface failures a stage absorbed instead of throwing (settled promises,+ * degrade-to-empty services). Without this the span looks healthy and a+ * timeout is indistinguishable from "nothing to discover".+ */+export const markDegradedStage = (span: Span, failureCount: number, failedWhat: string) => {+ span.setAttribute('lobehub.tool_discovery.failure_count', failureCount);+ if (failureCount > 0) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: `${failureCount} ${failedWhat} failed`,+ });+ }+};diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 5d216519592..fecbd02efb9 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -26,7 +26,7 @@ import { TRPCError } from '@trpc/server';import debug from 'debug';import type { ModelAbilities } from 'model-bank';-import type { loadModels } from '@/business/client/model-bank/loadModels';+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';@@ -85,6 +85,7 @@ import {import { resolveServerSearchDecision } from '../searchDecision';import { filterPluginsByShareGate, shareGateGrantsCloudSandbox } from '../shareGate';import type { ExecRunContext, InternalExecAgentParams } from '../types';+import { markDegradedStage, traceDiscoveryStage } from './discoveryTracing';const log = debug('lobe-server:ai-agent-service');@@ -276,12 +277,25 @@ export const discoverTools = async (}// Model metadata is needed both for tool support checks and agent-management context.- const { loadModels } = await import('@/business/client/model-bank/loadModels');const builtinModels = await loadModels();- const [modelMetadataResult, providerMetadataResult] = await Promise.allSettled([- new AiModelModel(deps.db, deps.userId, deps.workspaceId).findByIdAndProvider(model, provider),- new AiProviderModel(deps.db, deps.userId, deps.workspaceId).findById(provider),- ]);+ 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',+ );+ return results;+ },+ );if (modelMetadataResult.status === 'rejected') {log('execAgent: failed to load active model search metadata: %O', modelMetadataResult.reason);}@@ -442,7 +456,20 @@ export const discoverTools = async (// 5c. Fetch LobeHub Skills manifeststry {const marketService = await deps.getMarketService();- lobehubSkillManifests = await marketService.getLobehubSkillManifests();+ 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);}@@ -450,7 +477,9 @@ export const discoverTools = async (// 5d. Fetch Composio tool manifests from databasetry {- composioManifests = await deps.composioService.getComposioManifests(resolvedAgentId);+ composioManifests = await traceDiscoveryStage('composio', () =>+ deps.composioService.getComposioManifests(resolvedAgentId),+ );} catch (error) {log('execAgent: failed to fetch composio manifests: %O', error);}@@ -551,7 +580,9 @@ export const discoverTools = async (// downstream `onlineDeviceIds` / `deviceOnline` treat this list as the// online set.onlineDevices = (- await getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId)+ 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` (@@ -773,16 +804,18 @@ export const discoverTools = async (// 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 supportedDeviceTools =- activeDeviceId && canUseDevice && !disableLocalSystem- ? (- await deviceGateway.queryDeviceSystemInfo(+ const systemInfoDeviceId = canUseDevice && !disableLocalSystem ? activeDeviceId : undefined;+ const supportedDeviceTools = systemInfoDeviceId+ ? (+ await traceDiscoveryStage('device_system_info', () =>+ deviceGateway.queryDeviceSystemInfo(deps.userId,- activeDeviceId,+ systemInfoDeviceId,activeDeviceScope === 'workspace' ? deps.workspaceId : undefined,- )- )?.supportedTools- : undefined;+ ),+ )+ )?.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 DBdiff --git a/apps/server/src/services/market/index.test.ts b/apps/server/src/services/market/index.test.tsindex 2ccaf38b391..6767cb00a40 100644--- a/apps/server/src/services/market/index.test.ts+++ b/apps/server/src/services/market/index.test.ts@@ -5,7 +5,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { generateTrustedClientToken, getTrustedClientTokenForSession } from '@/libs/trusted-client';-import { extractAccessToken, LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS, MarketService } from './index';+import {+ extractAccessToken,+ LOBEHUB_SKILL_DISCOVERY_CONCURRENCY,+ LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS,+ MarketService,+} from './index';// Mock dependencies before importing the module under testvi.mock('@lobehub/market-sdk', () => {@@ -673,7 +678,9 @@ describe('MarketService', () => {const manifests = await service.getLobehubSkillManifests();- expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith('posthog');+ expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith('posthog', {+ signal: expect.any(AbortSignal),+ });expect((service as any).market.skills.listTools).not.toHaveBeenCalled();expect(manifests).toHaveLength(1);expect(manifests[0]).toMatchObject({@@ -765,6 +772,126 @@ describe('MarketService', () => {expect(manifests).toHaveLength(1);expect(manifests[0].identifier).toBe('working');});++ it('should fetch provider tools concurrently and keep connection order', async () => {+ const service = new MarketService();+ (service as any).market.connect.listConnections = vi.fn().mockResolvedValue({+ connections: [+ { providerId: 'linear', providerName: 'Linear' },+ { providerId: 'github', providerName: 'GitHub' },+ ],+ });+ const pending = new Map<string, (value: unknown) => void>();+ (service as any).market.skills.listTools = vi.fn().mockImplementation(+ (id: string) =>+ new Promise((resolve) => {+ pending.set(id, resolve);+ }),+ );++ const result = service.getLobehubSkillManifests();++ // A serial loop would only have issued the first request here.+ await vi.waitFor(() =>+ expect((service as any).market.skills.listTools).toHaveBeenCalledTimes(2),+ );++ pending.get('github')!({ tools: [{ description: 'Repo', inputSchema: {}, name: 'repo' }] });+ pending.get('linear')!({ tools: [{ description: 'Issue', inputSchema: {}, name: 'issue' }] });++ const manifests = await result;+ expect(manifests.map((manifest) => manifest.identifier)).toEqual(['linear', 'github']);+ });++ it('should cap how many provider tool lists are fetched at once', async () => {+ const service = new MarketService();+ const connectionCount = LOBEHUB_SKILL_DISCOVERY_CONCURRENCY + 3;+ (service as any).market.connect.listConnections = vi.fn().mockResolvedValue({+ connections: Array.from({ length: connectionCount }, (_, index) => ({+ providerId: `provider-${index}`,+ })),+ });+ let inFlight = 0;+ let maxInFlight = 0;+ (service as any).market.skills.listTools = vi.fn().mockImplementation(async () => {+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 5));+ inFlight -= 1;+ return { tools: [{ description: 'Do', inputSchema: {}, name: 'do' }] };+ });++ const manifests = await service.getLobehubSkillManifests();++ expect(manifests).toHaveLength(connectionCount);+ expect(maxInFlight).toBe(LOBEHUB_SKILL_DISCOVERY_CONCURRENCY);+ });++ it('should bound each provider request and fall back to static tools on live timeout', async () => {+ const service = new MarketService();+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout');+ const timeoutError = new Error('The operation was aborted due to timeout');+ timeoutError.name = 'TimeoutError';+ (service as any).market.connect.listConnections = vi.fn().mockResolvedValue({+ connections: [{ providerId: 'posthog', providerName: 'Workspace' }],+ });+ (service as any).market.skills.listLiveTools = vi.fn().mockRejectedValue(timeoutError);+ (service as any).market.skills.listTools = vi.fn().mockResolvedValue({+ tools: [{ description: 'Query', inputSchema: {}, name: 'query' }],+ });++ try {+ const manifests = await service.getLobehubSkillManifests();++ expect(manifests.map((manifest) => manifest.identifier)).toEqual(['posthog']);+ const signalArg = { signal: expect.any(AbortSignal) };+ expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith(+ 'posthog',+ signalArg,+ );+ expect((service as any).market.skills.listTools).toHaveBeenCalledWith('posthog', signalArg);+ // listConnections + live probe + static fallback each get their own budget.+ expect(timeoutSpy).toHaveBeenCalledTimes(3);+ expect(timeoutSpy).toHaveBeenCalledWith(LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS);+ } finally {+ timeoutSpy.mockRestore();+ }+ });++ it('should report each failed provider through onError', async () => {+ const service = new MarketService();+ const onError = vi.fn();+ const providerError = new Error('Failed');+ (service as any).market.connect.listConnections = vi.fn().mockResolvedValue({+ connections: [{ providerId: 'failing' }, { providerId: 'working' }],+ });+ (service as any).market.skills.listTools = vi+ .fn()+ .mockImplementation((id: string) =>+ id === 'failing'+ ? Promise.reject(providerError)+ : Promise.resolve({ tools: [{ description: 'Work', inputSchema: {}, name: 'work' }] }),+ );++ const manifests = await service.getLobehubSkillManifests({ onError });++ expect(manifests.map((manifest) => manifest.identifier)).toEqual(['working']);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError).toHaveBeenCalledWith(providerError, 'failing');+ });++ it('should report a failed connection lookup through onError', async () => {+ const service = new MarketService();+ const onError = vi.fn();+ const lookupError = new Error('The operation was aborted due to timeout');+ (service as any).market.connect.listConnections = vi.fn().mockRejectedValue(lookupError);++ const manifests = await service.getLobehubSkillManifests({ onError });++ expect(manifests).toEqual([]);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError).toHaveBeenCalledWith(lookupError);+ });});describe('skill comments & ratings', () => {diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex 8bb8b10ba4b..1f431a77e97 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -3,19 +3,42 @@ import { CacheRevalidate, CacheTag } from '@lobechat/types';import { MarketSDK, type OrgRef, orgRefToPathSegment } from '@lobehub/market-sdk';import debug from 'debug';import { type NextRequest } from 'next/server';+import pMap from 'p-map';import { type TrustedClientUserInfo } from '@/libs/trusted-client';import { generateTrustedClientToken, getTrustedClientTokenForSession } from '@/libs/trusted-client';import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';-import { listSkillToolsWithLiveFallback } from './listSkillToolsWithLiveFallback';+import {+ listSkillToolsWithLiveFallback,+ type SkillToolsClient,+} from './listSkillToolsWithLiveFallback';const log = debug('lobe-server:market-service');const MARKET_BASE_URL = process.env.MARKET_BASE_URL || 'https://market.lobehub.com';+/** Applies to `listConnections` and to each provider's tool-list request. */export const LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS = 3_000;+/** Max providers whose tool lists are fetched at once during discovery. */+export const LOBEHUB_SKILL_DISCOVERY_CONCURRENCY = 5;export const LOBEHUB_SKILL_EXECUTION_TIMEOUT_MS = 120_000;+/**+ * Provider display names for skill manifests. `connection.providerName` is the+ * *user's* display name on that provider (e.g. "LiJian" instead of "Linear"),+ * not the provider's own name. Static map β importing LOBEHUB_SKILL_PROVIDERS+ * pulls in react-icons (client-side only). Keep in sync with lobehubSkill.ts.+ */+const LOBEHUB_SKILL_PROVIDER_LABELS: Record<string, string> = {+ github: 'GitHub',+ linear: 'Linear',+ microsoft: 'Outlook Calendar',+ notion: 'Notion',+ posthog: 'PostHog',+ twitter: 'X',+ vercel: 'Vercel',+};+// ============================== Helper Functions ==============================/**@@ -375,12 +398,9 @@ export class MarketService {/*** List available tools for a provider*/- async listSkillTools(providerId: string) {+ async listSkillTools(providerId: string, options?: { timeoutMs?: number }) {return listSkillToolsWithLiveFallback(- this.market.skills as {- listLiveTools?: (providerId: string) => Promise<any>;- listTools: (providerId: string) => Promise<any>;- },+ this.market.skills as SkillToolsClient,providerId,(error) => {log(@@ -389,6 +409,7 @@ export class MarketService {error,);},+ options?.timeoutMs,);}@@ -745,9 +766,15 @@ export class MarketService {* Fetch LobeHub Skills manifests from Market API* Gets user's connected skills and builds tool manifests for agent execution*+ * @param options.onError - Called for each failure the method absorbs: a+ * provider whose tools could not be listed (with its `providerId`), or the+ * connection lookup itself (without one). Lets callers tell degraded+ * discovery apart from a user with no connected skills.* @returns Array of tool manifests for connected skills*/- async getLobehubSkillManifests(): Promise<LobeToolManifest[]> {+ async getLobehubSkillManifests(options?: {+ onError?: (error: unknown, providerId?: string) => void;+ }): Promise<LobeToolManifest[]> {try {// 1. Get user's connected skillsconst { connections } = await this.market.connect.listConnections({@@ -760,69 +787,62 @@ export class MarketService {log('getLobehubSkillManifests: found %d connected skills', connections.length);- // 2. Fetch tools for each connection and build manifests- const manifests: LobeToolManifest[] = [];-- for (const connection of connections) {- try {+ // 2. Fetch tools for connections concurrently (bounded). This runs on the+ // execAgent send path, so one slow provider must not serialize the rest;+ // pMap keeps the manifests in connection order.+ const manifests = await pMap(+ connections,+ async (connection): Promise<LobeToolManifest | undefined> => {// Connection returns providerId (e.g., 'twitter', 'linear'), not numeric idconst providerId = (connection as any).providerId;- if (!providerId) {- log('getLobehubSkillManifests: connection missing providerId: %O', connection);- continue;+ try {+ if (!providerId) {+ log('getLobehubSkillManifests: connection missing providerId: %O', connection);+ return;+ }+ const icon = (connection as any).icon;+ const providerLabel = LOBEHUB_SKILL_PROVIDER_LABELS[providerId] || providerId;++ const { tools, instruction } = await this.listSkillTools(providerId, {+ timeoutMs: LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS,+ });+ if (!tools || tools.length === 0) return;++ const manifest: LobeToolManifest = {+ api: tools.map((tool: any) => ({+ description: tool.description || '',+ name: tool.name,+ parameters: tool.inputSchema || { properties: {}, type: 'object' },+ })),+ identifier: providerId,+ meta: {+ avatar: icon || 'π',+ description: `LobeHub Skill: ${providerLabel}`,+ tags: ['lobehub-skill', providerId],+ title: providerLabel,+ },+ systemRole: instruction || undefined,+ type: 'builtin',+ };++ log(+ 'getLobehubSkillManifests: built manifest for %s with %d tools',+ providerId,+ tools.length,+ );+ return manifest;+ } catch (error) {+ log('getLobehubSkillManifests: failed to fetch tools for connection: %O', error);+ options?.onError?.(error, providerId);}- const icon = (connection as any).icon;-- // Look up the provider's display name from the static registry.- // connection.providerName is the *user's* display name on that provider,- // NOT the provider's own name (e.g., "LiJian" instead of "Linear").- // Static label map β avoids importing LOBEHUB_SKILL_PROVIDERS which- // pulls in react-icons (client-side only). Keep in sync with lobehubSkill.ts.- const PROVIDER_LABELS: Record<string, string> = {- github: 'GitHub',- linear: 'Linear',- microsoft: 'Outlook Calendar',- notion: 'Notion',- posthog: 'PostHog',- twitter: 'X',- vercel: 'Vercel',- };- const providerLabel = PROVIDER_LABELS[providerId] || providerId;-- const { tools, instruction } = await this.listSkillTools(providerId);- if (!tools || tools.length === 0) continue;-- const manifest: LobeToolManifest = {- api: tools.map((tool: any) => ({- description: tool.description || '',- name: tool.name,- parameters: tool.inputSchema || { properties: {}, type: 'object' },- })),- identifier: providerId,- meta: {- avatar: icon || 'π',- description: `LobeHub Skill: ${providerLabel}`,- tags: ['lobehub-skill', providerId],- title: providerLabel,- },- systemRole: instruction || undefined,- type: 'builtin',- };-- manifests.push(manifest);- log(- 'getLobehubSkillManifests: built manifest for %s with %d tools',- providerId,- tools.length,- );- } catch (error) {- log('getLobehubSkillManifests: failed to fetch tools for connection: %O', error);- }- }+ },+ { concurrency: LOBEHUB_SKILL_DISCOVERY_CONCURRENCY },+ );- return manifests;+ return manifests.filter((manifest): manifest is LobeToolManifest => !!manifest);} catch (error) {log('getLobehubSkillManifests: error fetching skills: %O', error);+ options?.onError?.(error);return [];}}diff --git a/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts b/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.tsindex a975319c513..d2b917a12e2 100644--- a/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts+++ b/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts@@ -79,4 +79,24 @@ describe('listSkillToolsWithLiveFallback', () => {expect(skills.listTools).toHaveBeenCalledWith('posthog');});++ it('should give the live probe and the static fallback separate timeout signals', async () => {+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ const skills = {+ listLiveTools: vi.fn().mockRejectedValue(new Error('timeout')),+ listTools: vi.fn().mockResolvedValue(staticResponse),+ };++ await expect(listSkillToolsWithLiveFallback(skills, 'posthog', undefined, 3000)).resolves.toBe(+ staticResponse,+ );++ const liveSignal = skills.listLiveTools.mock.calls[0][1]?.signal;+ const staticSignal = skills.listTools.mock.calls[0][1]?.signal;+ expect(liveSignal).toBeInstanceOf(AbortSignal);+ expect(staticSignal).toBeInstanceOf(AbortSignal);+ expect(staticSignal).not.toBe(liveSignal);+ });});diff --git a/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts b/apps/server/src/services/market/listSkillToolsWithLiveFallback.tsindex cc41073067b..37ad639a26b 100644--- a/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts+++ b/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts@@ -1,21 +1,29 @@export interface SkillToolsClient {- listLiveTools?: (providerId: string) => Promise<any>;- listTools: (providerId: string) => Promise<any>;+ listLiveTools?: (providerId: string, options?: RequestInit) => Promise<any>;+ listTools: (providerId: string, options?: RequestInit) => Promise<any>;}+/**+ * Each request gets its own timeout budget so a hanging live probe cannot+ * starve the static fallback that follows it.+ */+const requestOptions = (timeoutMs?: number): [RequestInit] | [] =>+ timeoutMs ? [{ signal: AbortSignal.timeout(timeoutMs) }] : [];+export const listSkillToolsWithLiveFallback = async (skills: SkillToolsClient,providerId: string,onLiveDiscoveryError?: (error: unknown) => void,+ timeoutMs?: number,) => {if (typeof skills.listLiveTools === 'function') {try {- const response = await skills.listLiveTools(providerId);+ const response = await skills.listLiveTools(providerId, ...requestOptions(timeoutMs));if (Array.isArray(response?.tools) && response.tools.length > 0) return response;} catch (error) {onLiveDiscoveryError?.(error);}}- return skills.listTools(providerId);+ return skills.listTools(providerId, ...requestOptions(timeoutMs));};