Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

⏱️ fix: Bound Outbound Calls Made Inside a Request (#17263)

Marco Beretta871833872878
diff --git a/api/app/clients/prompts/createContextHandlers.spec.js b/api/app/clients/prompts/createContextHandlers.spec.js
index 4181b28f0c..095dc5e3cf 100644
--- a/api/app/clients/prompts/createContextHandlers.spec.js
+++ b/api/app/clients/prompts/createContextHandlers.spec.js
@@ -43,5 +43,8 @@ it('still fetches context on file-only messages in full-document mode', async ()
expect(axios.post).not.toHaveBeenCalled();
expect(axios.get).toHaveBeenCalledWith('http://rag/documents/file-1/context', {
headers: { Authorization: 'Bearer signed-token' },
+ timeout: 30_000,
+ signal: expect.any(AbortSignal),
+ timeoutErrorMessage: expect.any(String),
});
});
diff --git a/api/server/middleware/moderateText.js b/api/server/middleware/moderateText.js
index 0e1b752974..cfcc4d0a15 100644
--- a/api/server/middleware/moderateText.js
+++ b/api/server/middleware/moderateText.js
@@ -5,8 +5,10 @@ const {
mergeQuotedText,
getBoundedAskUserAnswerValues,
serializeAskUserAnswerVariants,
+ getOutboundTimeoutMs,
+ outboundRequestBudget,
+ logAxiosError,
} = require('@librechat/api');
-const { logger } = require('@librechat/data-schemas');
const { ErrorTypes } = require('librechat-data-provider');
const denyRequest = require('./denyRequest');
@@ -96,6 +98,7 @@ async function moderateText(req, res, next) {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_MODERATION_API_KEY}`,
},
+ ...outboundRequestBudget(getOutboundTimeoutMs(req.config, 'moderationMs'), 'moderationMs'),
},
);
@@ -108,7 +111,7 @@ async function moderateText(req, res, next) {
return await denyRequest(req, res, errorMessage);
}
} catch (error) {
- logger.error('Error in moderateText:', error);
+ logAxiosError({ message: 'Error in moderateText:', error });
const errorMessage = 'error in moderation check';
return await denyRequest(req, res, errorMessage);
}
diff --git a/api/server/middleware/moderateText.spec.js b/api/server/middleware/moderateText.spec.js
index 062f9dc4ef..33c9822955 100644
--- a/api/server/middleware/moderateText.spec.js
+++ b/api/server/middleware/moderateText.spec.js
@@ -9,6 +9,9 @@ jest.mock('@librechat/api', () => ({
mergeQuotedText: jest.fn(),
getBoundedAskUserAnswerValues: jest.fn(() => []),
serializeAskUserAnswerVariants: jest.fn(() => []),
+ getOutboundTimeoutMs: (config, key) => config?.timeouts?.[key] ?? 10_000,
+ outboundRequestBudget: (timeout) => ({ timeout, signal: AbortSignal.timeout(timeout) }),
+ logAxiosError: jest.fn(),
}));
jest.mock('@librechat/data-schemas', () => ({ logger: { error: jest.fn() } }));
jest.mock('librechat-data-provider', () => ({ ErrorTypes: { MODERATION: 'moderation' } }));
@@ -32,4 +35,22 @@ describe('moderateText', () => {
expect(axios.post).not.toHaveBeenCalled();
expect(next).toHaveBeenCalledTimes(1);
});
+
+ it('bounds the moderation request by the configured timeout', async () => {
+ axios.post.mockResolvedValue({ data: { results: [{ flagged: false }] } });
+ const next = jest.fn();
+
+ await moderateText(
+ { body: { text: 'hello' }, config: { timeouts: { moderationMs: 2_500 } } },
+ {},
+ next,
+ );
+
+ expect(axios.post).toHaveBeenCalledWith(
+ expect.any(String),
+ { input: 'hello' },
+ expect.objectContaining({ timeout: 2_500 }),
+ );
+ expect(next).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/api/server/routes/actions.js b/api/server/routes/actions.js
index d9a2f2f7fa..17d9a76693 100644
--- a/api/server/routes/actions.js
+++ b/api/server/routes/actions.js
@@ -108,6 +108,7 @@ router.get('/:action_id/oauth/callback', async (req, res) => {
redirect_uri: flowState.metadata.redirect_uri,
token_exchange_method: flowState.metadata.token_exchange_method,
allowedAddresses: flowState.metadata.allowedAddresses,
+ timeout: flowState.metadata.timeout,
/** Encrypted values */
encrypted_oauth_client_id: flowState.metadata.encrypted_oauth_client_id,
encrypted_oauth_client_secret: flowState.metadata.encrypted_oauth_client_secret,
diff --git a/api/server/services/ActionService.js b/api/server/services/ActionService.js
index 6fcdb641c6..d46b9e9dd8 100644
--- a/api/server/services/ActionService.js
+++ b/api/server/services/ActionService.js
@@ -181,6 +181,7 @@ async function loadActionSets(query) {
* @param {number} [params.jobCreatedAt] - The generation epoch that owns emitted events.
* @param {boolean} [params.useSSRFProtection] - When true, uses SSRF-safe HTTP agents that validate resolved IPs at connect time.
* @param {string[] | null} [params.allowedAddresses] - Optional admin exemption list of host:port pairs that bypass the SSRF private-IP block.
+ * @param {number} [params.timeoutMs] - Milliseconds before an action HTTP call is abandoned.
* @returns { Promise<typeof tool | { _call: (toolInput: Object | string) => unknown}> } An object with `_call` method to execute the tool input.
*/
async function createActionTool({
@@ -196,6 +197,7 @@ async function createActionTool({
jobCreatedAt,
useSSRFProtection = false,
allowedAddresses,
+ timeoutMs,
}) {
const ssrfAgents = useSSRFProtection ? createSSRFSafeAgents(allowedAddresses) : undefined;
/** @type {(toolInput: Object | string, config: GraphRunnableConfig) => Promise<unknown>} */
@@ -287,6 +289,7 @@ async function createActionTool({
redirect_uri: redirectUri,
token_exchange_method: metadata.auth.token_exchange_method,
allowedAddresses,
+ timeout: timeoutMs,
/** Encrypted values */
encrypted_oauth_client_id: encrypted.oauth_client_id,
encrypted_oauth_client_secret: encrypted.oauth_client_secret,
@@ -358,6 +361,7 @@ async function createActionTool({
token_exchange_method: metadata.auth.token_exchange_method,
encrypted_oauth_client_secret: encrypted.oauth_client_secret,
allowedAddresses,
+ timeout: timeoutMs,
},
{
findToken,
@@ -412,7 +416,11 @@ async function createActionTool({
}
}
- const response = await preparedExecutor.execute(ssrfAgents);
+ const response = await preparedExecutor.execute({
+ ...ssrfAgents,
+ timeout: timeoutMs,
+ signal: config?.signal,
+ });
if (typeof response.data === 'object') {
return JSON.stringify(response.data);
diff --git a/api/server/services/ActionService.spec.js b/api/server/services/ActionService.spec.js
index 1ada3184d7..5ec4bf62ee 100644
--- a/api/server/services/ActionService.spec.js
+++ b/api/server/services/ActionService.spec.js
@@ -964,3 +964,52 @@ describe('backward-compatible tool name matching', () => {
});
});
});
+
+describe('createActionTool request budget', () => {
+ it('passes the configured timeout and the run abort signal to the action call', async () => {
+ const preparedExecutor = { execute: jest.fn().mockResolvedValue({ data: { ok: true } }) };
+ const requestBuilder = {
+ createExecutor: jest.fn(() => ({ setParams: jest.fn(() => preparedExecutor) })),
+ };
+ const actionTool = await createActionTool({
+ userId: 'action-user',
+ res: {},
+ action: { action_id: 'action-1', metadata: { domain: 'https://api.example.com' } },
+ requestBuilder,
+ timeoutMs: 5_000,
+ });
+ const { signal } = new AbortController();
+
+ await actionTool._call({}, { signal });
+
+ expect(preparedExecutor.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ timeout: 5_000, signal }),
+ );
+ });
+
+ it('reports a call that hit its deadline as a timeout, not as a stopped run', async () => {
+ const canceled = Object.assign(new Error('canceled'), {
+ code: 'ERR_CANCELED',
+ config: {
+ timeoutErrorMessage:
+ 'Exceeded timeouts.actionsMs (5 ms); raise it in librechat.yaml if this upstream is legitimately slow',
+ signal: { reason: new DOMException('timed out', 'TimeoutError') },
+ },
+ });
+ const preparedExecutor = { execute: jest.fn().mockRejectedValue(canceled) };
+ const requestBuilder = {
+ createExecutor: jest.fn(() => ({ setParams: jest.fn(() => preparedExecutor) })),
+ };
+ const actionTool = await createActionTool({
+ userId: 'action-user',
+ res: {},
+ action: { action_id: 'action-1', metadata: { domain: 'https://api.example.com' } },
+ requestBuilder,
+ timeoutMs: 5,
+ });
+
+ const result = await actionTool._call({}, {});
+
+ expect(result).toContain('timeouts.actionsMs (5 ms)');
+ });
+});
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index 3819777dcf..b6f3998c3b 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -76,6 +76,7 @@ const {
splitAssistantMCPToolResult,
appendAssistantMCPAppArtifact,
resolveMCPClientCapabilityProfile,
+ getOutboundTimeoutMs,
} = require('@librechat/api');
const {
Time,
@@ -700,6 +701,7 @@ async function processRequiredActions(client, requiredActions) {
encrypted, // Pass the encrypted values for OAuth flow
useSSRFProtection: !Array.isArray(_allowedDomains) || _allowedDomains.length === 0,
allowedAddresses: _allowedAddresses,
+ timeoutMs: getOutboundTimeoutMs(appConfig, 'actionsMs'),
});
if (!tool) {
logger.warn(
@@ -2093,6 +2095,7 @@ async function loadAgentTools({
jobCreatedAt,
useSSRFProtection: !Array.isArray(_allowedDomains) || _allowedDomains.length === 0,
allowedAddresses: _allowedAddresses,
+ timeoutMs: getOutboundTimeoutMs(appConfig, 'actionsMs'),
});
if (!tool) {
@@ -2693,6 +2696,7 @@ async function loadActionToolsForExecution({
description: functionSignature.description,
useSSRFProtection: !Array.isArray(allowedDomains) || allowedDomains.length === 0,
allowedAddresses,
+ timeoutMs: getOutboundTimeoutMs(appConfig, 'actionsMs'),
});
if (!tool) {
diff --git a/api/test/app/clients/tools/util/fileSearch.test.js b/api/test/app/clients/tools/util/fileSearch.test.js
index fd932f590e..b1a44115d6 100644
--- a/api/test/app/clients/tools/util/fileSearch.test.js
+++ b/api/test/app/clients/tools/util/fileSearch.test.js
@@ -177,6 +177,9 @@ describe('fileSearch.js - tuple return validation', () => {
Authorization: 'Bearer mock-jwt-token',
'Content-Type': 'application/json',
},
+ timeout: 30_000,
+ signal: expect.any(AbortSignal),
+ timeoutErrorMessage: expect.any(String),
},
);
});
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index b673ee1a45..9e0904515a 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -447,3 +447,7 @@ modelSpecs:
preset:
endpoint: 'Mock Provider A'
model: 'mock-model-a'
+
+# Short enough that a stalled fake RAG query fails the tool call well inside a test.
+timeouts:
+ ragMs: 3000
diff --git a/e2e/setup/fake-rag-server.js b/e2e/setup/fake-rag-server.js
index 4c7a0abbff..8fdaf5a94f 100644
--- a/e2e/setup/fake-rag-server.js
+++ b/e2e/setup/fake-rag-server.js
@@ -20,6 +20,9 @@
* assert a file's bytes actually reached the RAG env, independent of the DB write.
* `/__debug/reset` clears those recordings only; the stored embeds behind presence
* checks persist like real vectors until `DELETE /documents` removes them.
+ *
+ * `POST /__debug/stall` with `{ stall: true }` records file_search queries but never
+ * answers them, standing in for a hung RAG API; reset or `{ stall: false }` clears it.
*/
const http = require('http');
@@ -38,6 +41,7 @@ const queries = [];
const probes = [];
/** @type {Array<{ file_id: string; entity_id: string }>} */
const stored = [];
+let stallQueries = false;
/** @type {string[]} */
const deleted = [];
@@ -107,6 +111,9 @@ async function handleQuery(req, res) {
const entityId = body.entity_id || '';
if (body.k !== PROBE_K) {
queries.push({ file_id: body.file_id || '', query: body.query || '' });
+ if (stallQueries) {
+ return;
+ }
sendJson(res, 200, []);
return;
}
@@ -161,7 +168,14 @@ const server = http.createServer((req, res) => {
return;
}
+ if (pathname === '/__debug/stall' && req.method === 'POST') {
+ stallQueries = (await readJson(req)).stall === true;
+ sendJson(res, 200, { ok: true, stall: stallQueries });
+ return;
+ }
+
if (pathname === '/__debug/reset' && req.method === 'POST') {
+ stallQueries = false;
embedded.length = 0;
queries.length = 0;
probes.length = 0;
diff --git a/e2e/specs/mock/scenarios/rag-timeout.spec.ts b/e2e/specs/mock/scenarios/rag-timeout.spec.ts
new file mode 100644
index 0000000000..02513edf34
--- /dev/null
+++ b/e2e/specs/mock/scenarios/rag-timeout.spec.ts
@@ -0,0 +1,54 @@
+import { expect, test } from '@playwright/test';
+import type { UploadedFile } from '../helpers';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ RAG_API_BASE,
+ uniqueName,
+ getRagQueries,
+ enableFileSearch,
+ resetProvisioning,
+ selectMockEndpoint,
+ uploadViaUnifiedButton,
+ sendMessageAndWaitForCompletion,
+} from '../helpers';
+
+test.describe('outbound timeouts', () => {
+ test.afterEach(async ({ request }) => {
+ await request.post(`${RAG_API_BASE}/__debug/stall`, { data: { stall: false } });
+ });
+
+ /* The e2e config sets timeouts.ragMs to 3s; without a budget the stalled query held the
+ tool call, and with it the whole turn, open indefinitely. */
+ test('a file search against a stalled RAG API still finishes the turn @scenario:stalled-rag-query-finishes-the-turn', async ({
+ page,
+ request,
+ }) => {
+ test.setTimeout(120_000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10_000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[1]);
+ await resetProvisioning(page);
+ await enableFileSearch(page);
+
+ const fileName = `${uniqueName('stalled-rag')}.csv`;
+ const upload = await uploadViaUnifiedButton(page, {
+ name: fileName,
+ mimeType: 'text/csv',
+ content: 'k,v\nfoo,bar\n',
+ });
+ expect(upload.ok()).toBeTruthy();
+ const fileId = ((await upload.json()) as UploadedFile).file_id;
+ await expect(
+ page.getByTestId('composer-tray').getByRole('button', { name: fileName }),
+ ).toBeVisible({ timeout: 15_000 });
+
+ const stall = await request.post(`${RAG_API_BASE}/__debug/stall`, { data: { stall: true } });
+ expect(stall.ok()).toBeTruthy();
+
+ const startedAt = Date.now();
+ await sendMessageAndWaitForCompletion(page, `E2E_FILE_SEARCH:${uniqueName('stalled')}`);
+
+ expect((await getRagQueries(page)).some((query) => query.file_id === fileId)).toBe(true);
+ expect(Date.now() - startedAt).toBeLessThan(60_000);
+ });
+});
diff --git a/librechat.example.yaml b/librechat.example.yaml
index f39437a86f..98daf5e775 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -540,6 +540,14 @@ registration:
# passwordHashing:
# maxWorkers: 2 # default: one less than the CPU count, at most 4
+# Outbound call budgets, in milliseconds. Each omitted key keeps the default shown.
+# timeouts:
+# ragMs: 30000 # RAG API queries for file search and message context
+# ocrMs: 300000 # each OCR provider call
+# actionsMs: 300000 # each action (OpenAPI tool) HTTP call
+# moderationMs: 10000 # the OpenAI moderation check before a chat turn
+# imageFetchMs: 30000 # fetching a stored image to encode it for a provider
+
# rateLimits:
# # Per-user MCP App browser-route limits. Each limit uses a fixed one-minute window.
# mcpApps:
diff --git a/packages/api/src/files/encode/image.spec.ts b/packages/api/src/files/encode/image.spec.ts
index b3017a162b..4249b49c86 100644
--- a/packages/api/src/files/encode/image.spec.ts
+++ b/packages/api/src/files/encode/image.spec.ts
@@ -170,7 +170,12 @@ describe('encodeAndFormatImages', () => {
expect(result.image_urls).toEqual([
{ type: 'image', source: { type: 'base64', media_type: file.type, data: content } },
]);
- expect(httpClient.get).toHaveBeenCalledWith(file.filepath, { responseType: 'arraybuffer' });
+ expect(httpClient.get).toHaveBeenCalledWith(file.filepath, {
+ responseType: 'arraybuffer',
+ timeout: 30_000,
+ signal: expect.any(AbortSignal),
+ timeoutErrorMessage: expect.any(String),
+ });
expect(memoryGuard.runGuardedEncode).toHaveBeenCalledWith(file.bytes, expect.any(Function));
});
diff --git a/packages/api/src/files/encode/image.ts b/packages/api/src/files/encode/image.ts
index 3aae189831..57b439315a 100644
--- a/packages/api/src/files/encode/image.ts
+++ b/packages/api/src/files/encode/image.ts
@@ -11,6 +11,7 @@ import type { IMongoFile } from '@librechat/data-schemas';
import type { Agents } from 'librechat-data-provider';
import type { AxiosInstance } from 'axios';
import type { ServerRequest, StrategyFunctions } from '~/types';
+import { getOutboundTimeoutMs, outboundRequestBudget } from '~/utils/timeouts';
import { getFileStream, isAttachmentObjectNotFoundError } from './utils';
import { validateImage } from '~/files/validation';
import { sniffImageMimeType } from '~/files/mime';
@@ -138,9 +139,11 @@ export async function encodeAndFormatImages(
if (source !== FileSources.local && effectiveEndpoint && base64Only.has(effectiveEndpoint)) {
const entry = await runGuardedEncode<ImageEntry>(file.bytes ?? 0, async () => {
const [preparedFile, imageURL] = await preparePayload(req, file);
+ const fetchTimeoutMs = getOutboundTimeoutMs(req.config, 'imageFetchMs');
try {
const response = await httpClient.get<ArrayBuffer>(imageURL, {
responseType: 'arraybuffer',
+ ...outboundRequestBudget(fetchTimeoutMs, 'imageFetchMs'),
});
return [preparedFile, Buffer.from(response.data).toString('base64')];
} catch (error) {
diff --git a/packages/api/src/files/mistral/crud.spec.ts b/packages/api/src/files/mistral/crud.spec.ts
index 8c48a6e762..d482317fb4 100644
--- a/packages/api/src/files/mistral/crud.spec.ts
+++ b/packages/api/src/files/mistral/crud.spec.ts
@@ -44,6 +44,7 @@ jest.mock('axios', () => {
jest.mock('@librechat/data-schemas', () => ({
logger: {
+ warn: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
},
@@ -82,6 +83,7 @@ import { decryptConfigSecret, isEncryptedSecretPayload } from '~/admin/secrets';
import { logAxiosError } from '~/utils/axios';
import { readFileAsBuffer } from '~/utils/files';
import { loadServiceKey } from '~/utils/key';
+import { outboundTimeoutMessage } from '~/utils/timeouts';
import {
uploadDocumentToMistral,
uploadAzureMistralOCR,
@@ -271,6 +273,7 @@ describe('MistralOCR Service', () => {
maxRedirects: 0,
httpAgent: expect.anything(),
httpsAgent: expect.anything(),
+ timeout: 300_000,
}),
);
expect(result).toEqual(mockResponse.data);
@@ -525,6 +528,25 @@ describe('MistralOCR Service', () => {
});
expect(JSON.stringify(jest.mocked(mockLogger.error).mock.calls)).not.toContain('PRIVATE');
});
+
+ it('keeps the budget hint when a protected OCR call times out', async () => {
+ const timeoutErrorMessage = outboundTimeoutMessage('ocrMs', 300_000);
+ mockAxios.post!.mockRejectedValueOnce({
+ code: 'ECONNABORTED',
+ message: timeoutErrorMessage,
+ config: { timeoutErrorMessage },
+ });
+
+ await expect(
+ performOCR({
+ apiKey: 'test-api-key',
+ url: 'https://document-url.com',
+ contentProtected: true,
+ }),
+ ).rejects.toThrow('Error performing OCR.');
+
+ expect(mockLogger.warn).toHaveBeenCalledWith(`Error performing OCR. ${timeoutErrorMessage}`);
+ });
});
describe('uploadMistralOCR', () => {
@@ -644,6 +666,7 @@ describe('MistralOCR Service', () => {
baseURL: '${OCR_BASEURL}',
mistralModel: 'mistral-medium',
},
+ timeouts: { ocrMs: 120_000 },
},
} as unknown as ServerRequest;
@@ -677,6 +700,9 @@ describe('MistralOCR Service', () => {
text: expect.stringContaining('# PAGE 1'),
images: ['base64image1', 'base64image2'],
});
+ for (const call of [...mockAxios.post!.mock.calls, ...mockAxios.get!.mock.calls]) {
+ expect(call[call.length - 1]).toMatchObject({ timeout: 120_000 });
+ }
});
it('should process OCR for an image file and use image_url type', async () => {
diff --git a/packages/api/src/files/mistral/crud.ts b/packages/api/src/files/mistral/crud.ts
index 3d76005a44..abe146ffc9 100644
--- a/packages/api/src/files/mistral/crud.ts
+++ b/packages/api/src/files/mistral/crud.ts
@@ -20,6 +20,12 @@ import type {
OCRResult,
OCRImage,
} from '~/types';
+import {
+ getOutboundTimeout,
+ outboundRequestBudget,
+ getOutboundTimeoutMs,
+ DEFAULT_OUTBOUND_TIMEOUTS_MS,
+} from '~/utils/timeouts';
import { decryptConfigSecret, isEncryptedSecretPayload } from '~/admin/secrets';
import { logAxiosError, createAxiosInstance } from '~/utils/axios';
import { applySSRFSafeAgentIfDirect } from '~/auth/agent';
@@ -65,7 +71,13 @@ function createProtectedProviderError(
if (!contentProtected) {
return null;
}
- logger.error(message, getSafeErrorMetadata(error));
+ /** The budget message names only the config key, so it is safe to keep. */
+ const timeout = getOutboundTimeout(error);
+ if (timeout) {
+ logger.warn(`${message} ${timeout.message}`);
+ } else {
+ logger.error(message, getSafeErrorMetadata(error));
+ }
return new Error(message);
}
@@ -84,18 +96,21 @@ export async function uploadDocumentToMistral({
baseURL = DEFAULT_MISTRAL_BASE_URL,
fileName = '',
allowedAddresses,
+ timeout = DEFAULT_OUTBOUND_TIMEOUTS_MS.ocrMs,
}: {
apiKey: string;
filePath: string;
baseURL?: string;
fileName?: string;
allowedAddresses?: string[] | null;
+ timeout?: number;
}): Promise<MistralFileUploadResponse> {
const form = new FormData();
form.append('purpose', 'ocr');
const actualFileName = fileName || path.basename(filePath);
const config: AxiosRequestConfig = {
+ ...outboundRequestBudget(timeout, 'ocrMs'),
headers: {
Authorization: `Bearer ${apiKey}`,
...form.getHeaders(),
@@ -124,6 +139,7 @@ export async function getSignedUrl({
expiry = 24,
baseURL = DEFAULT_MISTRAL_BASE_URL,
allowedAddresses,
+ timeout = DEFAULT_OUTBOUND_TIMEOUTS_MS.ocrMs,
contentProtected = false,
}: {
apiKey: string;
@@ -131,9 +147,11 @@ export async function getSignedUrl({
expiry?: number;
baseURL?: string;
allowedAddresses?: string[] | null;
+ timeout?: number;
contentProtected?: boolean;
}): Promise<MistralSignedUrlResponse> {
const config: AxiosRequestConfig = {
+ ...outboundRequestBudget(timeout, 'ocrMs'),
headers: {
Authorization: `Bearer ${apiKey}`,
},
@@ -176,6 +194,7 @@ export async function performOCR({
baseURL = DEFAULT_MISTRAL_BASE_URL,
documentType = 'document_url',
allowedAddresses,
+ timeout = DEFAULT_OUTBOUND_TIMEOUTS_MS.ocrMs,
contentProtected = false,
}: {
url: string;
@@ -184,11 +203,13 @@ export async function performOCR({
baseURL?: string;
documentType?: 'document_url' | 'image_url';
allowedAddresses?: string[] | null;
+ timeout?: number;
contentProtected?: boolean;
}): Promise<OCRResult> {
const documentKey = documentType === 'image_url' ? 'image_url' : 'document_url';
const config: AxiosRequestConfig = {
+ ...outboundRequestBudget(timeout, 'ocrMs'),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
@@ -241,15 +262,18 @@ export async function deleteMistralFile({
apiKey,
baseURL = DEFAULT_MISTRAL_BASE_URL,
allowedAddresses,
+ timeout = DEFAULT_OUTBOUND_TIMEOUTS_MS.ocrMs,
contentProtected = false,
}: {
fileId: string;
apiKey: string;
baseURL?: string;
allowedAddresses?: string[] | null;
+ timeout?: number;
contentProtected?: boolean;
}): Promise<void> {
const config: AxiosRequestConfig = {
+ ...outboundRequestBudget(timeout, 'ocrMs'),
headers: {
Authorization: `Bearer ${apiKey}`,
},
@@ -450,6 +474,7 @@ export const uploadMistralOCR = async (context: OCRContext): Promise<MistralOCRU
const contentProtected = hasActiveFilePolicy(context.req.config?.filters);
const allowedAddresses = context.req.config?.ocr?.allowedAddresses;
+ const timeout = getOutboundTimeoutMs(context.req.config, 'ocrMs');
try {
const authConfig = await loadAuthConfig(context);
@@ -463,6 +488,7 @@ export const uploadMistralOCR = async (context: OCRContext): Promise<MistralOCRU
apiKey,
baseURL,
allowedAddresses,
+ timeout,
});
mistralFileId = mistralFile.id;
@@ -472,6 +498,7 @@ export const uploadMistralOCR = async (context: OCRContext): Promise<MistralOCRU
baseURL,
fileId: mistralFile.id,
allowedAddresses,
+ timeout,
contentProtected,
});
@@ -483,6 +510,7 @@ export const uploadMistralOCR = async (context: OCRContext): Promise<MistralOCRU
apiKey,
model,
allowedAddresses,
+ timeout,
contentProtected,
});
@@ -499,6 +527,7 @@ export const uploadMistralOCR = async (context: OCRContext): Promise<MistralOCRU
apiKey,
baseURL,
allowedAddresses,
+ timeout,
contentProtected,
});
}
@@ -517,6 +546,7 @@ export const uploadMistralOCR = async (context: OCRContext): Promise<MistralOCRU
apiKey,
baseURL,
allowedAddresses,
+ timeout,
contentProtected,
});
}
@@ -545,6 +575,7 @@ export const uploadAzureMistralOCR = async (
const { apiKey, baseURL } = await loadAuthConfig(context);
const model = getModelConfig(context.req.config?.ocr);
const allowedAddresses = context.req.config?.ocr?.allowedAddresses;
+ const timeout = getOutboundTimeoutMs(context.req.config, 'ocrMs');
const { content: buffer } = await readFileAsBuffer(context.file.path, {
fileSize: context.file.size,
@@ -561,6 +592,7 @@ export const uploadAzureMistralOCR = async (
url: `${base64Prefix}${base64}`,
documentType,
allowedAddresses,
+ timeout,
contentProtected,
});
@@ -591,7 +623,7 @@ export const uploadAzureMistralOCR = async (
/**
* Loads Google service account configuration
*/
-async function loadGoogleAuthConfig(): Promise<{
+async function loadGoogleAuthConfig(timeout: number): Promise<{
serviceAccount: GoogleServiceAccount;
accessToken: string;
}> {
@@ -613,7 +645,7 @@ async function loadGoogleAuthConfig(): Promise<{
}
const jwt = await createJWT(serviceKey as GoogleServiceAccount);
- const accessToken = await exchangeJWTForAccessToken(jwt);
+ const accessToken = await exchangeJWTForAccessToken(jwt, timeout);
return {
serviceAccount: serviceKey as GoogleServiceAccount,
@@ -658,8 +690,9 @@ async function createJWT(serviceKey: GoogleServiceAccount): Promise<string> {
/**
* Exchanges JWT for access token
*/
-async function exchangeJWTForAccessToken(jwt: string): Promise<string> {
+async function exchangeJWTForAccessToken(jwt: string, timeout: number): Promise<string> {
const config: AxiosRequestConfig = {
+ ...outboundRequestBudget(timeout, 'ocrMs'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
@@ -693,6 +726,7 @@ async function performGoogleVertexOCR({
model,
documentType = 'document_url',
contentProtected = false,
+ timeout = DEFAULT_OUTBOUND_TIMEOUTS_MS.ocrMs,
}: {
url: string;
accessToken: string;
@@ -700,6 +734,7 @@ async function performGoogleVertexOCR({
model: string;
documentType?: 'document_url' | 'image_url';
contentProtected?: boolean;
+ timeout?: number;
}): Promise<OCRResult> {
const location = process.env.GOOGLE_LOC || 'us-central1';
const modelId = model || 'mistral-ocr-2505';
@@ -731,6 +766,7 @@ async function performGoogleVertexOCR({
});
const config: AxiosRequestConfig = {
+ ...outboundRequestBudget(timeout, 'ocrMs'),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
@@ -785,7 +821,8 @@ export const uploadGoogleVertexMistralOCR = async (
): Promise<MistralOCRUploadResult> => {
const contentProtected = hasActiveFilePolicy(context.req.config?.filters);
try {
- const { serviceAccount, accessToken } = await loadGoogleAuthConfig();
+ const timeout = getOutboundTimeoutMs(context.req.config, 'ocrMs');
+ const { serviceAccount, accessToken } = await loadGoogleAuthConfig(timeout);
const model = getModelConfig(context.req.config?.ocr);
const { content: buffer } = await readFileAsBuffer(context.file.path, {
@@ -802,6 +839,7 @@ export const uploadGoogleVertexMistralOCR = async (
model,
documentType,
contentProtected,
+ timeout,
});
if (!ocrResult || !ocrResult.pages || ocrResult.pages.length === 0) {
diff --git a/packages/api/src/files/rag/context.spec.ts b/packages/api/src/files/rag/context.spec.ts
index 535cc3ca9e..93477dc0ee 100644
--- a/packages/api/src/files/rag/context.spec.ts
+++ b/packages/api/src/files/rag/context.spec.ts
@@ -1,6 +1,8 @@
import { createRagContextHandlers } from './context';
-const req = { user: { id: 'user-1' } };
+const req: { user: { id: string }; config?: { timeouts?: { ragMs?: number } } } = {
+ user: { id: 'user-1' },
+};
const files = ['a.pdf', 'b.pdf', 'c.pdf'].map((filename, index) => ({
file_id: `file-${index}`,
filename,
@@ -8,7 +10,12 @@ const files = ['a.pdf', 'b.pdf', 'c.pdf'].map((filename, index) => ({
embedded: true,
}));
-function setup(userMessageContent?: string, fullContextSetting?: string, ragApiUrl = 'http://rag') {
+function setup(
+ userMessageContent?: string,
+ fullContextSetting?: string,
+ ragApiUrl = 'http://rag',
+ request = req,
+) {
const httpClient = {
get: jest.fn().mockResolvedValue({ data: 'whole document' }),
post: jest.fn().mockResolvedValue({ data: [[{ page_content: 'Relevant excerpt' }, 0.1]] }),
@@ -17,7 +24,7 @@ function setup(userMessageContent?: string, fullContextSetting?: string, ragApiU
const isEnabled = jest.fn((setting?: string | boolean | null) => setting === 'true');
const logAxiosError = jest.fn(() => 'logged');
const handlers = createRagContextHandlers({
- req,
+ req: request,
userMessageContent,
ragApiUrl,
fullContextSetting,
@@ -52,10 +59,25 @@ describe('legacy RAG context', () => {
expect(httpClient.post).toHaveBeenCalledWith(
'http://rag/query',
{ file_id: 'file-0', query: ' what is the deadline? ', k: 4 },
- { headers: { Authorization: 'Bearer signed-token', 'Content-Type': 'application/json' } },
+ {
+ headers: { Authorization: 'Bearer signed-token', 'Content-Type': 'application/json' },
+ timeout: 30_000,
+ signal: expect.any(AbortSignal),
+ timeoutErrorMessage: expect.any(String),
+ },
);
});
+ it('bounds RAG queries by the configured timeout', async () => {
+ const { handlers, httpClient } = setup('deadline?', undefined, 'http://rag', {
+ ...req,
+ config: { timeouts: { ragMs: 5_000 } },
+ });
+ await handlers?.processFile(files[0]);
+ await handlers?.createContext();
+ expect(httpClient.post.mock.calls[0][2]).toMatchObject({ timeout: 5_000 });
+ });
+
it('continues to fetch the full document for a blank message in full-context mode', async () => {
const { handlers, httpClient } = setup('', 'true');
await handlers?.processFile(files[0]);
@@ -63,6 +85,9 @@ describe('legacy RAG context', () => {
expect(httpClient.post).not.toHaveBeenCalled();
expect(httpClient.get).toHaveBeenCalledWith('http://rag/documents/file-0/context', {
headers: { Authorization: 'Bearer signed-token' },
+ timeout: 30_000,
+ signal: expect.any(AbortSignal),
+ timeoutErrorMessage: expect.any(String),
});
});
diff --git a/packages/api/src/files/rag/context.ts b/packages/api/src/files/rag/context.ts
index 4f481d72de..c0e85b15df 100644
--- a/packages/api/src/files/rag/context.ts
+++ b/packages/api/src/files/rag/context.ts
@@ -2,6 +2,7 @@ import type { AxiosResponse } from 'axios';
import type axios from 'axios';
import type { logAxiosError } from '~/utils/axios';
import type { isEnabled } from '~/utils/common';
+import { getOutboundTimeoutMs, outboundRequestBudget } from '~/utils/timeouts';
interface ContextFile {
embedded?: boolean;
@@ -18,7 +19,7 @@ type SearchResults = [SearchHit, number][];
type ContextResponse = AxiosResponse<string | SearchResults>;
interface RagContextOptions {
- req: { user: { id: string } };
+ req: { user: { id: string }; config?: { timeouts?: { ragMs?: number } } };
userMessageContent?: string;
ragApiUrl?: string;
fullContextSetting?: string;
@@ -64,12 +65,15 @@ export function createRagContextHandlers({
const canSemanticSearch =
typeof userMessageContent === 'string' && userMessageContent.trim().length > 0;
+ const timeout = getOutboundTimeoutMs(req.config, 'ragMs');
+
const query = async (file: ContextFile): Promise<ContextResponse> => {
if (useFullContext) {
return httpClient.get<string>(`${ragApiUrl}/documents/${file.file_id}/context`, {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
+ ...outboundRequestBudget(timeout, 'ragMs'),
});
}
@@ -85,6 +89,7 @@ export function createRagContextHandlers({
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
},
+ ...outboundRequestBudget(timeout, 'ragMs'),
},
);
};
diff --git a/packages/api/src/files/rag/search.ts b/packages/api/src/files/rag/search.ts
index 6b6b3ccc3b..2a798a448a 100644
--- a/packages/api/src/files/rag/search.ts
+++ b/packages/api/src/files/rag/search.ts
@@ -3,6 +3,7 @@ import type { logger } from '@librechat/data-schemas';
import type axios from 'axios';
import type { FileCitationSelectionConfig, selectFileCitationSources } from '../citations';
import type { logAxiosError } from '~/utils/axios';
+import { getOutboundTimeoutMs, outboundRequestBudget } from '~/utils/timeouts';
type SearchFile = { file_id: string; fromAgent?: boolean };
type FileSearchResult = [
@@ -33,7 +34,10 @@ interface SearchOptions {
files: readonly SearchFile[];
entity_id?: string;
fileCitations: boolean;
- appConfig?: { endpoints?: Partial<Record<EModelEndpoint, FileCitationSelectionConfig>> };
+ appConfig?: {
+ endpoints?: Partial<Record<EModelEndpoint, FileCitationSelectionConfig>>;
+ timeouts?: { ragMs?: number };
+ };
ragApiUrl?: string;
httpClient: Pick<typeof axios, 'post'>;
generateShortLivedToken: (userId: string) => string;
@@ -83,6 +87,7 @@ export async function executeFileSearchQuery({
return body;
};
+ const timeout = getOutboundTimeoutMs(appConfig, 'ragMs');
const queryPromises = files.map((file) =>
httpClient
.post<SearchResults>(`${ragApiUrl}/query`, createQueryBody(file), {
@@ -90,6 +95,7 @@ export async function executeFileSearchQuery({
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
},
+ ...outboundRequestBudget(timeout, 'ragMs'),
})
.then((result) => ({ data: result.data, file_id: file.file_id }))
.catch((error) => {
diff --git a/packages/api/src/oauth/tokens.spec.ts b/packages/api/src/oauth/tokens.spec.ts
index 3d47840e79..0ac2303724 100644
--- a/packages/api/src/oauth/tokens.spec.ts
+++ b/packages/api/src/oauth/tokens.spec.ts
@@ -177,6 +177,37 @@ describe('action OAuth token exchange validation', () => {
expect(params.get('grant_type')).toBe('refresh_token');
expect(params.get('client_id')).toBe('client-id');
expect(params.get('client_secret')).toBe('client-secret');
+ expect(config.timeout).toBe(300_000);
+ });
+
+ it('bounds the refresh-token exchange by the caller timeout', async () => {
+ await refreshAccessToken(
+ {
+ ...baseFields,
+ refresh_token: 'refresh-token',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ timeout: 5_000,
+ },
+ createTokenMethods(),
+ );
+
+ expect(getAxiosConfig().timeout).toBe(5_000);
+ });
+
+ it('bounds the authorization-code exchange by the caller timeout', async () => {
+ await getAccessToken(
+ {
+ ...baseFields,
+ code: 'authorization-code',
+ redirect_uri: 'https://chat.example.com/api/actions/action-1/oauth/callback',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ timeout: 5_000,
+ },
+ createTokenMethods(),
+ );
+
+ expect(getAxiosConfig().timeout).toBe(5_000);
+ expect(getAxiosConfig().signal).toBeInstanceOf(AbortSignal);
});
it('uses Basic auth for refresh-token exchanges without putting client secrets in the body', async () => {
diff --git a/packages/api/src/oauth/tokens.ts b/packages/api/src/oauth/tokens.ts
index 2a44af334d..e23e20c9ae 100644
--- a/packages/api/src/oauth/tokens.ts
+++ b/packages/api/src/oauth/tokens.ts
@@ -3,11 +3,11 @@ import { logger, encryptV2 } from '@librechat/data-schemas';
import { TokenExchangeMethodEnum } from 'librechat-data-provider';
import type { IToken, TokenMethods } from '@librechat/data-schemas';
import type { AxiosError } from 'axios';
+import { logAxiosError, outboundRequestBudget, DEFAULT_OUTBOUND_TIMEOUTS_MS } from '~/utils';
import { DEFAULT_OAUTH_TOKEN_TTL_SECONDS, normalizeExpiresIn } from './expiry';
import { validateActionOAuthEndpoint } from './validation';
import { decryptSensitiveValue } from '~/actions/crypto';
import { createSSRFSafeAgents } from '~/auth';
-import { logAxiosError } from '~/utils';
const actionOAuthAgents = createSSRFSafeAgents();
const actionOAuthAgentsByAddress = new Map<string, ReturnType<typeof createSSRFSafeAgents>>();
@@ -162,6 +162,7 @@ export async function refreshAccessToken(
encrypted_oauth_client_id,
encrypted_oauth_client_secret,
allowedAddresses,
+ timeout = DEFAULT_OUTBOUND_TIMEOUTS_MS.actionsMs,
}: {
userId: string;
client_url: string;
@@ -171,6 +172,8 @@ export async function refreshAccessToken(
encrypted_oauth_client_id: string;
encrypted_oauth_client_secret: string;
allowedAddresses?: string[] | null;
+ /** Milliseconds before the token request is abandoned. */
+ timeout?: number;
},
{
findToken,
@@ -218,6 +221,7 @@ export async function refreshAccessToken(
maxRedirects: 0,
httpsAgent: getActionOAuthAgents(allowedAddresses).httpsAgent,
data: params.toString(),
+ ...outboundRequestBudget(timeout, 'actionsMs'),
});
await processAccessTokens(
response.data,
@@ -267,6 +271,7 @@ export async function getAccessToken(
encrypted_oauth_client_id,
encrypted_oauth_client_secret,
allowedAddresses,
+ timeout = DEFAULT_OUTBOUND_TIMEOUTS_MS.actionsMs,
}: {
code: string;
userId: string;
@@ -277,6 +282,8 @@ export async function getAccessToken(
encrypted_oauth_client_id: string;
encrypted_oauth_client_secret: string;
allowedAddresses?: string[] | null;
+ /** Milliseconds before the token request is abandoned. */
+ timeout?: number;
},
{
findToken,
@@ -325,6 +332,7 @@ export async function getAccessToken(
maxRedirects: 0,
httpsAgent: getActionOAuthAgents(allowedAddresses).httpsAgent,
data: params.toString(),
+ ...outboundRequestBudget(timeout, 'actionsMs'),
});
await processAccessTokens(
diff --git a/packages/api/src/utils/axios.ts b/packages/api/src/utils/axios.ts
index 83b1866540..0226a7918f 100644
--- a/packages/api/src/utils/axios.ts
+++ b/packages/api/src/utils/axios.ts
@@ -2,6 +2,7 @@ import axios from 'axios';
import { Buffer } from 'buffer';
import { logger } from '@librechat/data-schemas';
import type { AxiosInstance, AxiosProxyConfig, AxiosError } from 'axios';
+import { getOutboundTimeout } from './timeouts';
import { isClientDisconnect } from './streams';
/**
@@ -54,6 +55,12 @@ export const logAxiosError = ({
}
let logMessage = message;
try {
+ const timeout = getOutboundTimeout(error);
+ if (timeout) {
+ logMessage = `${message} ${timeout.message}`;
+ logger.warn(logMessage);
+ return logMessage;
+ }
const stack =
error != null
? (error as Error | AxiosError)?.stack || 'No stack trace available'
diff --git a/packages/api/src/utils/errors.ts b/packages/api/src/utils/errors.ts
index cf77c43769..a7e69f253c 100644
--- a/packages/api/src/utils/errors.ts
+++ b/packages/api/src/utils/errors.ts
@@ -1,3 +1,5 @@
+import { getOutboundTimeout } from './timeouts';
+
export interface SafeErrorMetadata {
readonly type: string;
readonly status?: number;
@@ -127,6 +129,11 @@ export function isAbortError(error: unknown): boolean {
while (current != null && typeof current === 'object' && !visited.has(current)) {
visited.add(current);
+ /** A request cancelled by its own `timeouts` deadline failed; nobody stopped it. */
+ if (getOutboundTimeout(current)) {
+ return false;
+ }
+
const name = readProperty(current, 'name');
const code = readProperty(current, 'code');
const messageValue = readProperty(current, 'message');
diff --git a/packages/api/src/utils/index.ts b/packages/api/src/utils/index.ts
index 12f1db8286..8b1906e44d 100644
--- a/packages/api/src/utils/index.ts
+++ b/packages/api/src/utils/index.ts
@@ -1,5 +1,6 @@
export * from './axios';
export * from './streams';
+export * from './timeouts';
export * from './azure';
export * from './code';
export * from './common';
diff --git a/packages/api/src/utils/timeouts.spec.ts b/packages/api/src/utils/timeouts.spec.ts
new file mode 100644
index 0000000000..c4c8143831
--- /dev/null
+++ b/packages/api/src/utils/timeouts.spec.ts
@@ -0,0 +1,129 @@
+import { logger } from '@librechat/data-schemas';
+import {
+ outboundTimeoutMessage,
+ getOutboundTimeout,
+ getOutboundTimeoutMs,
+ outboundRequestBudget,
+ DEFAULT_OUTBOUND_TIMEOUTS_MS,
+} from './timeouts';
+import { isAbortError } from './errors';
+import { logAxiosError } from './axios';
+
+describe('outbound timeouts', () => {
+ it('uses the default when the config omits the key', () => {
+ expect(getOutboundTimeoutMs(undefined, 'ragMs')).toBe(DEFAULT_OUTBOUND_TIMEOUTS_MS.ragMs);
+ expect(getOutboundTimeoutMs({ timeouts: { ocrMs: 1_000 } }, 'ragMs')).toBe(
+ DEFAULT_OUTBOUND_TIMEOUTS_MS.ragMs,
+ );
+ });
+
+ it('uses the configured value when present', () => {
+ expect(getOutboundTimeoutMs({ timeouts: { moderationMs: 2_500 } }, 'moderationMs')).toBe(2_500);
+ });
+});
+
+describe('outboundRequestBudget', () => {
+ it('aborts at the wall-clock deadline and names the key to raise', async () => {
+ const { timeout, timeoutErrorMessage, signal } = outboundRequestBudget(20, 'ragMs');
+
+ expect(timeout).toBe(20);
+ expect(timeoutErrorMessage).toBe(outboundTimeoutMessage('ragMs', 20));
+ await new Promise((resolve) => signal.addEventListener('abort', resolve));
+ expect(signal.reason).toMatchObject({ name: 'TimeoutError' });
+ });
+
+ it('also follows the caller signal', () => {
+ const controller = new AbortController();
+ const { signal } = outboundRequestBudget(60_000, 'actionsMs', controller.signal);
+
+ controller.abort();
+
+ expect(signal.aborted).toBe(true);
+ });
+});
+
+describe('getOutboundTimeout', () => {
+ const timeoutErrorMessage = outboundTimeoutMessage('actionsMs', 5);
+
+ it('recognizes a request cancelled by its deadline', () => {
+ const canceled = {
+ code: 'ERR_CANCELED',
+ message: 'canceled',
+ config: {
+ timeoutErrorMessage,
+ signal: { reason: new DOMException('timed out', 'TimeoutError') },
+ },
+ };
+
+ expect(getOutboundTimeout(canceled)?.message).toBe(timeoutErrorMessage);
+ expect(isAbortError(canceled)).toBe(false);
+ });
+
+ it('recognizes an idle timeout carrying the budget message', () => {
+ const idle = {
+ code: 'ECONNABORTED',
+ message: timeoutErrorMessage,
+ config: { timeoutErrorMessage },
+ };
+
+ expect(getOutboundTimeout(idle)).toBe(idle);
+ });
+
+ it('leaves a user stop as an abort', () => {
+ const stopped = {
+ code: 'ERR_CANCELED',
+ message: 'canceled',
+ config: {
+ timeoutErrorMessage,
+ signal: { reason: new DOMException('stopped', 'AbortError') },
+ },
+ };
+
+ expect(getOutboundTimeout(stopped)).toBeUndefined();
+ expect(isAbortError(stopped)).toBe(true);
+ });
+
+ it('still reports a deadline wrapped in a cause as a failure', () => {
+ const canceled = {
+ code: 'ERR_CANCELED',
+ message: 'canceled',
+ config: {
+ timeoutErrorMessage,
+ signal: { reason: new DOMException('timed out', 'TimeoutError') },
+ },
+ };
+
+ expect(isAbortError(new Error('tool failed', { cause: canceled }))).toBe(false);
+ });
+
+ it('does not read the message of an error without a budget', () => {
+ const guarded = Object.defineProperty({}, 'message', {
+ get() {
+ throw new Error('message must not be read');
+ },
+ });
+
+ expect(getOutboundTimeout(guarded)).toBeUndefined();
+ });
+});
+
+describe('logAxiosError on a budget overrun', () => {
+ it('warns with the key to raise instead of logging a generic failure', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const error = jest.spyOn(logger, 'error').mockImplementation(() => logger);
+ const timeoutErrorMessage = outboundTimeoutMessage('ragMs', 30_000);
+ const idle = {
+ code: 'ECONNABORTED',
+ message: timeoutErrorMessage,
+ config: { timeoutErrorMessage },
+ };
+
+ const message = logAxiosError({ message: 'RAG query failed:', error: idle });
+
+ expect(message).toContain('timeouts.ragMs (30000 ms)');
+ expect(warn).toHaveBeenCalledWith(message);
+ expect(error).not.toHaveBeenCalled();
+ warn.mockRestore();
+ error.mockRestore();
+ });
+});
diff --git a/packages/api/src/utils/timeouts.ts b/packages/api/src/utils/timeouts.ts
new file mode 100644
index 0000000000..990185853d
--- /dev/null
+++ b/packages/api/src/utils/timeouts.ts
@@ -0,0 +1,69 @@
+import type { AppConfig } from '@librechat/data-schemas';
+
+/** Budgets for outbound calls made inside a request, used when `timeouts` omits a key. */
+export const DEFAULT_OUTBOUND_TIMEOUTS_MS = {
+ ragMs: 30_000,
+ ocrMs: 300_000,
+ actionsMs: 300_000,
+ moderationMs: 10_000,
+ imageFetchMs: 30_000,
+} as const;
+
+export type OutboundTimeout = keyof typeof DEFAULT_OUTBOUND_TIMEOUTS_MS;
+
+/** The `librechat.yaml` `timeouts` value for `key`, else its default. */
+export function getOutboundTimeoutMs(
+ appConfig: Pick<AppConfig, 'timeouts'> | null | undefined,
+ key: OutboundTimeout,
+): number {
+ return appConfig?.timeouts?.[key] ?? DEFAULT_OUTBOUND_TIMEOUTS_MS[key];
+}
+
+/** What an operator sees when a budget runs out: the key to raise and its current value. */
+export function outboundTimeoutMessage(key: OutboundTimeout, timeoutMs: number): string {
+ return `Exceeded timeouts.${key} (${timeoutMs} ms); raise it in librechat.yaml if this upstream is legitimately slow`;
+}
+
+/**
+ * Axios options bounding one request by `timeoutMs`, both as socket idle time (`timeout`) and as
+ * wall-clock time (the abort signal), since a response that keeps trickling bytes never goes idle.
+ * `AbortSignal.timeout` holds its timer weakly, so a finished request leaves nothing scheduled.
+ * Either way the failure carries `outboundTimeoutMessage`, and the deadline also follows `signal`.
+ */
+export function outboundRequestBudget(
+ timeoutMs: number,
+ key: OutboundTimeout,
+ signal?: AbortSignal,
+): { timeout: number; timeoutErrorMessage: string; signal: AbortSignal } {
+ const deadline = AbortSignal.timeout(timeoutMs);
+ return {
+ timeout: timeoutMs,
+ timeoutErrorMessage: outboundTimeoutMessage(key, timeoutMs),
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
+ };
+}
+
+/**
+ * The budget overrun behind `error`, if it was one: an idle timeout, which axios reports with
+ * the budget message, or a passed deadline, which cancels with a `TimeoutError` reason.
+ */
+export function getOutboundTimeout(error: unknown): Error | undefined {
+ if (error == null || typeof error !== 'object') {
+ return undefined;
+ }
+ const { config } = error as {
+ config?: { timeoutErrorMessage?: unknown; signal?: { reason?: unknown } };
+ };
+ const budgetMessage = config?.timeoutErrorMessage;
+ if (typeof budgetMessage !== 'string' || !budgetMessage.startsWith('Exceeded timeouts.')) {
+ return undefined;
+ }
+ if ((error as { message?: unknown }).message === budgetMessage) {
+ return error as Error;
+ }
+ const reason = config?.signal?.reason as { name?: unknown } | undefined;
+ if (reason?.name === 'TimeoutError') {
+ return Object.assign(new Error(budgetMessage), { name: 'OutboundTimeoutError' });
+ }
+ return undefined;
+}
diff --git a/packages/data-provider/specs/actions.spec.ts b/packages/data-provider/specs/actions.spec.ts
index cd03c1596d..646bd1d9ac 100644
--- a/packages/data-provider/specs/actions.spec.ts
+++ b/packages/data-provider/specs/actions.spec.ts
@@ -75,6 +75,31 @@ describe('ActionRequest', () => {
expect(response.data).toEqual({ success: true, method: 'GET' });
});
+ it('bounds the request by the given timeout and abort signal', async () => {
+ const actionRequest = new ActionRequest(
+ 'https://example.com',
+ '/test',
+ 'GET',
+ 'testOp',
+ false,
+ 'application/json',
+ );
+ const executor = actionRequest.setParams({});
+ const controller = new AbortController();
+
+ await executor.execute({ timeout: 5_000, signal: controller.signal });
+
+ expect(mockedAxios.create).toHaveBeenLastCalledWith(
+ expect.objectContaining({ timeout: 5_000, maxRedirects: 0 }),
+ );
+ /* One signal follows both the caller and a wall-clock deadline. */
+ const { signal: combined } = mockedAxios.create.mock.lastCall?.[0] as { signal: AbortSignal };
+ expect(combined).toBeInstanceOf(AbortSignal);
+ expect(combined.aborted).toBe(false);
+ controller.abort();
+ expect(combined.aborted).toBe(true);
+ });
+
describe('ActionRequest', () => {
beforeEach(() => {
mockedAxios.get.mockClear();
diff --git a/packages/data-provider/specs/config-schemas.spec.ts b/packages/data-provider/specs/config-schemas.spec.ts
index 8f5d27c316..837f0c4bd4 100644
--- a/packages/data-provider/specs/config-schemas.spec.ts
+++ b/packages/data-provider/specs/config-schemas.spec.ts
@@ -27,6 +27,7 @@ import {
setMaxSubagents,
traceViewerDefaults,
resolveTraceViewerConfig,
+ outboundTimeoutsSchema,
} from '../src/config';
import {
tModelSpecPresetSchema,
@@ -2166,3 +2167,16 @@ describe('passwordHashing config', () => {
expect(configSchema.shape.passwordHashing.safeParse({ maxWorkers }).success).toBe(false);
});
});
+
+describe('outboundTimeoutsSchema', () => {
+ it('accepts budgets within the Node timer range', () => {
+ expect(outboundTimeoutsSchema.parse({ ragMs: 3_000, ocrMs: 2_147_483_647 })).toEqual({
+ ragMs: 3_000,
+ ocrMs: 2_147_483_647,
+ });
+ });
+
+ it.each([0, -1, 1.5, 2_147_483_648])('rejects %s, which no timer could honor', (value) => {
+ expect(outboundTimeoutsSchema.safeParse({ actionsMs: value }).success).toBe(false);
+ });
+});
diff --git a/packages/data-provider/src/actions.ts b/packages/data-provider/src/actions.ts
index 639ec3ca7f..86561c5a34 100644
--- a/packages/data-provider/src/actions.ts
+++ b/packages/data-provider/src/actions.ts
@@ -167,6 +167,26 @@ class RequestConfig {
) {}
}
+/**
+ * The abort signal for one action call: `timeout` alone only fires on an idle socket, so a
+ * deadline signal caps the whole exchange, combined with the caller's own `signal`.
+ */
+function requestSignal(
+ timeout?: number,
+ signal?: AbortSignal,
+): { signal?: AbortSignal; timeoutErrorMessage?: string } {
+ if (timeout == null) {
+ return signal ? { signal } : {};
+ }
+ /** Same wording as `outboundTimeoutMessage` in `@librechat/api`, which recognizes it. */
+ const message = `Exceeded timeouts.actionsMs (${timeout} ms); raise it in librechat.yaml if this upstream is legitimately slow`;
+ const deadline = AbortSignal.timeout(timeout);
+ return {
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
+ timeoutErrorMessage: message,
+ };
+}
+
class RequestExecutor {
path: string;
params?: Record<string, unknown>;
@@ -283,7 +303,14 @@ class RequestExecutor {
return this;
}
- async execute(options?: { httpAgent?: unknown; httpsAgent?: unknown }) {
+ async execute(options?: {
+ httpAgent?: unknown;
+ httpsAgent?: unknown;
+ /** Milliseconds before the request is abandoned; unset waits indefinitely. */
+ timeout?: number;
+ /** Aborts the request, for example when the run that called the action is stopped. */
+ signal?: AbortSignal;
+ }) {
const url = createURL(this.config.domain, this.path);
const headers: Record<string, string> = {
...this.authHeaders,
@@ -309,6 +336,8 @@ class RequestExecutor {
validateStatus: (status) => status >= 200 && status < 400,
...(options?.httpAgent != null ? { httpAgent: options.httpAgent } : {}),
...(options?.httpsAgent != null ? { httpsAgent: options.httpsAgent } : {}),
+ ...(options?.timeout != null ? { timeout: options.timeout } : {}),
+ ...requestSignal(options?.timeout, options?.signal),
});
// Initialize separate containers for query and body parameters.
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index d549ca30fb..f437e67f28 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -2497,6 +2497,26 @@ export const mcpAppRateLimitSchema = z
export type TMCPAppRateLimits = z.infer<typeof mcpAppRateLimitSchema>;
+/** Per-integration budgets, in milliseconds, for outbound calls that run inside a request.
+ * Omitted keys use the server defaults (`DEFAULT_OUTBOUND_TIMEOUTS_MS` in `@librechat/api`). */
+/** Node clamps a timer delay above 2^31 - 1 ms to 1 ms, so larger budgets would fail at once. */
+const outboundTimeoutMs = z.number().int().positive().max(2_147_483_647).optional();
+
+export const outboundTimeoutsSchema = z.object({
+ /** RAG API queries for file search and message context. */
+ ragMs: outboundTimeoutMs,
+ /** Each OCR provider call (upload, signed URL, OCR, delete). */
+ ocrMs: outboundTimeoutMs,
+ /** Each action (OpenAPI tool) HTTP call. */
+ actionsMs: outboundTimeoutMs,
+ /** The OpenAI moderation check that runs before a chat turn. */
+ moderationMs: outboundTimeoutMs,
+ /** Fetching a stored image by URL to encode it for a provider. */
+ imageFetchMs: outboundTimeoutMs,
+});
+
+export type TOutboundTimeouts = z.infer<typeof outboundTimeoutsSchema>;
+
export const rateLimitSchema = z.object({
twoFactorManagement: z
.object({
@@ -4323,6 +4343,7 @@ export const configSchema = z.object({
maxWorkers: z.number().int().min(1).max(32).optional(),
})
.optional(),
+ timeouts: outboundTimeoutsSchema.optional(),
fileConfig: fileConfigSchema.optional(),
modelSpecs: specsConfigSchema.optional(),
filters: filtersConfigSchema.optional(),
diff --git a/packages/data-schemas/src/app/service.ts b/packages/data-schemas/src/app/service.ts
index 85e11a3467..655e50d0dc 100644
--- a/packages/data-schemas/src/app/service.ts
+++ b/packages/data-schemas/src/app/service.ts
@@ -215,6 +215,7 @@ export const AppService = async (params?: {
skillDeletion,
webSearch,
githubCompare: config.githubCompare,
+ timeouts: config.timeouts,
mcpSettings,
mcpAppSandbox,
fileStrategy,
diff --git a/packages/data-schemas/src/types/app.ts b/packages/data-schemas/src/types/app.ts
index fd63f71297..7ba07d518b 100644
--- a/packages/data-schemas/src/types/app.ts
+++ b/packages/data-schemas/src/types/app.ts
@@ -69,6 +69,8 @@ export interface AppConfig {
/** Web search configuration */
webSearch?: TCustomConfig['webSearch'];
githubCompare?: TCustomConfig['githubCompare'];
+ /** Outbound call budgets; unset keys fall back to the server defaults */
+ timeouts?: TCustomConfig['timeouts'];
skillDeletion?: {
finalizationEnabled?: boolean;
sweepIntervalMs?: number;